[llvm] [Mips] Declare command line options in TableGen (PR #230738)

Fangrui Song via llvm-commits llvm-commits at lists.llvm.org
Fri Oct 9 22:20:06 PDT 2026


https://github.com/MaskRay created https://github.com/llvm/llvm-project/pull/230738

Move the cl::opts of MipsCodeGen into MipsOptions.td, and those of
MipsDesc into MCTargetDesc/MipsMCOptions.td, registered by
LLVMInitializeMipsTargetMC(). MipsTargetMachine holds `const MipsOptions
&CLOpts` and `const MipsMCOptions &MCCLOpts`, which MipsSubtarget
copies, since CodeGen also reads -mips-jalr-reloc and
-mno-check-zero-division. MipsAsmParser and MipsTargetELFStreamer hold
`const MipsMCOptions &CLOpts`.

CompactBranchPolicy becomes an enum class, and
MipsSubtarget::useConstantIslands() becomes a non-static member.

Aided by Opus 5.5

>From f9387c1fd96bac0d11b7638d339d54d0719079b6 Mon Sep 17 00:00:00 2001
From: Fangrui Song <i at maskray.me>
Date: Fri, 9 Oct 2026 21:06:23 -0700
Subject: [PATCH] [Mips] Declare command line options in TableGen

Move the cl::opts of MipsCodeGen into MipsOptions.td, and those of
MipsDesc into MCTargetDesc/MipsMCOptions.td, registered by
LLVMInitializeMipsTargetMC(). MipsTargetMachine holds `const MipsOptions
&CLOpts` and `const MipsMCOptions &MCCLOpts`, which MipsSubtarget
copies, since CodeGen also reads -mips-jalr-reloc and
-mno-check-zero-division. MipsAsmParser and MipsTargetELFStreamer hold
`const MipsMCOptions &CLOpts`.

CompactBranchPolicy becomes an enum class, and
MipsSubtarget::useConstantIslands() becomes a non-static member.

Aided by Opus 5.5
---
 .../Target/Mips/AsmParser/MipsAsmParser.cpp   | 17 ++--
 llvm/lib/Target/Mips/CMakeLists.txt           |  7 ++
 .../Target/Mips/MCTargetDesc/CMakeLists.txt   |  1 +
 .../Target/Mips/MCTargetDesc/MipsABIInfo.cpp  | 12 ---
 .../Target/Mips/MCTargetDesc/MipsMCOptions.h  | 15 ++++
 .../Target/Mips/MCTargetDesc/MipsMCOptions.td | 21 +++++
 .../Mips/MCTargetDesc/MipsMCTargetDesc.cpp    |  6 ++
 .../Mips/MCTargetDesc/MipsTargetStreamer.cpp  | 12 +--
 .../Mips/MCTargetDesc/MipsTargetStreamer.h    |  2 +
 llvm/lib/Target/Mips/Mips16ISelLowering.cpp   | 22 ++---
 llvm/lib/Target/Mips/MipsAsmPrinter.cpp       |  4 +-
 llvm/lib/Target/Mips/MipsBranchExpansion.cpp  | 14 +--
 .../Target/Mips/MipsConstantIslandPass.cpp    | 55 ++++--------
 llvm/lib/Target/Mips/MipsDelaySlotFiller.cpp  | 44 +++------
 llvm/lib/Target/Mips/MipsFastISel.cpp         | 10 +--
 llvm/lib/Target/Mips/MipsISelLowering.cpp     | 34 +++----
 llvm/lib/Target/Mips/MipsOptimizePICCall.cpp  | 23 ++---
 llvm/lib/Target/Mips/MipsOptions.td           | 89 +++++++++++++++++++
 llvm/lib/Target/Mips/MipsOs16.cpp             | 13 +--
 llvm/lib/Target/Mips/MipsSEISelLowering.cpp   | 15 ++--
 llvm/lib/Target/Mips/MipsSubtarget.cpp        | 41 +++------
 llvm/lib/Target/Mips/MipsSubtarget.h          | 29 ++++--
 llvm/lib/Target/Mips/MipsTargetMachine.cpp    | 16 ++--
 llvm/lib/Target/Mips/MipsTargetMachine.h      |  4 +
 llvm/lib/Target/Mips/MipsTargetObjectFile.cpp | 48 ++++------
 .../secondary/llvm/lib/Target/Mips/BUILD.gn   |  8 ++
 .../lib/Target/Mips/MCTargetDesc/BUILD.gn     |  8 ++
 .../llvm-project-overlay/llvm/BUILD.bazel     | 22 +++++
 28 files changed, 316 insertions(+), 276 deletions(-)
 create mode 100644 llvm/lib/Target/Mips/MCTargetDesc/MipsMCOptions.h
 create mode 100644 llvm/lib/Target/Mips/MCTargetDesc/MipsMCOptions.td
 create mode 100644 llvm/lib/Target/Mips/MipsOptions.td

diff --git a/llvm/lib/Target/Mips/AsmParser/MipsAsmParser.cpp b/llvm/lib/Target/Mips/AsmParser/MipsAsmParser.cpp
index 99cb6d26d2039c..eefc544e067182 100644
--- a/llvm/lib/Target/Mips/AsmParser/MipsAsmParser.cpp
+++ b/llvm/lib/Target/Mips/AsmParser/MipsAsmParser.cpp
@@ -11,6 +11,7 @@
 #include "MCTargetDesc/MipsBaseInfo.h"
 #include "MCTargetDesc/MipsInstPrinter.h"
 #include "MCTargetDesc/MipsMCAsmInfo.h"
+#include "MCTargetDesc/MipsMCOptions.h"
 #include "MCTargetDesc/MipsMCTargetDesc.h"
 #include "MCTargetDesc/MipsTargetStreamer.h"
 #include "TargetInfo/MipsTargetInfo.h"
@@ -42,7 +43,6 @@
 #include "llvm/MC/TargetRegistry.h"
 #include "llvm/Support/Alignment.h"
 #include "llvm/Support/Casting.h"
-#include "llvm/Support/CommandLine.h"
 #include "llvm/Support/Compiler.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/ErrorHandling.h"
@@ -69,9 +69,6 @@ class MCInstrInfo;
 
 } // end namespace llvm
 
-extern cl::opt<bool> EmitJalrReloc;
-extern cl::opt<bool> NoZeroDivCheck;
-
 namespace {
 
 class MipsAssemblerOptions {
@@ -143,6 +140,7 @@ class MipsAsmParser : public MCTargetAsmParser {
     return static_cast<MipsTargetStreamer &>(TS);
   }
 
+  const MipsMCOptions &CLOpts;
   MipsABIInfo ABI;
   SmallVector<std::unique_ptr<MipsAssemblerOptions>, 2> AssemblerOptions;
   MCSymbol *CurrentFn; // Pointer to the function being parsed. It may be a
@@ -521,7 +519,7 @@ class MipsAsmParser : public MCTargetAsmParser {
 
   MipsAsmParser(const MCSubtargetInfo &sti, MCAsmParser &parser,
                 const MCInstrInfo &MII)
-      : MCTargetAsmParser(sti, MII),
+      : MCTargetAsmParser(sti, MII), CLOpts(MipsMCOptions::Global),
         ABI(MipsABIInfo::computeTargetABI(
             sti.getTargetTriple(),
             parser.getContext().getTargetOptions().getABIName())) {
@@ -579,7 +577,7 @@ class MipsAsmParser : public MCTargetAsmParser {
   }
 
   bool isJalrRelocAvailable(const MCExpr *JalExpr) {
-    if (!EmitJalrReloc)
+    if (!CLOpts.jalr_reloc)
       return false;
     MCValue Res;
     if (!JalExpr->evaluateAsRelocatable(Res, nullptr))
@@ -4245,7 +4243,7 @@ bool MipsAsmParser::expandDivRem(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
     if (!ATReg)
       return true;
 
-    if (!NoZeroDivCheck && ImmValue == 0) {
+    if (!CLOpts.mno_check_zero_division && ImmValue == 0) {
       if (UseTraps)
         TOut.emitRRI(Mips::TEQ, ZeroReg, ZeroReg, 0x7, IDLoc, STI);
       else
@@ -4277,7 +4275,8 @@ bool MipsAsmParser::expandDivRem(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
   // break, insert the trap/break and exit. This gives a different result to
   // GAS. GAS has an inconsistency/missed optimization in that not all cases
   // are handled equivalently. As the observed behaviour is the same, we're ok.
-  if (!NoZeroDivCheck && (RtReg == Mips::ZERO || RtReg == Mips::ZERO_64)) {
+  if (!CLOpts.mno_check_zero_division &&
+      (RtReg == Mips::ZERO || RtReg == Mips::ZERO_64)) {
     if (UseTraps) {
       TOut.emitRRI(Mips::TEQ, ZeroReg, ZeroReg, 0x7, IDLoc, STI);
       return false;
@@ -4299,7 +4298,7 @@ bool MipsAsmParser::expandDivRem(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out,
   MCOperand LabelOp;
 
   TOut.emitRR(DivOp, RsReg, RtReg, IDLoc, STI);
-  if (!NoZeroDivCheck) {
+  if (!CLOpts.mno_check_zero_division) {
     if (UseTraps) {
       TOut.emitRRI(Mips::TEQ, RtReg, ZeroReg, 0x7, IDLoc, STI);
     } else {
diff --git a/llvm/lib/Target/Mips/CMakeLists.txt b/llvm/lib/Target/Mips/CMakeLists.txt
index 918a099b68df8a..13e0a40f96ca67 100644
--- a/llvm/lib/Target/Mips/CMakeLists.txt
+++ b/llvm/lib/Target/Mips/CMakeLists.txt
@@ -21,6 +21,12 @@ tablegen(LLVM MipsGenSDNodeInfo.inc -gen-sd-node-info)
 tablegen(LLVM MipsGenSubtargetInfo.inc -gen-subtarget)
 tablegen(LLVM MipsGenExegesis.inc -gen-exegesis)
 
+set(LLVM_TARGET_DEFINITIONS MipsOptions.td)
+tablegen(LLVM MipsOptions.inc -gen-opt-parser-defs)
+
+set(LLVM_TARGET_DEFINITIONS MCTargetDesc/MipsMCOptions.td)
+tablegen(LLVM MipsMCOptions.inc -gen-opt-parser-defs)
+
 add_public_tablegen_target(MipsCommonTableGen)
 
 add_llvm_target(MipsCodeGen
@@ -78,6 +84,7 @@ add_llvm_target(MipsCodeGen
   MC
   MipsDesc
   MipsInfo
+  Option
   SelectionDAG
   Support
   Target
diff --git a/llvm/lib/Target/Mips/MCTargetDesc/CMakeLists.txt b/llvm/lib/Target/Mips/MCTargetDesc/CMakeLists.txt
index 8ccd42ea0abfe0..adf2f0771ed954 100644
--- a/llvm/lib/Target/Mips/MCTargetDesc/CMakeLists.txt
+++ b/llvm/lib/Target/Mips/MCTargetDesc/CMakeLists.txt
@@ -17,6 +17,7 @@ add_llvm_component_library(LLVMMipsDesc
   CodeGenTypes
   MC
   MipsInfo
+  Option
   Support
   TargetParser
 
diff --git a/llvm/lib/Target/Mips/MCTargetDesc/MipsABIInfo.cpp b/llvm/lib/Target/Mips/MCTargetDesc/MipsABIInfo.cpp
index 3f7a0c7f2fa10f..2bdea8d62861fc 100644
--- a/llvm/lib/Target/Mips/MCTargetDesc/MipsABIInfo.cpp
+++ b/llvm/lib/Target/Mips/MCTargetDesc/MipsABIInfo.cpp
@@ -10,21 +10,9 @@
 #include "Mips.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/MC/MCTargetOptions.h"
-#include "llvm/Support/CommandLine.h"
 
 using namespace llvm;
 
-// Note: this option is defined here to be visible from libLLVMMipsAsmParser
-//       and libLLVMMipsCodeGen
-cl::opt<bool>
-EmitJalrReloc("mips-jalr-reloc", cl::Hidden,
-              cl::desc("MIPS: Emit R_{MICRO}MIPS_JALR relocation with jalr"),
-              cl::init(true));
-cl::opt<bool>
-    NoZeroDivCheck("mno-check-zero-division", cl::Hidden,
-                   cl::desc("MIPS: Don't trap on integer division by zero."),
-                   cl::init(false));
-
 namespace {
 static constexpr MCPhysReg O32IntRegs[] = {Mips::A0, Mips::A1, Mips::A2,
                                            Mips::A3};
diff --git a/llvm/lib/Target/Mips/MCTargetDesc/MipsMCOptions.h b/llvm/lib/Target/Mips/MCTargetDesc/MipsMCOptions.h
new file mode 100644
index 00000000000000..4503d41c992ef4
--- /dev/null
+++ b/llvm/lib/Target/Mips/MCTargetDesc/MipsMCOptions.h
@@ -0,0 +1,15 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_LIB_TARGET_MIPS_MCTARGETDESC_MIPSMCOPTIONS_H
+#define LLVM_LIB_TARGET_MIPS_MCTARGETDESC_MIPSMCOPTIONS_H
+
+#define OPTIONS_STRUCT_DECL
+#include "MipsMCOptions.inc"
+
+#endif // LLVM_LIB_TARGET_MIPS_MCTARGETDESC_MIPSMCOPTIONS_H
diff --git a/llvm/lib/Target/Mips/MCTargetDesc/MipsMCOptions.td b/llvm/lib/Target/Mips/MCTargetDesc/MipsMCOptions.td
new file mode 100644
index 00000000000000..da7bc248b46116
--- /dev/null
+++ b/llvm/lib/Target/Mips/MCTargetDesc/MipsMCOptions.td
@@ -0,0 +1,21 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+include "llvm/Option/LibraryOptions.td"
+
+def MipsMCOptions : OptionsStruct<prefix = "mips-">;
+
+// MCTargetDesc/MipsABIInfo.cpp
+defm : BoolField<"mips-jalr-reloc", "true",
+  "MIPS: Emit R_{MICRO}MIPS_JALR relocation with jalr">;
+defm : BoolField<"mno-check-zero-division", "false",
+  "MIPS: Don't trap on integer division by zero">;
+
+// MCTargetDesc/MipsTargetStreamer.cpp
+defm : BoolField<"mips-round-section-sizes", "false",
+  "Round section sizes up to the section alignment">;
diff --git a/llvm/lib/Target/Mips/MCTargetDesc/MipsMCTargetDesc.cpp b/llvm/lib/Target/Mips/MCTargetDesc/MipsMCTargetDesc.cpp
index fb4cff6b25a1bb..0191d0a5c9037d 100644
--- a/llvm/lib/Target/Mips/MCTargetDesc/MipsMCTargetDesc.cpp
+++ b/llvm/lib/Target/Mips/MCTargetDesc/MipsMCTargetDesc.cpp
@@ -16,6 +16,7 @@
 #include "MipsELFStreamer.h"
 #include "MipsInstPrinter.h"
 #include "MipsMCAsmInfo.h"
+#include "MipsMCOptions.h"
 #include "MipsTargetStreamer.h"
 #include "TargetInfo/MipsTargetInfo.h"
 #include "llvm/DebugInfo/CodeView/CodeView.h"
@@ -28,6 +29,7 @@
 #include "llvm/MC/MCSubtargetInfo.h"
 #include "llvm/MC/MCSymbol.h"
 #include "llvm/MC/TargetRegistry.h"
+#include "llvm/Option/LibraryOptions.h"
 #include "llvm/Support/Compiler.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/FormattedStream.h"
@@ -48,6 +50,9 @@ using namespace llvm;
 #define GET_REGISTER_MATCHER
 #include "MipsGenAsmMatcher.inc"
 
+#define OPTIONS_STRUCT_DEFS
+#include "MipsMCOptions.inc"
+
 MCRegister MIPS_MC::matchRegisterName(StringRef Name, const MCRegisterInfo &MRI,
                                       unsigned RegClassID, unsigned AltIdx) {
   MCRegister Reg = MatchRegisterAltName(Name, AltIdx);
@@ -327,6 +332,7 @@ static MCInstrAnalysis *createMipsMCInstrAnalysis(const MCInstrInfo *Info) {
 }
 
 extern "C" LLVM_ABI LLVM_EXTERNAL_VISIBILITY void LLVMInitializeMipsTargetMC() {
+  static opt::RegisterLibraryOptions<MipsMCOptions> O;
   for (Target *T : {&getTheMipsTarget(), &getTheMipselTarget(),
                     &getTheMips64Target(), &getTheMips64elTarget()}) {
     // Register the MC asm info.
diff --git a/llvm/lib/Target/Mips/MCTargetDesc/MipsTargetStreamer.cpp b/llvm/lib/Target/Mips/MCTargetDesc/MipsTargetStreamer.cpp
index f62ebc8b93b613..b9dd7848af1ad8 100644
--- a/llvm/lib/Target/Mips/MCTargetDesc/MipsTargetStreamer.cpp
+++ b/llvm/lib/Target/Mips/MCTargetDesc/MipsTargetStreamer.cpp
@@ -26,18 +26,11 @@
 #include "llvm/MC/MCSectionELF.h"
 #include "llvm/MC/MCSubtargetInfo.h"
 #include "llvm/MC/MCSymbolELF.h"
-#include "llvm/Support/CommandLine.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/FormattedStream.h"
 
 using namespace llvm;
 
-namespace {
-static cl::opt<bool> RoundSectionSizes(
-    "mips-round-section-sizes", cl::init(false),
-    cl::desc("Round section sizes up to the section alignment"), cl::Hidden);
-} // end anonymous namespace
-
 static bool isMicroMips(const MCSubtargetInfo *STI) {
   return STI->hasFeature(Mips::FeatureMicroMips);
 }
@@ -872,7 +865,8 @@ MipsTargetELFStreamer::getISAMode(const MCSubtargetInfo &STI) {
 
 MipsTargetELFStreamer::MipsTargetELFStreamer(MCStreamer &S,
                                              const MCSubtargetInfo &STI)
-    : MipsTargetStreamer(S), Mode(getISAMode(STI)), STI(STI) {
+    : MipsTargetStreamer(S), CLOpts(MipsMCOptions::Global),
+      Mode(getISAMode(STI)), STI(STI) {
   MCAssembler &MCA = getStreamer().getAssembler();
   ELFObjectWriter &W = getStreamer().getWriter();
 
@@ -982,7 +976,7 @@ void MipsTargetELFStreamer::finish() {
   DataSection.ensureMinAlignment(Align(16));
   BSSSection.ensureMinAlignment(Align(16));
 
-  if (RoundSectionSizes) {
+  if (CLOpts.round_section_sizes) {
     // Make sections sizes a multiple of the alignment. This is useful for
     // verifying the output of IAS against the output of other assemblers but
     // it's not necessary to produce a correct object and increases section
diff --git a/llvm/lib/Target/Mips/MCTargetDesc/MipsTargetStreamer.h b/llvm/lib/Target/Mips/MCTargetDesc/MipsTargetStreamer.h
index dd57315c721f90..96f83594c1b30a 100644
--- a/llvm/lib/Target/Mips/MCTargetDesc/MipsTargetStreamer.h
+++ b/llvm/lib/Target/Mips/MCTargetDesc/MipsTargetStreamer.h
@@ -11,6 +11,7 @@
 
 #include "MCTargetDesc/MipsABIFlagsSection.h"
 #include "MCTargetDesc/MipsABIInfo.h"
+#include "MCTargetDesc/MipsMCOptions.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/MC/MCELFStreamer.h"
@@ -335,6 +336,7 @@ class MipsTargetELFStreamer : public MipsTargetStreamer {
   enum class ISAMode { Standard, MicroMips, Mips16 };
   static ISAMode getISAMode(const MCSubtargetInfo &STI);
 
+  const MipsMCOptions &CLOpts;
   ISAMode Mode;
   SmallVector<ISAMode, 4> ModeStack;
   const MCSubtargetInfo &STI;
diff --git a/llvm/lib/Target/Mips/Mips16ISelLowering.cpp b/llvm/lib/Target/Mips/Mips16ISelLowering.cpp
index 122df08af99c10..9cf4d1b570f185 100644
--- a/llvm/lib/Target/Mips/Mips16ISelLowering.cpp
+++ b/llvm/lib/Target/Mips/Mips16ISelLowering.cpp
@@ -17,19 +17,11 @@
 #include "MipsTargetMachine.h"
 #include "llvm/CodeGen/MachineInstrBuilder.h"
 #include "llvm/CodeGen/TargetInstrInfo.h"
-#include "llvm/Support/CommandLine.h"
 
 using namespace llvm;
 
 #define DEBUG_TYPE "mips-lower"
 
-static cl::opt<bool> DontExpandCondPseudos16(
-  "mips16-dont-expand-cond-pseudo",
-  cl::init(false),
-  cl::desc("Don't expand conditional move related "
-           "pseudos for Mips 16"),
-  cl::Hidden);
-
 namespace {
 struct Mips16IntrinsicHelperType{
   const char* Name;
@@ -449,7 +441,7 @@ void Mips16TargetLowering::getOpndList(
 MachineBasicBlock *
 Mips16TargetLowering::emitSel16(unsigned Opc, MachineInstr &MI,
                                 MachineBasicBlock *BB) const {
-  if (DontExpandCondPseudos16)
+  if (Subtarget.getCLOpts().mips16_dont_expand_cond_pseudo)
     return BB;
   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
   DebugLoc DL = MI.getDebugLoc();
@@ -512,7 +504,7 @@ Mips16TargetLowering::emitSel16(unsigned Opc, MachineInstr &MI,
 MachineBasicBlock *
 Mips16TargetLowering::emitSelT16(unsigned Opc1, unsigned Opc2, MachineInstr &MI,
                                  MachineBasicBlock *BB) const {
-  if (DontExpandCondPseudos16)
+  if (Subtarget.getCLOpts().mips16_dont_expand_cond_pseudo)
     return BB;
   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
   DebugLoc DL = MI.getDebugLoc();
@@ -578,7 +570,7 @@ MachineBasicBlock *
 Mips16TargetLowering::emitSeliT16(unsigned Opc1, unsigned Opc2,
                                   MachineInstr &MI,
                                   MachineBasicBlock *BB) const {
-  if (DontExpandCondPseudos16)
+  if (Subtarget.getCLOpts().mips16_dont_expand_cond_pseudo)
     return BB;
   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
   DebugLoc DL = MI.getDebugLoc();
@@ -644,7 +636,7 @@ MachineBasicBlock *
 Mips16TargetLowering::emitFEXT_T8I816_ins(unsigned BtOpc, unsigned CmpOpc,
                                           MachineInstr &MI,
                                           MachineBasicBlock *BB) const {
-  if (DontExpandCondPseudos16)
+  if (Subtarget.getCLOpts().mips16_dont_expand_cond_pseudo)
     return BB;
   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
   Register regX = MI.getOperand(0).getReg();
@@ -661,7 +653,7 @@ Mips16TargetLowering::emitFEXT_T8I816_ins(unsigned BtOpc, unsigned CmpOpc,
 MachineBasicBlock *Mips16TargetLowering::emitFEXT_T8I8I16_ins(
     unsigned BtOpc, unsigned CmpiOpc, unsigned CmpiXOpc, bool ImmSigned,
     MachineInstr &MI, MachineBasicBlock *BB) const {
-  if (DontExpandCondPseudos16)
+  if (Subtarget.getCLOpts().mips16_dont_expand_cond_pseudo)
     return BB;
   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
   Register regX = MI.getOperand(0).getReg();
@@ -694,7 +686,7 @@ static unsigned Mips16WhichOp8uOr16simm
 MachineBasicBlock *
 Mips16TargetLowering::emitFEXT_CCRX16_ins(unsigned SltOpc, MachineInstr &MI,
                                           MachineBasicBlock *BB) const {
-  if (DontExpandCondPseudos16)
+  if (Subtarget.getCLOpts().mips16_dont_expand_cond_pseudo)
     return BB;
   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
   Register CC = MI.getOperand(0).getReg();
@@ -713,7 +705,7 @@ MachineBasicBlock *
 Mips16TargetLowering::emitFEXT_CCRXI16_ins(unsigned SltiOpc, unsigned SltiXOpc,
                                            MachineInstr &MI,
                                            MachineBasicBlock *BB) const {
-  if (DontExpandCondPseudos16)
+  if (Subtarget.getCLOpts().mips16_dont_expand_cond_pseudo)
     return BB;
   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
   Register CC = MI.getOperand(0).getReg();
diff --git a/llvm/lib/Target/Mips/MipsAsmPrinter.cpp b/llvm/lib/Target/Mips/MipsAsmPrinter.cpp
index d2d7e491223c3c..4191e077539051 100644
--- a/llvm/lib/Target/Mips/MipsAsmPrinter.cpp
+++ b/llvm/lib/Target/Mips/MipsAsmPrinter.cpp
@@ -70,8 +70,6 @@ using namespace llvm;
 
 #define DEBUG_TYPE "mips-asm-printer"
 
-extern cl::opt<bool> EmitJalrReloc;
-
 MipsTargetStreamer &MipsAsmPrinter::getTargetStreamer() const {
   return static_cast<MipsTargetStreamer &>(*OutStreamer->getTargetStreamer());
 }
@@ -236,7 +234,7 @@ void MipsAsmPrinter::emitInstruction(const MachineInstr *MI) {
     return;
   }
 
-  if (EmitJalrReloc &&
+  if (Subtarget->getMCCLOpts().jalr_reloc &&
       (MI->isReturn() || MI->isCall() || MI->isIndirectBranch())) {
     emitDirectiveRelocJalr(*MI, OutContext, TM, *OutStreamer, *Subtarget);
   }
diff --git a/llvm/lib/Target/Mips/MipsBranchExpansion.cpp b/llvm/lib/Target/Mips/MipsBranchExpansion.cpp
index 9d84ac0159fe1d..733288ddc619c3 100644
--- a/llvm/lib/Target/Mips/MipsBranchExpansion.cpp
+++ b/llvm/lib/Target/Mips/MipsBranchExpansion.cpp
@@ -91,7 +91,6 @@
 #include "llvm/CodeGen/MachineOperand.h"
 #include "llvm/CodeGen/TargetSubtargetInfo.h"
 #include "llvm/IR/DebugLoc.h"
-#include "llvm/Support/CommandLine.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Target/TargetMachine.h"
 #include <algorithm>
@@ -107,15 +106,6 @@ using namespace llvm;
 STATISTIC(NumInsertedNops, "Number of nops inserted");
 STATISTIC(LongBranches, "Number of long branches.");
 
-static cl::opt<bool>
-    SkipLongBranch("skip-mips-long-branch", cl::init(false),
-                   cl::desc("MIPS: Skip branch expansion pass."), cl::Hidden);
-
-static cl::opt<bool>
-    ForceLongBranch("force-mips-long-branch", cl::init(false),
-                    cl::desc("MIPS: Expand all branches to long format."),
-                    cl::Hidden);
-
 namespace {
 
 using Iter = MachineBasicBlock::iterator;
@@ -868,7 +858,7 @@ bool MipsBranchExpansion::handlePossibleLongBranch() {
   if (STI->inMips16Mode())
     return false;
 
-  if (SkipLongBranch)
+  if (STI->getCLOpts().skip_mips_long_branch)
     return false;
 
   bool EverMadeChange = false, MadeChange = true;
@@ -931,7 +921,7 @@ bool MipsBranchExpansion::runOnMachineFunction(MachineFunction &MF) {
 
   MFp = &MF;
 
-  ForceLongBranchFirstPass = ForceLongBranch;
+  ForceLongBranchFirstPass = STI->getCLOpts().force_mips_long_branch;
   // Run these at least once.
   bool longBranchChanged = handlePossibleLongBranch();
   bool forbiddenSlotChanged = handleForbiddenSlot();
diff --git a/llvm/lib/Target/Mips/MipsConstantIslandPass.cpp b/llvm/lib/Target/Mips/MipsConstantIslandPass.cpp
index 1a844ad64eeea4..af5478a5f0d5c6 100644
--- a/llvm/lib/Target/Mips/MipsConstantIslandPass.cpp
+++ b/llvm/lib/Target/Mips/MipsConstantIslandPass.cpp
@@ -41,7 +41,6 @@
 #include "llvm/IR/DebugLoc.h"
 #include "llvm/IR/Function.h"
 #include "llvm/IR/Type.h"
-#include "llvm/Support/CommandLine.h"
 #include "llvm/Support/Compiler.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/ErrorHandling.h"
@@ -61,27 +60,6 @@ STATISTIC(NumSplit,      "Number of uncond branches inserted");
 STATISTIC(NumCBrFixed,   "Number of cond branches fixed");
 STATISTIC(NumUBrFixed,   "Number of uncond branches fixed");
 
-// FIXME: This option should be removed once it has received sufficient testing.
-static cl::opt<bool>
-AlignConstantIslands("mips-align-constant-islands", cl::Hidden, cl::init(true),
-          cl::desc("Align constant islands in code"));
-
-// Rather than do make check tests with huge amounts of code, we force
-// the test to use this amount.
-static cl::opt<int> ConstantIslandsSmallOffset(
-  "mips-constant-islands-small-offset",
-  cl::init(0),
-  cl::desc("Make small offsets be this amount for testing purposes"),
-  cl::Hidden);
-
-// For testing purposes we tell it to not use relaxed load forms so that it
-// will split blocks.
-static cl::opt<bool> NoLoadRelaxation(
-  "mips-constant-islands-no-load-relaxation",
-  cl::init(false),
-  cl::desc("Don't relax loads to long loads - for testing purposes"),
-  cl::Hidden);
-
 static unsigned int branchTargetOperand(MachineInstr *MI) {
   switch (MI->getOpcode()) {
   case Mips::Bimm16:
@@ -271,11 +249,7 @@ namespace {
       }
 
       /// getMaxDisp - Returns the maximum displacement supported by MI.
-      unsigned getMaxDisp() const {
-        unsigned xMaxDisp = ConstantIslandsSmallOffset?
-                            ConstantIslandsSmallOffset: MaxDisp;
-        return xMaxDisp;
-      }
+      unsigned getMaxDisp() const { return MaxDisp; }
 
       void setMaxDisp(unsigned val) {
         MaxDisp = val;
@@ -369,6 +343,10 @@ namespace {
     void doInitialPlacement(std::vector<MachineInstr*> &CPEMIs);
     CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
     Align getCPEAlign(const MachineInstr &CPEMI);
+    unsigned getMaxDisp(const CPUser &U) const {
+      int SmallOffset = STI->getCLOpts().constant_islands_small_offset;
+      return SmallOffset ? SmallOffset : U.getMaxDisp();
+    }
     void initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs);
     unsigned getOffsetOf(MachineInstr *MI) const;
     unsigned getUserOffset(CPUser&) const;
@@ -413,8 +391,7 @@ char MipsConstantIslands::ID = 0;
 bool MipsConstantIslands::isOffsetInRange
   (unsigned UserOffset, unsigned TrialOffset,
    const CPUser &U) {
-  return isOffsetInRange(UserOffset, TrialOffset,
-                         U.getMaxDisp(), U.NegOk);
+  return isOffsetInRange(UserOffset, TrialOffset, getMaxDisp(U), U.NegOk);
 }
 
 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
@@ -436,7 +413,7 @@ bool MipsConstantIslands::runOnMachineFunction(MachineFunction &mf) {
   STI = &mf.getSubtarget<MipsSubtarget>();
   LLVM_DEBUG(dbgs() << "constant island machine function "
                     << "\n");
-  if (!STI->inMips16Mode() || !MipsSubtarget::useConstantIslands()) {
+  if (!STI->inMips16Mode() || !STI->useConstantIslands()) {
     return false;
   }
   TII = (const Mips16InstrInfo *)STI->getInstrInfo();
@@ -529,8 +506,10 @@ MipsConstantIslands::doInitialPlacement(std::vector<MachineInstr*> &CPEMIs) {
   const Align MaxAlign = MCP->getConstantPoolAlign();
 
   // Mark the basic block as required by the const-pool.
-  // If AlignConstantIslands isn't set, use 4-byte alignment for everything.
-  BB->setAlignment(AlignConstantIslands ? MaxAlign : Align(4));
+  // If -mips-align-constant-islands isn't set, use 4-byte alignment for
+  // everything.
+  BB->setAlignment(STI->getCLOpts().align_constant_islands ? MaxAlign
+                                                           : Align(4));
 
   // The function needs to be as aligned as the basic blocks. The linker may
   // move functions around based on their alignment.
@@ -613,8 +592,8 @@ MipsConstantIslands::CPEntry
 Align MipsConstantIslands::getCPEAlign(const MachineInstr &CPEMI) {
   assert(CPEMI.getOpcode() == Mips::CONSTPOOL_ENTRY);
 
-  // Everything is 4-byte aligned unless AlignConstantIslands is set.
-  if (!AlignConstantIslands)
+  // Everything is 4-byte aligned unless -mips-align-constant-islands is set.
+  if (!STI->getCLOpts().align_constant_islands)
     return Align(4);
 
   unsigned CPI = CPEMI.getOperand(1).getIndex();
@@ -1040,7 +1019,7 @@ int MipsConstantIslands::findInRangeCPEntry(CPUser& U, unsigned UserOffset)
   MachineInstr *CPEMI  = U.CPEMI;
 
   // Check to see if the CPE is already in-range.
-  if (isCPEntryInRange(UserMI, UserOffset, CPEMI, U.getMaxDisp(), U.NegOk,
+  if (isCPEntryInRange(UserMI, UserOffset, CPEMI, getMaxDisp(U), U.NegOk,
                        true)) {
     LLVM_DEBUG(dbgs() << "In range\n");
     return 1;
@@ -1056,7 +1035,7 @@ int MipsConstantIslands::findInRangeCPEntry(CPUser& U, unsigned UserOffset)
     // Removing CPEs can leave empty entries, skip
     if (CPE.CPEMI == nullptr)
       continue;
-    if (isCPEntryInRange(UserMI, UserOffset, CPE.CPEMI, U.getMaxDisp(),
+    if (isCPEntryInRange(UserMI, UserOffset, CPE.CPEMI, getMaxDisp(U),
                          U.NegOk)) {
       LLVM_DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#" << CPE.CPI
                         << "\n");
@@ -1243,7 +1222,7 @@ void MipsConstantIslands::createNewWater(unsigned CPUserIndex,
   // point where we can add a 4-byte branch instruction, and then align to
   // Align which is the largest possible alignment in the function.
   const Align Align = MF->getAlignment();
-  unsigned BaseInsertOffset = UserOffset + U.getMaxDisp();
+  unsigned BaseInsertOffset = UserOffset + getMaxDisp(U);
   LLVM_DEBUG(dbgs() << format("Split in middle of big block before %#x",
                               BaseInsertOffset));
 
@@ -1332,7 +1311,7 @@ bool MipsConstantIslands::handleConstantPoolUser(unsigned CPUserIndex) {
     // No water found.
     // we first see if a longer form of the instrucion could have reached
     // the constant. in that case we won't bother to split
-    if (!NoLoadRelaxation) {
+    if (!STI->getCLOpts().constant_islands_no_load_relaxation) {
       result = findLongFormInRangeCPEntry(U, UserOffset);
       if (result != 0) return true;
     }
diff --git a/llvm/lib/Target/Mips/MipsDelaySlotFiller.cpp b/llvm/lib/Target/Mips/MipsDelaySlotFiller.cpp
index 20afc2ea9ce89c..45322c22202c40 100644
--- a/llvm/lib/Target/Mips/MipsDelaySlotFiller.cpp
+++ b/llvm/lib/Target/Mips/MipsDelaySlotFiller.cpp
@@ -38,7 +38,6 @@
 #include "llvm/MC/MCRegisterInfo.h"
 #include "llvm/Support/Casting.h"
 #include "llvm/Support/CodeGen.h"
-#include "llvm/Support/CommandLine.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/raw_ostream.h"
 #include "llvm/Target/TargetMachine.h"
@@ -57,32 +56,6 @@ STATISTIC(UsefulSlots, "Number of delay slots filled with instructions that"
 STATISTIC(R5900ShortLoopNops, "Number of delay slots left as NOP for R5900 "
                               "short loop fix");
 
-static cl::opt<bool> DisableDelaySlotFiller(
-  "disable-mips-delay-filler",
-  cl::init(false),
-  cl::desc("Fill all delay slots with NOPs."),
-  cl::Hidden);
-
-static cl::opt<bool> DisableForwardSearch(
-  "disable-mips-df-forward-search",
-  cl::init(true),
-  cl::desc("Disallow MIPS delay filler to search forward."),
-  cl::Hidden);
-
-static cl::opt<bool> DisableSuccBBSearch(
-  "disable-mips-df-succbb-search",
-  cl::init(true),
-  cl::desc("Disallow MIPS delay filler to search successor basic blocks."),
-  cl::Hidden);
-
-static cl::opt<bool> DisableBackwardSearch(
-  "disable-mips-df-backward-search",
-  cl::init(false),
-  cl::desc("Disallow MIPS delay filler to search backward."),
-  cl::Hidden);
-
-extern cl::opt<CompactBranchPolicy> MipsCompactBranchPolicy;
-
 namespace {
 
   using Iter = MachineBasicBlock::iterator;
@@ -279,6 +252,7 @@ namespace {
 
     bool runOnMachineFunction(MachineFunction &F) override {
       TM = &F.getTarget();
+      CLOpts = &F.getSubtarget<MipsSubtarget>().getCLOpts();
       bool Changed = false;
       for (auto MBB = F.begin(); MBB != F.end();) {
         auto curMBB = MBB;
@@ -364,6 +338,7 @@ namespace {
     bool terminateSearch(const MachineInstr &Candidate) const;
 
     const TargetMachine *TM = nullptr;
+    const MipsOptions *CLOpts = nullptr;
   };
 
 } // end anonymous namespace
@@ -768,7 +743,7 @@ bool MipsDelaySlotFiller::runOnMachineBasicBlock(
 
     // Delay slot filling is disabled at -O0, in microMIPS32R6, or for R5900
     // short loop branches.
-    if (!DisableDelaySlotFiller &&
+    if (!CLOpts->disable_mips_delay_filler &&
         (TM->getOptLevel() != CodeGenOptLevel::None) &&
         !(InMicroMipsMode && STI.hasMips32r6()) && !SkipForFixR5900) {
 
@@ -776,8 +751,8 @@ bool MipsDelaySlotFiller::runOnMachineBasicBlock(
       const auto BranchInfo =
           BranchInformation(I, MBB.end(), FirstNextMBBInstr);
 
-      if (MipsCompactBranchPolicy.getValue() != CB_Always ||
-           !TII->getEquivalentCompactForm(I)) {
+      if (CLOpts->compact_branches != CompactBranchPolicy::Always ||
+          !TII->getEquivalentCompactForm(I)) {
         if (searchBackward(MBB, *I, BranchInfo)) {
           LLVM_DEBUG(dbgs() << DEBUG_TYPE ": found instruction for delay slot"
                                           " in backwards search.\n");
@@ -827,7 +802,8 @@ bool MipsDelaySlotFiller::runOnMachineBasicBlock(
     // form of the CTI. For indirect jumps this will not require inserting a
     // NOP and for branches will hopefully avoid requiring a NOP.
     if ((InMicroMipsMode ||
-         (STI.hasMips32r6() && MipsCompactBranchPolicy != CB_Never)) &&
+         (STI.hasMips32r6() &&
+          CLOpts->compact_branches != CompactBranchPolicy::Never)) &&
         TII->getEquivalentCompactForm(I)) {
       I = replaceWithCompactBranch(MBB, I, I->getDebugLoc());
       Changed = true;
@@ -929,7 +905,7 @@ bool MipsDelaySlotFiller::searchRange(MachineBasicBlock &MBB, IterTy Begin,
 bool MipsDelaySlotFiller::searchBackward(
     MachineBasicBlock &MBB, MachineInstr &Slot,
     const BranchInformation &BranchInfo) const {
-  if (DisableBackwardSearch)
+  if (CLOpts->disable_mips_df_backward_search)
     return false;
 
   auto *Fn = MBB.getParent();
@@ -957,7 +933,7 @@ bool MipsDelaySlotFiller::searchForward(
     MachineBasicBlock &MBB, Iter Slot,
     const BranchInformation &BranchInfo) const {
   // Can handle only calls.
-  if (DisableForwardSearch || !Slot->isCall())
+  if (CLOpts->disable_mips_df_forward_search || !Slot->isCall())
     return false;
 
   RegDefsUses RegDU(*MBB.getParent()->getSubtarget().getRegisterInfo());
@@ -982,7 +958,7 @@ bool MipsDelaySlotFiller::searchForward(
 bool MipsDelaySlotFiller::searchSuccBBs(
     MachineBasicBlock &MBB, Iter Slot,
     const BranchInformation &BranchInfo) const {
-  if (DisableSuccBBSearch)
+  if (CLOpts->disable_mips_df_succbb_search)
     return false;
 
   MachineBasicBlock *SuccBB = selectSuccBB(MBB);
diff --git a/llvm/lib/Target/Mips/MipsFastISel.cpp b/llvm/lib/Target/Mips/MipsFastISel.cpp
index e223d453f771b8..0a588fbaf953e9 100644
--- a/llvm/lib/Target/Mips/MipsFastISel.cpp
+++ b/llvm/lib/Target/Mips/MipsFastISel.cpp
@@ -72,9 +72,6 @@
 
 using namespace llvm;
 
-extern cl::opt<bool> EmitJalrReloc;
-extern cl::opt<bool> NoZeroDivCheck;
-
 namespace {
 
 class MipsFastISel final : public FastISel {
@@ -1579,7 +1576,7 @@ bool MipsFastISel::fastLowerCall(CallLoweringInfo &CLI) {
 
   CLI.Call = MIB;
 
-  if (EmitJalrReloc && !Subtarget->inMips16Mode()) {
+  if (Subtarget->getMCCLOpts().jalr_reloc && !Subtarget->inMips16Mode()) {
     // Attach callee address to the instruction, let asm printer emit
     // .reloc R_MIPS_JALR.
     if (Symbol)
@@ -1951,8 +1948,9 @@ bool MipsFastISel::selectDivRem(const Instruction *I, unsigned ISDOpcode) {
     return false;
 
   emitInst(DivOpc).addReg(Src0Reg).addReg(Src1Reg);
-  if (!NoZeroDivCheck && (!isa<ConstantInt>(I->getOperand(1)) ||
-                          dyn_cast<ConstantInt>(I->getOperand(1))->isZero())) {
+  if (!Subtarget->getMCCLOpts().mno_check_zero_division &&
+      (!isa<ConstantInt>(I->getOperand(1)) ||
+       dyn_cast<ConstantInt>(I->getOperand(1))->isZero())) {
     emitInst(Mips::TEQ).addReg(Src1Reg).addReg(Mips::ZERO).addImm(7);
   }
 
diff --git a/llvm/lib/Target/Mips/MipsISelLowering.cpp b/llvm/lib/Target/Mips/MipsISelLowering.cpp
index d8fc88cd905669..eb5be9214faac9 100644
--- a/llvm/lib/Target/Mips/MipsISelLowering.cpp
+++ b/llvm/lib/Target/Mips/MipsISelLowering.cpp
@@ -59,7 +59,6 @@
 #include "llvm/MC/MCContext.h"
 #include "llvm/Support/Casting.h"
 #include "llvm/Support/CodeGen.h"
-#include "llvm/Support/CommandLine.h"
 #include "llvm/Support/Compiler.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/MathExtras.h"
@@ -81,13 +80,6 @@ using namespace llvm;
 
 STATISTIC(NumTailCalls, "Number of tail calls");
 
-extern cl::opt<bool> EmitJalrReloc;
-extern cl::opt<bool> NoZeroDivCheck;
-
-static cl::opt<bool> UseMipsTailCalls("mips-tail-calls", cl::Hidden,
-                                      cl::desc("MIPS: permit tail calls."),
-                                      cl::init(false));
-
 static const MCPhysReg Mips64DPRegs[8] = {
   Mips::D12_64, Mips::D13_64, Mips::D14_64, Mips::D15_64,
   Mips::D16_64, Mips::D17_64, Mips::D18_64, Mips::D19_64
@@ -1293,10 +1285,10 @@ addLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
 }
 
 static MachineBasicBlock *
-insertDivByZeroTrap(MachineInstr &MI, MachineBasicBlock &MBB,
-                    const TargetInstrInfo &TII, bool Is64Bit,
-                    const DivByZeroTrapKind TrapKind) {
-  if (NoZeroDivCheck)
+insertDivByZeroTrap(const MipsMCOptions &MCCLOpts, MachineInstr &MI,
+                    MachineBasicBlock &MBB, const TargetInstrInfo &TII,
+                    bool Is64Bit, const DivByZeroTrapKind TrapKind) {
+  if (MCCLOpts.mno_check_zero_division)
     return &MBB;
 
   MachineOperand &Divisor = MI.getOperand(2);
@@ -1488,8 +1480,8 @@ MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
     const DivByZeroTrapKind TrapKind = !Subtarget.hasMips2()
                                            ? DivByZeroTrapKind::Break
                                            : DivByZeroTrapKind::Teq;
-    return insertDivByZeroTrap(MI, *BB, *Subtarget.getInstrInfo(), false,
-                               TrapKind);
+    return insertDivByZeroTrap(Subtarget.getMCCLOpts(), MI, *BB,
+                               *Subtarget.getInstrInfo(), false, TrapKind);
   }
   case Mips::SDIV_MM_Pseudo:
   case Mips::UDIV_MM_Pseudo:
@@ -1499,7 +1491,8 @@ MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
   case Mips::DIVU_MMR6:
   case Mips::MOD_MMR6:
   case Mips::MODU_MMR6:
-    return insertDivByZeroTrap(MI, *BB, *Subtarget.getInstrInfo(), false,
+    return insertDivByZeroTrap(Subtarget.getMCCLOpts(), MI, *BB,
+                               *Subtarget.getInstrInfo(), false,
                                DivByZeroTrapKind::TeqMM);
   case Mips::PseudoDSDIV:
   case Mips::PseudoDUDIV:
@@ -1507,7 +1500,8 @@ MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
   case Mips::DDIVU:
   case Mips::DMOD:
   case Mips::DMODU:
-    return insertDivByZeroTrap(MI, *BB, *Subtarget.getInstrInfo(), true,
+    return insertDivByZeroTrap(Subtarget.getMCCLOpts(), MI, *BB,
+                               *Subtarget.getInstrInfo(), true,
                                DivByZeroTrapKind::Teq);
 
   case Mips::PseudoSELECT_I:
@@ -3342,10 +3336,8 @@ void MipsTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
     case Mips::TAILCALL64R6REG:
     case Mips::TAILCALLREG_MM:
     case Mips::TAILCALLREG_MMR6: {
-      if (!EmitJalrReloc ||
-          Subtarget.inMips16Mode() ||
-          !isPositionIndependent() ||
-          Node->getNumOperands() < 1 ||
+      if (!Subtarget.getMCCLOpts().jalr_reloc || Subtarget.inMips16Mode() ||
+          !isPositionIndependent() || Node->getNumOperands() < 1 ||
           Node->getOperand(0).getNumOperands() < 2) {
         return;
       }
@@ -3476,7 +3468,7 @@ MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
   }
 
   if (IsTailCall) {
-    if (!UseMipsTailCalls) {
+    if (!Subtarget.getCLOpts().tail_calls) {
       IsTailCall = false;
       if (IsMustTail)
         report_fatal_error("failed to perform tail call elimination on a call "
diff --git a/llvm/lib/Target/Mips/MipsOptimizePICCall.cpp b/llvm/lib/Target/Mips/MipsOptimizePICCall.cpp
index 9d44aaa338d4d7..1a6663862b26c0 100644
--- a/llvm/lib/Target/Mips/MipsOptimizePICCall.cpp
+++ b/llvm/lib/Target/Mips/MipsOptimizePICCall.cpp
@@ -32,7 +32,6 @@
 #include "llvm/CodeGen/TargetSubtargetInfo.h"
 #include "llvm/CodeGenTypes/MachineValueType.h"
 #include "llvm/Support/Allocator.h"
-#include "llvm/Support/CommandLine.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/RecyclingAllocator.h"
 #include <cassert>
@@ -42,15 +41,6 @@ using namespace llvm;
 
 #define DEBUG_TYPE "optimize-mips-pic-call"
 
-static cl::opt<bool> LoadTargetFromGOT("mips-load-target-from-got",
-                                       cl::init(true),
-                                       cl::desc("Load target address from GOT"),
-                                       cl::Hidden);
-
-static cl::opt<bool> EraseGPOpnd("mips-erase-gp-opnd",
-                                 cl::init(true), cl::desc("Erase GP Operand"),
-                                 cl::Hidden);
-
 namespace {
 
 using ValueType = PointerUnion<const Value *, const PseudoSourceValue *>;
@@ -159,8 +149,8 @@ static void setCallTargetReg(MachineBasicBlock *MBB,
 }
 
 /// Search MI's operands for register GP and erase it.
-static bool eraseGPOpnd(MachineInstr &MI) {
-  if (!EraseGPOpnd)
+static bool eraseGPOpnd(const MipsOptions &CLOpts, MachineInstr &MI) {
+  if (!CLOpts.erase_gp_opnd)
     return false;
 
   MachineFunction &MF = *MI.getParent()->getParent();
@@ -228,8 +218,9 @@ bool OptimizePICCall::runOnMachineFunction(MachineFunction &F) {
 bool OptimizePICCall::visitNode(MBBInfo &MBBI) {
   bool Changed = false;
   MachineBasicBlock *MBB = MBBI.getNode()->getBlock();
-  const MipsRegisterInfo &TRI =
-      *MBB->getParent()->getSubtarget<MipsSubtarget>().getRegisterInfo();
+  const MipsSubtarget &STI = MBB->getParent()->getSubtarget<MipsSubtarget>();
+  const MipsOptions &CLOpts = STI.getCLOpts();
+  const MipsRegisterInfo &TRI = *STI.getRegisterInfo();
 
   // Definition of $gp reaching the current instruction.
   MachineOperand *GPDef = nullptr;
@@ -248,13 +239,13 @@ bool OptimizePICCall::visitNode(MBBInfo &MBBI) {
         // If a function has been called more than twice, we do not have to emit
         // a load instruction to get the function address from the GOT, but can
         // instead reuse the address that has been loaded before.
-        if (N >= 2 && !LoadTargetFromGOT)
+        if (N >= 2 && !CLOpts.load_target_from_got)
           getCallTargetRegOpnd(*I)->setReg(getReg(Entry));
 
         // Erase the $gp operand if this isn't the first time a function has
         // been called. $gp needs to be set up only if the function call can go
         // through a lazy binding stub.
-        if (eraseGPOpnd(*I) && GPDef)
+        if (eraseGPOpnd(CLOpts, *I) && GPDef)
           GPDef->setIsDead();
       }
 
diff --git a/llvm/lib/Target/Mips/MipsOptions.td b/llvm/lib/Target/Mips/MipsOptions.td
new file mode 100644
index 00000000000000..22e0c8e652b538
--- /dev/null
+++ b/llvm/lib/Target/Mips/MipsOptions.td
@@ -0,0 +1,89 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+include "llvm/Option/LibraryOptions.td"
+
+def MipsOptions : OptionsStruct<prefix = "mips-">;
+
+// Mips16ISelLowering.cpp
+defm : BoolField<"mips16-dont-expand-cond-pseudo", "false",
+  "Don't expand conditional move related pseudos for Mips 16">;
+
+// MipsBranchExpansion.cpp
+defm : BoolField<"force-mips-long-branch", "false",
+  "MIPS: Expand all branches to long format">;
+defm : BoolField<"skip-mips-long-branch", "false",
+  "MIPS: Skip branch expansion pass">;
+
+// MipsConstantIslandPass.cpp
+// FIXME: This option should be removed once it has received sufficient testing.
+defm : BoolField<"mips-align-constant-islands", "true",
+  "Align constant islands in code">;
+// For testing purposes we tell it to not use relaxed load forms so that it will
+// split blocks.
+defm : BoolField<"mips-constant-islands-no-load-relaxation", "false",
+  "Don't relax loads to long loads - for testing purposes">;
+// Rather than do make check tests with huge amounts of code, we force the test
+// to use this amount.
+defm : ValueField<"mips-constant-islands-small-offset", "int", "0",
+  "Make small offsets be this amount for testing purposes">;
+
+// MipsDelaySlotFiller.cpp
+defm : BoolField<"disable-mips-delay-filler", "false",
+  "Fill all delay slots with NOPs">;
+defm : BoolField<"disable-mips-df-backward-search", "false",
+  "Disallow MIPS delay filler to search backward">;
+defm : BoolField<"disable-mips-df-forward-search", "true",
+  "Disallow MIPS delay filler to search forward">;
+defm : BoolField<"disable-mips-df-succbb-search", "true",
+  "Disallow MIPS delay filler to search successor basic blocks">;
+
+// MipsISelLowering.cpp
+defm : BoolField<"mips-tail-calls", "false",
+  "MIPS: permit tail calls">;
+
+// MipsOptimizePICCall.cpp
+defm : BoolField<"mips-erase-gp-opnd", "true",
+  "Erase GP Operand">;
+defm : BoolField<"mips-load-target-from-got", "true",
+  "Load target address from GOT">;
+
+// MipsOs16.cpp
+defm : ValueField<"mips32-function-mask", "StringRef", "",
+  "Force function to be mips32">;
+
+// MipsSEISelLowering.cpp
+defm : BoolField<"mno-ldc1-sdc1", "false",
+  "Expand double precision loads and stores to their single precision counterparts">;
+
+// MipsSubtarget.cpp
+defm : BoolField<"mgpopt", "false",
+  "Enable gp-relative addressing of mips small data items">;
+defm : EnumField<"mips-compact-branches", "CompactBranchPolicy", "CompactBranchPolicy::Optimal",
+  "never,optimal,always", ["CompactBranchPolicy::Never", "CompactBranchPolicy::Optimal", "CompactBranchPolicy::Always"],
+  "MIPS Specific: Compact branch policy">;
+defm : BoolField<"mips16-constant-islands", "true",
+  "Enable mips16 constant islands">;
+defm : BoolField<"mips16-hard-float", "false",
+  "Enable mips16 hard float">;
+
+// MipsTargetMachine.cpp
+defm : BoolField<"mfix4300", "false",
+  "Enable the VR4300 mulmul bug fix">;
+defm : BoolField<"mips-os16", "false",
+  "Compile all functions that don't use floating point as Mips 16">;
+
+// MipsTargetObjectFile.cpp
+defm : BoolField<"membedded-data", "false",
+  "MIPS: Try to allocate variables in the following sections if possible: .rodata, .sdata, .data">;
+defm : BoolField<"mextern-sdata", "true",
+  "MIPS: Use gp_rel for data that is not defined by the current object">;
+defm : ValueField<"mips-ssection-threshold", "unsigned", "8",
+  "Small data and bss section threshold size">;
+defm : BoolField<"mlocal-sdata", "true",
+  "MIPS: Use gp_rel for object-local data">;
diff --git a/llvm/lib/Target/Mips/MipsOs16.cpp b/llvm/lib/Target/Mips/MipsOs16.cpp
index f6346a8bbc8bcb..5d2c10960f5a31 100644
--- a/llvm/lib/Target/Mips/MipsOs16.cpp
+++ b/llvm/lib/Target/Mips/MipsOs16.cpp
@@ -11,10 +11,10 @@
 //===----------------------------------------------------------------------===//
 
 #include "Mips.h"
+#include "MipsSubtarget.h"
 #include "llvm/IR/Instructions.h"
 #include "llvm/IR/Module.h"
 #include "llvm/Pass.h"
-#include "llvm/Support/CommandLine.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/raw_ostream.h"
 
@@ -22,12 +22,6 @@ using namespace llvm;
 
 #define DEBUG_TYPE "mips-os16"
 
-static cl::opt<std::string> Mips32FunctionMask(
-  "mips32-function-mask",
-  cl::init(""),
-  cl::desc("Force function to be mips32"),
-  cl::Hidden);
-
 namespace {
   class MipsOs16 : public ModulePass {
   public:
@@ -108,7 +102,8 @@ static bool needsFP(Function &F) {
 
 
 bool MipsOs16::runOnModule(Module &M) {
-  bool usingMask = Mips32FunctionMask.length() > 0;
+  StringRef Mips32FunctionMask = MipsOptions::Global.mips32_function_mask;
+  bool usingMask = !Mips32FunctionMask.empty();
   bool doneUsingMask = false; // this will make it stop repeating
 
   LLVM_DEBUG(dbgs() << "Run on Module MipsOs16 \n"
@@ -126,7 +121,7 @@ bool MipsOs16::runOnModule(Module &M) {
     LLVM_DEBUG(dbgs() << "Working on " << F.getName() << "\n");
     if (usingMask) {
       if (!doneUsingMask) {
-        if (functionIndex == Mips32FunctionMask.length())
+        if (functionIndex == Mips32FunctionMask.size())
           functionIndex = 0;
         switch (Mips32FunctionMask[functionIndex]) {
         case '1':
diff --git a/llvm/lib/Target/Mips/MipsSEISelLowering.cpp b/llvm/lib/Target/Mips/MipsSEISelLowering.cpp
index b3de06a2844bb6..9edca90c71fc41 100644
--- a/llvm/lib/Target/Mips/MipsSEISelLowering.cpp
+++ b/llvm/lib/Target/Mips/MipsSEISelLowering.cpp
@@ -35,7 +35,6 @@
 #include "llvm/IR/Intrinsics.h"
 #include "llvm/IR/IntrinsicsMips.h"
 #include "llvm/Support/Casting.h"
-#include "llvm/Support/CommandLine.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/raw_ostream.h"
@@ -51,11 +50,6 @@ using namespace llvm;
 
 #define DEBUG_TYPE "mips-isel"
 
-static cl::opt<bool> NoDPLoadStore("mno-ldc1-sdc1", cl::init(false),
-                                   cl::desc("Expand double precision loads and "
-                                            "stores to their single precision "
-                                            "counterparts"));
-
 // Widen the v2 vectors to the register width, i.e. v2i16 -> v8i16,
 // v2i32 -> v4i32, etc, to ensure the correct rail size is used, i.e.
 // INST.h for v16, INST.w for v32, INST.d for v64.
@@ -251,7 +245,8 @@ MipsSETargetLowering::MipsSETargetLowering(const MipsTargetMachine &TM,
     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
   }
 
-  if (NoDPLoadStore || (Subtarget.hasMips1() && !Subtarget.hasMips2())) {
+  if (Subtarget.getCLOpts().mno_ldc1_sdc1 ||
+      (Subtarget.hasMips1() && !Subtarget.hasMips2())) {
     setOperationAction(ISD::LOAD, MVT::f64, Custom);
     setOperationAction(ISD::STORE, MVT::f64, Custom);
   }
@@ -1360,7 +1355,8 @@ void MipsSETargetLowering::getOpndList(
 SDValue MipsSETargetLowering::lowerLOAD(SDValue Op, SelectionDAG &DAG) const {
   LoadSDNode &Nd = *cast<LoadSDNode>(Op);
 
-  if (Nd.getMemoryVT() != MVT::f64 || (!NoDPLoadStore && Subtarget.hasMips2()))
+  if (Nd.getMemoryVT() != MVT::f64 ||
+      (!Subtarget.getCLOpts().mno_ldc1_sdc1 && Subtarget.hasMips2()))
     return MipsTargetLowering::lowerLOAD(Op, DAG);
 
   // Replace a double precision load with two i32 loads and a buildpair64.
@@ -1395,7 +1391,8 @@ SDValue MipsSETargetLowering::lowerLOAD(SDValue Op, SelectionDAG &DAG) const {
 SDValue MipsSETargetLowering::lowerSTORE(SDValue Op, SelectionDAG &DAG) const {
   StoreSDNode &Nd = *cast<StoreSDNode>(Op);
 
-  if (Nd.getMemoryVT() != MVT::f64 || (!NoDPLoadStore && Subtarget.hasMips2()))
+  if (Nd.getMemoryVT() != MVT::f64 ||
+      (!Subtarget.getCLOpts().mno_ldc1_sdc1 && Subtarget.hasMips2()))
     return MipsTargetLowering::lowerSTORE(Op, DAG);
 
   // Replace a double precision store with two extractelement64s and i32 stores.
diff --git a/llvm/lib/Target/Mips/MipsSubtarget.cpp b/llvm/lib/Target/Mips/MipsSubtarget.cpp
index 0d21f5d7982e85..f75a8c2c0e30ad 100644
--- a/llvm/lib/Target/Mips/MipsSubtarget.cpp
+++ b/llvm/lib/Target/Mips/MipsSubtarget.cpp
@@ -21,40 +21,20 @@
 #include "llvm/IR/Attributes.h"
 #include "llvm/IR/Function.h"
 #include "llvm/MC/TargetRegistry.h"
-#include "llvm/Support/CommandLine.h"
+#include "llvm/Option/LibraryOptions.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/raw_ostream.h"
 
 using namespace llvm;
 
-cl::opt<CompactBranchPolicy> MipsCompactBranchPolicy(
-    "mips-compact-branches", cl::init(CB_Optimal),
-    cl::desc("MIPS Specific: Compact branch policy."),
-    cl::values(clEnumValN(CB_Never, "never",
-                          "Do not use compact branches if possible."),
-               clEnumValN(CB_Optimal, "optimal",
-                          "Use compact branches where appropriate (default)."),
-               clEnumValN(CB_Always, "always",
-                          "Always use compact branches if possible.")));
-
 #define DEBUG_TYPE "mips-subtarget"
 
 #define GET_SUBTARGETINFO_TARGET_DESC
 #define GET_SUBTARGETINFO_CTOR
 #include "MipsGenSubtargetInfo.inc"
 
-static cl::opt<bool> Mips16HardFloat("mips16-hard-float", cl::NotHidden,
-                                     cl::desc("Enable mips16 hard float."),
-                                     cl::init(false));
-
-static cl::opt<bool>
-    Mips16ConstantIslands("mips16-constant-islands", cl::NotHidden,
-                          cl::desc("Enable mips16 constant islands."),
-                          cl::init(true));
-
-static cl::opt<bool>
-    GPOpt("mgpopt", cl::Hidden,
-          cl::desc("Enable gp-relative addressing of mips small data items"));
+#define OPTIONS_STRUCT_DEFS
+#include "MipsOptions.inc"
 
 bool MipsSubtarget::DspWarningPrinted = false;
 bool MipsSubtarget::MSAWarningPrinted = false;
@@ -69,18 +49,19 @@ MipsSubtarget::MipsSubtarget(const Triple &TT, StringRef CPU, StringRef FS,
                              const MipsTargetMachine &TM,
                              MaybeAlign StackAlignOverride)
     : MipsGenSubtargetInfo(TT, CPU, /*TuneCPU*/ CPU, FS),
+      CLOpts(TM.getCLOpts()), MCCLOpts(TM.getMCCLOpts()),
       MipsArchVersion(MipsDefault), IsLittle(little), IsSoftFloat(false),
       IsSingleFloat(false), IsFPXX(false), NoABICalls(false), Abs2008(false),
       IsFP64bit(false), UseOddSPReg(true), IsNaN2008bit(false),
       IsGP64bit(false), HasVFPU(false), HasCnMips(false), HasCnMipsP(false),
       IsR5900(false), FixR5900(false), HasMips3_32(false), HasMips3_32r2(false),
       HasMips4_32(false), HasMips4_32r2(false), HasMips5_32r2(false),
-      InMips16Mode(false), InMips16HardFloat(Mips16HardFloat),
+      InMips16Mode(false), InMips16HardFloat(CLOpts.mips16_hard_float),
       InMicroMipsMode(false), HasDSP(false), HasDSPR2(false), HasDSPR3(false),
       HasMSA(false), UseTCCInDIV(false), HasSym32(false), HasEVA(false),
       DisableMadd4(false), HasMT(false), HasCRC(false), HasVirt(false),
       HasGINV(false), UseIndirectJumpsHazard(false), StrictAlign(false),
-      UseCompactBranches(MipsCompactBranchPolicy != CB_Never),
+      UseCompactBranches(CLOpts.compact_branches != CompactBranchPolicy::Never),
       StackAlignOverride(StackAlignOverride), TM(TM),
       ABI(MipsABIInfo::computeTargetABI(TT, ABIName)),
       InstrInfo(
@@ -153,8 +134,8 @@ MipsSubtarget::MipsSubtarget(const Triple &TT, StringRef CPU, StringRef FS,
     NoABICalls = true;
 
   // Set UseSmallSection.
-  UseSmallSection = GPOpt;
-  if (!NoABICalls && GPOpt) {
+  UseSmallSection = CLOpts.mgpopt;
+  if (!NoABICalls && CLOpts.mgpopt) {
     errs() << "warning: cannot use small-data accesses for '-mabicalls'"
            << "\n";
     UseSmallSection = false;
@@ -265,10 +246,10 @@ MipsSubtarget::initializeSubtargetDependencies(StringRef CPU, StringRef FS,
   return *this;
 }
 
-bool MipsSubtarget::useConstantIslands() {
-  LLVM_DEBUG(dbgs() << "use constant islands " << Mips16ConstantIslands
+bool MipsSubtarget::useConstantIslands() const {
+  LLVM_DEBUG(dbgs() << "use constant islands " << CLOpts.mips16_constant_islands
                     << "\n");
-  return Mips16ConstantIslands;
+  return CLOpts.mips16_constant_islands;
 }
 
 Reloc::Model MipsSubtarget::getRelocationModel() const {
diff --git a/llvm/lib/Target/Mips/MipsSubtarget.h b/llvm/lib/Target/Mips/MipsSubtarget.h
index f431299784052b..26bdec22894afa 100644
--- a/llvm/lib/Target/Mips/MipsSubtarget.h
+++ b/llvm/lib/Target/Mips/MipsSubtarget.h
@@ -14,6 +14,7 @@
 #define LLVM_LIB_TARGET_MIPS_MIPSSUBTARGET_H
 
 #include "MCTargetDesc/MipsABIInfo.h"
+#include "MCTargetDesc/MipsMCOptions.h"
 #include "MipsFrameLowering.h"
 #include "MipsISelLowering.h"
 #include "MipsInstrInfo.h"
@@ -32,19 +33,27 @@
 namespace llvm {
 class StringRef;
 
-enum CompactBranchPolicy {
-  CB_Never,   ///< The policy 'never' may in some circumstances or for some
-              ///< ISAs not be absolutely adhered to.
-  CB_Optimal, ///< Optimal is the default and will produce compact branches
-              ///< when appropriate.
-  CB_Always   ///< 'always' may in some circumstances may not be
-              ///< absolutely adhered to, there may not be a corresponding
-              ///< compact form of a branch.
+enum class CompactBranchPolicy {
+  Never,   ///< The policy 'never' may in some circumstances or for some
+           ///< ISAs not be absolutely adhered to.
+  Optimal, ///< Optimal is the default and will produce compact branches
+           ///< when appropriate.
+  Always   ///< 'always' may in some circumstances may not be
+           ///< absolutely adhered to, there may not be a corresponding
+           ///< compact form of a branch.
 };
+} // namespace llvm
 
+#define OPTIONS_STRUCT_DECL
+#include "MipsOptions.inc"
+
+namespace llvm {
 class MipsTargetMachine;
 
 class MipsSubtarget : public MipsGenSubtargetInfo {
+  const MipsOptions &CLOpts;
+  const MipsMCOptions &MCCLOpts;
+
   virtual void anchor();
 
   enum MipsArchEnum {
@@ -368,7 +377,7 @@ class MipsSubtarget : public MipsGenSubtargetInfo {
 
   // for now constant islands are on for the whole compilation unit but we only
   // really use them if in addition we are in mips16 mode
-  static bool useConstantIslands();
+  bool useConstantIslands() const;
 
   Align getStackAlignment() const { return stackAlignment; }
 
@@ -389,6 +398,8 @@ class MipsSubtarget : public MipsGenSubtargetInfo {
 
   const SelectionDAGTargetInfo *getSelectionDAGInfo() const override;
 
+  const MipsOptions &getCLOpts() const { return CLOpts; }
+  const MipsMCOptions &getMCCLOpts() const { return MCCLOpts; }
   const MipsInstrInfo *getInstrInfo() const override { return InstrInfo.get(); }
   const TargetFrameLowering *getFrameLowering() const override {
     return FrameLowering.get();
diff --git a/llvm/lib/Target/Mips/MipsTargetMachine.cpp b/llvm/lib/Target/Mips/MipsTargetMachine.cpp
index b0d76b0aa633a2..c9000cf5ed8f22 100644
--- a/llvm/lib/Target/Mips/MipsTargetMachine.cpp
+++ b/llvm/lib/Target/Mips/MipsTargetMachine.cpp
@@ -36,6 +36,7 @@
 #include "llvm/IR/Function.h"
 #include "llvm/InitializePasses.h"
 #include "llvm/MC/TargetRegistry.h"
+#include "llvm/Option/LibraryOptions.h"
 #include "llvm/Support/CodeGen.h"
 #include "llvm/Support/Compiler.h"
 #include "llvm/Support/Debug.h"
@@ -48,16 +49,8 @@ using namespace llvm;
 
 #define DEBUG_TYPE "mips"
 
-static cl::opt<bool>
-    EnableMulMulFix("mfix4300", cl::init(false),
-                    cl::desc("Enable the VR4300 mulmul bug fix."), cl::Hidden);
-
-static cl::opt<bool> MipsOs16(
-    "mips-os16", cl::init(false),
-    cl::desc("Compile all functions that don't use floating point as Mips 16"),
-    cl::Hidden);
-
 extern "C" LLVM_ABI LLVM_EXTERNAL_VISIBILITY void LLVMInitializeMipsTarget() {
+  static opt::RegisterLibraryOptions<MipsOptions> O;
   // Register the target.
   RegisterTargetMachine<MipsebTargetMachine> X(getTheMipsTarget());
   RegisterTargetMachine<MipselTargetMachine> Y(getTheMipselTarget());
@@ -103,6 +96,7 @@ MipsTargetMachine::MipsTargetMachine(const Target &T, const Triple &TT,
     : CodeGenTargetMachineImpl(T, TT, CPU, FS, Options,
                                getEffectiveRelocModel(RM),
                                getEffectiveCodeModel(CM, CodeModel::Small), OL),
+      CLOpts(MipsOptions::Global), MCCLOpts(MipsMCOptions::Global),
       isLittle(isLittle), IsJIT(JIT),
       DefaultSubtarget(TT, CPU, FS, Options.MCOptions.getABIName(), isLittle,
                        *this, std::nullopt),
@@ -222,7 +216,7 @@ std::unique_ptr<CSEConfigBase> MipsPassConfig::getCSEConfig() const {
 void MipsPassConfig::addIRPasses() {
   TargetPassConfig::addIRPasses();
   addPass(createAtomicExpandLegacyPass());
-  if (MipsOs16)
+  if (getMipsTargetMachine().getCLOpts().os16)
     addPass(createMipsOs16Pass());
   addPass(createMips16HardFloatPass());
 }
@@ -263,7 +257,7 @@ void MipsPassConfig::addPreEmitPass() {
 
   // This pass inserts a nop instruction between two back-to-back multiplication
   // instructions when the "mfix4300" flag is passed.
-  if (EnableMulMulFix)
+  if (getMipsTargetMachine().getCLOpts().mfix4300)
     addPass(createMipsMulMulBugPass());
 
   // The delay slot filler pass can potientially create forbidden slot hazards
diff --git a/llvm/lib/Target/Mips/MipsTargetMachine.h b/llvm/lib/Target/Mips/MipsTargetMachine.h
index 3103ca252bf22f..f3206aa5e53c1a 100644
--- a/llvm/lib/Target/Mips/MipsTargetMachine.h
+++ b/llvm/lib/Target/Mips/MipsTargetMachine.h
@@ -25,6 +25,8 @@
 namespace llvm {
 
 class MipsTargetMachine : public CodeGenTargetMachineImpl {
+  const MipsOptions &CLOpts;
+  const MipsMCOptions &MCCLOpts;
   bool isLittle;
   bool IsJIT;
   // Used to initialize module-wide object-file policy.
@@ -43,6 +45,8 @@ class MipsTargetMachine : public CodeGenTargetMachineImpl {
 
   TargetTransformInfo getTargetTransformInfo(const Function &F) const override;
 
+  const MipsOptions &getCLOpts() const { return CLOpts; }
+  const MipsMCOptions &getMCCLOpts() const { return MCCLOpts; }
   const MipsSubtarget *getSubtargetImpl(const Function &F) const override;
 
   // Pass Pipeline Configuration
diff --git a/llvm/lib/Target/Mips/MipsTargetObjectFile.cpp b/llvm/lib/Target/Mips/MipsTargetObjectFile.cpp
index 3ca44a2ab3e378..e4d9fbadc6dcad 100644
--- a/llvm/lib/Target/Mips/MipsTargetObjectFile.cpp
+++ b/llvm/lib/Target/Mips/MipsTargetObjectFile.cpp
@@ -9,37 +9,15 @@
 #include "MipsTargetObjectFile.h"
 #include "MCTargetDesc/MipsMCAsmInfo.h"
 #include "MipsSubtarget.h"
+#include "MipsTargetMachine.h"
 #include "llvm/BinaryFormat/ELF.h"
 #include "llvm/IR/DataLayout.h"
 #include "llvm/IR/GlobalVariable.h"
 #include "llvm/MC/MCContext.h"
 #include "llvm/MC/MCSectionELF.h"
-#include "llvm/Support/CommandLine.h"
 #include "llvm/Target/TargetMachine.h"
 using namespace llvm;
 
-static cl::opt<unsigned>
-SSThreshold("mips-ssection-threshold", cl::Hidden,
-            cl::desc("Small data and bss section threshold size (default=8)"),
-            cl::init(8));
-
-static cl::opt<bool>
-LocalSData("mlocal-sdata", cl::Hidden,
-           cl::desc("MIPS: Use gp_rel for object-local data."),
-           cl::init(true));
-
-static cl::opt<bool>
-ExternSData("mextern-sdata", cl::Hidden,
-            cl::desc("MIPS: Use gp_rel for data that is not defined by the "
-                     "current object."),
-            cl::init(true));
-
-static cl::opt<bool>
-EmbeddedData("membedded-data", cl::Hidden,
-             cl::desc("MIPS: Try to allocate variables in the following"
-                      " sections if possible: .rodata, .sdata, .data ."),
-             cl::init(false));
-
 void MipsTargetObjectFile::Initialize(MCContext &Ctx, const TargetMachine &TM){
   TargetLoweringObjectFileELF::Initialize(Ctx, TM);
 
@@ -55,10 +33,10 @@ void MipsTargetObjectFile::Initialize(MCContext &Ctx, const TargetMachine &TM){
 // A address must be loaded from a small section if its size is less than the
 // small section size threshold. Data in this section must be addressed using
 // gp_rel operator.
-static bool IsInSmallSection(uint64_t Size) {
+static bool isInSmallSection(const MipsOptions &CLOpts, uint64_t Size) {
   // gcc has traditionally not treated zero-sized objects as small data, so this
   // is effectively part of the ABI.
-  return Size > 0 && Size <= SSThreshold;
+  return Size > 0 && Size <= CLOpts.ssection_threshold;
 }
 
 /// Return true if this global address should be placed into small data/bss
@@ -88,6 +66,8 @@ bool MipsTargetObjectFile::IsGlobalInSmallSection(const GlobalObject *GO,
 /// kind.
 bool MipsTargetObjectFile::IsGlobalInSmallSectionImpl(
     const GlobalObject *GO) const {
+  const MipsOptions &CLOpts =
+      static_cast<const MipsTargetMachine *>(TM)->getCLOpts();
   // Only global variables, not functions.
   const GlobalVariable *GVA = dyn_cast<GlobalVariable>(GO);
   if (!GVA)
@@ -117,16 +97,17 @@ bool MipsTargetObjectFile::IsGlobalInSmallSectionImpl(
     return false;
 
   // Enforce -mlocal-sdata.
-  if (!LocalSData && GVA->hasLocalLinkage())
+  if (!CLOpts.mlocal_sdata && GVA->hasLocalLinkage())
     return false;
 
   // Enforce -mextern-sdata.
-  if (!ExternSData && ((GVA->hasExternalLinkage() && GVA->isDeclaration()) ||
-                       GVA->hasCommonLinkage()))
+  if (!CLOpts.mextern_sdata &&
+      ((GVA->hasExternalLinkage() && GVA->isDeclaration()) ||
+       GVA->hasCommonLinkage()))
     return false;
 
   // Enforce -membedded-data.
-  if (EmbeddedData && GVA->isConstant())
+  if (CLOpts.membedded_data && GVA->isConstant())
     return false;
 
   Type *Ty = GVA->getValueType();
@@ -137,8 +118,7 @@ bool MipsTargetObjectFile::IsGlobalInSmallSectionImpl(
   if (!Ty->isSized())
     return false;
 
-  return IsInSmallSection(
-      GVA->getDataLayout().getTypeAllocSize(Ty));
+  return isInSmallSection(CLOpts, GVA->getDataLayout().getTypeAllocSize(Ty));
 }
 
 MCSection *MipsTargetObjectFile::SelectSectionForGlobal(
@@ -165,8 +145,10 @@ bool MipsTargetObjectFile::IsConstantInSmallSection(const DataLayout &DL,
   bool UseSmallSection =
       F ? TM->getSubtarget<MipsSubtarget>(*F).useSmallSection()
         : this->UseSmallSection;
-  return UseSmallSection && CN && LocalSData &&
-         IsInSmallSection(DL.getTypeAllocSize(CN->getType()));
+  const MipsOptions &CLOpts =
+      static_cast<const MipsTargetMachine *>(TM)->getCLOpts();
+  return UseSmallSection && CN && CLOpts.mlocal_sdata &&
+         isInSmallSection(CLOpts, DL.getTypeAllocSize(CN->getType()));
 }
 
 /// Return true if this constant should be placed into small data section.
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 91ca99b03cdbc7..c9504bd8fab57b 100644
--- a/llvm/utils/gn/secondary/llvm/lib/Target/Mips/BUILD.gn
+++ b/llvm/utils/gn/secondary/llvm/lib/Target/Mips/BUILD.gn
@@ -51,6 +51,12 @@ tablegen("MipsGenSDNodeInfo") {
   td_file = "Mips.td"
 }
 
+tablegen("MipsOptions") {
+  visibility = [ ":LLVMMipsCodeGen" ]
+  args = [ "-gen-opt-parser-defs" ]
+  td_file = "MipsOptions.td"
+}
+
 static_library("LLVMMipsCodeGen") {
   deps = [
     ":MipsGenCallingConv",
@@ -61,6 +67,7 @@ static_library("LLVMMipsCodeGen") {
     ":MipsGenPostLegalizeGICombiner",
     ":MipsGenRegisterBank",
     ":MipsGenSDNodeInfo",
+    ":MipsOptions",
     "MCTargetDesc",
     "TargetInfo",
     "//llvm/include/llvm/Config:llvm-config",
@@ -71,6 +78,7 @@ static_library("LLVMMipsCodeGen") {
     "//llvm/lib/CodeGen/SelectionDAG",
     "//llvm/lib/IR",
     "//llvm/lib/MC",
+    "//llvm/lib/Option",
     "//llvm/lib/Support",
     "//llvm/lib/Target",
     "//llvm/lib/TargetParser",
diff --git a/llvm/utils/gn/secondary/llvm/lib/Target/Mips/MCTargetDesc/BUILD.gn b/llvm/utils/gn/secondary/llvm/lib/Target/Mips/MCTargetDesc/BUILD.gn
index 061adf054b40e9..37a6164e1a668f 100644
--- a/llvm/utils/gn/secondary/llvm/lib/Target/Mips/MCTargetDesc/BUILD.gn
+++ b/llvm/utils/gn/secondary/llvm/lib/Target/Mips/MCTargetDesc/BUILD.gn
@@ -30,6 +30,12 @@ tablegen("MipsGenSubtargetInfo") {
   td_file = "../Mips.td"
 }
 
+tablegen("MipsMCOptions") {
+  visibility = [ ":tablegen" ]
+  args = [ "-gen-opt-parser-defs" ]
+  td_file = "MipsMCOptions.td"
+}
+
 # This should contain tablegen targets generating .inc files included
 # by other targets. .inc files only used by .cpp files in this directory
 # should be in deps on the static_library instead.
@@ -42,6 +48,7 @@ group("tablegen") {
     ":MipsGenInstrInfo",
     ":MipsGenRegisterInfo",
     ":MipsGenSubtargetInfo",
+    ":MipsMCOptions",
   ]
 }
 
@@ -53,6 +60,7 @@ static_library("MCTargetDesc") {
     ":MipsGenMCCodeEmitter",
     "//llvm/lib/CodeGen",
     "//llvm/lib/MC",
+    "//llvm/lib/Option",
     "//llvm/lib/Support",
     "//llvm/lib/Target/Mips/AsmParser:MipsGenAsmMatcher",
     "//llvm/lib/Target/Mips/TargetInfo",
diff --git a/utils/bazel/llvm-project-overlay/llvm/BUILD.bazel b/utils/bazel/llvm-project-overlay/llvm/BUILD.bazel
index 8f0c5d24ee5315..2bd09fa8dd578c 100644
--- a/utils/bazel/llvm-project-overlay/llvm/BUILD.bazel
+++ b/utils/bazel/llvm-project-overlay/llvm/BUILD.bazel
@@ -3257,6 +3257,10 @@ llvm_target_lib_list = [lib for lib in [
                 "lib/Target/Mips/MipsGenSubtargetInfo.inc",
             ),
         ],
+        "tbl_deps": [
+            ":MipsMCOptionsTableGen",
+            ":MipsOptionsTableGen",
+        ],
     },
     {
         "name": "MSP430",
@@ -4118,6 +4122,24 @@ gentbl_cc_library(
     deps = [":OptParserTdFiles"],
 )
 
+gentbl_cc_library(
+    name = "MipsMCOptionsTableGen",
+    strip_include_prefix = "lib/Target/Mips",
+    tbl_outs = {"lib/Target/Mips/MipsMCOptions.inc": ["-gen-opt-parser-defs"]},
+    tblgen = ":llvm-tblgen",
+    td_file = "lib/Target/Mips/MCTargetDesc/MipsMCOptions.td",
+    deps = [":OptParserTdFiles"],
+)
+
+gentbl_cc_library(
+    name = "MipsOptionsTableGen",
+    strip_include_prefix = "lib/Target/Mips",
+    tbl_outs = {"lib/Target/Mips/MipsOptions.inc": ["-gen-opt-parser-defs"]},
+    tblgen = ":llvm-tblgen",
+    td_file = "lib/Target/Mips/MipsOptions.td",
+    deps = [":OptParserTdFiles"],
+)
+
 gentbl_cc_library(
     name = "RISCVMCOptionsTableGen",
     strip_include_prefix = "lib/Target/RISCV",



More information about the llvm-commits mailing list