[llvm] [TableGen] Add a backend to generate MacroFusion predicators (PR #72222)

Wang Pengcheng via llvm-commits llvm-commits at lists.llvm.org
Tue Nov 14 22:37:52 PST 2023


https://github.com/wangpc-pp updated https://github.com/llvm/llvm-project/pull/72222

>From ead0fdf883643d6c0494d916e9dad72ec6257c85 Mon Sep 17 00:00:00 2001
From: wangpc <wangpengcheng.pp at bytedance.com>
Date: Fri, 10 Nov 2023 18:18:18 +0800
Subject: [PATCH] [TableGen] Add a backend to generate MacroFusion predicators

The MacroFusion contains four predicates, which are for first MI,
second MI, prolog and epilog.

The generated code will be like:
```
bool isNAME(const TargetInstrInfo &TII,
            const TargetSubtargetInfo &STI,
            const MachineInstr *FirstMI,
            const MachineInstr &SecondMI) {
  auto &MRI = SecondMI.getMF()->getRegInfo();
  /* Prolog */
  /* Predicate for `FirstMI` */
  /* Predicate for `SecondMI` */
  /* Epilog */
  return true;
}
```

The predicates of first/second MI can be any predicates defined in
`TargetInstrPredicate.td`
---
 .../llvm/Target/TargetInstrPredicate.td       |   6 +
 llvm/include/llvm/Target/TargetSchedule.td    |  61 ++++++
 llvm/utils/TableGen/CMakeLists.txt            |   1 +
 .../TableGen/MacroFusionPredicatorEmitter.cpp | 177 ++++++++++++++++++
 llvm/utils/TableGen/PredicateExpander.cpp     |   8 +
 llvm/utils/TableGen/PredicateExpander.h       |   1 +
 6 files changed, 254 insertions(+)
 create mode 100644 llvm/utils/TableGen/MacroFusionPredicatorEmitter.cpp

diff --git a/llvm/include/llvm/Target/TargetInstrPredicate.td b/llvm/include/llvm/Target/TargetInstrPredicate.td
index 9f2cde9d923050a..82c4c7b23a49b6a 100644
--- a/llvm/include/llvm/Target/TargetInstrPredicate.td
+++ b/llvm/include/llvm/Target/TargetInstrPredicate.td
@@ -95,6 +95,12 @@ class MCOperandPredicate<int Index> : MCInstPredicate {
 // Return true if machine operand at position `Index` is a register operand.
 class CheckIsRegOperand<int Index> : MCOperandPredicate<Index>;
 
+// Return true if machine operand at position `Index` is a virtual register operand.
+class CheckIsVRegOperand<int Index> : MCOperandPredicate<Index>;
+
+// Return true if machine operand at position `Index` is not a virtual register operand.
+class CheckIsNotVRegOperand<int Index> : CheckNot<CheckIsVRegOperand<Index>>;
+
 // Return true if machine operand at position `Index` is an immediate operand.
 class CheckIsImmOperand<int Index> : MCOperandPredicate<Index>;
 
diff --git a/llvm/include/llvm/Target/TargetSchedule.td b/llvm/include/llvm/Target/TargetSchedule.td
index 949baa5d2105c45..699d35875b1fbdb 100644
--- a/llvm/include/llvm/Target/TargetSchedule.td
+++ b/llvm/include/llvm/Target/TargetSchedule.td
@@ -469,6 +469,67 @@ class SchedAlias<SchedReadWrite match, SchedReadWrite alias> {
   SchedMachineModel SchedModel = ?;
 }
 
+// Base class of MacroFusionPredicate, etc. The avaliable variables are:
+// * const TargetInstrInfo &TII
+// * const TargetSubtargetInfo &STI
+// * const MachineRegisterInfo &MRI
+// * const MachineInstr *FirstMI
+// * const MachineInstr &SecondMI
+class MacroFusionPredicateBase;
+
+// MacroFusionPredicate with raw code predicate.
+class MacroFusionPredicate<code pred> : MacroFusionPredicateBase {
+  code Predicate = pred;
+}
+
+// Tie firstOpIdx and secondOpIdx. The operand of `FirstMI` at position
+// `firstOpIdx` should be the same as the operand of `SenondMI` at position
+// `secondOpIdx`.
+class TieReg<int firstOpIdx, int secondOpIdx> : MacroFusionPredicateBase {
+  int FirstOpIdx = firstOpIdx;
+  int SecondOpIdx = secondOpIdx;
+}
+
+// A predicate for wildcard. The generated code will be like:
+// ```
+// if (!FirstMI)
+//   return ReturnValue;
+// ```
+class WildcardPred<bit ret> : MacroFusionPredicateBase {
+  bit ReturnValue = ret;
+}
+def WildcardFalse : WildcardPred<0>;
+def WildcardTrue : WildcardPred<1>;
+
+// Indicates that the destination register of `FirstMI` should be have one
+// use if it is an virtual register.
+class OneUsePred : MacroFusionPredicateBase;
+def OneUse : OneUsePred;
+
+// Handled by MacroFusionPredicatorEmitter backend.
+// The generated predicator will be like:
+// ```
+// bool isNAME(const TargetInstrInfo &TII,
+//             const TargetSubtargetInfo &STI,
+//             const MachineInstr *FirstMI,
+//             const MachineInstr &SecondMI) {
+//   auto &MRI = SecondMI.getMF()->getRegInfo();
+//   /* Prolog */
+//   /* Predicate for `FirstMI` */
+//   /* Predicate for `SecondMI` */
+//   /* Epilog */
+//   return true;
+// }
+// ```
+class MacroFusion<MCInstPredicate first, MCInstPredicate second,
+                  list<MacroFusionPredicateBase> prolog = [],
+                  list<MacroFusionPredicateBase> epilog = []> {
+  MCInstPredicate First = first;
+  MCInstPredicate Second = second;
+  list<MacroFusionPredicateBase> Prolog = prolog;
+  list<MacroFusionPredicateBase> Epilog = epilog;
+}
+
 // Allow the definition of processor register files for register renaming
 // purposes.
 //
diff --git a/llvm/utils/TableGen/CMakeLists.txt b/llvm/utils/TableGen/CMakeLists.txt
index 071ea3bc07054bb..f765cc36d3bebed 100644
--- a/llvm/utils/TableGen/CMakeLists.txt
+++ b/llvm/utils/TableGen/CMakeLists.txt
@@ -72,6 +72,7 @@ add_tablegen(llvm-tblgen LLVM
   PredicateExpander.cpp
   PseudoLoweringEmitter.cpp
   CompressInstEmitter.cpp
+  MacroFusionPredicatorEmitter.cpp
   RegisterBankEmitter.cpp
   RegisterInfoEmitter.cpp
   SearchableTableEmitter.cpp
diff --git a/llvm/utils/TableGen/MacroFusionPredicatorEmitter.cpp b/llvm/utils/TableGen/MacroFusionPredicatorEmitter.cpp
new file mode 100644
index 000000000000000..c4da91542128b21
--- /dev/null
+++ b/llvm/utils/TableGen/MacroFusionPredicatorEmitter.cpp
@@ -0,0 +1,177 @@
+//===--- MacroFusionPredicatorEmitter.cpp - Generator for MacroFusion ----===//
+//
+// 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
+//
+// MacroFusionPredicatorEmitter implements a TableGen-driven predicators
+// generator for MacroFusion.
+//
+//===---------------------------------------------------------------------===//
+
+#include "CodeGenTarget.h"
+#include "PredicateExpander.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/Support/Debug.h"
+#include "llvm/TableGen/Error.h"
+#include "llvm/TableGen/Record.h"
+#include "llvm/TableGen/TableGenBackend.h"
+#include <set>
+#include <vector>
+
+using namespace llvm;
+
+#define DEBUG_TYPE "macro-fusion-predicator"
+
+namespace {
+class MacroFusionPredicatorEmitter {
+  RecordKeeper &Records;
+  CodeGenTarget Target;
+
+  void emitMacroFusionDecl(std::vector<Record *> MacroFusions,
+                           PredicateExpander &PE, raw_ostream &OS);
+  void emitMacroFusionImpl(std::vector<Record *> MacroFusions,
+                           PredicateExpander &PE, raw_ostream &OS);
+  void emitFirstPredicate(Record *FirstPredicate, PredicateExpander &PE,
+                          raw_ostream &OS);
+  void emitSecondPredicate(Record *SecondPredicate, PredicateExpander &PE,
+                           raw_ostream &OS);
+  void emitPrologAndEpilog(std::vector<Record *> Predicates,
+                           PredicateExpander &PE, raw_ostream &OS);
+
+public:
+  MacroFusionPredicatorEmitter(RecordKeeper &R) : Records(R), Target(R) {}
+
+  void run(raw_ostream &OS);
+};
+} // End anonymous namespace.
+
+void MacroFusionPredicatorEmitter::emitMacroFusionDecl(
+    std::vector<Record *> MacroFusions, PredicateExpander &PE,
+    raw_ostream &OS) {
+  OS << "#ifdef GET_" << Target.getName() << "_MACRO_FUSION_PRED_DECL\n\n";
+
+  for (Record *MacroFusion : MacroFusions) {
+    OS << "bool is" << MacroFusion->getName() << "(const TargetInstrInfo &, "
+       << "const TargetSubtargetInfo &, "
+       << "const MachineInstr *, "
+       << "const MachineInstr &);\n";
+  }
+
+  OS << "\n#endif\n";
+  OS << "#undef GET_" << Target.getName() << "_MACRO_FUSION_PRED_DECL\n";
+}
+
+void MacroFusionPredicatorEmitter::emitMacroFusionImpl(
+    std::vector<Record *> MacroFusions, PredicateExpander &PE,
+    raw_ostream &OS) {
+  OS << "#ifdef GET_" << Target.getName() << "_MACRO_FUSION_PRED_IMPL\n\n";
+
+  for (Record *MacroFusion : MacroFusions) {
+    Record *First = MacroFusion->getValueAsDef("First");
+    Record *Second = MacroFusion->getValueAsDef("Second");
+    std::vector<Record *> Prolog = MacroFusion->getValueAsListOfDefs("Prolog");
+    std::vector<Record *> Epilog = MacroFusion->getValueAsListOfDefs("Epilog");
+
+    OS << "bool is" << MacroFusion->getName() << "(\n";
+    OS.indent(5) << "const TargetInstrInfo &TII,\n";
+    OS.indent(5) << "const TargetSubtargetInfo &STI,\n";
+    OS.indent(5) << "const MachineInstr *FirstMI,\n";
+    OS.indent(5) << "const MachineInstr &SecondMI) {\n";
+    OS.indent(2) << "auto &MRI = SecondMI.getMF()->getRegInfo();\n";
+
+    emitFirstPredicate(First, PE, OS);
+    emitSecondPredicate(Second, PE, OS);
+
+    if (!Prolog.empty())
+      emitPrologAndEpilog(Prolog, PE, OS);
+
+    OS.indent(2) << "if (!matchFirst(FirstMI))\n";
+    OS.indent(2) << "  return false;\n";
+    OS.indent(2) << "if (!matchSecond(&SecondMI))\n";
+    OS.indent(2) << "  return false;\n";
+
+    if (!Epilog.empty())
+      emitPrologAndEpilog(Epilog, PE, OS);
+
+    OS.indent(2) << "return true;\n";
+    OS << "}\n";
+  }
+
+  OS << "\n#endif\n";
+  OS << "#undef GET_" << Target.getName() << "_MACRO_FUSION_PRED_IMPL\n\n";
+}
+
+void MacroFusionPredicatorEmitter::emitFirstPredicate(Record *FirstPredicate,
+                                                      PredicateExpander &PE,
+                                                      raw_ostream &OS) {
+
+  OS.indent(2) << "auto matchFirst = [&](const MachineInstr *MI) {\n";
+  OS.indent(4) << "return ";
+  PE.expandPredicate(OS, FirstPredicate);
+  OS << ";\n";
+  OS.indent(2) << "};\n";
+}
+
+void MacroFusionPredicatorEmitter::emitSecondPredicate(Record *SecondPredicate,
+                                                       PredicateExpander &PE,
+                                                       raw_ostream &OS) {
+  OS.indent(2) << "auto matchSecond = [&](const MachineInstr *MI) {\n";
+  OS.indent(4) << "return ";
+  PE.expandPredicate(OS, SecondPredicate);
+  OS << ";\n";
+  OS.indent(2) << "};\n";
+}
+
+void MacroFusionPredicatorEmitter::emitPrologAndEpilog(
+    std::vector<Record *> Predicates, PredicateExpander &PE, raw_ostream &OS) {
+  for (auto *Predicate : Predicates) {
+    if (Predicate->isSubClassOf("MacroFusionPredicate"))
+      OS << Predicate->getValueAsString("Predicate");
+    else if (Predicate->isSubClassOf("WildcardPred")) {
+      OS.indent(2) << "if (!FirstMI)\n";
+      OS.indent(2) << "  return "
+                   << (Predicate->getValueAsBit("ReturnValue") ? "true"
+                                                               : "false")
+                   << ";\n";
+    } else if (Predicate->isSubClassOf("OneUsePred")) {
+      OS.indent(2) << "Register FirstDest = FirstMI->getOperand(0).getReg();\n";
+      OS.indent(2)
+          << "if (FirstDest.isVirtual() && !MRI.hasOneNonDBGUse(FirstDest))\n";
+      OS.indent(2) << "  return false;\n";
+    } else if (Predicate->isSubClassOf("TieReg")) {
+      int FirstOpIdx = Predicate->getValueAsInt("FirstOpIdx");
+      int SecondOpIdx = Predicate->getValueAsInt("SecondOpIdx");
+      OS.indent(2) << "if (!(FirstMI->getOperand(" << FirstOpIdx
+                   << ").isReg() &&\n";
+      OS.indent(2) << "      SecondMI.getOperand(" << SecondOpIdx
+                   << ").isReg() &&\n";
+      OS.indent(2) << "      FirstMI->getOperand(" << FirstOpIdx
+                   << ").getReg() == SecondMI.getOperand(" << SecondOpIdx
+                   << ").getReg()))\n";
+      OS.indent(2) << "  return false;\n";
+    } else
+      PrintFatalError(Predicate->getLoc(),
+                      "Unsupported subclass of 'MacroFusionPredicateBase':" +
+                          Predicate->getType()->getAsString());
+  }
+}
+
+void MacroFusionPredicatorEmitter::run(raw_ostream &OS) {
+  // Emit file header.
+  emitSourceFileHeader("Macro Fusion Predicators", OS);
+
+  PredicateExpander PE(Target.getName());
+  PE.setByRef(false);
+  PE.setExpandForMC(false);
+
+  std::vector<Record *> MacroFusions =
+      Records.getAllDerivedDefinitions("MacroFusion");
+  // Sort macro fusions by name.
+  llvm::sort(MacroFusions, LessRecord());
+  emitMacroFusionDecl(MacroFusions, PE, OS);
+  emitMacroFusionImpl(MacroFusions, PE, OS);
+}
+
+static TableGen::Emitter::OptClass<MacroFusionPredicatorEmitter>
+    X("gen-macro-fusion-pred", "Generate macro fusion predicators.");
diff --git a/llvm/utils/TableGen/PredicateExpander.cpp b/llvm/utils/TableGen/PredicateExpander.cpp
index 8f96d3307ded8be..d3a73e02cd916f8 100644
--- a/llvm/utils/TableGen/PredicateExpander.cpp
+++ b/llvm/utils/TableGen/PredicateExpander.cpp
@@ -194,6 +194,11 @@ void PredicateExpander::expandCheckIsRegOperand(raw_ostream &OS, int OpIndex) {
      << "getOperand(" << OpIndex << ").isReg() ";
 }
 
+void PredicateExpander::expandCheckIsVRegOperand(raw_ostream &OS, int OpIndex) {
+  OS << (shouldNegate() ? "!" : "") << "MI" << (isByRef() ? "." : "->")
+     << "getOperand(" << OpIndex << ").getReg().isVirtual()";
+}
+
 void PredicateExpander::expandCheckIsImmOperand(raw_ostream &OS, int OpIndex) {
   OS << (shouldNegate() ? "!" : "") << "MI" << (isByRef() ? "." : "->")
      << "getOperand(" << OpIndex << ").isImm() ";
@@ -319,6 +324,9 @@ void PredicateExpander::expandPredicate(raw_ostream &OS, const Record *Rec) {
   if (Rec->isSubClassOf("CheckIsRegOperand"))
     return expandCheckIsRegOperand(OS, Rec->getValueAsInt("OpIndex"));
 
+  if (Rec->isSubClassOf("CheckIsVRegOperand"))
+    return expandCheckIsVRegOperand(OS, Rec->getValueAsInt("OpIndex"));
+
   if (Rec->isSubClassOf("CheckIsImmOperand"))
     return expandCheckIsImmOperand(OS, Rec->getValueAsInt("OpIndex"));
 
diff --git a/llvm/utils/TableGen/PredicateExpander.h b/llvm/utils/TableGen/PredicateExpander.h
index 27f049a715aad56..cfb0a3d51e67764 100644
--- a/llvm/utils/TableGen/PredicateExpander.h
+++ b/llvm/utils/TableGen/PredicateExpander.h
@@ -75,6 +75,7 @@ class PredicateExpander {
                                bool IsCheckAll);
   void expandTIIFunctionCall(raw_ostream &OS, StringRef MethodName);
   void expandCheckIsRegOperand(raw_ostream &OS, int OpIndex);
+  void expandCheckIsVRegOperand(raw_ostream &OS, int OpIndex);
   void expandCheckIsImmOperand(raw_ostream &OS, int OpIndex);
   void expandCheckInvalidRegOperand(raw_ostream &OS, int OpIndex);
   void expandCheckFunctionPredicate(raw_ostream &OS, StringRef MCInstFn,



More information about the llvm-commits mailing list