[llvm] [Mips] Use CompressPat for microMIPS instruction compression (PR #224217)

Jiaxun Yang via llvm-commits llvm-commits at lists.llvm.org
Thu Sep 17 02:13:47 PDT 2026


https://github.com/FlyGoat updated https://github.com/llvm/llvm-project/pull/224217

>From 59e5aed8d44ea50cda35dd5530d7b860b6f544d4 Mon Sep 17 00:00:00 2001
From: Jiaxun Yang <jiaxun.yang at flygoat.com>
Date: Thu, 17 Sep 2026 08:07:45 +0100
Subject: [PATCH 1/2] [TableGen] Support MachineInstr rewriting in
 CompressInstEmitter

microMIPS needs instruction compression before delay-slot filling so the
filler sees compressed instruction widths when selecting compatible branch
and delay-slot forms. Compressing MCInsts during assembly emission happens
too late for those decisions. A MachineInstr interface lets MIPS reuse
CompressPat rules at the appropriate point in its pass pipeline, and lets
subsequent branch expansion account for the compressed sizes.

Generate MachineInstr overloads of compressInst and uncompressInst, sharing
operand validation and emission with the existing MCInst and compressibility
query variants. Build def/use-aware operand mappings when parsing patterns,
preserve trailing operands and instruction metadata, and update
instruction-reference debug mappings when rewriting.

Handle RegisterOperand wrappers and compression-only pattern sets. Add the
ImmLeaf predicate required by MachineInstr uncompression of RISC-V LUI, and
cover tied operands, fixed operands, variadic instructions and both rewrite
directions in TableGen tests.
---
 llvm/lib/Target/RISCV/RISCVInstrInfo.td       |   3 +-
 .../CompressInstEmitter/register-operands.td  | 108 ++++++
 llvm/utils/TableGen/CompressInstEmitter.cpp   | 318 ++++++++++++++----
 3 files changed, 366 insertions(+), 63 deletions(-)
 create mode 100644 llvm/test/TableGen/CompressInstEmitter/register-operands.td

diff --git a/llvm/lib/Target/RISCV/RISCVInstrInfo.td b/llvm/lib/Target/RISCV/RISCVInstrInfo.td
index 10d43acea0329..004b215d3eff4 100644
--- a/llvm/lib/Target/RISCV/RISCVInstrInfo.td
+++ b/llvm/lib/Target/RISCV/RISCVInstrInfo.td
@@ -471,7 +471,8 @@ class UImm20OperandMaybeSym : RISCVUImmOp<20> {
   }];
 }
 
-def uimm20_lui : UImm20OperandMaybeSym {
+def uimm20_lui : UImm20OperandMaybeSym,
+                 ImmLeaf<XLenVT, [{ return isUInt<20>(Imm); }]> {
   let ParserMatchClass = UImmAsmOperand<20, "LUI">;
   let OperandType = "OPERAND_UIMM20_LUI";
 }
diff --git a/llvm/test/TableGen/CompressInstEmitter/register-operands.td b/llvm/test/TableGen/CompressInstEmitter/register-operands.td
new file mode 100644
index 0000000000000..cda59ee54740e
--- /dev/null
+++ b/llvm/test/TableGen/CompressInstEmitter/register-operands.td
@@ -0,0 +1,108 @@
+// RUN: llvm-tblgen -gen-compress-inst-emitter -I %p/../../../include %s | FileCheck %s
+
+include "llvm/Target/Target.td"
+
+def TestInstrInfo : InstrInfo;
+def TestAsmWriter : AsmWriter {
+  let PassSubtarget = 1;
+}
+def Test : Target {
+  let InstructionSet = TestInstrInfo;
+  let AssemblyWriters = [TestAsmWriter];
+}
+def R0 : Register<"r0">;
+def R1 : Register<"r1">;
+def GPR : RegisterClass<"Test", [i32], 32, (add R0, R1)>;
+def GPROp : RegisterOperand<GPR>;
+
+class TestInst<dag outs, dag ins, int size> : Instruction {
+  let Namespace = "Test";
+  let OutOperandList = outs;
+  let InOperandList = ins;
+  let Size = size;
+}
+def Wide : TestInst<(outs GPROp:$dst), (ins GPROp:$src), 4>;
+def NarrowZero : TestInst<(outs GPROp:$dst), (ins), 2>;
+def NarrowTied : TestInst<(outs GPROp:$dst), (ins GPROp:$src), 2> {
+  let Constraints = "$src = $dst";
+}
+
+def WideTied : TestInst<(outs GPROp:$dst), (ins GPROp:$src), 4> {
+  let Constraints = "$src = $dst";
+}
+def : CompressPat<(WideTied GPROp:$dst), (NarrowTied GPROp:$dst)>;
+
+// Fixed and repeated registers must work with RegisterOperand wrappers as
+// well as bare register classes.
+def : CompressPat<(Wide GPROp:$dst, R0), (NarrowZero GPROp:$dst)>;
+def : CompressPat<(Wide GPROp:$dst, GPROp:$dst), (NarrowTied GPROp:$dst)>;
+
+def SmallImm : Operand<i32>, ImmLeaf<i32, [{ return isUInt<4>(Imm); }]> {
+  let MCOperandPredicate = [{ return MCOp.isImm() && isUInt<4>(MCOp.getImm()); }];
+}
+def WideImm : TestInst<(outs GPROp:$dst), (ins SmallImm:$imm), 4>;
+def NarrowImm : TestInst<(outs GPROp:$dst), (ins), 2>;
+def : CompressPat<(WideImm GPROp:$dst, 7), (NarrowImm GPROp:$dst)>;
+
+def WideOnly : TestInst<(outs GPROp:$dst), (ins), 4>;
+def NarrowOnly : TestInst<(outs GPROp:$dst), (ins), 2>;
+let isCompressOnly = true in
+  def : CompressPat<(WideOnly GPROp:$dst), (NarrowOnly GPROp:$dst)>;
+
+def WideVariadic : TestInst<(outs GPROp:$dst),
+                            (ins GPROp:$src, variable_ops), 4>;
+def NarrowVariadic : TestInst<(outs GPROp:$dst),
+                              (ins GPROp:$src, variable_ops), 2>;
+def : CompressPat<(WideVariadic GPROp:$dst, GPROp:$src),
+                  (NarrowVariadic GPROp:$dst, GPROp:$src)>;
+
+// CHECK-LABEL: #ifdef GEN_COMPRESS_MACHINE_INSTR
+// CHECK: #ifndef Test_MACHINE_INSTR_REWRITE
+// CHECK: static inline void rewriteMachineInstr(
+// CHECK: Operands[I].setImplicit(false);
+// CHECK: unsigned NumFixedOperands = MI.getDesc().getNumOperands();
+// CHECK: Operands.push_back(MI.getOperand(I));
+// CHECK: MO.setImplicit();
+// CHECK: MI.getMF()->makeDebugValueSubstitution(
+// CHECK-LABEL: static bool compressInst(MachineInstr &MI,
+// CHECK-NOT: isVariadic()
+// CHECK-NOT: MI.operands()
+// CHECK: case Test::Wide:
+// CHECK: Operands.push_back(MI.getOperand(0));
+// CHECK: Operands.push_back(MI.getOperand(1));
+// CHECK-NEXT: rewriteMachineInstr(MI, STI.getInstrInfo()->get(Test::NarrowTied), std::move(Operands), {0, 1});
+// CHECK: rewriteMachineInstr(MI, STI.getInstrInfo()->get(Test::NarrowZero), std::move(Operands), {0});
+// CHECK: case Test::WideTied:
+// CHECK: Operands.push_back(MI.getOperand(0));
+// CHECK: Operands.push_back(MI.getOperand(1));
+// CHECK-NEXT: rewriteMachineInstr(MI, STI.getInstrInfo()->get(Test::NarrowTied), std::move(Operands), {0, 1});
+
+// CHECK: case Test::WideVariadic:
+// CHECK: rewriteMachineInstr(MI, STI.getInstrInfo()->get(Test::NarrowVariadic), std::move(Operands), {0, 1});
+
+// CHECK-LABEL: #ifdef GEN_UNCOMPRESS_MACHINE_INSTR
+// CHECK: #ifndef Test_MACHINE_INSTR_REWRITE
+// CHECK: static bool TestValidateMachineOperandForUncompress(
+// CHECK: return isUInt<4>(Imm);
+// CHECK-LABEL: static bool uncompressInst(MachineInstr &MI,
+// CHECK: case Test::NarrowImm:
+// CHECK: Operands.push_back(MachineOperand::CreateImm(7));
+// CHECK: rewriteMachineInstr(MI, STI.getInstrInfo()->get(Test::WideImm), std::move(Operands), {0, std::nullopt});
+// CHECK-NOT: case Test::NarrowOnly:
+// CHECK: case Test::NarrowTied:
+// CHECK: Operands.push_back(MI.getOperand(0));
+// CHECK: Operands.push_back(MI.getOperand(1));
+// CHECK: rewriteMachineInstr(MI, STI.getInstrInfo()->get(Test::Wide), std::move(Operands), {0, 1});
+// CHECK: case Test::NarrowVariadic:
+// CHECK: rewriteMachineInstr(MI, STI.getInstrInfo()->get(Test::WideVariadic), std::move(Operands), {0, 1});
+// CHECK: case Test::NarrowZero:
+// CHECK: Operands.push_back(MI.getOperand(0));
+// CHECK: Operands.push_back(MachineOperand::CreateReg(Test::R0, false));
+// CHECK: rewriteMachineInstr(MI, STI.getInstrInfo()->get(Test::Wide), std::move(Operands), {0, std::nullopt});
+
+// CHECK-LABEL: static bool isCompressibleInst(
+// CHECK: case Test::Wide:
+// CHECK: MI.getOperand(1).getReg() == MI.getOperand(0).getReg()
+// CHECK: return true;
+// CHECK: MI.getOperand(1).getReg() == Test::R0
+// CHECK: return true;
diff --git a/llvm/utils/TableGen/CompressInstEmitter.cpp b/llvm/utils/TableGen/CompressInstEmitter.cpp
index 8f8245ea9ed27..58635c8ca0b24 100644
--- a/llvm/utils/TableGen/CompressInstEmitter.cpp
+++ b/llvm/utils/TableGen/CompressInstEmitter.cpp
@@ -50,8 +50,17 @@
 // bool uncompressInst(MCInst &OutInst, const MCInst &MI,
 //                     const MCSubtargetInfo &STI);
 //
+// GEN_COMPRESS_MACHINE_INSTR and GEN_UNCOMPRESS_MACHINE_INSTR provide
+// post-register-allocation overloads:
+//
+// bool compressInst(MachineInstr &MI, const <TargetName>Subtarget &STI);
+// bool uncompressInst(MachineInstr &MI, const <TargetName>Subtarget &STI);
+//
+// These overloads rewrite MachineInstrs in place. Targets decide whether
+// bundles and delay-slot instructions may change.
+//
 // In addition, it exports a function for checking whether
-// an instruction is compressable:
+// an instruction is compressible:
 //
 // bool isCompressibleInst(const MachineInstr& MI,
 //                         const <TargetName>Subtarget &STI);
@@ -77,6 +86,7 @@
 #include "llvm/TableGen/Record.h"
 #include "llvm/TableGen/TableGenBackend.h"
 #include <limits>
+#include <optional>
 #include <set>
 #include <vector>
 using namespace llvm;
@@ -87,6 +97,9 @@ namespace {
 class CompressInstEmitter {
   struct OpData {
     enum MapKind { Operand, Imm, Reg } Kind;
+    StringRef Name;
+    // Corresponding operand with the same def/use role, for MachineInstrs.
+    std::optional<unsigned> MachineIdx;
     // Info for an operand.
     struct OpndInfo {
       // Record from the Dag.
@@ -131,7 +144,13 @@ class CompressInstEmitter {
           SourceOperandMap(SourceMap), DestOperandMap(DestMap),
           IsCompressOnly(IsCompressOnly) {}
   };
-  enum EmitterType { Compress, Uncompress, CheckCompress };
+  enum EmitterType {
+    Compress,
+    Uncompress,
+    CompressMachine,
+    UncompressMachine,
+    CheckCompress
+  };
   const RecordKeeper &Records;
   const CodeGenTarget Target;
   std::vector<CompressPat> CompressPatterns;
@@ -154,6 +173,7 @@ class CompressInstEmitter {
                                 IndexedMap<OpData> &SourceOperandMap,
                                 IndexedMap<OpData> &DestOperandMap,
                                 StringMap<ArgData> &SourceOperands,
+                                const CodeGenInstruction &SourceInst,
                                 const CodeGenInstruction &DestInst);
 
 public:
@@ -169,7 +189,8 @@ bool CompressInstEmitter::validateRegister(const Record *Reg,
   assert((Reg->isSubClassOf("Register") ||
           Reg->isSubClassOf("RegisterByHwMode")) &&
          "Reg record should be a Register");
-  assert(RegClass->isSubClassOf("RegisterClassLike") &&
+  RegClass = Target.getAsRegClassLike(RegClass);
+  assert(RegClass && RegClass->isSubClassOf("RegisterClassLike") &&
          "RegClass record should be RegisterClassLike");
   return Target.getRegBank().regClassContainsReg(RegClass, Reg, Loc);
 }
@@ -292,6 +313,7 @@ void CompressInstEmitter::addDagOperandMapping(const Record *Rec,
         // appears twice in the same Dag (tied in the compressed instruction),
         // we note the previous index in the TiedOpIdx field.
         StringRef ArgName = Dag->getArgNameStr(DAGOpNo);
+        OperandMap[OpNo].Name = ArgName;
         if (ArgName.empty())
           continue;
 
@@ -367,7 +389,8 @@ void CompressInstEmitter::checkDagOperandMapping(
 void CompressInstEmitter::createInstOperandMapping(
     const Record *Rec, const DagInit *SourceDag, const DagInit *DestDag,
     IndexedMap<OpData> &SourceOperandMap, IndexedMap<OpData> &DestOperandMap,
-    StringMap<ArgData> &SourceOperands, const CodeGenInstruction &DestInst) {
+    StringMap<ArgData> &SourceOperands, const CodeGenInstruction &SourceInst,
+    const CodeGenInstruction &DestInst) {
   // TiedCount keeps track of the number of operands skipped in Inst
   // operands list to get to the corresponding Dag operand.
   unsigned TiedCount = 0;
@@ -414,6 +437,33 @@ void CompressInstEmitter::createInstOperandMapping(
       LLVM_DEBUG(dbgs() << "    " << SourceOpNo << " ====> " << OpNo << "\n");
     }
   }
+
+  // Retain separate def and use mappings for both rewrite directions.
+  unsigned NumSourceOps = SourceInst.Operands.empty()
+                              ? 0
+                              : SourceInst.Operands.back().MIOperandNo +
+                                    SourceInst.Operands.back().MINumOperands;
+  for (unsigned SrcNo = 0; SrcNo != NumSourceOps; ++SrcNo) {
+    OpData &Src = SourceOperandMap[SrcNo];
+    if (Src.Kind == OpData::Imm)
+      continue;
+    bool IsReg =
+        Src.Kind == OpData::Reg || Target.getAsRegClassLike(Src.OpInfo.DagRec);
+    for (unsigned DstNo = 0; DstNo != OpNo; ++DstNo) {
+      OpData &Dst = DestOperandMap[DstNo];
+      if (Src.Kind != Dst.Kind ||
+          (IsReg && (SrcNo < SourceInst.Operands.NumDefs) !=
+                        (DstNo < DestInst.Operands.NumDefs)))
+        continue;
+      if (Src.Kind == OpData::Reg ? Src.RegRec != Dst.RegRec
+                                  : Src.Name != Dst.Name)
+        continue;
+      if (!Src.MachineIdx)
+        Src.MachineIdx = DstNo;
+      if (!Dst.MachineIdx)
+        Dst.MachineIdx = SrcNo;
+    }
+  }
 }
 
 /// Validates the CompressPattern and create operand mapping.
@@ -485,7 +535,8 @@ void CompressInstEmitter::evaluateCompressPat(const Record *Rec) {
   checkDagOperandMapping(Rec, DestOperands, SourceDag, DestDag);
   // Create operand mapping between the source and destination instructions.
   createInstOperandMapping(Rec, SourceDag, DestDag, SourceOperandMap,
-                           DestOperandMap, SourceOperands, DestInst);
+                           DestOperandMap, SourceOperands, SourceInst,
+                           DestInst);
 
   // Get the target features for the CompressPat.
   std::vector<const Record *> PatReqFeatures;
@@ -584,15 +635,19 @@ void CompressInstEmitter::emitCompressInstEmitter(raw_ostream &OS,
                     "for target features.");
 
   StringRef TargetName = Target.getName();
+  bool IsUncompress = EType == EmitterType::Uncompress ||
+                      EType == EmitterType::UncompressMachine;
+  bool IsMachineRewrite = EType == EmitterType::CompressMachine ||
+                          EType == EmitterType::UncompressMachine;
 
   // Sort entries in CompressPatterns to handle instructions that can have more
   // than one candidate for compression\uncompression, e.g ADD can be
   // transformed to a C_ADD or a C_MV. When emitting 'uncompress()' function the
   // source and destination are flipped and the sort key needs to change
   // accordingly.
-  llvm::stable_sort(CompressPatterns, [EType](const CompressPat &LHS,
-                                              const CompressPat &RHS) {
-    if (EType == EmitterType::Compress || EType == EmitterType::CheckCompress)
+  llvm::stable_sort(CompressPatterns, [IsUncompress](const CompressPat &LHS,
+                                                     const CompressPat &RHS) {
+    if (!IsUncompress)
       return LHS.Source.getName() < RHS.Source.getName();
     return LHS.Dest.getName() < RHS.Dest.getName();
   });
@@ -615,6 +670,10 @@ void CompressInstEmitter::emitCompressInstEmitter(raw_ostream &OS,
       return "GEN_COMPRESS_INSTR";
     case EmitterType::Uncompress:
       return "GEN_UNCOMPRESS_INSTR";
+    case EmitterType::CompressMachine:
+      return "GEN_COMPRESS_MACHINE_INSTR";
+    case EmitterType::UncompressMachine:
+      return "GEN_UNCOMPRESS_MACHINE_INSTR";
     case EmitterType::CheckCompress:
       return "GEN_CHECK_COMPRESS_INSTR";
     }
@@ -623,6 +682,107 @@ void CompressInstEmitter::emitCompressInstEmitter(raw_ostream &OS,
 
   IfDefEmitter IfDef(OS, GetEmitterGuard());
 
+  if (IsMachineRewrite) {
+    std::string Guard = (TargetName + "_MACHINE_INSTR_REWRITE").str();
+    OS << "#ifndef " << Guard << "\n#define " << Guard << "\n";
+    OS << R"cpp(
+// Map identifies the source operand for each copied destination operand.
+static inline void rewriteMachineInstr(
+    MachineInstr &MI, const MCInstrDesc &Desc,
+    SmallVector<MachineOperand, 8> Operands, SmallVector<std::optional<unsigned>, 8> Map) {
+  SmallVector<bool, 8> Used(MI.getNumOperands(), false);
+  for (unsigned I = 0, E = Operands.size(); I != E; ++I) {
+    // Reuse implicit registers made explicit by expansion, retaining their flags.
+    if (!Map[I] && Operands[I].isReg())
+      for (unsigned J = MI.getNumExplicitOperands(), End = MI.getNumOperands();
+           J != End; ++J) {
+        const MachineOperand &MO = MI.getOperand(J);
+        if (!Used[J] && MO.isReg() && MO.isImplicit() &&
+            MO.getReg() == Operands[I].getReg() &&
+            MO.isDef() == Operands[I].isDef()) {
+          Operands[I] = MO;
+          Operands[I].setImplicit(false);
+          Map[I] = J;
+          break;
+        }
+      }
+    if (Map[I])
+      Used[*Map[I]] = true;
+  }
+
+  // Trailing operands are not described by the pattern.
+  unsigned NumFixedOperands = MI.getDesc().getNumOperands();
+  for (unsigned I = NumFixedOperands, E = MI.getNumOperands(); I != E; ++I) {
+    if (Used[I])
+      continue;
+    Operands.push_back(MI.getOperand(I));
+    Map.push_back(I);
+  }
+
+  // Registers omitted by the encoding remain implicit dependencies.
+  for (unsigned I = 0; I != NumFixedOperands; ++I) {
+    if (Used[I] || !MI.getOperand(I).isReg())
+      continue;
+    MachineOperand MO = MI.getOperand(I);
+    MO.setImplicit();
+    MO.setIsRenamable(false);
+    Operands.push_back(MO);
+    Map.push_back(I);
+  }
+
+  auto AddImplicit = [&](MCPhysReg Reg, bool IsDef) {
+    for (const MachineOperand &MO : Operands)
+      if (MO.isReg() && MO.isImplicit() && MO.getReg() == Reg &&
+          MO.isDef() == IsDef)
+        return;
+    Operands.push_back(MachineOperand::CreateReg(Reg, IsDef, true));
+    Map.push_back(std::nullopt);
+  };
+  for (MCPhysReg Reg : Desc.implicit_defs())
+    AddImplicit(Reg, true);
+  for (MCPhysReg Reg : Desc.implicit_uses())
+    AddImplicit(Reg, false);
+
+  // Keep kill flags on the last use after reordering operands.
+  for (unsigned I = 0, E = Operands.size(); I != E; ++I) {
+    MachineOperand &MO = Operands[I];
+    if (!MO.isReg() || !MO.isUse() || !MO.isKill())
+      continue;
+    for (unsigned J = I + 1; J != E; ++J) {
+      MachineOperand &Later = Operands[J];
+      if (Later.isReg() && Later.isUse() && Later.getReg() == MO.getReg()) {
+        MO.setIsKill(false);
+        Later.setIsKill(true);
+      }
+    }
+  }
+
+  unsigned OldDebugNum = MI.peekDebugInstrNum();
+  if (OldDebugNum) {
+    MI.dropDebugNumber();
+    unsigned NewDebugNum = MI.getDebugInstrNum();
+    for (unsigned I = 0, E = Operands.size(); I != E; ++I)
+      if (Map[I] && Operands[I].isReg() && Operands[I].isDef())
+        MI.getMF()->makeDebugValueSubstitution(
+            {OldDebugNum, *Map[I]}, {NewDebugNum, I});
+    if (MI.mayStore())
+      MI.getMF()->makeDebugValueSubstitution(
+          {OldDebugNum, MachineFunction::DebugOperandMemNumber},
+          {NewDebugNum, MachineFunction::DebugOperandMemNumber});
+  }
+
+  // Remove uses before defs to clear ties; addOperand applies the new constraints.
+  while (MI.getNumOperands())
+    MI.removeOperand(MI.getNumOperands() - 1);
+  MI.setDesc(Desc);
+  for (const MachineOperand &MO : Operands)
+    MI.addOperand(MO);
+}
+
+)cpp";
+    OS << "#endif // " << Guard << "\n\n";
+  }
+
   if (EType == EmitterType::Compress) {
     FuncH << "static bool compressInst(MCInst &OutInst,\n";
     FuncH.indent(25) << "const MCInst &MI,\n";
@@ -631,7 +791,11 @@ void CompressInstEmitter::emitCompressInstEmitter(raw_ostream &OS,
     FuncH << "static bool uncompressInst(MCInst &OutInst,\n";
     FuncH.indent(27) << "const MCInst &MI,\n";
     FuncH.indent(27) << "const MCSubtargetInfo &STI) {\n";
-  } else if (EType == EmitterType::CheckCompress) {
+  } else if (IsMachineRewrite) {
+    FuncH << "static bool "
+          << (IsUncompress ? "uncompressInst" : "compressInst")
+          << "(MachineInstr &MI, const " << TargetName << "Subtarget &STI) {\n";
+  } else {
     FuncH << "static bool isCompressibleInst(const MachineInstr &MI,\n";
     FuncH.indent(31) << "const " << TargetName << "Subtarget &STI) {\n";
   }
@@ -653,19 +817,26 @@ void CompressInstEmitter::emitCompressInstEmitter(raw_ostream &OS,
   CaseStream << "  switch (MI.getOpcode()) {\n";
   CaseStream << "  default: return false;\n";
 
-  bool CompressOrCheck =
-      EType == EmitterType::Compress || EType == EmitterType::CheckCompress;
-  bool CompressOrUncompress =
+  bool EmitOperands = EType != EmitterType::CheckCompress;
+  StringRef AddOperand =
+      IsMachineRewrite ? "Operands.push_back(" : "OutInst.addOperand(";
+  StringRef OperandType =
+      IsMachineRewrite ? "MachineOperand::Create" : "MCOperand::create";
+  std::string MachineValidatorName =
+      (TargetName + "ValidateMachineOperand" +
+       (IsMachineRewrite ? (IsUncompress ? "ForUncompress" : "ForCompress")
+                         : ""))
+          .str();
+  bool IsMCInst =
       EType == EmitterType::Compress || EType == EmitterType::Uncompress;
   std::string ValidatorName =
-      CompressOrUncompress
-          ? (TargetName + "ValidateMCOperandFor" +
-             (EType == EmitterType::Compress ? "Compress" : "Uncompress"))
-                .str()
-          : "";
+      IsMCInst ? (TargetName + "ValidateMCOperandFor" +
+                  (EType == EmitterType::Compress ? "Compress" : "Uncompress"))
+                     .str()
+               : "";
 
   for (const auto &CompressPat : CompressPatterns) {
-    if (EType == EmitterType::Uncompress && CompressPat.IsCompressOnly)
+    if (IsUncompress && CompressPat.IsCompressOnly)
       continue;
 
     std::string CondString;
@@ -673,15 +844,15 @@ void CompressInstEmitter::emitCompressInstEmitter(raw_ostream &OS,
     raw_string_ostream CondStream(CondString);
     raw_string_ostream CodeStream(CodeString);
     const CodeGenInstruction &Source =
-        CompressOrCheck ? CompressPat.Source : CompressPat.Dest;
+        !IsUncompress ? CompressPat.Source : CompressPat.Dest;
     const CodeGenInstruction &Dest =
-        CompressOrCheck ? CompressPat.Dest : CompressPat.Source;
+        !IsUncompress ? CompressPat.Dest : CompressPat.Source;
     const IndexedMap<OpData> &SourceOperandMap =
-        CompressOrCheck ? CompressPat.SourceOperandMap
-                        : CompressPat.DestOperandMap;
+        !IsUncompress ? CompressPat.SourceOperandMap
+                      : CompressPat.DestOperandMap;
     const IndexedMap<OpData> &DestOperandMap =
-        CompressOrCheck ? CompressPat.DestOperandMap
-                        : CompressPat.SourceOperandMap;
+        !IsUncompress ? CompressPat.DestOperandMap
+                      : CompressPat.SourceOperandMap;
 
     CurOp = Source.getName();
     // Check current and previous opcode to decide to continue or end a case.
@@ -738,7 +909,7 @@ void CompressInstEmitter::emitCompressInstEmitter(raw_ostream &OS,
         switch (SourceOperandMap[OpNo].Kind) {
         case OpData::Operand:
           if (SourceOperandMap[OpNo].OpInfo.TiedOpIdx != -1) {
-            if (Source.Operands[OpNo].Rec->isSubClassOf("RegisterClassLike"))
+            if (Target.getAsRegClassLike(SourceOperand.Rec))
               CondStream << CondSep << "MI.getOperand(" << OpNo
                          << ").isReg() && MI.getOperand("
                          << SourceOperandMap[OpNo].OpInfo.TiedOpIdx
@@ -777,9 +948,12 @@ void CompressInstEmitter::emitCompressInstEmitter(raw_ostream &OS,
       }
     }
     CodeStream.indent(6) << "// " << Dest.AsmString << "\n";
-    if (CompressOrUncompress)
+    if (IsMCInst)
       CodeStream.indent(6) << "OutInst.setOpcode(" << TargetName
                            << "::" << Dest.getName() << ");\n";
+    SmallVector<std::optional<unsigned>, 8> MachineMap;
+    if (IsMachineRewrite)
+      CodeStream.indent(6) << "SmallVector<MachineOperand, 8> Operands;\n";
     OpNo = 0;
     for (const auto &DestOperand : Dest.Operands) {
       CodeStream.indent(6) << "// Operand: " << DestOperand.Name << "\n";
@@ -791,6 +965,8 @@ void CompressInstEmitter::emitCompressInstEmitter(raw_ostream &OS,
           DestRec =
               cast<DefInit>(DestOperand.MIOperandInfo->getArg(SubOp))->getDef();
 
+        std::string OperandExpr;
+        raw_string_ostream OperandStream(OperandExpr);
         switch (DestOperandMap[OpNo].Kind) {
         case OpData::Operand: {
           unsigned OpIdx = DestOperandMap[OpNo].OpInfo.Idx;
@@ -803,7 +979,7 @@ void CompressInstEmitter::emitCompressInstEmitter(raw_ostream &OS,
             // for the operand it's tied to.
             if (DestOperand.getTiedRegister() == -1) {
               CondStream << CondSep << "MI.getOperand(" << OpIdx << ").isReg()";
-              if (EType == EmitterType::CheckCompress)
+              if (!IsMCInst)
                 CondStream << " && MI.getOperand(" << OpIdx
                            << ").getReg().isPhysical()";
               CondStream << CondSep << "get" << TargetName
@@ -819,12 +995,9 @@ void CompressInstEmitter::emitCompressInstEmitter(raw_ostream &OS,
                          << ").getReg())";
             }
 
-            if (CompressOrUncompress)
-              CodeStream.indent(6)
-                  << "OutInst.addOperand(MI.getOperand(" << OpIdx << "));\n";
           } else {
             // Handling immediate operands.
-            if (CompressOrUncompress) {
+            if (IsMCInst) {
               unsigned Entry = getPredicates(MCOpPredicateMap, MCOpPredicates,
                                              DagRec, "MCOperandPredicate");
               CondStream << CondSep << ValidatorName << "("
@@ -843,7 +1016,7 @@ void CompressInstEmitter::emitCompressInstEmitter(raw_ostream &OS,
                   getPredicates(ImmLeafPredicateMap, ImmLeafPredicates, DagRec,
                                 "ImmediateCode");
               CondStream << CondSep << "MI.getOperand(" << OpIdx << ").isImm()";
-              CondStream << CondSep << TargetName << "ValidateMachineOperand("
+              CondStream << CondSep << MachineValidatorName << "("
                          << "MI.getOperand(" << OpIdx << "), &STI, " << Entry
                          << " /* " << DagRec->getName() << " */)";
               if (DagRec != DestRec) {
@@ -851,19 +1024,17 @@ void CompressInstEmitter::emitCompressInstEmitter(raw_ostream &OS,
                                       DestRec, "ImmediateCode");
                 CondStream << CondSep << "MI.getOperand(" << OpIdx
                            << ").isImm()";
-                CondStream << CondSep << TargetName << "ValidateMachineOperand("
+                CondStream << CondSep << MachineValidatorName << "("
                            << "MI.getOperand(" << OpIdx << "), &STI, " << Entry
                            << " /* " << DestRec->getName() << " */)";
               }
             }
-            if (CompressOrUncompress)
-              CodeStream.indent(6)
-                  << "OutInst.addOperand(MI.getOperand(" << OpIdx << "));\n";
           }
+          OperandStream << "MI.getOperand(" << OpIdx << ")";
           break;
         }
         case OpData::Imm: {
-          if (CompressOrUncompress) {
+          if (IsMCInst) {
             unsigned Entry = getPredicates(MCOpPredicateMap, MCOpPredicates,
                                            DestRec, "MCOperandPredicate");
             CondStream << CondSep << ValidatorName << "("
@@ -874,42 +1045,63 @@ void CompressInstEmitter::emitCompressInstEmitter(raw_ostream &OS,
             unsigned Entry =
                 getPredicates(ImmLeafPredicateMap, ImmLeafPredicates, DestRec,
                               "ImmediateCode");
-            CondStream << CondSep << TargetName
-                       << "ValidateMachineOperand(MachineOperand::CreateImm("
+            CondStream << CondSep << MachineValidatorName
+                       << "(MachineOperand::CreateImm("
                        << DestOperandMap[OpNo].ImmVal << "), &STI, " << Entry
                        << " /* " << DestRec->getName() << " */)";
           }
-          if (CompressOrUncompress)
-            CodeStream.indent(6) << "OutInst.addOperand(MCOperand::createImm("
-                                 << DestOperandMap[OpNo].ImmVal << "));\n";
+          OperandStream << OperandType << "Imm(" << DestOperandMap[OpNo].ImmVal
+                        << ")";
         } break;
         case OpData::Reg: {
-          if (CompressOrUncompress) {
-            // Fixed register has been validated at pattern validation time.
-            const Record *Reg = DestOperandMap[OpNo].RegRec;
-            CodeStream.indent(6) << "OutInst.addOperand(MCOperand::createReg(";
-            if (Reg->isSubClassOf("RegisterByHwMode")) {
-              RegisterByHwMode(Reg, Target.getRegBank())
-                  .emitResolverCall(CodeStream, "HwModeId");
-            } else {
-              CodeStream << TargetName << "::" << Reg->getName();
-            }
-            CodeStream << "));\n";
-          }
-        } break;
+          // Fixed register has been validated at pattern validation time.
+          const Record *Reg = DestOperandMap[OpNo].RegRec;
+          OperandStream << OperandType << "Reg(";
+          if (Reg->isSubClassOf("RegisterByHwMode"))
+            RegisterByHwMode(Reg, Target.getRegBank())
+                .emitResolverCall(OperandStream, "HwModeId");
+          else
+            OperandStream << TargetName << "::" << Reg->getName();
+          if (IsMachineRewrite)
+            OperandStream << ", "
+                          << (OpNo < Dest.Operands.NumDefs ? "true" : "false");
+          OperandStream << ")";
+          break;
+        }
+        }
+        if (IsMachineRewrite) {
+          std::optional<unsigned> Index = DestOperandMap[OpNo].MachineIdx;
+          MachineMap.push_back(Index);
+          if (Index)
+            OperandExpr = "MI.getOperand(" + utostr(*Index) + ")";
+          else if (DestOperandMap[OpNo].Kind == OpData::Operand)
+            // A variable operand must have a source with the same def/use role.
+            CodeStream.indent(6) << "return false;\n";
         }
+        if (EmitOperands)
+          CodeStream.indent(6) << AddOperand << OperandExpr << ");\n";
         ++OpNo;
       }
     }
-    if (CompressOrUncompress)
+    if (IsMCInst)
       CodeStream.indent(6) << "OutInst.setLoc(MI.getLoc());\n";
+    if (IsMachineRewrite) {
+      CodeStream.indent(6) << "rewriteMachineInstr(MI, STI.getInstrInfo()->get("
+                           << TargetName << "::" << Dest.getName()
+                           << "), std::move(Operands), {";
+      ListSeparator Sep;
+      for (std::optional<unsigned> Index : MachineMap)
+        CodeStream << Sep << (Index ? utostr(*Index) : "std::nullopt");
+      CodeStream << "});\n";
+    }
     mergeCondAndCode(CaseStream, CondString, CodeString);
     PrevOp = CurOp;
   }
   Func << CaseString;
-  Func.indent(4) << "break;\n";
-  // Close brace for the last case.
-  Func.indent(2) << "} // case " << CurOp << "\n";
+  if (!PrevOp.empty()) {
+    Func.indent(4) << "break;\n";
+    Func.indent(2) << "} // case " << PrevOp << "\n";
+  }
   Func.indent(2) << "} // switch\n";
   Func.indent(2) << "return false;\n}\n";
 
@@ -930,9 +1122,9 @@ void CompressInstEmitter::emitCompressInstEmitter(raw_ostream &OS,
   }
 
   if (!ImmLeafPredicates.empty()) {
-    auto IndentLength = TargetName.size() + 35;
-    OS << "static bool " << TargetName
-       << "ValidateMachineOperand(const MachineOperand &MO,\n";
+    auto IndentLength = MachineValidatorName.size() + 13;
+    OS << "static bool " << MachineValidatorName
+       << "(const MachineOperand &MO,\n";
     OS.indent(IndentLength)
         << "const " << TargetName << "Subtarget *Subtarget,\n";
     OS.indent(IndentLength)
@@ -964,6 +1156,8 @@ void CompressInstEmitter::run(raw_ostream &OS) {
   emitCompressInstEmitter(OS, EmitterType::Compress);
   // Generate uncompressInst() function.
   emitCompressInstEmitter(OS, EmitterType::Uncompress);
+  emitCompressInstEmitter(OS, EmitterType::CompressMachine);
+  emitCompressInstEmitter(OS, EmitterType::UncompressMachine);
   // Generate isCompressibleInst() function.
   emitCompressInstEmitter(OS, EmitterType::CheckCompress);
 }

>From c490ed8c364f4ac62f00a8523d921c7349a94efe Mon Sep 17 00:00:00 2001
From: Jiaxun Yang <jiaxun.yang at flygoat.com>
Date: Thu, 17 Sep 2026 08:43:04 +0100
Subject: [PATCH 2/2] [Mips] Use CompressPat for microMIPS instruction
 compression

Express the single-instruction size reductions as CompressPat rules and call
the generated MachineInstr compressor from MicroMipsSizeReduce. Remove the
corresponding handwritten register checks, immediate checks and operand
transfers.

Keep the existing pass placement and feature gates, with LWP/SWP/MOVEP
pairing taking priority over single-instruction compression. Add coverage
for operand restrictions, immediate boundaries, metadata preservation,
delay slots and branch sizes.
---
 llvm/lib/Target/Mips/CMakeLists.txt           |   1 +
 .../Mips/MCTargetDesc/MipsMCTargetDesc.h      |   1 +
 llvm/lib/Target/Mips/MicroMipsInstrInfo.td    |  84 +++-
 .../Target/Mips/MicroMipsSizeReduction.cpp    | 371 +++---------------
 llvm/lib/Target/Mips/MipsRegisterInfo.td      |   3 +
 .../micromips-sizereduction/branch-size.mir   |  46 +++
 .../compress-metadata.mir                     |  48 +++
 .../micromips-sizereduction/compress-pat.mir  | 273 +++++++++++++
 .../delay-slot-compression.mir                |  88 +++++
 .../secondary/llvm/lib/Target/Mips/BUILD.gn   |   7 +
 10 files changed, 602 insertions(+), 320 deletions(-)
 create mode 100644 llvm/test/CodeGen/Mips/micromips-sizereduction/branch-size.mir
 create mode 100644 llvm/test/CodeGen/Mips/micromips-sizereduction/compress-metadata.mir
 create mode 100644 llvm/test/CodeGen/Mips/micromips-sizereduction/compress-pat.mir
 create mode 100644 llvm/test/CodeGen/Mips/micromips-sizereduction/delay-slot-compression.mir

diff --git a/llvm/lib/Target/Mips/CMakeLists.txt b/llvm/lib/Target/Mips/CMakeLists.txt
index 26afdcba94c69..0f082c5aa2ae9 100644
--- a/llvm/lib/Target/Mips/CMakeLists.txt
+++ b/llvm/lib/Target/Mips/CMakeLists.txt
@@ -5,6 +5,7 @@ set(LLVM_TARGET_DEFINITIONS Mips.td)
 tablegen(LLVM MipsGenAsmMatcher.inc -gen-asm-matcher)
 tablegen(LLVM MipsGenAsmWriter.inc -gen-asm-writer)
 tablegen(LLVM MipsGenCallingConv.inc -gen-callingconv)
+tablegen(LLVM MipsGenCompressInstEmitter.inc -gen-compress-inst-emitter)
 tablegen(LLVM MipsGenDAGISel.inc -gen-dag-isel)
 tablegen(LLVM MipsGenDisassemblerTables.inc -gen-disassembler
               -ignore-non-decodable-operands)
diff --git a/llvm/lib/Target/Mips/MCTargetDesc/MipsMCTargetDesc.h b/llvm/lib/Target/Mips/MCTargetDesc/MipsMCTargetDesc.h
index f3e3e6e8d1073..d879e48e7ef1f 100644
--- a/llvm/lib/Target/Mips/MCTargetDesc/MipsMCTargetDesc.h
+++ b/llvm/lib/Target/Mips/MCTargetDesc/MipsMCTargetDesc.h
@@ -13,6 +13,7 @@
 #ifndef LLVM_LIB_TARGET_MIPS_MCTARGETDESC_MIPSMCTARGETDESC_H
 #define LLVM_LIB_TARGET_MIPS_MCTARGETDESC_MIPSMCTARGETDESC_H
 
+#include "llvm/Support/Compiler.h"
 #include "llvm/Support/DataTypes.h"
 
 #include <memory>
diff --git a/llvm/lib/Target/Mips/MicroMipsInstrInfo.td b/llvm/lib/Target/Mips/MicroMipsInstrInfo.td
index dff57a5d59dc1..f69530cef5cb1 100644
--- a/llvm/lib/Target/Mips/MicroMipsInstrInfo.td
+++ b/llvm/lib/Target/Mips/MicroMipsInstrInfo.td
@@ -15,7 +15,31 @@ def addrimm12 : ComplexPattern<iPTR, 2, "selectIntAddr12MM", [frameindex]>;
 def addrimm16 : ComplexPattern<iPTR, 2, "selectIntAddr16MM", [frameindex]>;
 def addrimm4lsl2 : ComplexPattern<iPTR, 2, "selectIntAddrLSL2MM", [frameindex]>;
 
-def simm9_addiusp : Operand<i32> {
+class MicroMipsCompressImm<string Cond> : Operand<i32>,
+    ImmLeaf<i32, !strconcat("return ", Cond, ";")> {
+  let MCOperandPredicate = !strconcat([{
+    if (!MCOp.isImm())
+      return false;
+    int64_t Imm = MCOp.getImm();
+    return }], Cond, ";");
+}
+
+// LBU16 and SB16 share a memory operand; their compression patterns narrow
+// this union to the range accepted by each instruction.
+def mm_imm4 : MicroMipsCompressImm<"Imm >= -1 && Imm < 16">;
+def mm_lbu_imm4 : MicroMipsCompressImm<"Imm >= -1 && Imm < 15">;
+def mm_sb_imm4 : MicroMipsCompressImm<"isUInt<4>(Imm)">;
+def mm_imm4_lsl1 : MicroMipsCompressImm<"isShiftedUInt<4, 1>(Imm)">;
+def mm_imm5_lsl2 : MicroMipsCompressImm<"isShiftedUInt<5, 2>(Imm)">;
+def mm_imm6_lsl2 : MicroMipsCompressImm<"isShiftedUInt<6, 2>(Imm)"> {
+  let EncoderMethod = "getUImm6Lsl2Encoding";
+  let DecoderMethod = "DecodeUImmWithOffsetAndScale<6, 0, 4>";
+  let ParserMatchClass = ConstantUImm6Lsl2AsmOperandClass;
+}
+
+def simm9_addiusp : MicroMipsCompressImm<
+    "(Imm % 4 == 0) && ((Imm >= 8 && Imm <= 1028) || " #
+    "(Imm >= -1032 && Imm <= -12))"> {
   let EncoderMethod = "getSImm9AddiuspValue";
   let DecoderMethod = "DecodeSimm9SP";
 }
@@ -65,10 +89,12 @@ class mem_mm_4_generic : Operand<i32> {
 }
 
 def mem_mm_4 : mem_mm_4_generic {
+  let MIOperandInfo = (ops ptr_gpr16mm_rc, mm_imm4);
   let EncoderMethod = "getMemEncodingMMImm4";
 }
 
 def mem_mm_4_lsl1 : mem_mm_4_generic {
+  let MIOperandInfo = (ops ptr_gpr16mm_rc, mm_imm4_lsl1);
   let EncoderMethod = "getMemEncodingMMImm4Lsl1";
 }
 
@@ -92,7 +118,7 @@ def MicroMipsMemGPAsmOperand : AsmOperandClass {
 
 def mem_mm_sp_imm5_lsl2 : Operand<i32> {
   let PrintMethod = "printMemOperand";
-  let MIOperandInfo = (ops ptr_sp_rc:$base, simm5:$offset);
+  let MIOperandInfo = (ops ptr_sp_rc:$base, mm_imm5_lsl2:$offset);
   let OperandType = "OPERAND_MEMORY";
   let ParserMatchClass = MicroMipsMemSPAsmOperand;
   let EncoderMethod = "getMemEncodingMMSPImm5Lsl2";
@@ -378,7 +404,7 @@ class AddImmUS5<string opstr, RegisterOperand RO> :
 }
 
 class AddImmUR1SP<string opstr, RegisterOperand RO> :
-  MicroMipsInst16<(outs RO:$rd), (ins uimm6_lsl2:$imm),
+  MicroMipsInst16<(outs RO:$rd), (ins mm_imm6_lsl2:$imm),
                   !strconcat(opstr, "\t$rd, $imm"), [], FrmR>;
 
 class AddImmUSP<string opstr> :
@@ -1417,3 +1443,55 @@ def : MipsInstAlias<"mthgc0 $rt, $rs",
 def : MipsInstAlias<"sw $rt, $offset",
                     (SWSP_MM GPR32Opnd:$rt, mem_mm_sp_imm5_lsl2:$offset), 1>,
                     ISA_MICROMIPS;
+
+// microMIPS32r2-r5 instruction compression.
+let Predicates = [InMicroMips, HasMips32r2, NotMips32r6],
+    isCompressOnly = true in {
+  foreach Op = [ADDiu, ADDiu_MM] in
+    def : CompressPat<(Op GPRMM16Opnd:$dst, SP, mm_imm6_lsl2:$imm),
+                      (ADDIUR1SP_MM GPRMM16Opnd:$dst, mm_imm6_lsl2:$imm)>;
+  foreach Op = [LEA_ADDiu, LEA_ADDiu_MM] in
+    def : CompressPat<(Op GPRMM16Opnd:$dst, SPByHwMode, mm_imm6_lsl2:$imm),
+                      (ADDIUR1SP_MM GPRMM16Opnd:$dst, mm_imm6_lsl2:$imm)>;
+  foreach Op = [ADDiu, ADDiu_MM] in
+    def : CompressPat<(Op SP, SP, simm9_addiusp:$imm),
+                      (ADDIUSP_MM simm9_addiusp:$imm)>;
+  foreach Op = [ADDu, ADDu_MM] in
+    def : CompressPat<(Op GPRMM16Opnd:$dst, GPRMM16Opnd:$lhs, GPRMM16Opnd:$rhs),
+                      (ADDU16_MM GPRMM16Opnd:$dst, GPRMM16Opnd:$lhs,
+                                 GPRMM16Opnd:$rhs)>;
+  foreach Op = [SUBu, SUBu_MM] in
+    def : CompressPat<(Op GPRMM16Opnd:$dst, GPRMM16Opnd:$lhs, GPRMM16Opnd:$rhs),
+                      (SUBU16_MM GPRMM16Opnd:$dst, GPRMM16Opnd:$lhs,
+                                 GPRMM16Opnd:$rhs)>;
+  foreach Op = [XOR, XOR_MM] in {
+    def : CompressPat<(Op GPRMM16Opnd:$dst, GPRMM16Opnd:$src, GPRMM16Opnd:$dst),
+                      (XOR16_MM GPRMM16Opnd:$dst, GPRMM16Opnd:$src)>;
+    def : CompressPat<(Op GPRMM16Opnd:$dst, GPRMM16Opnd:$dst, GPRMM16Opnd:$src),
+                      (XOR16_MM GPRMM16Opnd:$dst, GPRMM16Opnd:$src)>;
+  }
+  foreach Op = [LBu, LBu_MM] in
+    def : CompressPat<(Op GPRMM16Opnd:$dst, ptr_gpr16mm_rc:$base, mm_lbu_imm4:$imm),
+                      (LBU16_MM GPRMM16Opnd:$dst, ptr_gpr16mm_rc:$base,
+                                mm_lbu_imm4:$imm)>;
+  foreach Op = [LHu, LHu_MM] in
+    def : CompressPat<(Op GPRMM16Opnd:$dst, ptr_gpr16mm_rc:$base, mm_imm4_lsl1:$imm),
+                      (LHU16_MM GPRMM16Opnd:$dst, ptr_gpr16mm_rc:$base,
+                                mm_imm4_lsl1:$imm)>;
+  foreach Op = [SB, SB_MM] in
+    def : CompressPat<(Op GPRMM16OpndZero:$src, ptr_gpr16mm_rc:$base,
+                           mm_sb_imm4:$imm),
+                      (SB16_MM GPRMM16OpndZero:$src, ptr_gpr16mm_rc:$base,
+                               mm_sb_imm4:$imm)>;
+  foreach Op = [SH, SH_MM] in
+    def : CompressPat<(Op GPRMM16OpndZero:$src, ptr_gpr16mm_rc:$base,
+                           mm_imm4_lsl1:$imm),
+                      (SH16_MM GPRMM16OpndZero:$src, ptr_gpr16mm_rc:$base,
+                               mm_imm4_lsl1:$imm)>;
+  foreach Op = [LW, LW_MM] in
+    def : CompressPat<(Op GPR32Opnd:$reg, SPByHwMode, mm_imm5_lsl2:$imm),
+                      (LWSP_MM GPR32Opnd:$reg, SPByHwMode, mm_imm5_lsl2:$imm)>;
+  foreach Op = [SW, SW_MM] in
+    def : CompressPat<(Op GPR32Opnd:$reg, SPByHwMode, mm_imm5_lsl2:$imm),
+                      (SWSP_MM GPR32Opnd:$reg, SPByHwMode, mm_imm5_lsl2:$imm)>;
+}
diff --git a/llvm/lib/Target/Mips/MicroMipsSizeReduction.cpp b/llvm/lib/Target/Mips/MicroMipsSizeReduction.cpp
index 4633df5d1b6a5..4d3fa8da2c119 100644
--- a/llvm/lib/Target/Mips/MicroMipsSizeReduction.cpp
+++ b/llvm/lib/Target/Mips/MicroMipsSizeReduction.cpp
@@ -25,28 +25,20 @@ using namespace llvm;
 STATISTIC(NumReduced, "Number of instructions reduced (32-bit to 16-bit ones, "
                       "or two instructions into one");
 
+#define GEN_COMPRESS_MACHINE_INSTR
+#include "MipsGenCompressInstEmitter.inc"
+
 namespace {
 
 /// Order of operands to transfer
 // TODO: Will be extended when additional optimizations are added
 enum OperandTransfer {
   OT_NA,            ///< Not applicable
-  OT_OperandsAll,   ///< Transfer all operands
-  OT_Operands02,    ///< Transfer operands 0 and 2
-  OT_Operand2,      ///< Transfer just operand 2
-  OT_OperandsXOR,   ///< Transfer operands for XOR16
   OT_OperandsLwp,   ///< Transfer operands for LWP
   OT_OperandsSwp,   ///< Transfer operands for SWP
   OT_OperandsMovep, ///< Transfer operands for MOVEP
 };
 
-/// Reduction type
-// TODO: Will be extended when additional optimizations are added
-enum ReduceType {
-  RT_TwoInstr, ///< Reduce two instructions into one instruction
-  RT_OneInstr  ///< Reduce one instruction into a smaller instruction
-};
-
 // Information about immediate field restrictions
 struct ImmField {
   ImmField() : ImmFieldOperand(-1), Shift(0), LBound(0), HBound(0) {}
@@ -86,17 +78,15 @@ typedef struct ReduceEntryFunArgs ReduceEntryFunArgs;
 /// opcodes to narrow
 struct ReduceEntry {
 
-  enum ReduceType eRType; ///< Reduction type
   bool (*ReduceFunction)(
       ReduceEntryFunArgs *Arguments); ///< Pointer to reduce function
   struct OpCodes Ops;                 ///< All relevant OpCodes
   struct OpInfo OpInf;                ///< Characteristics of operands
   struct ImmField Imm;                ///< Characteristics of immediate field
 
-  ReduceEntry(enum ReduceType RType, struct OpCodes Op,
-              bool (*F)(ReduceEntryFunArgs *Arguments), struct OpInfo OpInf,
-              struct ImmField Imm)
-      : eRType(RType), ReduceFunction(F), Ops(Op), OpInf(OpInf), Imm(Imm) {}
+  ReduceEntry(struct OpCodes Op, bool (*F)(ReduceEntryFunArgs *Arguments),
+              struct OpInfo OpInf, struct ImmField Imm)
+      : ReduceFunction(F), Ops(Op), OpInf(OpInf), Imm(Imm) {}
 
   unsigned NarrowOpc() const { return Ops.NarrowOpc; }
   unsigned WideOpc() const { return Ops.WideOpc; }
@@ -107,7 +97,6 @@ struct ReduceEntry {
   enum OperandTransfer TransferOperands() const {
     return OpInf.TransferOperands;
   }
-  enum ReduceType RType() const { return eRType; }
 
   // operator used by std::equal_range
   bool operator<(const unsigned int r) const { return (WideOpc() < r); }
@@ -154,45 +143,15 @@ class MicroMipsSizeReduce : public MachineFunctionPass {
   bool ReduceMI(const MachineBasicBlock::instr_iterator &MII,
                 MachineBasicBlock::instr_iterator &NextMII);
 
-  // Attempts to reduce LW/SW instruction into LWSP/SWSP,
-  // returns true on success.
-  static bool ReduceXWtoXWSP(ReduceEntryFunArgs *Arguments);
-
   // Attempts to reduce two LW/SW instructions into LWP/SWP instruction,
   // returns true on success.
   static bool ReduceXWtoXWP(ReduceEntryFunArgs *Arguments);
 
-  // Attempts to reduce LBU/LHU instruction into LBU16/LHU16,
-  // returns true on success.
-  static bool ReduceLXUtoLXU16(ReduceEntryFunArgs *Arguments);
-
-  // Attempts to reduce SB/SH instruction into SB16/SH16,
-  // returns true on success.
-  static bool ReduceSXtoSX16(ReduceEntryFunArgs *Arguments);
-
   // Attempts to reduce two MOVE instructions into MOVEP instruction,
   // returns true on success.
   static bool ReduceMoveToMovep(ReduceEntryFunArgs *Arguments);
 
-  // Attempts to reduce arithmetic instructions, returns true on success.
-  static bool ReduceArithmeticInstructions(ReduceEntryFunArgs *Arguments);
-
-  // Attempts to reduce ADDIU into ADDIUSP instruction,
-  // returns true on success.
-  static bool ReduceADDIUToADDIUSP(ReduceEntryFunArgs *Arguments);
-
-  // Attempts to reduce ADDIU into ADDIUR1SP instruction,
-  // returns true on success.
-  static bool ReduceADDIUToADDIUR1SP(ReduceEntryFunArgs *Arguments);
-
-  // Attempts to reduce XOR into XOR16 instruction,
-  // returns true on success.
-  static bool ReduceXORtoXOR16(ReduceEntryFunArgs *Arguments);
-
-  // Changes opcode of an instruction, replaces an instruction with a
-  // new one, or replaces two instructions with a new instruction
-  // depending on their order i.e. if these are consecutive forward
-  // or consecutive backward
+  // Replace two instructions with a pair in encoding order.
   static bool ReplaceInstruction(MachineInstr *MI, const ReduceEntry &Entry,
                                  MachineInstr *MI2 = nullptr,
                                  bool ConsecutiveForward = true);
@@ -204,105 +163,31 @@ class MicroMipsSizeReduce : public MachineFunctionPass {
 char MicroMipsSizeReduce::ID = 0;
 const MipsInstrInfo *MicroMipsSizeReduce::MipsII;
 
-// This table must be sorted by WideOpc as a main criterion and
-// ReduceType as a sub-criterion (when wide opcodes are the same).
+// This table must be sorted by WideOpc.
 ReduceEntryVector MicroMipsSizeReduce::ReduceTable = {
-
-    // ReduceType, OpCodes, ReduceFunction,
+    // OpCodes, ReduceFunction,
     // OpInfo(TransferOperands),
     // ImmField(Shift, LBound, HBound, ImmFieldPosition)
-    {RT_OneInstr, OpCodes(Mips::ADDiu, Mips::ADDIUR1SP_MM),
-     ReduceADDIUToADDIUR1SP, OpInfo(OT_Operands02), ImmField(2, 0, 64, 2)},
-    {RT_OneInstr, OpCodes(Mips::ADDiu, Mips::ADDIUSP_MM), ReduceADDIUToADDIUSP,
-     OpInfo(OT_Operand2), ImmField(0, 0, 0, 2)},
-    {RT_OneInstr, OpCodes(Mips::ADDiu_MM, Mips::ADDIUR1SP_MM),
-     ReduceADDIUToADDIUR1SP, OpInfo(OT_Operands02), ImmField(2, 0, 64, 2)},
-    {RT_OneInstr, OpCodes(Mips::ADDiu_MM, Mips::ADDIUSP_MM),
-     ReduceADDIUToADDIUSP, OpInfo(OT_Operand2), ImmField(0, 0, 0, 2)},
-    {RT_OneInstr, OpCodes(Mips::ADDu, Mips::ADDU16_MM),
-     ReduceArithmeticInstructions, OpInfo(OT_OperandsAll),
-     ImmField(0, 0, 0, -1)},
-    {RT_OneInstr, OpCodes(Mips::ADDu_MM, Mips::ADDU16_MM),
-     ReduceArithmeticInstructions, OpInfo(OT_OperandsAll),
-     ImmField(0, 0, 0, -1)},
-    {RT_OneInstr, OpCodes(Mips::LBu, Mips::LBU16_MM), ReduceLXUtoLXU16,
-     OpInfo(OT_OperandsAll), ImmField(0, -1, 15, 2)},
-    {RT_OneInstr, OpCodes(Mips::LBu_MM, Mips::LBU16_MM), ReduceLXUtoLXU16,
-     OpInfo(OT_OperandsAll), ImmField(0, -1, 15, 2)},
-    {RT_OneInstr, OpCodes(Mips::LEA_ADDiu, Mips::ADDIUR1SP_MM),
-     ReduceADDIUToADDIUR1SP, OpInfo(OT_Operands02), ImmField(2, 0, 64, 2)},
-    {RT_OneInstr, OpCodes(Mips::LEA_ADDiu_MM, Mips::ADDIUR1SP_MM),
-     ReduceADDIUToADDIUR1SP, OpInfo(OT_Operands02), ImmField(2, 0, 64, 2)},
-    {RT_OneInstr, OpCodes(Mips::LHu, Mips::LHU16_MM), ReduceLXUtoLXU16,
-     OpInfo(OT_OperandsAll), ImmField(1, 0, 16, 2)},
-    {RT_OneInstr, OpCodes(Mips::LHu_MM, Mips::LHU16_MM), ReduceLXUtoLXU16,
-     OpInfo(OT_OperandsAll), ImmField(1, 0, 16, 2)},
-    {RT_TwoInstr, OpCodes(Mips::LW, Mips::LWP_MM), ReduceXWtoXWP,
-     OpInfo(OT_OperandsLwp), ImmField(0, -2048, 2048, 2)},
-    {RT_OneInstr, OpCodes(Mips::LW, Mips::LWSP_MM), ReduceXWtoXWSP,
-     OpInfo(OT_OperandsAll), ImmField(2, 0, 32, 2)},
-    {RT_TwoInstr, OpCodes(Mips::LW16_MM, Mips::LWP_MM), ReduceXWtoXWP,
-     OpInfo(OT_OperandsLwp), ImmField(0, -2048, 2048, 2)},
-    {RT_TwoInstr, OpCodes(Mips::LW_MM, Mips::LWP_MM), ReduceXWtoXWP,
+    {OpCodes(Mips::LW, Mips::LWP_MM), ReduceXWtoXWP, OpInfo(OT_OperandsLwp),
+     ImmField(0, -2048, 2048, 2)},
+    {OpCodes(Mips::LW16_MM, Mips::LWP_MM), ReduceXWtoXWP,
      OpInfo(OT_OperandsLwp), ImmField(0, -2048, 2048, 2)},
-    {RT_OneInstr, OpCodes(Mips::LW_MM, Mips::LWSP_MM), ReduceXWtoXWSP,
-     OpInfo(OT_OperandsAll), ImmField(2, 0, 32, 2)},
-    {RT_TwoInstr, OpCodes(Mips::MOVE16_MM, Mips::MOVEP_MM), ReduceMoveToMovep,
+    {OpCodes(Mips::LW_MM, Mips::LWP_MM), ReduceXWtoXWP, OpInfo(OT_OperandsLwp),
+     ImmField(0, -2048, 2048, 2)},
+    {OpCodes(Mips::MOVE16_MM, Mips::MOVEP_MM), ReduceMoveToMovep,
      OpInfo(OT_OperandsMovep), ImmField(0, 0, 0, -1)},
-    {RT_OneInstr, OpCodes(Mips::SB, Mips::SB16_MM), ReduceSXtoSX16,
-     OpInfo(OT_OperandsAll), ImmField(0, 0, 16, 2)},
-    {RT_OneInstr, OpCodes(Mips::SB_MM, Mips::SB16_MM), ReduceSXtoSX16,
-     OpInfo(OT_OperandsAll), ImmField(0, 0, 16, 2)},
-    {RT_OneInstr, OpCodes(Mips::SH, Mips::SH16_MM), ReduceSXtoSX16,
-     OpInfo(OT_OperandsAll), ImmField(1, 0, 16, 2)},
-    {RT_OneInstr, OpCodes(Mips::SH_MM, Mips::SH16_MM), ReduceSXtoSX16,
-     OpInfo(OT_OperandsAll), ImmField(1, 0, 16, 2)},
-    {RT_OneInstr, OpCodes(Mips::SUBu, Mips::SUBU16_MM),
-     ReduceArithmeticInstructions, OpInfo(OT_OperandsAll),
-     ImmField(0, 0, 0, -1)},
-    {RT_OneInstr, OpCodes(Mips::SUBu_MM, Mips::SUBU16_MM),
-     ReduceArithmeticInstructions, OpInfo(OT_OperandsAll),
-     ImmField(0, 0, 0, -1)},
-    {RT_TwoInstr, OpCodes(Mips::SW, Mips::SWP_MM), ReduceXWtoXWP,
+    {OpCodes(Mips::SW, Mips::SWP_MM), ReduceXWtoXWP, OpInfo(OT_OperandsSwp),
+     ImmField(0, -2048, 2048, 2)},
+    {OpCodes(Mips::SW16_MM, Mips::SWP_MM), ReduceXWtoXWP,
      OpInfo(OT_OperandsSwp), ImmField(0, -2048, 2048, 2)},
-    {RT_OneInstr, OpCodes(Mips::SW, Mips::SWSP_MM), ReduceXWtoXWSP,
-     OpInfo(OT_OperandsAll), ImmField(2, 0, 32, 2)},
-    {RT_TwoInstr, OpCodes(Mips::SW16_MM, Mips::SWP_MM), ReduceXWtoXWP,
-     OpInfo(OT_OperandsSwp), ImmField(0, -2048, 2048, 2)},
-    {RT_TwoInstr, OpCodes(Mips::SW_MM, Mips::SWP_MM), ReduceXWtoXWP,
-     OpInfo(OT_OperandsSwp), ImmField(0, -2048, 2048, 2)},
-    {RT_OneInstr, OpCodes(Mips::SW_MM, Mips::SWSP_MM), ReduceXWtoXWSP,
-     OpInfo(OT_OperandsAll), ImmField(2, 0, 32, 2)},
-    {RT_OneInstr, OpCodes(Mips::XOR, Mips::XOR16_MM), ReduceXORtoXOR16,
-     OpInfo(OT_OperandsXOR), ImmField(0, 0, 0, -1)},
-    {RT_OneInstr, OpCodes(Mips::XOR_MM, Mips::XOR16_MM), ReduceXORtoXOR16,
-     OpInfo(OT_OperandsXOR), ImmField(0, 0, 0, -1)}};
+    {OpCodes(Mips::SW_MM, Mips::SWP_MM), ReduceXWtoXWP, OpInfo(OT_OperandsSwp),
+     ImmField(0, -2048, 2048, 2)},
+};
 } // end anonymous namespace
 
 INITIALIZE_PASS(MicroMipsSizeReduce, DEBUG_TYPE, MICROMIPS_SIZE_REDUCE_NAME,
                 false, false)
 
-// Returns true if the machine operand MO is register SP.
-static bool IsSP(const MachineOperand &MO) {
-  if (MO.isReg() && ((MO.getReg() == Mips::SP)))
-    return true;
-  return false;
-}
-
-// Returns true if the machine operand MO is register $16, $17, or $2-$7.
-static bool isMMThreeBitGPRegister(const MachineOperand &MO) {
-  if (MO.isReg() && Mips::GPRMM16RegClass.contains(MO.getReg()))
-    return true;
-  return false;
-}
-
-// Returns true if the machine operand MO is register $0, $17, or $2-$7.
-static bool isMMSourceRegister(const MachineOperand &MO) {
-  if (MO.isReg() && Mips::GPRMM16ZeroRegClass.contains(MO.getReg()))
-    return true;
-  return false;
-}
-
 // Returns true if the operand Op is an immediate value
 // and writes the immediate value into variable Imm.
 static bool GetImm(MachineInstr *MI, unsigned Op, int64_t &Imm) {
@@ -313,15 +198,6 @@ static bool GetImm(MachineInstr *MI, unsigned Op, int64_t &Imm) {
   return true;
 }
 
-// Returns true if the value is a valid immediate for ADDIUSP.
-static bool AddiuspImmValue(int64_t Value) {
-  int64_t Value2 = Value >> 2;
-  if (((Value & (int64_t)maskTrailingZeros<uint64_t>(2)) == Value) &&
-      ((Value2 >= 2 && Value2 <= 257) || (Value2 >= -258 && Value2 <= -3)))
-    return true;
-  return false;
-}
-
 // Returns true if the variable Value has the number of least-significant zero
 // bits equal to Shift and if the shifted value is between the bounds.
 static bool InRange(int64_t Value, unsigned short Shift, int LBound,
@@ -425,32 +301,21 @@ bool MicroMipsSizeReduce::ReduceMI(const MachineBasicBlock::instr_iterator &MII,
             ReduceEntryVector::const_iterator>
       Range = std::equal_range(Start, End, Opcode);
 
-  if (Range.first == Range.second)
-    return false;
-
   for (ReduceEntryVector::const_iterator Entry = Range.first;
        Entry != Range.second; ++Entry) {
     ReduceEntryFunArgs Arguments(&(*MII), *Entry, NextMII);
     if (((*Entry).ReduceFunction)(&Arguments))
       return true;
   }
+  if (!MI->isBundled() && !MI->hasDelaySlot() &&
+      compressInst(*MI, *Subtarget)) {
+    ++NumReduced;
+    LLVM_DEBUG(dbgs() << "Reduced to: " << *MI);
+    return true;
+  }
   return false;
 }
 
-bool MicroMipsSizeReduce::ReduceXWtoXWSP(ReduceEntryFunArgs *Arguments) {
-
-  MachineInstr *MI = Arguments->MI;
-  const ReduceEntry &Entry = Arguments->Entry;
-
-  if (!ImmInRange(MI, Entry))
-    return false;
-
-  if (!IsSP(MI->getOperand(1)))
-    return false;
-
-  return ReplaceInstruction(MI, Entry);
-}
-
 bool MicroMipsSizeReduce::ReduceXWtoXWP(ReduceEntryFunArgs *Arguments) {
 
   const ReduceEntry &Entry = Arguments->Entry;
@@ -491,83 +356,6 @@ bool MicroMipsSizeReduce::ReduceXWtoXWP(ReduceEntryFunArgs *Arguments) {
   return ReplaceInstruction(MI1, Entry, MI2, ConsecutiveForward);
 }
 
-bool MicroMipsSizeReduce::ReduceArithmeticInstructions(
-    ReduceEntryFunArgs *Arguments) {
-
-  MachineInstr *MI = Arguments->MI;
-  const ReduceEntry &Entry = Arguments->Entry;
-
-  if (!isMMThreeBitGPRegister(MI->getOperand(0)) ||
-      !isMMThreeBitGPRegister(MI->getOperand(1)) ||
-      !isMMThreeBitGPRegister(MI->getOperand(2)))
-    return false;
-
-  return ReplaceInstruction(MI, Entry);
-}
-
-bool MicroMipsSizeReduce::ReduceADDIUToADDIUR1SP(
-    ReduceEntryFunArgs *Arguments) {
-
-  MachineInstr *MI = Arguments->MI;
-  const ReduceEntry &Entry = Arguments->Entry;
-
-  if (!ImmInRange(MI, Entry))
-    return false;
-
-  if (!isMMThreeBitGPRegister(MI->getOperand(0)) || !IsSP(MI->getOperand(1)))
-    return false;
-
-  return ReplaceInstruction(MI, Entry);
-}
-
-bool MicroMipsSizeReduce::ReduceADDIUToADDIUSP(ReduceEntryFunArgs *Arguments) {
-
-  MachineInstr *MI = Arguments->MI;
-  const ReduceEntry &Entry = Arguments->Entry;
-
-  int64_t ImmValue;
-  if (!GetImm(MI, Entry.ImmField(), ImmValue))
-    return false;
-
-  if (!AddiuspImmValue(ImmValue))
-    return false;
-
-  if (!IsSP(MI->getOperand(0)) || !IsSP(MI->getOperand(1)))
-    return false;
-
-  return ReplaceInstruction(MI, Entry);
-}
-
-bool MicroMipsSizeReduce::ReduceLXUtoLXU16(ReduceEntryFunArgs *Arguments) {
-
-  MachineInstr *MI = Arguments->MI;
-  const ReduceEntry &Entry = Arguments->Entry;
-
-  if (!ImmInRange(MI, Entry))
-    return false;
-
-  if (!isMMThreeBitGPRegister(MI->getOperand(0)) ||
-      !isMMThreeBitGPRegister(MI->getOperand(1)))
-    return false;
-
-  return ReplaceInstruction(MI, Entry);
-}
-
-bool MicroMipsSizeReduce::ReduceSXtoSX16(ReduceEntryFunArgs *Arguments) {
-
-  MachineInstr *MI = Arguments->MI;
-  const ReduceEntry &Entry = Arguments->Entry;
-
-  if (!ImmInRange(MI, Entry))
-    return false;
-
-  if (!isMMSourceRegister(MI->getOperand(0)) ||
-      !isMMThreeBitGPRegister(MI->getOperand(1)))
-    return false;
-
-  return ReplaceInstruction(MI, Entry);
-}
-
 // Returns true if Reg can be a source register
 // of MOVEP instruction
 static bool IsMovepSrcRegister(unsigned Reg) {
@@ -651,23 +439,6 @@ bool MicroMipsSizeReduce::ReduceMoveToMovep(ReduceEntryFunArgs *Arguments) {
   return ReplaceInstruction(MI1, Entry, MI2, ConsecutiveForward);
 }
 
-bool MicroMipsSizeReduce::ReduceXORtoXOR16(ReduceEntryFunArgs *Arguments) {
-
-  MachineInstr *MI = Arguments->MI;
-  const ReduceEntry &Entry = Arguments->Entry;
-
-  if (!isMMThreeBitGPRegister(MI->getOperand(0)) ||
-      !isMMThreeBitGPRegister(MI->getOperand(1)) ||
-      !isMMThreeBitGPRegister(MI->getOperand(2)))
-    return false;
-
-  if (!(MI->getOperand(0).getReg() == MI->getOperand(2).getReg()) &&
-      !(MI->getOperand(0).getReg() == MI->getOperand(1).getReg()))
-    return false;
-
-  return ReplaceInstruction(MI, Entry);
-}
-
 bool MicroMipsSizeReduce::ReduceMBB(MachineBasicBlock &MBB) {
   bool Modified = false;
   MachineBasicBlock::instr_iterator MII = MBB.instr_begin(),
@@ -700,76 +471,42 @@ bool MicroMipsSizeReduce::ReplaceInstruction(MachineInstr *MI,
   LLVM_DEBUG(dbgs() << "Converting 32-bit: " << *MI);
   ++NumReduced;
 
-  if (OpTransfer == OT_OperandsAll) {
-    MI->setDesc(MipsII->get(Entry.NarrowOpc()));
-    LLVM_DEBUG(dbgs() << "       to 16-bit: " << *MI);
-    return true;
-  } else {
-    MachineBasicBlock &MBB = *MI->getParent();
-    const MCInstrDesc &NewMCID = MipsII->get(Entry.NarrowOpc());
-    DebugLoc dl = MI->getDebugLoc();
-    MachineInstrBuilder MIB = BuildMI(MBB, MI, dl, NewMCID);
-    switch (OpTransfer) {
-    case OT_Operand2:
-      MIB.add(MI->getOperand(2));
-      break;
-    case OT_Operands02: {
+  MachineBasicBlock &MBB = *MI->getParent();
+  const MCInstrDesc &NewMCID = MipsII->get(Entry.NarrowOpc());
+  DebugLoc dl = MI->getDebugLoc();
+  MachineInstrBuilder MIB = BuildMI(MBB, MI, dl, NewMCID);
+  switch (OpTransfer) {
+  case OT_OperandsMovep:
+  case OT_OperandsLwp:
+  case OT_OperandsSwp: {
+    if (ConsecutiveForward) {
       MIB.add(MI->getOperand(0));
-      MIB.add(MI->getOperand(2));
-      break;
-    }
-    case OT_OperandsXOR: {
-      if (MI->getOperand(0).getReg() == MI->getOperand(2).getReg()) {
-        MIB.add(MI->getOperand(0));
-        MIB.add(MI->getOperand(1));
-        MIB.add(MI->getOperand(2));
-      } else {
-        MIB.add(MI->getOperand(0));
+      MIB.add(MI2->getOperand(0));
+      MIB.add(MI->getOperand(1));
+      if (OpTransfer == OT_OperandsMovep)
+        MIB.add(MI2->getOperand(1));
+      else
         MIB.add(MI->getOperand(2));
+    } else { // consecutive backward
+      MIB.add(MI2->getOperand(0));
+      MIB.add(MI->getOperand(0));
+      MIB.add(MI2->getOperand(1));
+      if (OpTransfer == OT_OperandsMovep)
         MIB.add(MI->getOperand(1));
-      }
-      break;
-    }
-    case OT_OperandsMovep:
-    case OT_OperandsLwp:
-    case OT_OperandsSwp: {
-      if (ConsecutiveForward) {
-        MIB.add(MI->getOperand(0));
-        MIB.add(MI2->getOperand(0));
-        MIB.add(MI->getOperand(1));
-        if (OpTransfer == OT_OperandsMovep)
-          MIB.add(MI2->getOperand(1));
-        else
-          MIB.add(MI->getOperand(2));
-      } else { // consecutive backward
-        MIB.add(MI2->getOperand(0));
-        MIB.add(MI->getOperand(0));
-        MIB.add(MI2->getOperand(1));
-        if (OpTransfer == OT_OperandsMovep)
-          MIB.add(MI->getOperand(1));
-        else
-          MIB.add(MI2->getOperand(2));
-      }
-
-      LLVM_DEBUG(dbgs() << "and converting 32-bit: " << *MI2
-                        << "       to: " << *MIB);
-
-      MBB.erase_instr(MI);
-      MBB.erase_instr(MI2);
-      return true;
-    }
-    default:
-      llvm_unreachable("Unknown operand transfer!");
+      else
+        MIB.add(MI2->getOperand(2));
     }
 
-    // Transfer MI flags.
-    MIB.setMIFlags(MI->getFlags());
+    LLVM_DEBUG(dbgs() << "and converting 32-bit: " << *MI2
+                      << "       to: " << *MIB);
 
-    LLVM_DEBUG(dbgs() << "       to 16-bit: " << *MIB);
     MBB.erase_instr(MI);
+    MBB.erase_instr(MI2);
     return true;
   }
-  return false;
+  default:
+    llvm_unreachable("Unknown operand transfer!");
+  }
 }
 
 bool MicroMipsSizeReduce::runOnMachineFunction(MachineFunction &MF) {
diff --git a/llvm/lib/Target/Mips/MipsRegisterInfo.td b/llvm/lib/Target/Mips/MipsRegisterInfo.td
index 765179a43980d..84a2d1edcbb87 100644
--- a/llvm/lib/Target/Mips/MipsRegisterInfo.td
+++ b/llvm/lib/Target/Mips/MipsRegisterInfo.td
@@ -772,6 +772,9 @@ def ptr_sp_rc : RegClassByHwMode<
   [MIPS32, MIPS64],
   [SP32, SP64]>;
 
+def SPByHwMode : RegisterByHwMode<ptr_sp_rc,
+    [MIPS32, MIPS64], [SP, SP_64]>;
+
 def ptr_gp_rc : RegClassByHwMode<
   [MIPS32, MIPS64],
   [GP32, GP64]>;
diff --git a/llvm/test/CodeGen/Mips/micromips-sizereduction/branch-size.mir b/llvm/test/CodeGen/Mips/micromips-sizereduction/branch-size.mir
new file mode 100644
index 0000000000000..4f231d17ca6a5
--- /dev/null
+++ b/llvm/test/CodeGen/Mips/micromips-sizereduction/branch-size.mir
@@ -0,0 +1,46 @@
+# RUN: llc -mtriple=mipsel -mcpu=mips32r2 -mattr=+micromips \
+# RUN:   -run-pass=micromips-reduce-size,mips-branch-expansion -verify-machineinstrs %s -o - | FileCheck %s
+
+# Branch expansion sees the compressed MIR instruction sizes directly.
+# A register that prevents ADDu compression pushes the branch out of range.
+---
+name: compressed
+tracksRegLiveness: false
+body: |
+  bb.0:
+    successors: %bb.1, %bb.2
+    ; CHECK-LABEL: name: compressed
+    ; CHECK: BEQ_MM $a0, $zero, %bb.2
+    BEQ_MM $a0, $zero, %bb.2, implicit-def $at {
+      $zero = SLL $zero, 0
+    }
+  bb.1:
+    successors: %bb.2
+    INLINEASM &".space 65528", sideeffect attdialect
+    $v0 = ADDu $a0, $a1
+  bb.2:
+    PseudoReturn $ra {
+      $zero = SLL $zero, 0
+    }
+...
+---
+name: uncompressed
+tracksRegLiveness: false
+body: |
+  bb.0:
+    successors: %bb.1, %bb.2
+    ; CHECK-LABEL: name: uncompressed
+    ; CHECK: BNE_MM $a0, $zero,
+    ; CHECK: J %bb.
+    BEQ_MM $a0, $zero, %bb.2, implicit-def $at {
+      $zero = SLL $zero, 0
+    }
+  bb.1:
+    successors: %bb.2
+    INLINEASM &".space 65528", sideeffect attdialect
+    $t0 = ADDu $a0, $a1
+  bb.2:
+    PseudoReturn $ra {
+      $zero = SLL $zero, 0
+    }
+...
diff --git a/llvm/test/CodeGen/Mips/micromips-sizereduction/compress-metadata.mir b/llvm/test/CodeGen/Mips/micromips-sizereduction/compress-metadata.mir
new file mode 100644
index 0000000000000..4b64de0cf232b
--- /dev/null
+++ b/llvm/test/CodeGen/Mips/micromips-sizereduction/compress-metadata.mir
@@ -0,0 +1,48 @@
+# RUN: llc -mtriple=mipsel -mcpu=mips32r2 -mattr=+micromips \
+# RUN:   -run-pass=micromips-reduce-size -verify-machineinstrs %s -o - | FileCheck %s
+# RUN: llc -mtriple=mipsel -mcpu=mips32r2 -mattr=+micromips \
+# RUN:   -run-pass=micromips-reduce-size,mips-delay-slot-filler \
+# RUN:   -verify-machineinstrs %s -o - | FileCheck %s --check-prefix=SLOT
+
+--- |
+  declare void @callee()
+  define void @metadata() { ret void }
+  define void @call_slot() { ret void }
+...
+---
+name: metadata
+# CHECK-LABEL: name: metadata
+# CHECK: debugValueSubstitutions:
+# CHECK-NEXT: { srcinst: 1, srcop: 0, dstinst: 3, dstop: 1, subreg: 0 }
+# CHECK-NEXT: { srcinst: 2, srcop: 0, dstinst: 4, dstop: 0, subreg: 0 }
+tracksRegLiveness: false
+body: |
+  bb.0:
+    ; CHECK: ADDIUSP_MM -16, implicit-def $sp, implicit killed $sp, debug-instr-number 3
+    $sp = ADDiu killed $sp, -16, debug-instr-number 1
+    ; CHECK: dead $v0 = frame-setup ADDIUR1SP_MM 20, implicit killed $sp, debug-instr-number 4
+    dead $v0 = frame-setup ADDiu killed $sp, 20, debug-instr-number 2
+    ; CHECK: dead renamable $v0 = XOR16_MM killed renamable $a0, killed renamable $v0
+    dead renamable $v0 = XOR killed renamable $v0, killed renamable $a0
+    ; CHECK: dead $v0 = XOR16_MM undef $a0, killed $v0
+    dead $v0 = XOR undef $a0, killed $v0
+    ; CHECK: $v0 = ADDU16_MM $a0, $a1, csr_o32, implicit $a3
+    $v0 = ADDu $a0, $a1, csr_o32, implicit $a3
+    ; CHECK: dead $v0 = LWSP_MM killed $sp, 20, implicit $a3 :: (volatile load (s32), align 8)
+    dead $v0 = LW killed $sp, 20, implicit $a3 :: (volatile load (s32) from unknown-address, align 8)
+...
+---
+name: call_slot
+tracksRegLiveness: false
+body: |
+  bb.0:
+    ; CHECK-LABEL: name: call_slot
+    ; CHECK: $v0 = ADDU16_MM $a0, $a1
+    ; CHECK-NEXT: JAL_MM @callee
+    ; SLOT-LABEL: name: call_slot
+    ; SLOT: JALS_MM @callee{{.*}} {
+    ; SLOT-NEXT: $v0 = ADDU16_MM $a0, $a1
+    ; SLOT-NEXT: }
+    $v0 = ADDu $a0, $a1
+    JAL_MM @callee, csr_o32, implicit-def $ra, implicit $v0
+...
diff --git a/llvm/test/CodeGen/Mips/micromips-sizereduction/compress-pat.mir b/llvm/test/CodeGen/Mips/micromips-sizereduction/compress-pat.mir
new file mode 100644
index 0000000000000..63c5716663a67
--- /dev/null
+++ b/llvm/test/CodeGen/Mips/micromips-sizereduction/compress-pat.mir
@@ -0,0 +1,273 @@
+# RUN: llc -mtriple=mipsel -mcpu=mips32r2 -mattr=+micromips \
+# RUN:   -run-pass=micromips-reduce-size -verify-machineinstrs %s -o %t.mir
+# RUN: llc -mtriple=mipsel -mcpu=mips32r2 -mattr=+micromips \
+# RUN:   -start-after=mips-branch-expansion -asm-show-inst -verify-machineinstrs %t.mir -o - | FileCheck %s
+# RUN: llc -mtriple=mipsel -mcpu=mips32r6 -mattr=+micromips \
+# RUN:   -run-pass=micromips-reduce-size -verify-machineinstrs %s -o %t-r6.mir
+# RUN: llc -mtriple=mipsel -mcpu=mips32r6 -mattr=+micromips \
+# RUN:   -start-after=mips-branch-expansion -asm-show-inst -verify-machineinstrs %t-r6.mir -o - | FileCheck %s --check-prefix=UNCHANGED
+# RUN: llc -mtriple=mipsel -mcpu=mips32r2 -mattr=-micromips \
+# RUN:   -run-pass=micromips-reduce-size -verify-machineinstrs %s -o %t-nomicro.mir
+# RUN: llc -mtriple=mipsel -mcpu=mips32r2 -mattr=-micromips \
+# RUN:   -start-after=mips-branch-expansion -asm-show-inst -verify-machineinstrs %t-nomicro.mir -o - | FileCheck %s --check-prefix=UNCHANGED
+
+# Exercise both opcode families, immediate boundaries, register restrictions,
+# commuted XOR operands, instruction flags, and the subtarget gate.
+
+---
+name: arithmetic
+tracksRegLiveness: false
+body: |
+  bb.0:
+    ; CHECK-LABEL: arithmetic:
+    ; UNCHANGED-LABEL: arithmetic:
+    ; CHECK: <MCInst #{{[0-9]+}} ADDU16_MM{{$}}
+    ; UNCHANGED: <MCInst #{{[0-9]+}} ADDu{{$}}
+    $v0 = ADDu $s0, $s1
+    ; CHECK: <MCInst #{{[0-9]+}} ADDU16_MM{{$}}
+    ; UNCHANGED: <MCInst #{{[0-9]+}} ADDu_MM{{$}}
+    $v0 = ADDu_MM $a0, $a1
+    ; CHECK: <MCInst #{{[0-9]+}} SUBU16_MM{{$}}
+    ; UNCHANGED: <MCInst #{{[0-9]+}} SUBu{{$}}
+    $v0 = SUBu $a0, $a1
+    ; CHECK: <MCInst #{{[0-9]+}} SUBU16_MM{{$}}
+    ; UNCHANGED: <MCInst #{{[0-9]+}} SUBu_MM{{$}}
+    $v0 = SUBu_MM $a0, $a1
+    ; CHECK: <MCInst #{{[0-9]+}} ADDu{{$}}
+    ; UNCHANGED: <MCInst #{{[0-9]+}} ADDu{{$}}
+    $t0 = ADDu $a0, $a1
+    ; CHECK: <MCInst #{{[0-9]+}} ADDu{{$}}
+    ; UNCHANGED: <MCInst #{{[0-9]+}} ADDu{{$}}
+    $v0 = ADDu $t0, $a1
+    ; CHECK: <MCInst #{{[0-9]+}} SUBu{{$}}
+    ; UNCHANGED: <MCInst #{{[0-9]+}} SUBu{{$}}
+    $v0 = SUBu $a0, $t0
+    ; CHECK: <MCInst #{{[0-9]+}} XOR16_MM{{$}}
+    ; CHECK-NEXT: # <MCOperand Reg:V0>
+    ; CHECK-NEXT: # <MCOperand Reg:A0>
+    ; CHECK-NEXT: # <MCOperand Reg:V0>
+    ; UNCHANGED: <MCInst #{{[0-9]+}} XOR{{$}}
+    $v0 = XOR $a0, $v0
+    ; CHECK: <MCInst #{{[0-9]+}} XOR16_MM{{$}}
+    ; CHECK-NEXT: # <MCOperand Reg:V0>
+    ; CHECK-NEXT: # <MCOperand Reg:A0>
+    ; CHECK-NEXT: # <MCOperand Reg:V0>
+    ; UNCHANGED: <MCInst #{{[0-9]+}} XOR_MM{{$}}
+    $v0 = XOR_MM $v0, $a0
+    ; CHECK: <MCInst #{{[0-9]+}} XOR16_MM{{$}}
+    ; CHECK-NEXT: # <MCOperand Reg:V0>
+    ; CHECK-NEXT: # <MCOperand Reg:A0>
+    ; CHECK-NEXT: # <MCOperand Reg:V0>
+    ; UNCHANGED: <MCInst #{{[0-9]+}} XOR{{$}}
+    dead $v0 = XOR killed $v0, killed $a0
+    ; CHECK: <MCInst #{{[0-9]+}} XOR{{$}}
+    ; UNCHANGED: <MCInst #{{[0-9]+}} XOR{{$}}
+    $v0 = XOR $a0, $a1
+    ; CHECK: <MCInst #{{[0-9]+}} XOR{{$}}
+    ; UNCHANGED: <MCInst #{{[0-9]+}} XOR{{$}}
+    $v0 = XOR $v0, $t0
+...
+
+---
+name: stack_arithmetic
+tracksRegLiveness: false
+body: |
+  bb.0:
+    ; CHECK-LABEL: stack_arithmetic:
+    ; UNCHANGED-LABEL: stack_arithmetic:
+    ; CHECK: <MCInst #{{[0-9]+}} ADDIUR1SP_MM{{$}}
+    ; CHECK-NEXT: # <MCOperand Reg:V0>
+    ; CHECK-NEXT: # <MCOperand Imm:0>
+    ; UNCHANGED: <MCInst #{{[0-9]+}} ADDiu{{$}}
+    $v0 = ADDiu $sp, 0
+    ; CHECK: <MCInst #{{[0-9]+}} ADDIUR1SP_MM{{$}}
+    ; CHECK-NEXT: # <MCOperand Reg:S0>
+    ; CHECK-NEXT: # <MCOperand Imm:252>
+    ; UNCHANGED: <MCInst #{{[0-9]+}} ADDiu_MM{{$}}
+    $s0 = ADDiu_MM $sp, 252
+    ; CHECK: <MCInst #{{[0-9]+}} ADDIUR1SP_MM{{$}}
+    ; CHECK-NEXT: # <MCOperand Reg:A0>
+    ; CHECK-NEXT: # <MCOperand Imm:4>
+    ; UNCHANGED: <MCInst #{{[0-9]+}} LEA_ADDiu{{$}}
+    $a0 = LEA_ADDiu $sp, 4
+    ; CHECK: <MCInst #{{[0-9]+}} ADDIUR1SP_MM{{$}}
+    ; CHECK-NEXT: # <MCOperand Reg:A1>
+    ; CHECK-NEXT: # <MCOperand Imm:8>
+    ; UNCHANGED: <MCInst #{{[0-9]+}} LEA_ADDiu_MM{{$}}
+    $a1 = LEA_ADDiu_MM $sp, 8
+    ; CHECK: <MCInst #{{[0-9]+}} ADDiu{{$}}
+    ; UNCHANGED: <MCInst #{{[0-9]+}} ADDiu{{$}}
+    $v0 = ADDiu $sp, -4
+    ; CHECK: <MCInst #{{[0-9]+}} ADDiu{{$}}
+    ; UNCHANGED: <MCInst #{{[0-9]+}} ADDiu{{$}}
+    $v0 = ADDiu $sp, 256
+    ; CHECK: <MCInst #{{[0-9]+}} ADDiu{{$}}
+    ; UNCHANGED: <MCInst #{{[0-9]+}} ADDiu{{$}}
+    $v0 = ADDiu $sp, 2
+    ; CHECK: <MCInst #{{[0-9]+}} ADDiu{{$}}
+    ; UNCHANGED: <MCInst #{{[0-9]+}} ADDiu{{$}}
+    $t0 = ADDiu $sp, 4
+    ; CHECK: <MCInst #{{[0-9]+}} ADDiu{{$}}
+    ; UNCHANGED: <MCInst #{{[0-9]+}} ADDiu{{$}}
+    $v0 = ADDiu $a0, 4
+    ; CHECK: <MCInst #{{[0-9]+}} ADDIUSP_MM{{$}}
+    ; CHECK-NEXT: # <MCOperand Imm:-1032>
+    ; UNCHANGED: <MCInst #{{[0-9]+}} ADDiu{{$}}
+    $sp = frame-setup ADDiu $sp, -1032
+    ; CHECK: <MCInst #{{[0-9]+}} ADDIUSP_MM{{$}}
+    ; CHECK-NEXT: # <MCOperand Imm:-12>
+    ; UNCHANGED: <MCInst #{{[0-9]+}} ADDiu_MM{{$}}
+    $sp = ADDiu_MM $sp, -12
+    ; CHECK: <MCInst #{{[0-9]+}} ADDIUSP_MM{{$}}
+    ; CHECK-NEXT: # <MCOperand Imm:8>
+    ; UNCHANGED: <MCInst #{{[0-9]+}} ADDiu{{$}}
+    $sp = ADDiu $sp, 8
+    ; CHECK: <MCInst #{{[0-9]+}} ADDIUSP_MM{{$}}
+    ; CHECK-NEXT: # <MCOperand Imm:1028>
+    ; UNCHANGED: <MCInst #{{[0-9]+}} ADDiu{{$}}
+    $sp = frame-destroy ADDiu $sp, 1028
+    ; CHECK: <MCInst #{{[0-9]+}} ADDiu{{$}}
+    ; UNCHANGED: <MCInst #{{[0-9]+}} ADDiu{{$}}
+    $sp = ADDiu $sp, -1036
+    ; CHECK: <MCInst #{{[0-9]+}} ADDiu{{$}}
+    ; UNCHANGED: <MCInst #{{[0-9]+}} ADDiu{{$}}
+    $sp = ADDiu $sp, -8
+    ; CHECK: <MCInst #{{[0-9]+}} ADDiu{{$}}
+    ; UNCHANGED: <MCInst #{{[0-9]+}} ADDiu{{$}}
+    $sp = ADDiu $sp, 4
+    ; CHECK: <MCInst #{{[0-9]+}} ADDiu{{$}}
+    ; UNCHANGED: <MCInst #{{[0-9]+}} ADDiu{{$}}
+    $sp = ADDiu $sp, 1032
+    ; CHECK: <MCInst #{{[0-9]+}} ADDiu{{$}}
+    ; UNCHANGED: <MCInst #{{[0-9]+}} ADDiu{{$}}
+    $sp = ADDiu $sp, 9
+...
+
+---
+name: loads
+tracksRegLiveness: false
+body: |
+  bb.0:
+    ; CHECK-LABEL: loads:
+    ; UNCHANGED-LABEL: loads:
+    ; CHECK: <MCInst #{{[0-9]+}} LBU16_MM{{$}}
+    ; UNCHANGED: <MCInst #{{[0-9]+}} LBu{{$}}
+    $v0 = LBu $a0, -1
+    ; CHECK: <MCInst #{{[0-9]+}} LBU16_MM{{$}}
+    ; UNCHANGED: <MCInst #{{[0-9]+}} LBu_MM{{$}}
+    $s0 = LBu_MM $s1, 14
+    ; CHECK: <MCInst #{{[0-9]+}} LBu{{$}}
+    ; UNCHANGED: <MCInst #{{[0-9]+}} LBu{{$}}
+    $v0 = LBu $a0, -2
+    ; CHECK: <MCInst #{{[0-9]+}} LBu{{$}}
+    ; UNCHANGED: <MCInst #{{[0-9]+}} LBu{{$}}
+    $v0 = LBu $a0, 15
+    ; CHECK: <MCInst #{{[0-9]+}} LBu{{$}}
+    ; UNCHANGED: <MCInst #{{[0-9]+}} LBu{{$}}
+    $t0 = LBu $a0, 0
+    ; CHECK: <MCInst #{{[0-9]+}} LBu{{$}}
+    ; UNCHANGED: <MCInst #{{[0-9]+}} LBu{{$}}
+    $v0 = LBu $t0, 0
+    ; CHECK: <MCInst #{{[0-9]+}} LHU16_MM{{$}}
+    ; UNCHANGED: <MCInst #{{[0-9]+}} LHu{{$}}
+    $v0 = LHu $a0, 0
+    ; CHECK: <MCInst #{{[0-9]+}} LHU16_MM{{$}}
+    ; UNCHANGED: <MCInst #{{[0-9]+}} LHu_MM{{$}}
+    $v0 = LHu_MM $a0, 30
+    ; CHECK: <MCInst #{{[0-9]+}} LHu{{$}}
+    ; UNCHANGED: <MCInst #{{[0-9]+}} LHu{{$}}
+    $v0 = LHu $a0, -2
+    ; CHECK: <MCInst #{{[0-9]+}} LHu{{$}}
+    ; UNCHANGED: <MCInst #{{[0-9]+}} LHu{{$}}
+    $v0 = LHu $a0, 32
+    ; CHECK: <MCInst #{{[0-9]+}} LHu{{$}}
+    ; UNCHANGED: <MCInst #{{[0-9]+}} LHu{{$}}
+    $v0 = LHu $a0, 1
+...
+
+---
+name: stores
+tracksRegLiveness: false
+body: |
+  bb.0:
+    ; CHECK-LABEL: stores:
+    ; UNCHANGED-LABEL: stores:
+    ; CHECK: <MCInst #{{[0-9]+}} SB16_MM{{$}}
+    ; UNCHANGED: <MCInst #{{[0-9]+}} SB{{$}}
+    SB $zero, $a0, 0
+    ; CHECK: <MCInst #{{[0-9]+}} SB16_MM{{$}}
+    ; UNCHANGED: <MCInst #{{[0-9]+}} SB_MM{{$}}
+    SB_MM $s1, $a0, 15
+    ; CHECK: <MCInst #{{[0-9]+}} SB{{$}}
+    ; UNCHANGED: <MCInst #{{[0-9]+}} SB{{$}}
+    SB $s0, $a0, 0
+    ; CHECK: <MCInst #{{[0-9]+}} SB{{$}}
+    ; UNCHANGED: <MCInst #{{[0-9]+}} SB{{$}}
+    SB $v0, $a0, -1
+    ; CHECK: <MCInst #{{[0-9]+}} SB{{$}}
+    ; UNCHANGED: <MCInst #{{[0-9]+}} SB{{$}}
+    SB $v0, $a0, 16
+    ; CHECK: <MCInst #{{[0-9]+}} SB{{$}}
+    ; UNCHANGED: <MCInst #{{[0-9]+}} SB{{$}}
+    SB $v0, $t0, 0
+    ; CHECK: <MCInst #{{[0-9]+}} SH16_MM{{$}}
+    ; UNCHANGED: <MCInst #{{[0-9]+}} SH{{$}}
+    SH $zero, $a0, 0
+    ; CHECK: <MCInst #{{[0-9]+}} SH16_MM{{$}}
+    ; UNCHANGED: <MCInst #{{[0-9]+}} SH_MM{{$}}
+    SH_MM $s1, $a0, 30
+    ; CHECK: <MCInst #{{[0-9]+}} SH{{$}}
+    ; UNCHANGED: <MCInst #{{[0-9]+}} SH{{$}}
+    SH $v0, $a0, 1
+    ; CHECK: <MCInst #{{[0-9]+}} SH{{$}}
+    ; UNCHANGED: <MCInst #{{[0-9]+}} SH{{$}}
+    SH $v0, $a0, 32
+    ; CHECK: <MCInst #{{[0-9]+}} SH{{$}}
+    ; UNCHANGED: <MCInst #{{[0-9]+}} SH{{$}}
+    SH $s0, $a0, 0
+...
+
+---
+name: stack_memory
+tracksRegLiveness: false
+body: |
+  bb.0:
+    ; CHECK-LABEL: stack_memory:
+    ; UNCHANGED-LABEL: stack_memory:
+    ; CHECK: <MCInst #{{[0-9]+}} LWSP_MM{{$}}
+    ; UNCHANGED: <MCInst #{{[0-9]+}} LW{{$}}
+    $t0 = LW $sp, 0 :: (load (s32))
+    ; CHECK: <MCInst #{{[0-9]+}} LWSP_MM{{$}}
+    ; UNCHANGED: <MCInst #{{[0-9]+}} LW_MM{{$}}
+    $t0 = LW_MM $sp, 124
+    ; CHECK: <MCInst #{{[0-9]+}} LW{{$}}
+    ; UNCHANGED: <MCInst #{{[0-9]+}} LW{{$}}
+    $t0 = LW $sp, -4
+    ; CHECK: <MCInst #{{[0-9]+}} LW{{$}}
+    ; UNCHANGED: <MCInst #{{[0-9]+}} LW{{$}}
+    $t0 = LW $sp, 128
+    ; CHECK: <MCInst #{{[0-9]+}} LW{{$}}
+    ; UNCHANGED: <MCInst #{{[0-9]+}} LW{{$}}
+    $t0 = LW $sp, 2
+    ; CHECK: <MCInst #{{[0-9]+}} LW{{$}}
+    ; UNCHANGED: <MCInst #{{[0-9]+}} LW{{$}}
+    $t0 = LW $a0, 0
+    ; CHECK: <MCInst #{{[0-9]+}} SWSP_MM{{$}}
+    ; UNCHANGED: <MCInst #{{[0-9]+}} SW{{$}}
+    SW $t0, $sp, 0
+    ; CHECK: <MCInst #{{[0-9]+}} SWSP_MM{{$}}
+    ; UNCHANGED: <MCInst #{{[0-9]+}} SW_MM{{$}}
+    SW_MM $t0, $sp, 124
+    ; CHECK: <MCInst #{{[0-9]+}} SW{{$}}
+    ; UNCHANGED: <MCInst #{{[0-9]+}} SW{{$}}
+    SW $t0, $sp, -4
+    ; CHECK: <MCInst #{{[0-9]+}} SW{{$}}
+    ; UNCHANGED: <MCInst #{{[0-9]+}} SW{{$}}
+    SW $t0, $sp, 128
+    ; CHECK: <MCInst #{{[0-9]+}} SW{{$}}
+    ; UNCHANGED: <MCInst #{{[0-9]+}} SW{{$}}
+    SW $t0, $sp, 2
+    ; CHECK: <MCInst #{{[0-9]+}} SW{{$}}
+    ; UNCHANGED: <MCInst #{{[0-9]+}} SW{{$}}
+    SW $t0, $a0, 0
+...
diff --git a/llvm/test/CodeGen/Mips/micromips-sizereduction/delay-slot-compression.mir b/llvm/test/CodeGen/Mips/micromips-sizereduction/delay-slot-compression.mir
new file mode 100644
index 0000000000000..6e285414e068d
--- /dev/null
+++ b/llvm/test/CodeGen/Mips/micromips-sizereduction/delay-slot-compression.mir
@@ -0,0 +1,88 @@
+# RUN: llc -run-pass=micromips-reduce-size -mtriple=mipsel \
+# RUN:   -mcpu=mips32r2 -mattr=+micromips -verify-machineinstrs %s -o %t.mir
+# RUN: llc -mtriple=mipsel -mcpu=mips32r2 -mattr=+micromips \
+# RUN:   -start-after=mips-branch-expansion -asm-show-inst \
+# RUN:   -verify-machineinstrs %t.mir -o - | FileCheck %s
+
+# The compression pass leaves prefilled delay-slot bundles unchanged.
+--- |
+  declare void @callee()
+  define void @full_call_slot() { ret void }
+  define void @short_call_slot() { ret void }
+  define void @full_jump_slot() { ret void }
+  define void @short_jump_slot() { ret void }
+  define void @uncompressible_call_slot() { ret void }
+  define void @already_short_slot() { ret void }
+...
+---
+name: full_call_slot
+tracksRegLiveness: false
+body: |
+  bb.0:
+    ; CHECK-LABEL: full_call_slot:
+    ; CHECK: <MCInst #{{[0-9]+}} JAL_MM
+    ; CHECK: <MCInst #{{[0-9]+}} ADDu{{$}}
+    JAL_MM @callee, csr_o32, implicit-def $ra {
+      $v0 = ADDu $a0, $a1
+    }
+...
+---
+name: short_call_slot
+tracksRegLiveness: false
+body: |
+  bb.0:
+    ; CHECK-LABEL: short_call_slot:
+    ; CHECK: <MCInst #{{[0-9]+}} JALS_MM
+    ; CHECK: <MCInst #{{[0-9]+}} ADDU16_MM
+    JALS_MM @callee, csr_o32, implicit-def $ra {
+      $v0 = ADDU16_MM $a0, $a1
+    }
+...
+---
+name: full_jump_slot
+tracksRegLiveness: false
+body: |
+  bb.0:
+    ; CHECK-LABEL: full_jump_slot:
+    ; CHECK: <MCInst #{{[0-9]+}} JR{{$}}
+    ; CHECK: <MCInst #{{[0-9]+}} ADDiu{{$}}
+    JR $at {
+      $sp = ADDiu $sp, 8
+    }
+...
+---
+name: short_jump_slot
+tracksRegLiveness: false
+body: |
+  bb.0:
+    ; CHECK-LABEL: short_jump_slot:
+    ; CHECK: <MCInst #{{[0-9]+}} JR16_MM
+    ; CHECK: <MCInst #{{[0-9]+}} ADDiu{{$}}
+    JR16_MM $at {
+      $sp = ADDiu $sp, 8
+    }
+...
+---
+name: uncompressible_call_slot
+tracksRegLiveness: false
+body: |
+  bb.0:
+    ; CHECK-LABEL: uncompressible_call_slot:
+    ; CHECK: <MCInst #{{[0-9]+}} JAL_MM
+    ; CHECK: <MCInst #{{[0-9]+}} ADDu{{$}}
+    JAL_MM @callee, csr_o32, implicit-def $ra {
+      $t0 = ADDu $a0, $a1
+    }
+...
+---
+name: already_short_slot
+tracksRegLiveness: false
+body: |
+  bb.0:
+    ; CHECK-LABEL: already_short_slot:
+    ; CHECK: <MCInst #{{[0-9]+}} JALS_MM
+    ; CHECK: <MCInst #{{[0-9]+}} MOVE16_MM
+    JALS_MM @callee, csr_o32, implicit-def $ra {
+      $v0 = MOVE16_MM $a0
+    }
+...
diff --git a/llvm/utils/gn/secondary/llvm/lib/Target/Mips/BUILD.gn b/llvm/utils/gn/secondary/llvm/lib/Target/Mips/BUILD.gn
index 14b56358e790d..b21fb51161bd7 100644
--- a/llvm/utils/gn/secondary/llvm/lib/Target/Mips/BUILD.gn
+++ b/llvm/utils/gn/secondary/llvm/lib/Target/Mips/BUILD.gn
@@ -6,6 +6,12 @@ tablegen("MipsGenCallingConv") {
   td_file = "Mips.td"
 }
 
+tablegen("MipsGenCompressInstEmitter") {
+  visibility = [ ":LLVMMipsCodeGen" ]
+  args = [ "-gen-compress-inst-emitter" ]
+  td_file = "Mips.td"
+}
+
 tablegen("MipsGenDAGISel") {
   visibility = [ ":LLVMMipsCodeGen" ]
   args = [ "-gen-dag-isel" ]
@@ -54,6 +60,7 @@ tablegen("MipsGenSDNodeInfo") {
 static_library("LLVMMipsCodeGen") {
   deps = [
     ":MipsGenCallingConv",
+    ":MipsGenCompressInstEmitter",
     ":MipsGenDAGISel",
     ":MipsGenFastISel",
     ":MipsGenGlobalISel",



More information about the llvm-commits mailing list