1 //===- GlobalISelEmitter.cpp - Generate an instruction selector -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 /// \file
11 /// This tablegen backend emits code for use by the GlobalISel instruction
12 /// selector. See include/llvm/CodeGen/TargetGlobalISel.td.
13 ///
14 /// This file analyzes the patterns recognized by the SelectionDAGISel tablegen
15 /// backend, filters out the ones that are unsupported, maps
16 /// SelectionDAG-specific constructs to their GlobalISel counterpart
17 /// (when applicable: MVT to LLT;  SDNode to generic Instruction).
18 ///
19 /// Not all patterns are supported: pass the tablegen invocation
20 /// "-warn-on-skipped-patterns" to emit a warning when a pattern is skipped,
21 /// as well as why.
22 ///
23 /// The generated file defines a single method:
24 ///     bool <Target>InstructionSelector::selectImpl(MachineInstr &I) const;
25 /// intended to be used in InstructionSelector::select as the first-step
26 /// selector for the patterns that don't require complex C++.
27 ///
28 /// FIXME: We'll probably want to eventually define a base
29 /// "TargetGenInstructionSelector" class.
30 ///
31 //===----------------------------------------------------------------------===//
32 
33 #include "CodeGenDAGPatterns.h"
34 #include "SubtargetFeatureInfo.h"
35 #include "llvm/ADT/Optional.h"
36 #include "llvm/ADT/SmallSet.h"
37 #include "llvm/ADT/Statistic.h"
38 #include "llvm/CodeGen/MachineValueType.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/Error.h"
41 #include "llvm/Support/LowLevelTypeImpl.h"
42 #include "llvm/Support/ScopedPrinter.h"
43 #include "llvm/TableGen/Error.h"
44 #include "llvm/TableGen/Record.h"
45 #include "llvm/TableGen/TableGenBackend.h"
46 #include <string>
47 #include <numeric>
48 using namespace llvm;
49 
50 #define DEBUG_TYPE "gisel-emitter"
51 
52 STATISTIC(NumPatternTotal, "Total number of patterns");
53 STATISTIC(NumPatternImported, "Number of patterns imported from SelectionDAG");
54 STATISTIC(NumPatternImportsSkipped, "Number of SelectionDAG imports skipped");
55 STATISTIC(NumPatternEmitted, "Number of patterns emitted");
56 
57 cl::OptionCategory GlobalISelEmitterCat("Options for -gen-global-isel");
58 
59 static cl::opt<bool> WarnOnSkippedPatterns(
60     "warn-on-skipped-patterns",
61     cl::desc("Explain why a pattern was skipped for inclusion "
62              "in the GlobalISel selector"),
63     cl::init(false), cl::cat(GlobalISelEmitterCat));
64 
65 namespace {
66 //===- Helper functions ---------------------------------------------------===//
67 
68 
69 /// Get the name of the enum value used to number the predicate function.
70 std::string getEnumNameForPredicate(const TreePredicateFn &Predicate) {
71   return "GIPFP_" + Predicate.getImmTypeIdentifier() + "_" +
72          Predicate.getFnName();
73 }
74 
75 /// Get the opcode used to check this predicate.
76 std::string getMatchOpcodeForPredicate(const TreePredicateFn &Predicate) {
77   return "GIM_Check" + Predicate.getImmTypeIdentifier() + "ImmPredicate";
78 }
79 
80 /// This class stands in for LLT wherever we want to tablegen-erate an
81 /// equivalent at compiler run-time.
82 class LLTCodeGen {
83 private:
84   LLT Ty;
85 
86 public:
87   LLTCodeGen(const LLT &Ty) : Ty(Ty) {}
88 
89   std::string getCxxEnumValue() const {
90     std::string Str;
91     raw_string_ostream OS(Str);
92 
93     emitCxxEnumValue(OS);
94     return OS.str();
95   }
96 
97   void emitCxxEnumValue(raw_ostream &OS) const {
98     if (Ty.isScalar()) {
99       OS << "GILLT_s" << Ty.getSizeInBits();
100       return;
101     }
102     if (Ty.isVector()) {
103       OS << "GILLT_v" << Ty.getNumElements() << "s" << Ty.getScalarSizeInBits();
104       return;
105     }
106     llvm_unreachable("Unhandled LLT");
107   }
108 
109   void emitCxxConstructorCall(raw_ostream &OS) const {
110     if (Ty.isScalar()) {
111       OS << "LLT::scalar(" << Ty.getSizeInBits() << ")";
112       return;
113     }
114     if (Ty.isVector()) {
115       OS << "LLT::vector(" << Ty.getNumElements() << ", "
116          << Ty.getScalarSizeInBits() << ")";
117       return;
118     }
119     llvm_unreachable("Unhandled LLT");
120   }
121 
122   const LLT &get() const { return Ty; }
123 
124   /// This ordering is used for std::unique() and std::sort(). There's no
125   /// particular logic behind the order but either A < B or B < A must be
126   /// true if A != B.
127   bool operator<(const LLTCodeGen &Other) const {
128     if (Ty.isValid() != Other.Ty.isValid())
129       return Ty.isValid() < Other.Ty.isValid();
130     if (!Ty.isValid())
131       return false;
132 
133     if (Ty.isVector() != Other.Ty.isVector())
134       return Ty.isVector() < Other.Ty.isVector();
135     if (Ty.isScalar() != Other.Ty.isScalar())
136       return Ty.isScalar() < Other.Ty.isScalar();
137     if (Ty.isPointer() != Other.Ty.isPointer())
138       return Ty.isPointer() < Other.Ty.isPointer();
139 
140     if (Ty.isPointer() && Ty.getAddressSpace() != Other.Ty.getAddressSpace())
141       return Ty.getAddressSpace() < Other.Ty.getAddressSpace();
142 
143     if (Ty.isVector() && Ty.getNumElements() != Other.Ty.getNumElements())
144       return Ty.getNumElements() < Other.Ty.getNumElements();
145 
146     return Ty.getSizeInBits() < Other.Ty.getSizeInBits();
147   }
148 };
149 
150 class InstructionMatcher;
151 /// Convert an MVT to an equivalent LLT if possible, or the invalid LLT() for
152 /// MVTs that don't map cleanly to an LLT (e.g., iPTR, *any, ...).
153 static Optional<LLTCodeGen> MVTToLLT(MVT::SimpleValueType SVT) {
154   MVT VT(SVT);
155   if (VT.isVector() && VT.getVectorNumElements() != 1)
156     return LLTCodeGen(
157         LLT::vector(VT.getVectorNumElements(), VT.getScalarSizeInBits()));
158   if (VT.isInteger() || VT.isFloatingPoint())
159     return LLTCodeGen(LLT::scalar(VT.getSizeInBits()));
160   return None;
161 }
162 
163 static std::string explainPredicates(const TreePatternNode *N) {
164   std::string Explanation = "";
165   StringRef Separator = "";
166   for (const auto &P : N->getPredicateFns()) {
167     Explanation +=
168         (Separator + P.getOrigPatFragRecord()->getRecord()->getName()).str();
169     if (P.isAlwaysTrue())
170       Explanation += " always-true";
171     if (P.isImmediatePattern())
172       Explanation += " immediate";
173   }
174   return Explanation;
175 }
176 
177 std::string explainOperator(Record *Operator) {
178   if (Operator->isSubClassOf("SDNode"))
179     return (" (" + Operator->getValueAsString("Opcode") + ")").str();
180 
181   if (Operator->isSubClassOf("Intrinsic"))
182     return (" (Operator is an Intrinsic, " + Operator->getName() + ")").str();
183 
184   return " (Operator not understood)";
185 }
186 
187 /// Helper function to let the emitter report skip reason error messages.
188 static Error failedImport(const Twine &Reason) {
189   return make_error<StringError>(Reason, inconvertibleErrorCode());
190 }
191 
192 static Error isTrivialOperatorNode(const TreePatternNode *N) {
193   std::string Explanation = "";
194   std::string Separator = "";
195 
196   bool HasUnsupportedPredicate = false;
197   for (const auto &Predicate : N->getPredicateFns()) {
198     if (Predicate.isAlwaysTrue())
199       continue;
200 
201     if (Predicate.isImmediatePattern())
202       continue;
203 
204     HasUnsupportedPredicate = true;
205     Explanation = Separator + "Has a predicate (" + explainPredicates(N) + ")";
206     Separator = ", ";
207     break;
208   }
209 
210   if (N->getTransformFn()) {
211     Explanation += Separator + "Has a transform function";
212     Separator = ", ";
213   }
214 
215   if (!HasUnsupportedPredicate && !N->getTransformFn())
216     return Error::success();
217 
218   return failedImport(Explanation);
219 }
220 
221 static Record *getInitValueAsRegClass(Init *V) {
222   if (DefInit *VDefInit = dyn_cast<DefInit>(V)) {
223     if (VDefInit->getDef()->isSubClassOf("RegisterOperand"))
224       return VDefInit->getDef()->getValueAsDef("RegClass");
225     if (VDefInit->getDef()->isSubClassOf("RegisterClass"))
226       return VDefInit->getDef();
227   }
228   return nullptr;
229 }
230 
231 std::string
232 getNameForFeatureBitset(const std::vector<Record *> &FeatureBitset) {
233   std::string Name = "GIFBS";
234   for (const auto &Feature : FeatureBitset)
235     Name += ("_" + Feature->getName()).str();
236   return Name;
237 }
238 
239 //===- MatchTable Helpers -------------------------------------------------===//
240 
241 class MatchTable;
242 
243 /// A record to be stored in a MatchTable.
244 ///
245 /// This class represents any and all output that may be required to emit the
246 /// MatchTable. Instances  are most often configured to represent an opcode or
247 /// value that will be emitted to the table with some formatting but it can also
248 /// represent commas, comments, and other formatting instructions.
249 struct MatchTableRecord {
250   enum RecordFlagsBits {
251     MTRF_None = 0x0,
252     /// Causes EmitStr to be formatted as comment when emitted.
253     MTRF_Comment = 0x1,
254     /// Causes the record value to be followed by a comma when emitted.
255     MTRF_CommaFollows = 0x2,
256     /// Causes the record value to be followed by a line break when emitted.
257     MTRF_LineBreakFollows = 0x4,
258     /// Indicates that the record defines a label and causes an additional
259     /// comment to be emitted containing the index of the label.
260     MTRF_Label = 0x8,
261     /// Causes the record to be emitted as the index of the label specified by
262     /// LabelID along with a comment indicating where that label is.
263     MTRF_JumpTarget = 0x10,
264     /// Causes the formatter to add a level of indentation before emitting the
265     /// record.
266     MTRF_Indent = 0x20,
267     /// Causes the formatter to remove a level of indentation after emitting the
268     /// record.
269     MTRF_Outdent = 0x40,
270   };
271 
272   /// When MTRF_Label or MTRF_JumpTarget is used, indicates a label id to
273   /// reference or define.
274   unsigned LabelID;
275   /// The string to emit. Depending on the MTRF_* flags it may be a comment, a
276   /// value, a label name.
277   std::string EmitStr;
278 
279 private:
280   /// The number of MatchTable elements described by this record. Comments are 0
281   /// while values are typically 1. Values >1 may occur when we need to emit
282   /// values that exceed the size of a MatchTable element.
283   unsigned NumElements;
284 
285 public:
286   /// A bitfield of RecordFlagsBits flags.
287   unsigned Flags;
288 
289   MatchTableRecord(Optional<unsigned> LabelID_, StringRef EmitStr,
290                    unsigned NumElements, unsigned Flags)
291       : LabelID(LabelID_.hasValue() ? LabelID_.getValue() : ~0u),
292         EmitStr(EmitStr), NumElements(NumElements), Flags(Flags) {
293     assert((!LabelID_.hasValue() || LabelID != ~0u) &&
294            "This value is reserved for non-labels");
295   }
296 
297   void emit(raw_ostream &OS, bool LineBreakNextAfterThis,
298             const MatchTable &Table) const;
299   unsigned size() const { return NumElements; }
300 };
301 
302 /// Holds the contents of a generated MatchTable to enable formatting and the
303 /// necessary index tracking needed to support GIM_Try.
304 class MatchTable {
305   /// An unique identifier for the table. The generated table will be named
306   /// MatchTable${ID}.
307   unsigned ID;
308   /// The records that make up the table. Also includes comments describing the
309   /// values being emitted and line breaks to format it.
310   std::vector<MatchTableRecord> Contents;
311   /// The currently defined labels.
312   DenseMap<unsigned, unsigned> LabelMap;
313   /// Tracks the sum of MatchTableRecord::NumElements as the table is built.
314   unsigned CurrentSize;
315 
316   /// A unique identifier for a MatchTable label.
317   static unsigned CurrentLabelID;
318 
319 public:
320   static MatchTableRecord LineBreak;
321   static MatchTableRecord Comment(StringRef Comment) {
322     return MatchTableRecord(None, Comment, 0, MatchTableRecord::MTRF_Comment);
323   }
324   static MatchTableRecord Opcode(StringRef Opcode, int IndentAdjust = 0) {
325     unsigned ExtraFlags = 0;
326     if (IndentAdjust > 0)
327       ExtraFlags |= MatchTableRecord::MTRF_Indent;
328     if (IndentAdjust < 0)
329       ExtraFlags |= MatchTableRecord::MTRF_Outdent;
330 
331     return MatchTableRecord(None, Opcode, 1,
332                             MatchTableRecord::MTRF_CommaFollows | ExtraFlags);
333   }
334   static MatchTableRecord NamedValue(StringRef NamedValue) {
335     return MatchTableRecord(None, NamedValue, 1,
336                             MatchTableRecord::MTRF_CommaFollows);
337   }
338   static MatchTableRecord NamedValue(StringRef Namespace,
339                                      StringRef NamedValue) {
340     return MatchTableRecord(None, (Namespace + "::" + NamedValue).str(), 1,
341                             MatchTableRecord::MTRF_CommaFollows);
342   }
343   static MatchTableRecord IntValue(int64_t IntValue) {
344     return MatchTableRecord(None, llvm::to_string(IntValue), 1,
345                             MatchTableRecord::MTRF_CommaFollows);
346   }
347   static MatchTableRecord Label(unsigned LabelID) {
348     return MatchTableRecord(LabelID, "Label " + llvm::to_string(LabelID), 0,
349                             MatchTableRecord::MTRF_Label |
350                                 MatchTableRecord::MTRF_Comment |
351                                 MatchTableRecord::MTRF_LineBreakFollows);
352   }
353   static MatchTableRecord JumpTarget(unsigned LabelID) {
354     return MatchTableRecord(LabelID, "Label " + llvm::to_string(LabelID), 1,
355                             MatchTableRecord::MTRF_JumpTarget |
356                                 MatchTableRecord::MTRF_Comment |
357                                 MatchTableRecord::MTRF_CommaFollows);
358   }
359 
360   MatchTable(unsigned ID) : ID(ID), CurrentSize(0) {}
361 
362   void push_back(const MatchTableRecord &Value) {
363     if (Value.Flags & MatchTableRecord::MTRF_Label)
364       defineLabel(Value.LabelID);
365     Contents.push_back(Value);
366     CurrentSize += Value.size();
367   }
368 
369   unsigned allocateLabelID() const { return CurrentLabelID++; }
370 
371   void defineLabel(unsigned LabelID) {
372     LabelMap.insert(std::make_pair(LabelID, CurrentSize));
373   }
374 
375   unsigned getLabelIndex(unsigned LabelID) const {
376     const auto I = LabelMap.find(LabelID);
377     assert(I != LabelMap.end() && "Use of undeclared label");
378     return I->second;
379   }
380 
381   void emitUse(raw_ostream &OS) const { OS << "MatchTable" << ID; }
382 
383   void emitDeclaration(raw_ostream &OS) const {
384     unsigned Indentation = 4;
385     OS << "  constexpr static int64_t MatchTable" << ID << "[] = {";
386     LineBreak.emit(OS, true, *this);
387     OS << std::string(Indentation, ' ');
388 
389     for (auto I = Contents.begin(), E = Contents.end(); I != E;
390          ++I) {
391       bool LineBreakIsNext = false;
392       const auto &NextI = std::next(I);
393 
394       if (NextI != E) {
395         if (NextI->EmitStr == "" &&
396             NextI->Flags == MatchTableRecord::MTRF_LineBreakFollows)
397           LineBreakIsNext = true;
398       }
399 
400       if (I->Flags & MatchTableRecord::MTRF_Indent)
401         Indentation += 2;
402 
403       I->emit(OS, LineBreakIsNext, *this);
404       if (I->Flags & MatchTableRecord::MTRF_LineBreakFollows)
405         OS << std::string(Indentation, ' ');
406 
407       if (I->Flags & MatchTableRecord::MTRF_Outdent)
408         Indentation -= 2;
409     }
410     OS << "};\n";
411   }
412 };
413 
414 unsigned MatchTable::CurrentLabelID = 0;
415 
416 MatchTableRecord MatchTable::LineBreak = {
417     None, "" /* Emit String */, 0 /* Elements */,
418     MatchTableRecord::MTRF_LineBreakFollows};
419 
420 void MatchTableRecord::emit(raw_ostream &OS, bool LineBreakIsNextAfterThis,
421                             const MatchTable &Table) const {
422   bool UseLineComment =
423       LineBreakIsNextAfterThis | (Flags & MTRF_LineBreakFollows);
424   if (Flags & (MTRF_JumpTarget | MTRF_CommaFollows))
425     UseLineComment = false;
426 
427   if (Flags & MTRF_Comment)
428     OS << (UseLineComment ? "// " : "/*");
429 
430   OS << EmitStr;
431   if (Flags & MTRF_Label)
432     OS << ": @" << Table.getLabelIndex(LabelID);
433 
434   if (Flags & MTRF_Comment && !UseLineComment)
435     OS << "*/";
436 
437   if (Flags & MTRF_JumpTarget) {
438     if (Flags & MTRF_Comment)
439       OS << " ";
440     OS << Table.getLabelIndex(LabelID);
441   }
442 
443   if (Flags & MTRF_CommaFollows) {
444     OS << ",";
445     if (!LineBreakIsNextAfterThis && !(Flags & MTRF_LineBreakFollows))
446       OS << " ";
447   }
448 
449   if (Flags & MTRF_LineBreakFollows)
450     OS << "\n";
451 }
452 
453 MatchTable &operator<<(MatchTable &Table, const MatchTableRecord &Value) {
454   Table.push_back(Value);
455   return Table;
456 }
457 
458 //===- Matchers -----------------------------------------------------------===//
459 
460 class OperandMatcher;
461 class MatchAction;
462 
463 /// Generates code to check that a match rule matches.
464 class RuleMatcher {
465   /// A list of matchers that all need to succeed for the current rule to match.
466   /// FIXME: This currently supports a single match position but could be
467   /// extended to support multiple positions to support div/rem fusion or
468   /// load-multiple instructions.
469   std::vector<std::unique_ptr<InstructionMatcher>> Matchers;
470 
471   /// A list of actions that need to be taken when all predicates in this rule
472   /// have succeeded.
473   std::vector<std::unique_ptr<MatchAction>> Actions;
474 
475   typedef std::map<const InstructionMatcher *, unsigned>
476       DefinedInsnVariablesMap;
477   /// A map of instruction matchers to the local variables created by
478   /// emitCaptureOpcodes().
479   DefinedInsnVariablesMap InsnVariableIDs;
480 
481   /// A map of named operands defined by the matchers that may be referenced by
482   /// the renderers.
483   StringMap<OperandMatcher *> DefinedOperands;
484 
485   /// ID for the next instruction variable defined with defineInsnVar()
486   unsigned NextInsnVarID;
487 
488   std::vector<Record *> RequiredFeatures;
489 
490   ArrayRef<SMLoc> SrcLoc;
491 
492 public:
493   RuleMatcher(ArrayRef<SMLoc> SrcLoc)
494       : Matchers(), Actions(), InsnVariableIDs(), DefinedOperands(),
495         NextInsnVarID(0), SrcLoc(SrcLoc) {}
496   RuleMatcher(RuleMatcher &&Other) = default;
497   RuleMatcher &operator=(RuleMatcher &&Other) = default;
498 
499   InstructionMatcher &addInstructionMatcher(StringRef SymbolicName);
500   void addRequiredFeature(Record *Feature);
501   const std::vector<Record *> &getRequiredFeatures() const;
502 
503   template <class Kind, class... Args> Kind &addAction(Args &&... args);
504 
505   /// Define an instruction without emitting any code to do so.
506   /// This is used for the root of the match.
507   unsigned implicitlyDefineInsnVar(const InstructionMatcher &Matcher);
508   /// Define an instruction and emit corresponding state-machine opcodes.
509   unsigned defineInsnVar(MatchTable &Table, const InstructionMatcher &Matcher,
510                          unsigned InsnVarID, unsigned OpIdx);
511   unsigned getInsnVarID(const InstructionMatcher &InsnMatcher) const;
512   DefinedInsnVariablesMap::const_iterator defined_insn_vars_begin() const {
513     return InsnVariableIDs.begin();
514   }
515   DefinedInsnVariablesMap::const_iterator defined_insn_vars_end() const {
516     return InsnVariableIDs.end();
517   }
518   iterator_range<typename DefinedInsnVariablesMap::const_iterator>
519   defined_insn_vars() const {
520     return make_range(defined_insn_vars_begin(), defined_insn_vars_end());
521   }
522 
523   void defineOperand(StringRef SymbolicName, OperandMatcher &OM);
524 
525   const InstructionMatcher &getInstructionMatcher(StringRef SymbolicName) const;
526   const OperandMatcher &getOperandMatcher(StringRef Name) const;
527 
528   void emitCaptureOpcodes(MatchTable &Table);
529 
530   void emit(MatchTable &Table);
531 
532   /// Compare the priority of this object and B.
533   ///
534   /// Returns true if this object is more important than B.
535   bool isHigherPriorityThan(const RuleMatcher &B) const;
536 
537   /// Report the maximum number of temporary operands needed by the rule
538   /// matcher.
539   unsigned countRendererFns() const;
540 
541   // FIXME: Remove this as soon as possible
542   InstructionMatcher &insnmatcher_front() const { return *Matchers.front(); }
543 };
544 
545 template <class PredicateTy> class PredicateListMatcher {
546 private:
547   typedef std::vector<std::unique_ptr<PredicateTy>> PredicateVec;
548   PredicateVec Predicates;
549 
550   /// Template instantiations should specialize this to return a string to use
551   /// for the comment emitted when there are no predicates.
552   std::string getNoPredicateComment() const;
553 
554 public:
555   /// Construct a new operand predicate and add it to the matcher.
556   template <class Kind, class... Args>
557   Optional<Kind *> addPredicate(Args&&... args) {
558     Predicates.emplace_back(
559         llvm::make_unique<Kind>(std::forward<Args>(args)...));
560     return static_cast<Kind *>(Predicates.back().get());
561   }
562 
563   typename PredicateVec::const_iterator predicates_begin() const {
564     return Predicates.begin();
565   }
566   typename PredicateVec::const_iterator predicates_end() const {
567     return Predicates.end();
568   }
569   iterator_range<typename PredicateVec::const_iterator> predicates() const {
570     return make_range(predicates_begin(), predicates_end());
571   }
572   typename PredicateVec::size_type predicates_size() const {
573     return Predicates.size();
574   }
575 
576   /// Emit MatchTable opcodes that tests whether all the predicates are met.
577   template <class... Args>
578   void emitPredicateListOpcodes(MatchTable &Table, Args &&... args) const {
579     if (Predicates.empty()) {
580       Table << MatchTable::Comment(getNoPredicateComment())
581             << MatchTable::LineBreak;
582       return;
583     }
584 
585     for (const auto &Predicate : predicates())
586       Predicate->emitPredicateOpcodes(Table, std::forward<Args>(args)...);
587   }
588 };
589 
590 /// Generates code to check a predicate of an operand.
591 ///
592 /// Typical predicates include:
593 /// * Operand is a particular register.
594 /// * Operand is assigned a particular register bank.
595 /// * Operand is an MBB.
596 class OperandPredicateMatcher {
597 public:
598   /// This enum is used for RTTI and also defines the priority that is given to
599   /// the predicate when generating the matcher code. Kinds with higher priority
600   /// must be tested first.
601   ///
602   /// The relative priority of OPM_LLT, OPM_RegBank, and OPM_MBB do not matter
603   /// but OPM_Int must have priority over OPM_RegBank since constant integers
604   /// are represented by a virtual register defined by a G_CONSTANT instruction.
605   enum PredicateKind {
606     OPM_Tie,
607     OPM_ComplexPattern,
608     OPM_IntrinsicID,
609     OPM_Instruction,
610     OPM_Int,
611     OPM_LiteralInt,
612     OPM_LLT,
613     OPM_RegBank,
614     OPM_MBB,
615   };
616 
617 protected:
618   PredicateKind Kind;
619 
620 public:
621   OperandPredicateMatcher(PredicateKind Kind) : Kind(Kind) {}
622   virtual ~OperandPredicateMatcher() {}
623 
624   PredicateKind getKind() const { return Kind; }
625 
626   /// Emit MatchTable opcodes to capture instructions into the MIs table.
627   ///
628   /// Only InstructionOperandMatcher needs to do anything for this method the
629   /// rest just walk the tree.
630   virtual void emitCaptureOpcodes(MatchTable &Table, RuleMatcher &Rule,
631                                   unsigned InsnVarID, unsigned OpIdx) const {}
632 
633   /// Emit MatchTable opcodes that check the predicate for the given operand.
634   virtual void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
635                                     unsigned InsnVarID,
636                                     unsigned OpIdx) const = 0;
637 
638   /// Compare the priority of this object and B.
639   ///
640   /// Returns true if this object is more important than B.
641   virtual bool isHigherPriorityThan(const OperandPredicateMatcher &B) const;
642 
643   /// Report the maximum number of temporary operands needed by the predicate
644   /// matcher.
645   virtual unsigned countRendererFns() const { return 0; }
646 };
647 
648 template <>
649 std::string
650 PredicateListMatcher<OperandPredicateMatcher>::getNoPredicateComment() const {
651   return "No operand predicates";
652 }
653 
654 /// Generates code to check that a register operand is defined by the same exact
655 /// one as another.
656 class SameOperandMatcher : public OperandPredicateMatcher {
657   std::string TiedTo;
658 
659 public:
660   SameOperandMatcher(StringRef TiedTo)
661       : OperandPredicateMatcher(OPM_Tie), TiedTo(TiedTo) {}
662 
663   static bool classof(const OperandPredicateMatcher *P) {
664     return P->getKind() == OPM_Tie;
665   }
666 
667   void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
668                             unsigned InsnVarID, unsigned OpIdx) const override;
669 };
670 
671 /// Generates code to check that an operand is a particular LLT.
672 class LLTOperandMatcher : public OperandPredicateMatcher {
673 protected:
674   LLTCodeGen Ty;
675 
676 public:
677   static std::set<LLTCodeGen> KnownTypes;
678 
679   LLTOperandMatcher(const LLTCodeGen &Ty)
680       : OperandPredicateMatcher(OPM_LLT), Ty(Ty) {
681     KnownTypes.insert(Ty);
682   }
683 
684   static bool classof(const OperandPredicateMatcher *P) {
685     return P->getKind() == OPM_LLT;
686   }
687 
688   void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
689                             unsigned InsnVarID, unsigned OpIdx) const override {
690     Table << MatchTable::Opcode("GIM_CheckType") << MatchTable::Comment("MI")
691           << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Op")
692           << MatchTable::IntValue(OpIdx) << MatchTable::Comment("Type")
693           << MatchTable::NamedValue(Ty.getCxxEnumValue())
694           << MatchTable::LineBreak;
695   }
696 };
697 
698 std::set<LLTCodeGen> LLTOperandMatcher::KnownTypes;
699 
700 /// Generates code to check that an operand is a particular target constant.
701 class ComplexPatternOperandMatcher : public OperandPredicateMatcher {
702 protected:
703   const OperandMatcher &Operand;
704   const Record &TheDef;
705 
706   unsigned getAllocatedTemporariesBaseID() const;
707 
708 public:
709   ComplexPatternOperandMatcher(const OperandMatcher &Operand,
710                                const Record &TheDef)
711       : OperandPredicateMatcher(OPM_ComplexPattern), Operand(Operand),
712         TheDef(TheDef) {}
713 
714   static bool classof(const OperandPredicateMatcher *P) {
715     return P->getKind() == OPM_ComplexPattern;
716   }
717 
718   void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
719                             unsigned InsnVarID, unsigned OpIdx) const override {
720     unsigned ID = getAllocatedTemporariesBaseID();
721     Table << MatchTable::Opcode("GIM_CheckComplexPattern")
722           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
723           << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
724           << MatchTable::Comment("Renderer") << MatchTable::IntValue(ID)
725           << MatchTable::NamedValue(("GICP_" + TheDef.getName()).str())
726           << MatchTable::LineBreak;
727   }
728 
729   unsigned countRendererFns() const override {
730     return 1;
731   }
732 };
733 
734 /// Generates code to check that an operand is in a particular register bank.
735 class RegisterBankOperandMatcher : public OperandPredicateMatcher {
736 protected:
737   const CodeGenRegisterClass &RC;
738 
739 public:
740   RegisterBankOperandMatcher(const CodeGenRegisterClass &RC)
741       : OperandPredicateMatcher(OPM_RegBank), RC(RC) {}
742 
743   static bool classof(const OperandPredicateMatcher *P) {
744     return P->getKind() == OPM_RegBank;
745   }
746 
747   void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
748                             unsigned InsnVarID, unsigned OpIdx) const override {
749     Table << MatchTable::Opcode("GIM_CheckRegBankForClass")
750           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
751           << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
752           << MatchTable::Comment("RC")
753           << MatchTable::NamedValue(RC.getQualifiedName() + "RegClassID")
754           << MatchTable::LineBreak;
755   }
756 };
757 
758 /// Generates code to check that an operand is a basic block.
759 class MBBOperandMatcher : public OperandPredicateMatcher {
760 public:
761   MBBOperandMatcher() : OperandPredicateMatcher(OPM_MBB) {}
762 
763   static bool classof(const OperandPredicateMatcher *P) {
764     return P->getKind() == OPM_MBB;
765   }
766 
767   void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
768                             unsigned InsnVarID, unsigned OpIdx) const override {
769     Table << MatchTable::Opcode("GIM_CheckIsMBB") << MatchTable::Comment("MI")
770           << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Op")
771           << MatchTable::IntValue(OpIdx) << MatchTable::LineBreak;
772   }
773 };
774 
775 /// Generates code to check that an operand is a G_CONSTANT with a particular
776 /// int.
777 class ConstantIntOperandMatcher : public OperandPredicateMatcher {
778 protected:
779   int64_t Value;
780 
781 public:
782   ConstantIntOperandMatcher(int64_t Value)
783       : OperandPredicateMatcher(OPM_Int), Value(Value) {}
784 
785   static bool classof(const OperandPredicateMatcher *P) {
786     return P->getKind() == OPM_Int;
787   }
788 
789   void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
790                             unsigned InsnVarID, unsigned OpIdx) const override {
791     Table << MatchTable::Opcode("GIM_CheckConstantInt")
792           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
793           << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
794           << MatchTable::IntValue(Value) << MatchTable::LineBreak;
795   }
796 };
797 
798 /// Generates code to check that an operand is a raw int (where MO.isImm() or
799 /// MO.isCImm() is true).
800 class LiteralIntOperandMatcher : public OperandPredicateMatcher {
801 protected:
802   int64_t Value;
803 
804 public:
805   LiteralIntOperandMatcher(int64_t Value)
806       : OperandPredicateMatcher(OPM_LiteralInt), Value(Value) {}
807 
808   static bool classof(const OperandPredicateMatcher *P) {
809     return P->getKind() == OPM_LiteralInt;
810   }
811 
812   void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
813                             unsigned InsnVarID, unsigned OpIdx) const override {
814     Table << MatchTable::Opcode("GIM_CheckLiteralInt")
815           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
816           << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
817           << MatchTable::IntValue(Value) << MatchTable::LineBreak;
818   }
819 };
820 
821 /// Generates code to check that an operand is an intrinsic ID.
822 class IntrinsicIDOperandMatcher : public OperandPredicateMatcher {
823 protected:
824   const CodeGenIntrinsic *II;
825 
826 public:
827   IntrinsicIDOperandMatcher(const CodeGenIntrinsic *II)
828       : OperandPredicateMatcher(OPM_IntrinsicID), II(II) {}
829 
830   static bool classof(const OperandPredicateMatcher *P) {
831     return P->getKind() == OPM_IntrinsicID;
832   }
833 
834   void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
835                             unsigned InsnVarID, unsigned OpIdx) const override {
836     Table << MatchTable::Opcode("GIM_CheckIntrinsicID")
837           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
838           << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
839           << MatchTable::NamedValue("Intrinsic::" + II->EnumName)
840           << MatchTable::LineBreak;
841   }
842 };
843 
844 /// Generates code to check that a set of predicates match for a particular
845 /// operand.
846 class OperandMatcher : public PredicateListMatcher<OperandPredicateMatcher> {
847 protected:
848   InstructionMatcher &Insn;
849   unsigned OpIdx;
850   std::string SymbolicName;
851 
852   /// The index of the first temporary variable allocated to this operand. The
853   /// number of allocated temporaries can be found with
854   /// countRendererFns().
855   unsigned AllocatedTemporariesBaseID;
856 
857 public:
858   OperandMatcher(InstructionMatcher &Insn, unsigned OpIdx,
859                  const std::string &SymbolicName,
860                  unsigned AllocatedTemporariesBaseID)
861       : Insn(Insn), OpIdx(OpIdx), SymbolicName(SymbolicName),
862         AllocatedTemporariesBaseID(AllocatedTemporariesBaseID) {}
863 
864   bool hasSymbolicName() const { return !SymbolicName.empty(); }
865   const StringRef getSymbolicName() const { return SymbolicName; }
866   void setSymbolicName(StringRef Name) {
867     assert(SymbolicName.empty() && "Operand already has a symbolic name");
868     SymbolicName = Name;
869   }
870   unsigned getOperandIndex() const { return OpIdx; }
871 
872   std::string getOperandExpr(unsigned InsnVarID) const {
873     return "State.MIs[" + llvm::to_string(InsnVarID) + "]->getOperand(" +
874            llvm::to_string(OpIdx) + ")";
875   }
876 
877   InstructionMatcher &getInstructionMatcher() const { return Insn; }
878 
879   /// Emit MatchTable opcodes to capture instructions into the MIs table.
880   void emitCaptureOpcodes(MatchTable &Table, RuleMatcher &Rule,
881                           unsigned InsnVarID) const {
882     for (const auto &Predicate : predicates())
883       Predicate->emitCaptureOpcodes(Table, Rule, InsnVarID, OpIdx);
884   }
885 
886   /// Emit MatchTable opcodes that test whether the instruction named in
887   /// InsnVarID matches all the predicates and all the operands.
888   void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
889                             unsigned InsnVarID) const {
890     std::string Comment;
891     raw_string_ostream CommentOS(Comment);
892     CommentOS << "MIs[" << InsnVarID << "] ";
893     if (SymbolicName.empty())
894       CommentOS << "Operand " << OpIdx;
895     else
896       CommentOS << SymbolicName;
897     Table << MatchTable::Comment(CommentOS.str()) << MatchTable::LineBreak;
898 
899     emitPredicateListOpcodes(Table, Rule, InsnVarID, OpIdx);
900   }
901 
902   /// Compare the priority of this object and B.
903   ///
904   /// Returns true if this object is more important than B.
905   bool isHigherPriorityThan(const OperandMatcher &B) const {
906     // Operand matchers involving more predicates have higher priority.
907     if (predicates_size() > B.predicates_size())
908       return true;
909     if (predicates_size() < B.predicates_size())
910       return false;
911 
912     // This assumes that predicates are added in a consistent order.
913     for (const auto &Predicate : zip(predicates(), B.predicates())) {
914       if (std::get<0>(Predicate)->isHigherPriorityThan(*std::get<1>(Predicate)))
915         return true;
916       if (std::get<1>(Predicate)->isHigherPriorityThan(*std::get<0>(Predicate)))
917         return false;
918     }
919 
920     return false;
921   };
922 
923   /// Report the maximum number of temporary operands needed by the operand
924   /// matcher.
925   unsigned countRendererFns() const {
926     return std::accumulate(
927         predicates().begin(), predicates().end(), 0,
928         [](unsigned A,
929            const std::unique_ptr<OperandPredicateMatcher> &Predicate) {
930           return A + Predicate->countRendererFns();
931         });
932   }
933 
934   unsigned getAllocatedTemporariesBaseID() const {
935     return AllocatedTemporariesBaseID;
936   }
937 
938   bool isSameAsAnotherOperand() const {
939     for (const auto &Predicate : predicates())
940       if (isa<SameOperandMatcher>(Predicate))
941         return true;
942     return false;
943   }
944 };
945 
946 // Specialize OperandMatcher::addPredicate() to refrain from adding redundant
947 // predicates.
948 template <>
949 template <class Kind, class... Args>
950 Optional<Kind *>
951 PredicateListMatcher<OperandPredicateMatcher>::addPredicate(Args &&... args) {
952   if (static_cast<OperandMatcher *>(this)->isSameAsAnotherOperand())
953     return None;
954   Predicates.emplace_back(llvm::make_unique<Kind>(std::forward<Args>(args)...));
955   return static_cast<Kind *>(Predicates.back().get());
956 }
957 
958 unsigned ComplexPatternOperandMatcher::getAllocatedTemporariesBaseID() const {
959   return Operand.getAllocatedTemporariesBaseID();
960 }
961 
962 /// Generates code to check a predicate on an instruction.
963 ///
964 /// Typical predicates include:
965 /// * The opcode of the instruction is a particular value.
966 /// * The nsw/nuw flag is/isn't set.
967 class InstructionPredicateMatcher {
968 protected:
969   /// This enum is used for RTTI and also defines the priority that is given to
970   /// the predicate when generating the matcher code. Kinds with higher priority
971   /// must be tested first.
972   enum PredicateKind {
973     IPM_Opcode,
974     IPM_ImmPredicate,
975   };
976 
977   PredicateKind Kind;
978 
979 public:
980   InstructionPredicateMatcher(PredicateKind Kind) : Kind(Kind) {}
981   virtual ~InstructionPredicateMatcher() {}
982 
983   PredicateKind getKind() const { return Kind; }
984 
985   /// Emit MatchTable opcodes that test whether the instruction named in
986   /// InsnVarID matches the predicate.
987   virtual void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
988                                     unsigned InsnVarID) const = 0;
989 
990   /// Compare the priority of this object and B.
991   ///
992   /// Returns true if this object is more important than B.
993   virtual bool
994   isHigherPriorityThan(const InstructionPredicateMatcher &B) const {
995     return Kind < B.Kind;
996   };
997 
998   /// Report the maximum number of temporary operands needed by the predicate
999   /// matcher.
1000   virtual unsigned countRendererFns() const { return 0; }
1001 };
1002 
1003 template <>
1004 std::string
1005 PredicateListMatcher<InstructionPredicateMatcher>::getNoPredicateComment() const {
1006   return "No instruction predicates";
1007 }
1008 
1009 /// Generates code to check the opcode of an instruction.
1010 class InstructionOpcodeMatcher : public InstructionPredicateMatcher {
1011 protected:
1012   const CodeGenInstruction *I;
1013 
1014 public:
1015   InstructionOpcodeMatcher(const CodeGenInstruction *I)
1016       : InstructionPredicateMatcher(IPM_Opcode), I(I) {}
1017 
1018   static bool classof(const InstructionPredicateMatcher *P) {
1019     return P->getKind() == IPM_Opcode;
1020   }
1021 
1022   void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
1023                             unsigned InsnVarID) const override {
1024     Table << MatchTable::Opcode("GIM_CheckOpcode") << MatchTable::Comment("MI")
1025           << MatchTable::IntValue(InsnVarID)
1026           << MatchTable::NamedValue(I->Namespace, I->TheDef->getName())
1027           << MatchTable::LineBreak;
1028   }
1029 
1030   /// Compare the priority of this object and B.
1031   ///
1032   /// Returns true if this object is more important than B.
1033   bool
1034   isHigherPriorityThan(const InstructionPredicateMatcher &B) const override {
1035     if (InstructionPredicateMatcher::isHigherPriorityThan(B))
1036       return true;
1037     if (B.InstructionPredicateMatcher::isHigherPriorityThan(*this))
1038       return false;
1039 
1040     // Prioritize opcodes for cosmetic reasons in the generated source. Although
1041     // this is cosmetic at the moment, we may want to drive a similar ordering
1042     // using instruction frequency information to improve compile time.
1043     if (const InstructionOpcodeMatcher *BO =
1044             dyn_cast<InstructionOpcodeMatcher>(&B))
1045       return I->TheDef->getName() < BO->I->TheDef->getName();
1046 
1047     return false;
1048   };
1049 
1050   bool isConstantInstruction() const {
1051     return I->TheDef->getName() == "G_CONSTANT";
1052   }
1053 };
1054 
1055 /// Generates code to check that this instruction is a constant whose value
1056 /// meets an immediate predicate.
1057 ///
1058 /// Immediates are slightly odd since they are typically used like an operand
1059 /// but are represented as an operator internally. We typically write simm8:$src
1060 /// in a tablegen pattern, but this is just syntactic sugar for
1061 /// (imm:i32)<<P:Predicate_simm8>>:$imm which more directly describes the nodes
1062 /// that will be matched and the predicate (which is attached to the imm
1063 /// operator) that will be tested. In SelectionDAG this describes a
1064 /// ConstantSDNode whose internal value will be tested using the simm8 predicate.
1065 ///
1066 /// The corresponding GlobalISel representation is %1 = G_CONSTANT iN Value. In
1067 /// this representation, the immediate could be tested with an
1068 /// InstructionMatcher, InstructionOpcodeMatcher, OperandMatcher, and a
1069 /// OperandPredicateMatcher-subclass to check the Value meets the predicate but
1070 /// there are two implementation issues with producing that matcher
1071 /// configuration from the SelectionDAG pattern:
1072 /// * ImmLeaf is a PatFrag whose root is an InstructionMatcher. This means that
1073 ///   were we to sink the immediate predicate to the operand we would have to
1074 ///   have two partial implementations of PatFrag support, one for immediates
1075 ///   and one for non-immediates.
1076 /// * At the point we handle the predicate, the OperandMatcher hasn't been
1077 ///   created yet. If we were to sink the predicate to the OperandMatcher we
1078 ///   would also have to complicate (or duplicate) the code that descends and
1079 ///   creates matchers for the subtree.
1080 /// Overall, it's simpler to handle it in the place it was found.
1081 class InstructionImmPredicateMatcher : public InstructionPredicateMatcher {
1082 protected:
1083   TreePredicateFn Predicate;
1084 
1085 public:
1086   InstructionImmPredicateMatcher(const TreePredicateFn &Predicate)
1087       : InstructionPredicateMatcher(IPM_ImmPredicate), Predicate(Predicate) {}
1088 
1089   static bool classof(const InstructionPredicateMatcher *P) {
1090     return P->getKind() == IPM_ImmPredicate;
1091   }
1092 
1093   void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
1094                             unsigned InsnVarID) const override {
1095     Table << MatchTable::Opcode(getMatchOpcodeForPredicate(Predicate))
1096           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1097           << MatchTable::Comment("Predicate")
1098           << MatchTable::NamedValue(getEnumNameForPredicate(Predicate))
1099           << MatchTable::LineBreak;
1100   }
1101 };
1102 
1103 /// Generates code to check that a set of predicates and operands match for a
1104 /// particular instruction.
1105 ///
1106 /// Typical predicates include:
1107 /// * Has a specific opcode.
1108 /// * Has an nsw/nuw flag or doesn't.
1109 class InstructionMatcher
1110     : public PredicateListMatcher<InstructionPredicateMatcher> {
1111 protected:
1112   typedef std::vector<std::unique_ptr<OperandMatcher>> OperandVec;
1113 
1114   RuleMatcher &Rule;
1115 
1116   /// The operands to match. All rendered operands must be present even if the
1117   /// condition is always true.
1118   OperandVec Operands;
1119 
1120   std::string SymbolicName;
1121 
1122 public:
1123   InstructionMatcher(RuleMatcher &Rule, StringRef SymbolicName)
1124       : Rule(Rule), SymbolicName(SymbolicName) {}
1125 
1126   RuleMatcher &getRuleMatcher() const { return Rule; }
1127 
1128   /// Add an operand to the matcher.
1129   OperandMatcher &addOperand(unsigned OpIdx, const std::string &SymbolicName,
1130                              unsigned AllocatedTemporariesBaseID) {
1131     Operands.emplace_back(new OperandMatcher(*this, OpIdx, SymbolicName,
1132                                              AllocatedTemporariesBaseID));
1133     if (!SymbolicName.empty())
1134       Rule.defineOperand(SymbolicName, *Operands.back());
1135 
1136     return *Operands.back();
1137   }
1138 
1139   OperandMatcher &getOperand(unsigned OpIdx) {
1140     auto I = std::find_if(Operands.begin(), Operands.end(),
1141                           [&OpIdx](const std::unique_ptr<OperandMatcher> &X) {
1142                             return X->getOperandIndex() == OpIdx;
1143                           });
1144     if (I != Operands.end())
1145       return **I;
1146     llvm_unreachable("Failed to lookup operand");
1147   }
1148 
1149   StringRef getSymbolicName() const { return SymbolicName; }
1150   unsigned getNumOperands() const { return Operands.size(); }
1151   OperandVec::iterator operands_begin() { return Operands.begin(); }
1152   OperandVec::iterator operands_end() { return Operands.end(); }
1153   iterator_range<OperandVec::iterator> operands() {
1154     return make_range(operands_begin(), operands_end());
1155   }
1156   OperandVec::const_iterator operands_begin() const { return Operands.begin(); }
1157   OperandVec::const_iterator operands_end() const { return Operands.end(); }
1158   iterator_range<OperandVec::const_iterator> operands() const {
1159     return make_range(operands_begin(), operands_end());
1160   }
1161 
1162   /// Emit MatchTable opcodes to check the shape of the match and capture
1163   /// instructions into the MIs table.
1164   void emitCaptureOpcodes(MatchTable &Table, RuleMatcher &Rule,
1165                           unsigned InsnID) {
1166     Table << MatchTable::Opcode("GIM_CheckNumOperands")
1167           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnID)
1168           << MatchTable::Comment("Expected")
1169           << MatchTable::IntValue(getNumOperands()) << MatchTable::LineBreak;
1170     for (const auto &Operand : Operands)
1171       Operand->emitCaptureOpcodes(Table, Rule, InsnID);
1172   }
1173 
1174   /// Emit MatchTable opcodes that test whether the instruction named in
1175   /// InsnVarName matches all the predicates and all the operands.
1176   void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
1177                             unsigned InsnVarID) const {
1178     emitPredicateListOpcodes(Table, Rule, InsnVarID);
1179     for (const auto &Operand : Operands)
1180       Operand->emitPredicateOpcodes(Table, Rule, InsnVarID);
1181   }
1182 
1183   /// Compare the priority of this object and B.
1184   ///
1185   /// Returns true if this object is more important than B.
1186   bool isHigherPriorityThan(const InstructionMatcher &B) const {
1187     // Instruction matchers involving more operands have higher priority.
1188     if (Operands.size() > B.Operands.size())
1189       return true;
1190     if (Operands.size() < B.Operands.size())
1191       return false;
1192 
1193     for (const auto &Predicate : zip(predicates(), B.predicates())) {
1194       if (std::get<0>(Predicate)->isHigherPriorityThan(*std::get<1>(Predicate)))
1195         return true;
1196       if (std::get<1>(Predicate)->isHigherPriorityThan(*std::get<0>(Predicate)))
1197         return false;
1198     }
1199 
1200     for (const auto &Operand : zip(Operands, B.Operands)) {
1201       if (std::get<0>(Operand)->isHigherPriorityThan(*std::get<1>(Operand)))
1202         return true;
1203       if (std::get<1>(Operand)->isHigherPriorityThan(*std::get<0>(Operand)))
1204         return false;
1205     }
1206 
1207     return false;
1208   };
1209 
1210   /// Report the maximum number of temporary operands needed by the instruction
1211   /// matcher.
1212   unsigned countRendererFns() const {
1213     return std::accumulate(predicates().begin(), predicates().end(), 0,
1214                            [](unsigned A,
1215                               const std::unique_ptr<InstructionPredicateMatcher>
1216                                   &Predicate) {
1217                              return A + Predicate->countRendererFns();
1218                            }) +
1219            std::accumulate(
1220                Operands.begin(), Operands.end(), 0,
1221                [](unsigned A, const std::unique_ptr<OperandMatcher> &Operand) {
1222                  return A + Operand->countRendererFns();
1223                });
1224   }
1225 
1226   bool isConstantInstruction() const {
1227     for (const auto &P : predicates())
1228       if (const InstructionOpcodeMatcher *Opcode =
1229               dyn_cast<InstructionOpcodeMatcher>(P.get()))
1230         return Opcode->isConstantInstruction();
1231     return false;
1232   }
1233 };
1234 
1235 /// Generates code to check that the operand is a register defined by an
1236 /// instruction that matches the given instruction matcher.
1237 ///
1238 /// For example, the pattern:
1239 ///   (set $dst, (G_MUL (G_ADD $src1, $src2), $src3))
1240 /// would use an InstructionOperandMatcher for operand 1 of the G_MUL to match
1241 /// the:
1242 ///   (G_ADD $src1, $src2)
1243 /// subpattern.
1244 class InstructionOperandMatcher : public OperandPredicateMatcher {
1245 protected:
1246   std::unique_ptr<InstructionMatcher> InsnMatcher;
1247 
1248 public:
1249   InstructionOperandMatcher(RuleMatcher &Rule, StringRef SymbolicName)
1250       : OperandPredicateMatcher(OPM_Instruction),
1251         InsnMatcher(new InstructionMatcher(Rule, SymbolicName)) {}
1252 
1253   static bool classof(const OperandPredicateMatcher *P) {
1254     return P->getKind() == OPM_Instruction;
1255   }
1256 
1257   InstructionMatcher &getInsnMatcher() const { return *InsnMatcher; }
1258 
1259   void emitCaptureOpcodes(MatchTable &Table, RuleMatcher &Rule,
1260                           unsigned InsnID, unsigned OpIdx) const override {
1261     unsigned InsnVarID = Rule.defineInsnVar(Table, *InsnMatcher, InsnID, OpIdx);
1262     InsnMatcher->emitCaptureOpcodes(Table, Rule, InsnVarID);
1263   }
1264 
1265   void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
1266                             unsigned InsnVarID_,
1267                             unsigned OpIdx_) const override {
1268     unsigned InsnVarID = Rule.getInsnVarID(*InsnMatcher);
1269     InsnMatcher->emitPredicateOpcodes(Table, Rule, InsnVarID);
1270   }
1271 };
1272 
1273 //===- Actions ------------------------------------------------------------===//
1274 class OperandRenderer {
1275 public:
1276   enum RendererKind {
1277     OR_Copy,
1278     OR_CopySubReg,
1279     OR_CopyConstantAsImm,
1280     OR_CopyFConstantAsFPImm,
1281     OR_Imm,
1282     OR_Register,
1283     OR_ComplexPattern
1284   };
1285 
1286 protected:
1287   RendererKind Kind;
1288 
1289 public:
1290   OperandRenderer(RendererKind Kind) : Kind(Kind) {}
1291   virtual ~OperandRenderer() {}
1292 
1293   RendererKind getKind() const { return Kind; }
1294 
1295   virtual void emitRenderOpcodes(MatchTable &Table,
1296                                  RuleMatcher &Rule) const = 0;
1297 };
1298 
1299 /// A CopyRenderer emits code to copy a single operand from an existing
1300 /// instruction to the one being built.
1301 class CopyRenderer : public OperandRenderer {
1302 protected:
1303   unsigned NewInsnID;
1304   /// The matcher for the instruction that this operand is copied from.
1305   /// This provides the facility for looking up an a operand by it's name so
1306   /// that it can be used as a source for the instruction being built.
1307   const InstructionMatcher &Matched;
1308   /// The name of the operand.
1309   const StringRef SymbolicName;
1310 
1311 public:
1312   CopyRenderer(unsigned NewInsnID, const InstructionMatcher &Matched,
1313                StringRef SymbolicName)
1314       : OperandRenderer(OR_Copy), NewInsnID(NewInsnID), Matched(Matched),
1315         SymbolicName(SymbolicName) {
1316     assert(!SymbolicName.empty() && "Cannot copy from an unspecified source");
1317   }
1318 
1319   static bool classof(const OperandRenderer *R) {
1320     return R->getKind() == OR_Copy;
1321   }
1322 
1323   const StringRef getSymbolicName() const { return SymbolicName; }
1324 
1325   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
1326     const OperandMatcher &Operand = Rule.getOperandMatcher(SymbolicName);
1327     unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
1328     Table << MatchTable::Opcode("GIR_Copy") << MatchTable::Comment("NewInsnID")
1329           << MatchTable::IntValue(NewInsnID) << MatchTable::Comment("OldInsnID")
1330           << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
1331           << MatchTable::IntValue(Operand.getOperandIndex())
1332           << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
1333   }
1334 };
1335 
1336 /// A CopyConstantAsImmRenderer emits code to render a G_CONSTANT instruction to
1337 /// an extended immediate operand.
1338 class CopyConstantAsImmRenderer : public OperandRenderer {
1339 protected:
1340   unsigned NewInsnID;
1341   /// The name of the operand.
1342   const std::string SymbolicName;
1343   bool Signed;
1344 
1345 public:
1346   CopyConstantAsImmRenderer(unsigned NewInsnID, StringRef SymbolicName)
1347       : OperandRenderer(OR_CopyConstantAsImm), NewInsnID(NewInsnID),
1348         SymbolicName(SymbolicName), Signed(true) {}
1349 
1350   static bool classof(const OperandRenderer *R) {
1351     return R->getKind() == OR_CopyConstantAsImm;
1352   }
1353 
1354   const StringRef getSymbolicName() const { return SymbolicName; }
1355 
1356   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
1357     const InstructionMatcher &InsnMatcher = Rule.getInstructionMatcher(SymbolicName);
1358     unsigned OldInsnVarID = Rule.getInsnVarID(InsnMatcher);
1359     Table << MatchTable::Opcode(Signed ? "GIR_CopyConstantAsSImm"
1360                                        : "GIR_CopyConstantAsUImm")
1361           << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
1362           << MatchTable::Comment("OldInsnID")
1363           << MatchTable::IntValue(OldInsnVarID)
1364           << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
1365   }
1366 };
1367 
1368 /// A CopyFConstantAsFPImmRenderer emits code to render a G_FCONSTANT
1369 /// instruction to an extended immediate operand.
1370 class CopyFConstantAsFPImmRenderer : public OperandRenderer {
1371 protected:
1372   unsigned NewInsnID;
1373   /// The name of the operand.
1374   const std::string SymbolicName;
1375 
1376 public:
1377   CopyFConstantAsFPImmRenderer(unsigned NewInsnID, StringRef SymbolicName)
1378       : OperandRenderer(OR_CopyFConstantAsFPImm), NewInsnID(NewInsnID),
1379         SymbolicName(SymbolicName) {}
1380 
1381   static bool classof(const OperandRenderer *R) {
1382     return R->getKind() == OR_CopyFConstantAsFPImm;
1383   }
1384 
1385   const StringRef getSymbolicName() const { return SymbolicName; }
1386 
1387   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
1388     const InstructionMatcher &InsnMatcher = Rule.getInstructionMatcher(SymbolicName);
1389     unsigned OldInsnVarID = Rule.getInsnVarID(InsnMatcher);
1390     Table << MatchTable::Opcode("GIR_CopyFConstantAsFPImm")
1391           << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
1392           << MatchTable::Comment("OldInsnID")
1393           << MatchTable::IntValue(OldInsnVarID)
1394           << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
1395   }
1396 };
1397 
1398 /// A CopySubRegRenderer emits code to copy a single register operand from an
1399 /// existing instruction to the one being built and indicate that only a
1400 /// subregister should be copied.
1401 class CopySubRegRenderer : public OperandRenderer {
1402 protected:
1403   unsigned NewInsnID;
1404   /// The matcher for the instruction that this operand is copied from.
1405   /// This provides the facility for looking up an a operand by it's name so
1406   /// that it can be used as a source for the instruction being built.
1407   const InstructionMatcher &Matched;
1408   /// The name of the operand.
1409   const StringRef SymbolicName;
1410   /// The subregister to extract.
1411   const CodeGenSubRegIndex *SubReg;
1412 
1413 public:
1414   CopySubRegRenderer(unsigned NewInsnID, const InstructionMatcher &Matched,
1415                      StringRef SymbolicName, const CodeGenSubRegIndex *SubReg)
1416       : OperandRenderer(OR_CopySubReg), NewInsnID(NewInsnID), Matched(Matched),
1417         SymbolicName(SymbolicName), SubReg(SubReg) {}
1418 
1419   static bool classof(const OperandRenderer *R) {
1420     return R->getKind() == OR_CopySubReg;
1421   }
1422 
1423   const StringRef getSymbolicName() const { return SymbolicName; }
1424 
1425   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
1426     const OperandMatcher &Operand = Rule.getOperandMatcher(SymbolicName);
1427     unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
1428     Table << MatchTable::Opcode("GIR_CopySubReg")
1429           << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
1430           << MatchTable::Comment("OldInsnID")
1431           << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
1432           << MatchTable::IntValue(Operand.getOperandIndex())
1433           << MatchTable::Comment("SubRegIdx")
1434           << MatchTable::IntValue(SubReg->EnumValue)
1435           << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
1436   }
1437 };
1438 
1439 /// Adds a specific physical register to the instruction being built.
1440 /// This is typically useful for WZR/XZR on AArch64.
1441 class AddRegisterRenderer : public OperandRenderer {
1442 protected:
1443   unsigned InsnID;
1444   const Record *RegisterDef;
1445 
1446 public:
1447   AddRegisterRenderer(unsigned InsnID, const Record *RegisterDef)
1448       : OperandRenderer(OR_Register), InsnID(InsnID), RegisterDef(RegisterDef) {
1449   }
1450 
1451   static bool classof(const OperandRenderer *R) {
1452     return R->getKind() == OR_Register;
1453   }
1454 
1455   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
1456     Table << MatchTable::Opcode("GIR_AddRegister")
1457           << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1458           << MatchTable::NamedValue(
1459                  (RegisterDef->getValue("Namespace")
1460                       ? RegisterDef->getValueAsString("Namespace")
1461                       : ""),
1462                  RegisterDef->getName())
1463           << MatchTable::LineBreak;
1464   }
1465 };
1466 
1467 /// Adds a specific immediate to the instruction being built.
1468 class ImmRenderer : public OperandRenderer {
1469 protected:
1470   unsigned InsnID;
1471   int64_t Imm;
1472 
1473 public:
1474   ImmRenderer(unsigned InsnID, int64_t Imm)
1475       : OperandRenderer(OR_Imm), InsnID(InsnID), Imm(Imm) {}
1476 
1477   static bool classof(const OperandRenderer *R) {
1478     return R->getKind() == OR_Imm;
1479   }
1480 
1481   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
1482     Table << MatchTable::Opcode("GIR_AddImm") << MatchTable::Comment("InsnID")
1483           << MatchTable::IntValue(InsnID) << MatchTable::Comment("Imm")
1484           << MatchTable::IntValue(Imm) << MatchTable::LineBreak;
1485   }
1486 };
1487 
1488 /// Adds operands by calling a renderer function supplied by the ComplexPattern
1489 /// matcher function.
1490 class RenderComplexPatternOperand : public OperandRenderer {
1491 private:
1492   unsigned InsnID;
1493   const Record &TheDef;
1494   /// The name of the operand.
1495   const StringRef SymbolicName;
1496   /// The renderer number. This must be unique within a rule since it's used to
1497   /// identify a temporary variable to hold the renderer function.
1498   unsigned RendererID;
1499 
1500   unsigned getNumOperands() const {
1501     return TheDef.getValueAsDag("Operands")->getNumArgs();
1502   }
1503 
1504 public:
1505   RenderComplexPatternOperand(unsigned InsnID, const Record &TheDef,
1506                               StringRef SymbolicName, unsigned RendererID)
1507       : OperandRenderer(OR_ComplexPattern), InsnID(InsnID), TheDef(TheDef),
1508         SymbolicName(SymbolicName), RendererID(RendererID) {}
1509 
1510   static bool classof(const OperandRenderer *R) {
1511     return R->getKind() == OR_ComplexPattern;
1512   }
1513 
1514   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
1515     Table << MatchTable::Opcode("GIR_ComplexRenderer")
1516           << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1517           << MatchTable::Comment("RendererID")
1518           << MatchTable::IntValue(RendererID) << MatchTable::LineBreak;
1519   }
1520 };
1521 
1522 /// An action taken when all Matcher predicates succeeded for a parent rule.
1523 ///
1524 /// Typical actions include:
1525 /// * Changing the opcode of an instruction.
1526 /// * Adding an operand to an instruction.
1527 class MatchAction {
1528 public:
1529   virtual ~MatchAction() {}
1530 
1531   /// Emit the MatchTable opcodes to implement the action.
1532   ///
1533   /// \param RecycleInsnID If given, it's an instruction to recycle. The
1534   ///                      requirements on the instruction vary from action to
1535   ///                      action.
1536   virtual void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule,
1537                                  unsigned RecycleInsnID) const = 0;
1538 };
1539 
1540 /// Generates a comment describing the matched rule being acted upon.
1541 class DebugCommentAction : public MatchAction {
1542 private:
1543   const PatternToMatch &P;
1544 
1545 public:
1546   DebugCommentAction(const PatternToMatch &P) : P(P) {}
1547 
1548   void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule,
1549                          unsigned RecycleInsnID) const override {
1550     Table << MatchTable::Comment(llvm::to_string(*P.getSrcPattern()) + "  =>  " +
1551                                llvm::to_string(*P.getDstPattern()))
1552           << MatchTable::LineBreak;
1553   }
1554 };
1555 
1556 /// Generates code to build an instruction or mutate an existing instruction
1557 /// into the desired instruction when this is possible.
1558 class BuildMIAction : public MatchAction {
1559 private:
1560   unsigned InsnID;
1561   const CodeGenInstruction *I;
1562   const InstructionMatcher &Matched;
1563   std::vector<std::unique_ptr<OperandRenderer>> OperandRenderers;
1564 
1565   /// True if the instruction can be built solely by mutating the opcode.
1566   bool canMutate(RuleMatcher &Rule) const {
1567     if (OperandRenderers.size() != Matched.getNumOperands())
1568       return false;
1569 
1570     for (const auto &Renderer : enumerate(OperandRenderers)) {
1571       if (const auto *Copy = dyn_cast<CopyRenderer>(&*Renderer.value())) {
1572         const OperandMatcher &OM = Rule.getOperandMatcher(Copy->getSymbolicName());
1573         if (&Matched != &OM.getInstructionMatcher() ||
1574             OM.getOperandIndex() != Renderer.index())
1575           return false;
1576       } else
1577         return false;
1578     }
1579 
1580     return true;
1581   }
1582 
1583 public:
1584   BuildMIAction(unsigned InsnID, const CodeGenInstruction *I,
1585                 const InstructionMatcher &Matched)
1586       : InsnID(InsnID), I(I), Matched(Matched) {}
1587 
1588   template <class Kind, class... Args>
1589   Kind &addRenderer(Args&&... args) {
1590     OperandRenderers.emplace_back(
1591         llvm::make_unique<Kind>(std::forward<Args>(args)...));
1592     return *static_cast<Kind *>(OperandRenderers.back().get());
1593   }
1594 
1595   void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule,
1596                          unsigned RecycleInsnID) const override {
1597     if (canMutate(Rule)) {
1598       Table << MatchTable::Opcode("GIR_MutateOpcode")
1599             << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1600             << MatchTable::Comment("RecycleInsnID")
1601             << MatchTable::IntValue(RecycleInsnID)
1602             << MatchTable::Comment("Opcode")
1603             << MatchTable::NamedValue(I->Namespace, I->TheDef->getName())
1604             << MatchTable::LineBreak;
1605 
1606       if (!I->ImplicitDefs.empty() || !I->ImplicitUses.empty()) {
1607         for (auto Def : I->ImplicitDefs) {
1608           auto Namespace = Def->getValue("Namespace")
1609                                ? Def->getValueAsString("Namespace")
1610                                : "";
1611           Table << MatchTable::Opcode("GIR_AddImplicitDef")
1612                 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1613                 << MatchTable::NamedValue(Namespace, Def->getName())
1614                 << MatchTable::LineBreak;
1615         }
1616         for (auto Use : I->ImplicitUses) {
1617           auto Namespace = Use->getValue("Namespace")
1618                                ? Use->getValueAsString("Namespace")
1619                                : "";
1620           Table << MatchTable::Opcode("GIR_AddImplicitUse")
1621                 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1622                 << MatchTable::NamedValue(Namespace, Use->getName())
1623                 << MatchTable::LineBreak;
1624         }
1625       }
1626       return;
1627     }
1628 
1629     // TODO: Simple permutation looks like it could be almost as common as
1630     //       mutation due to commutative operations.
1631 
1632     Table << MatchTable::Opcode("GIR_BuildMI") << MatchTable::Comment("InsnID")
1633           << MatchTable::IntValue(InsnID) << MatchTable::Comment("Opcode")
1634           << MatchTable::NamedValue(I->Namespace, I->TheDef->getName())
1635           << MatchTable::LineBreak;
1636     for (const auto &Renderer : OperandRenderers)
1637       Renderer->emitRenderOpcodes(Table, Rule);
1638 
1639     if (I->mayLoad || I->mayStore) {
1640       Table << MatchTable::Opcode("GIR_MergeMemOperands")
1641             << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1642             << MatchTable::Comment("MergeInsnID's");
1643       // Emit the ID's for all the instructions that are matched by this rule.
1644       // TODO: Limit this to matched instructions that mayLoad/mayStore or have
1645       //       some other means of having a memoperand. Also limit this to
1646       //       emitted instructions that expect to have a memoperand too. For
1647       //       example, (G_SEXT (G_LOAD x)) that results in separate load and
1648       //       sign-extend instructions shouldn't put the memoperand on the
1649       //       sign-extend since it has no effect there.
1650       std::vector<unsigned> MergeInsnIDs;
1651       for (const auto &IDMatcherPair : Rule.defined_insn_vars())
1652         MergeInsnIDs.push_back(IDMatcherPair.second);
1653       std::sort(MergeInsnIDs.begin(), MergeInsnIDs.end());
1654       for (const auto &MergeInsnID : MergeInsnIDs)
1655         Table << MatchTable::IntValue(MergeInsnID);
1656       Table << MatchTable::NamedValue("GIU_MergeMemOperands_EndOfList")
1657             << MatchTable::LineBreak;
1658     }
1659 
1660     Table << MatchTable::Opcode("GIR_EraseFromParent")
1661           << MatchTable::Comment("InsnID")
1662           << MatchTable::IntValue(RecycleInsnID) << MatchTable::LineBreak;
1663   }
1664 };
1665 
1666 /// Generates code to constrain the operands of an output instruction to the
1667 /// register classes specified by the definition of that instruction.
1668 class ConstrainOperandsToDefinitionAction : public MatchAction {
1669   unsigned InsnID;
1670 
1671 public:
1672   ConstrainOperandsToDefinitionAction(unsigned InsnID) : InsnID(InsnID) {}
1673 
1674   void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule,
1675                          unsigned RecycleInsnID) const override {
1676     Table << MatchTable::Opcode("GIR_ConstrainSelectedInstOperands")
1677           << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1678           << MatchTable::LineBreak;
1679   }
1680 };
1681 
1682 /// Generates code to constrain the specified operand of an output instruction
1683 /// to the specified register class.
1684 class ConstrainOperandToRegClassAction : public MatchAction {
1685   unsigned InsnID;
1686   unsigned OpIdx;
1687   const CodeGenRegisterClass &RC;
1688 
1689 public:
1690   ConstrainOperandToRegClassAction(unsigned InsnID, unsigned OpIdx,
1691                                    const CodeGenRegisterClass &RC)
1692       : InsnID(InsnID), OpIdx(OpIdx), RC(RC) {}
1693 
1694   void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule,
1695                          unsigned RecycleInsnID) const override {
1696     Table << MatchTable::Opcode("GIR_ConstrainOperandRC")
1697           << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1698           << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1699           << MatchTable::Comment("RC " + RC.getName())
1700           << MatchTable::IntValue(RC.EnumValue) << MatchTable::LineBreak;
1701   }
1702 };
1703 
1704 InstructionMatcher &RuleMatcher::addInstructionMatcher(StringRef SymbolicName) {
1705   Matchers.emplace_back(new InstructionMatcher(*this, SymbolicName));
1706   return *Matchers.back();
1707 }
1708 
1709 void RuleMatcher::addRequiredFeature(Record *Feature) {
1710   RequiredFeatures.push_back(Feature);
1711 }
1712 
1713 const std::vector<Record *> &RuleMatcher::getRequiredFeatures() const {
1714   return RequiredFeatures;
1715 }
1716 
1717 template <class Kind, class... Args>
1718 Kind &RuleMatcher::addAction(Args &&... args) {
1719   Actions.emplace_back(llvm::make_unique<Kind>(std::forward<Args>(args)...));
1720   return *static_cast<Kind *>(Actions.back().get());
1721 }
1722 
1723 unsigned
1724 RuleMatcher::implicitlyDefineInsnVar(const InstructionMatcher &Matcher) {
1725   unsigned NewInsnVarID = NextInsnVarID++;
1726   InsnVariableIDs[&Matcher] = NewInsnVarID;
1727   return NewInsnVarID;
1728 }
1729 
1730 unsigned RuleMatcher::defineInsnVar(MatchTable &Table,
1731                                     const InstructionMatcher &Matcher,
1732                                     unsigned InsnID, unsigned OpIdx) {
1733   unsigned NewInsnVarID = implicitlyDefineInsnVar(Matcher);
1734   Table << MatchTable::Opcode("GIM_RecordInsn")
1735         << MatchTable::Comment("DefineMI") << MatchTable::IntValue(NewInsnVarID)
1736         << MatchTable::Comment("MI") << MatchTable::IntValue(InsnID)
1737         << MatchTable::Comment("OpIdx") << MatchTable::IntValue(OpIdx)
1738         << MatchTable::Comment("MIs[" + llvm::to_string(NewInsnVarID) + "]")
1739         << MatchTable::LineBreak;
1740   return NewInsnVarID;
1741 }
1742 
1743 unsigned RuleMatcher::getInsnVarID(const InstructionMatcher &InsnMatcher) const {
1744   const auto &I = InsnVariableIDs.find(&InsnMatcher);
1745   if (I != InsnVariableIDs.end())
1746     return I->second;
1747   llvm_unreachable("Matched Insn was not captured in a local variable");
1748 }
1749 
1750 void RuleMatcher::defineOperand(StringRef SymbolicName, OperandMatcher &OM) {
1751   if (DefinedOperands.find(SymbolicName) == DefinedOperands.end()) {
1752     DefinedOperands[SymbolicName] = &OM;
1753     return;
1754   }
1755 
1756   // If the operand is already defined, then we must ensure both references in
1757   // the matcher have the exact same node.
1758   OM.addPredicate<SameOperandMatcher>(OM.getSymbolicName());
1759 }
1760 
1761 const InstructionMatcher &
1762 RuleMatcher::getInstructionMatcher(StringRef SymbolicName) const {
1763   for (const auto &I : InsnVariableIDs)
1764     if (I.first->getSymbolicName() == SymbolicName)
1765       return *I.first;
1766   llvm_unreachable(
1767       ("Failed to lookup instruction " + SymbolicName).str().c_str());
1768 }
1769 
1770 const OperandMatcher &
1771 RuleMatcher::getOperandMatcher(StringRef Name) const {
1772   const auto &I = DefinedOperands.find(Name);
1773 
1774   if (I == DefinedOperands.end())
1775     PrintFatalError(SrcLoc, "Operand " + Name + " was not declared in matcher");
1776 
1777   return *I->second;
1778 }
1779 
1780 /// Emit MatchTable opcodes to check the shape of the match and capture
1781 /// instructions into local variables.
1782 void RuleMatcher::emitCaptureOpcodes(MatchTable &Table) {
1783   assert(Matchers.size() == 1 && "Cannot handle multi-root matchers yet");
1784   unsigned InsnVarID = implicitlyDefineInsnVar(*Matchers.front());
1785   Matchers.front()->emitCaptureOpcodes(Table, *this, InsnVarID);
1786 }
1787 
1788 void RuleMatcher::emit(MatchTable &Table) {
1789   if (Matchers.empty())
1790     llvm_unreachable("Unexpected empty matcher!");
1791 
1792   // The representation supports rules that require multiple roots such as:
1793   //    %ptr(p0) = ...
1794   //    %elt0(s32) = G_LOAD %ptr
1795   //    %1(p0) = G_ADD %ptr, 4
1796   //    %elt1(s32) = G_LOAD p0 %1
1797   // which could be usefully folded into:
1798   //    %ptr(p0) = ...
1799   //    %elt0(s32), %elt1(s32) = TGT_LOAD_PAIR %ptr
1800   // on some targets but we don't need to make use of that yet.
1801   assert(Matchers.size() == 1 && "Cannot handle multi-root matchers yet");
1802 
1803   unsigned LabelID = Table.allocateLabelID();
1804   Table << MatchTable::Opcode("GIM_Try", +1)
1805         << MatchTable::Comment("On fail goto") << MatchTable::JumpTarget(LabelID)
1806         << MatchTable::LineBreak;
1807 
1808   if (!RequiredFeatures.empty()) {
1809     Table << MatchTable::Opcode("GIM_CheckFeatures")
1810           << MatchTable::NamedValue(getNameForFeatureBitset(RequiredFeatures))
1811           << MatchTable::LineBreak;
1812   }
1813 
1814   emitCaptureOpcodes(Table);
1815 
1816   Matchers.front()->emitPredicateOpcodes(Table, *this,
1817                                          getInsnVarID(*Matchers.front()));
1818 
1819   // We must also check if it's safe to fold the matched instructions.
1820   if (InsnVariableIDs.size() >= 2) {
1821     // Invert the map to create stable ordering (by var names)
1822     SmallVector<unsigned, 2> InsnIDs;
1823     for (const auto &Pair : InsnVariableIDs) {
1824       // Skip the root node since it isn't moving anywhere. Everything else is
1825       // sinking to meet it.
1826       if (Pair.first == Matchers.front().get())
1827         continue;
1828 
1829       InsnIDs.push_back(Pair.second);
1830     }
1831     std::sort(InsnIDs.begin(), InsnIDs.end());
1832 
1833     for (const auto &InsnID : InsnIDs) {
1834       // Reject the difficult cases until we have a more accurate check.
1835       Table << MatchTable::Opcode("GIM_CheckIsSafeToFold")
1836             << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1837             << MatchTable::LineBreak;
1838 
1839       // FIXME: Emit checks to determine it's _actually_ safe to fold and/or
1840       //        account for unsafe cases.
1841       //
1842       //        Example:
1843       //          MI1--> %0 = ...
1844       //                 %1 = ... %0
1845       //          MI0--> %2 = ... %0
1846       //          It's not safe to erase MI1. We currently handle this by not
1847       //          erasing %0 (even when it's dead).
1848       //
1849       //        Example:
1850       //          MI1--> %0 = load volatile @a
1851       //                 %1 = load volatile @a
1852       //          MI0--> %2 = ... %0
1853       //          It's not safe to sink %0's def past %1. We currently handle
1854       //          this by rejecting all loads.
1855       //
1856       //        Example:
1857       //          MI1--> %0 = load @a
1858       //                 %1 = store @a
1859       //          MI0--> %2 = ... %0
1860       //          It's not safe to sink %0's def past %1. We currently handle
1861       //          this by rejecting all loads.
1862       //
1863       //        Example:
1864       //                   G_CONDBR %cond, @BB1
1865       //                 BB0:
1866       //          MI1-->   %0 = load @a
1867       //                   G_BR @BB1
1868       //                 BB1:
1869       //          MI0-->   %2 = ... %0
1870       //          It's not always safe to sink %0 across control flow. In this
1871       //          case it may introduce a memory fault. We currentl handle this
1872       //          by rejecting all loads.
1873     }
1874   }
1875 
1876   for (const auto &MA : Actions)
1877     MA->emitActionOpcodes(Table, *this, 0);
1878   Table << MatchTable::Opcode("GIR_Done", -1) << MatchTable::LineBreak
1879         << MatchTable::Label(LabelID);
1880 }
1881 
1882 bool RuleMatcher::isHigherPriorityThan(const RuleMatcher &B) const {
1883   // Rules involving more match roots have higher priority.
1884   if (Matchers.size() > B.Matchers.size())
1885     return true;
1886   if (Matchers.size() < B.Matchers.size())
1887     return false;
1888 
1889   for (const auto &Matcher : zip(Matchers, B.Matchers)) {
1890     if (std::get<0>(Matcher)->isHigherPriorityThan(*std::get<1>(Matcher)))
1891       return true;
1892     if (std::get<1>(Matcher)->isHigherPriorityThan(*std::get<0>(Matcher)))
1893       return false;
1894   }
1895 
1896   return false;
1897 }
1898 
1899 unsigned RuleMatcher::countRendererFns() const {
1900   return std::accumulate(
1901       Matchers.begin(), Matchers.end(), 0,
1902       [](unsigned A, const std::unique_ptr<InstructionMatcher> &Matcher) {
1903         return A + Matcher->countRendererFns();
1904       });
1905 }
1906 
1907 bool OperandPredicateMatcher::isHigherPriorityThan(
1908     const OperandPredicateMatcher &B) const {
1909   // Generally speaking, an instruction is more important than an Int or a
1910   // LiteralInt because it can cover more nodes but theres an exception to
1911   // this. G_CONSTANT's are less important than either of those two because they
1912   // are more permissive.
1913 
1914   const InstructionOperandMatcher *AOM =
1915       dyn_cast<InstructionOperandMatcher>(this);
1916   const InstructionOperandMatcher *BOM =
1917       dyn_cast<InstructionOperandMatcher>(&B);
1918   bool AIsConstantInsn = AOM && AOM->getInsnMatcher().isConstantInstruction();
1919   bool BIsConstantInsn = BOM && BOM->getInsnMatcher().isConstantInstruction();
1920 
1921   if (AOM && BOM) {
1922     // The relative priorities between a G_CONSTANT and any other instruction
1923     // don't actually matter but this code is needed to ensure a strict weak
1924     // ordering. This is particularly important on Windows where the rules will
1925     // be incorrectly sorted without it.
1926     if (AIsConstantInsn != BIsConstantInsn)
1927       return AIsConstantInsn < BIsConstantInsn;
1928     return false;
1929   }
1930 
1931   if (AOM && AIsConstantInsn && (B.Kind == OPM_Int || B.Kind == OPM_LiteralInt))
1932     return false;
1933   if (BOM && BIsConstantInsn && (Kind == OPM_Int || Kind == OPM_LiteralInt))
1934     return true;
1935 
1936   return Kind < B.Kind;
1937 }
1938 
1939 void SameOperandMatcher::emitPredicateOpcodes(MatchTable &Table,
1940                                               RuleMatcher &Rule,
1941                                               unsigned InsnVarID,
1942                                               unsigned OpIdx) const {
1943   const OperandMatcher &OtherOM = Rule.getOperandMatcher(TiedTo);
1944   unsigned OtherInsnVarID = Rule.getInsnVarID(OtherOM.getInstructionMatcher());
1945 
1946   Table << MatchTable::Opcode("GIM_CheckIsSameOperand")
1947         << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1948         << MatchTable::Comment("OpIdx") << MatchTable::IntValue(OpIdx)
1949         << MatchTable::Comment("OtherMI")
1950         << MatchTable::IntValue(OtherInsnVarID)
1951         << MatchTable::Comment("OtherOpIdx")
1952         << MatchTable::IntValue(OtherOM.getOperandIndex())
1953         << MatchTable::LineBreak;
1954 }
1955 
1956 //===- GlobalISelEmitter class --------------------------------------------===//
1957 
1958 class GlobalISelEmitter {
1959 public:
1960   explicit GlobalISelEmitter(RecordKeeper &RK);
1961   void run(raw_ostream &OS);
1962 
1963 private:
1964   const RecordKeeper &RK;
1965   const CodeGenDAGPatterns CGP;
1966   const CodeGenTarget &Target;
1967   CodeGenRegBank CGRegs;
1968 
1969   /// Keep track of the equivalence between SDNodes and Instruction.
1970   /// This is defined using 'GINodeEquiv' in the target description.
1971   DenseMap<Record *, const CodeGenInstruction *> NodeEquivs;
1972 
1973   /// Keep track of the equivalence between ComplexPattern's and
1974   /// GIComplexOperandMatcher. Map entries are specified by subclassing
1975   /// GIComplexPatternEquiv.
1976   DenseMap<const Record *, const Record *> ComplexPatternEquivs;
1977 
1978   // Map of predicates to their subtarget features.
1979   SubtargetFeatureInfoMap SubtargetFeatures;
1980 
1981   void gatherNodeEquivs();
1982   const CodeGenInstruction *findNodeEquiv(Record *N) const;
1983 
1984   Error importRulePredicates(RuleMatcher &M, ArrayRef<Predicate> Predicates);
1985   Expected<InstructionMatcher &>
1986   createAndImportSelDAGMatcher(InstructionMatcher &InsnMatcher,
1987                                const TreePatternNode *Src,
1988                                unsigned &TempOpIdx) const;
1989   Error importChildMatcher(InstructionMatcher &InsnMatcher,
1990                            const TreePatternNode *SrcChild, unsigned OpIdx,
1991                            unsigned &TempOpIdx) const;
1992   Expected<BuildMIAction &>
1993   createAndImportInstructionRenderer(RuleMatcher &M, const TreePatternNode *Dst,
1994                                      const InstructionMatcher &InsnMatcher);
1995   Error importExplicitUseRenderer(RuleMatcher &Rule,
1996                                   BuildMIAction &DstMIBuilder,
1997                                   TreePatternNode *DstChild,
1998                                   const InstructionMatcher &InsnMatcher) const;
1999   Error importDefaultOperandRenderers(BuildMIAction &DstMIBuilder,
2000                                       DagInit *DefaultOps) const;
2001   Error
2002   importImplicitDefRenderers(BuildMIAction &DstMIBuilder,
2003                              const std::vector<Record *> &ImplicitDefs) const;
2004 
2005   void emitImmPredicates(raw_ostream &OS, StringRef TypeIdentifier,
2006                          StringRef Type,
2007                          std::function<bool(const Record *R)> Filter);
2008 
2009   /// Analyze pattern \p P, returning a matcher for it if possible.
2010   /// Otherwise, return an Error explaining why we don't support it.
2011   Expected<RuleMatcher> runOnPattern(const PatternToMatch &P);
2012 
2013   void declareSubtargetFeature(Record *Predicate);
2014 };
2015 
2016 void GlobalISelEmitter::gatherNodeEquivs() {
2017   assert(NodeEquivs.empty());
2018   for (Record *Equiv : RK.getAllDerivedDefinitions("GINodeEquiv"))
2019     NodeEquivs[Equiv->getValueAsDef("Node")] =
2020         &Target.getInstruction(Equiv->getValueAsDef("I"));
2021 
2022   assert(ComplexPatternEquivs.empty());
2023   for (Record *Equiv : RK.getAllDerivedDefinitions("GIComplexPatternEquiv")) {
2024     Record *SelDAGEquiv = Equiv->getValueAsDef("SelDAGEquivalent");
2025     if (!SelDAGEquiv)
2026       continue;
2027     ComplexPatternEquivs[SelDAGEquiv] = Equiv;
2028  }
2029 }
2030 
2031 const CodeGenInstruction *GlobalISelEmitter::findNodeEquiv(Record *N) const {
2032   return NodeEquivs.lookup(N);
2033 }
2034 
2035 GlobalISelEmitter::GlobalISelEmitter(RecordKeeper &RK)
2036     : RK(RK), CGP(RK), Target(CGP.getTargetInfo()),
2037       CGRegs(RK, Target.getHwModes()) {}
2038 
2039 //===- Emitter ------------------------------------------------------------===//
2040 
2041 Error
2042 GlobalISelEmitter::importRulePredicates(RuleMatcher &M,
2043                                         ArrayRef<Predicate> Predicates) {
2044   for (const Predicate &P : Predicates) {
2045     if (!P.Def)
2046       continue;
2047     declareSubtargetFeature(P.Def);
2048     M.addRequiredFeature(P.Def);
2049   }
2050 
2051   return Error::success();
2052 }
2053 
2054 Expected<InstructionMatcher &>
2055 GlobalISelEmitter::createAndImportSelDAGMatcher(InstructionMatcher &InsnMatcher,
2056                                                 const TreePatternNode *Src,
2057                                                 unsigned &TempOpIdx) const {
2058   const CodeGenInstruction *SrcGIOrNull = nullptr;
2059 
2060   // Start with the defined operands (i.e., the results of the root operator).
2061   if (Src->getExtTypes().size() > 1)
2062     return failedImport("Src pattern has multiple results");
2063 
2064   if (Src->isLeaf()) {
2065     Init *SrcInit = Src->getLeafValue();
2066     if (isa<IntInit>(SrcInit)) {
2067       InsnMatcher.addPredicate<InstructionOpcodeMatcher>(
2068           &Target.getInstruction(RK.getDef("G_CONSTANT")));
2069     } else
2070       return failedImport(
2071           "Unable to deduce gMIR opcode to handle Src (which is a leaf)");
2072   } else {
2073     SrcGIOrNull = findNodeEquiv(Src->getOperator());
2074     if (!SrcGIOrNull)
2075       return failedImport("Pattern operator lacks an equivalent Instruction" +
2076                           explainOperator(Src->getOperator()));
2077     auto &SrcGI = *SrcGIOrNull;
2078 
2079     // The operators look good: match the opcode
2080     InsnMatcher.addPredicate<InstructionOpcodeMatcher>(&SrcGI);
2081   }
2082 
2083   unsigned OpIdx = 0;
2084   for (const TypeSetByHwMode &VTy : Src->getExtTypes()) {
2085     auto OpTyOrNone = VTy.isMachineValueType()
2086                           ? MVTToLLT(VTy.getMachineValueType().SimpleTy)
2087                           : None;
2088     if (!OpTyOrNone)
2089       return failedImport(
2090           "Result of Src pattern operator has an unsupported type");
2091 
2092     // Results don't have a name unless they are the root node. The caller will
2093     // set the name if appropriate.
2094     OperandMatcher &OM = InsnMatcher.addOperand(OpIdx++, "", TempOpIdx);
2095     OM.addPredicate<LLTOperandMatcher>(*OpTyOrNone);
2096   }
2097 
2098   for (const auto &Predicate : Src->getPredicateFns()) {
2099     if (Predicate.isAlwaysTrue())
2100       continue;
2101 
2102     if (Predicate.isImmediatePattern()) {
2103       InsnMatcher.addPredicate<InstructionImmPredicateMatcher>(Predicate);
2104       continue;
2105     }
2106 
2107     return failedImport("Src pattern child has predicate (" +
2108                         explainPredicates(Src) + ")");
2109   }
2110 
2111   if (Src->isLeaf()) {
2112     Init *SrcInit = Src->getLeafValue();
2113     if (IntInit *SrcIntInit = dyn_cast<IntInit>(SrcInit)) {
2114       OperandMatcher &OM =
2115           InsnMatcher.addOperand(OpIdx++, Src->getName(), TempOpIdx);
2116       OM.addPredicate<LiteralIntOperandMatcher>(SrcIntInit->getValue());
2117     } else
2118       return failedImport(
2119           "Unable to deduce gMIR opcode to handle Src (which is a leaf)");
2120   } else {
2121     assert(SrcGIOrNull &&
2122            "Expected to have already found an equivalent Instruction");
2123     if (SrcGIOrNull->TheDef->getName() == "G_CONSTANT" ||
2124         SrcGIOrNull->TheDef->getName() == "G_FCONSTANT") {
2125       // imm/fpimm still have operands but we don't need to do anything with it
2126       // here since we don't support ImmLeaf predicates yet. However, we still
2127       // need to note the hidden operand to get GIM_CheckNumOperands correct.
2128       InsnMatcher.addOperand(OpIdx++, "", TempOpIdx);
2129       return InsnMatcher;
2130     }
2131 
2132     // Match the used operands (i.e. the children of the operator).
2133     for (unsigned i = 0, e = Src->getNumChildren(); i != e; ++i) {
2134       TreePatternNode *SrcChild = Src->getChild(i);
2135 
2136       // For G_INTRINSIC/G_INTRINSIC_W_SIDE_EFFECTS, the operand immediately
2137       // following the defs is an intrinsic ID.
2138       if ((SrcGIOrNull->TheDef->getName() == "G_INTRINSIC" ||
2139            SrcGIOrNull->TheDef->getName() == "G_INTRINSIC_W_SIDE_EFFECTS") &&
2140           i == 0) {
2141         if (const CodeGenIntrinsic *II = Src->getIntrinsicInfo(CGP)) {
2142           OperandMatcher &OM =
2143               InsnMatcher.addOperand(OpIdx++, SrcChild->getName(), TempOpIdx);
2144           OM.addPredicate<IntrinsicIDOperandMatcher>(II);
2145           continue;
2146         }
2147 
2148         return failedImport("Expected IntInit containing instrinsic ID)");
2149       }
2150 
2151       if (auto Error =
2152               importChildMatcher(InsnMatcher, SrcChild, OpIdx++, TempOpIdx))
2153         return std::move(Error);
2154     }
2155   }
2156 
2157   return InsnMatcher;
2158 }
2159 
2160 Error GlobalISelEmitter::importChildMatcher(InstructionMatcher &InsnMatcher,
2161                                             const TreePatternNode *SrcChild,
2162                                             unsigned OpIdx,
2163                                             unsigned &TempOpIdx) const {
2164   OperandMatcher &OM =
2165       InsnMatcher.addOperand(OpIdx, SrcChild->getName(), TempOpIdx);
2166   if (OM.isSameAsAnotherOperand())
2167     return Error::success();
2168 
2169   ArrayRef<TypeSetByHwMode> ChildTypes = SrcChild->getExtTypes();
2170   if (ChildTypes.size() != 1)
2171     return failedImport("Src pattern child has multiple results");
2172 
2173   // Check MBB's before the type check since they are not a known type.
2174   if (!SrcChild->isLeaf()) {
2175     if (SrcChild->getOperator()->isSubClassOf("SDNode")) {
2176       auto &ChildSDNI = CGP.getSDNodeInfo(SrcChild->getOperator());
2177       if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") {
2178         OM.addPredicate<MBBOperandMatcher>();
2179         return Error::success();
2180       }
2181     }
2182   }
2183 
2184   Optional<LLTCodeGen> OpTyOrNone = None;
2185   if (ChildTypes.front().isMachineValueType())
2186     OpTyOrNone = MVTToLLT(ChildTypes.front().getMachineValueType().SimpleTy);
2187   if (!OpTyOrNone)
2188     return failedImport("Src operand has an unsupported type (" + to_string(*SrcChild) + ")");
2189   OM.addPredicate<LLTOperandMatcher>(*OpTyOrNone);
2190 
2191   // Check for nested instructions.
2192   if (!SrcChild->isLeaf()) {
2193     auto MaybeInsnOperand = OM.addPredicate<InstructionOperandMatcher>(
2194         InsnMatcher.getRuleMatcher(), SrcChild->getName());
2195     if (!MaybeInsnOperand.hasValue()) {
2196       // This isn't strictly true. If the user were to provide exactly the same
2197       // matchers as the original operand then we could allow it. However, it's
2198       // simpler to not permit the redundant specification.
2199       return failedImport("Nested instruction cannot be the same as another operand");
2200     }
2201 
2202     // Map the node to a gMIR instruction.
2203     InstructionOperandMatcher &InsnOperand = **MaybeInsnOperand;
2204     auto InsnMatcherOrError = createAndImportSelDAGMatcher(
2205         InsnOperand.getInsnMatcher(), SrcChild, TempOpIdx);
2206     if (auto Error = InsnMatcherOrError.takeError())
2207       return Error;
2208 
2209     return Error::success();
2210   }
2211 
2212   // Check for constant immediates.
2213   if (auto *ChildInt = dyn_cast<IntInit>(SrcChild->getLeafValue())) {
2214     OM.addPredicate<ConstantIntOperandMatcher>(ChildInt->getValue());
2215     return Error::success();
2216   }
2217 
2218   // Check for def's like register classes or ComplexPattern's.
2219   if (auto *ChildDefInit = dyn_cast<DefInit>(SrcChild->getLeafValue())) {
2220     auto *ChildRec = ChildDefInit->getDef();
2221 
2222     // Check for register classes.
2223     if (ChildRec->isSubClassOf("RegisterClass") ||
2224         ChildRec->isSubClassOf("RegisterOperand")) {
2225       OM.addPredicate<RegisterBankOperandMatcher>(
2226           Target.getRegisterClass(getInitValueAsRegClass(ChildDefInit)));
2227       return Error::success();
2228     }
2229 
2230     // Check for ValueType.
2231     if (ChildRec->isSubClassOf("ValueType")) {
2232       // We already added a type check as standard practice so this doesn't need
2233       // to do anything.
2234       return Error::success();
2235     }
2236 
2237     // Check for ComplexPattern's.
2238     if (ChildRec->isSubClassOf("ComplexPattern")) {
2239       const auto &ComplexPattern = ComplexPatternEquivs.find(ChildRec);
2240       if (ComplexPattern == ComplexPatternEquivs.end())
2241         return failedImport("SelectionDAG ComplexPattern (" +
2242                             ChildRec->getName() + ") not mapped to GlobalISel");
2243 
2244       OM.addPredicate<ComplexPatternOperandMatcher>(OM,
2245                                                     *ComplexPattern->second);
2246       TempOpIdx++;
2247       return Error::success();
2248     }
2249 
2250     if (ChildRec->isSubClassOf("ImmLeaf")) {
2251       return failedImport(
2252           "Src pattern child def is an unsupported tablegen class (ImmLeaf)");
2253     }
2254 
2255     return failedImport(
2256         "Src pattern child def is an unsupported tablegen class");
2257   }
2258 
2259   return failedImport("Src pattern child is an unsupported kind");
2260 }
2261 
2262 Error GlobalISelEmitter::importExplicitUseRenderer(
2263     RuleMatcher &Rule, BuildMIAction &DstMIBuilder, TreePatternNode *DstChild,
2264     const InstructionMatcher &InsnMatcher) const {
2265   if (DstChild->getTransformFn() != nullptr) {
2266     return failedImport("Dst pattern child has transform fn " +
2267                         DstChild->getTransformFn()->getName());
2268   }
2269 
2270   if (!DstChild->isLeaf()) {
2271     // We accept 'bb' here. It's an operator because BasicBlockSDNode isn't
2272     // inline, but in MI it's just another operand.
2273     if (DstChild->getOperator()->isSubClassOf("SDNode")) {
2274       auto &ChildSDNI = CGP.getSDNodeInfo(DstChild->getOperator());
2275       if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") {
2276         DstMIBuilder.addRenderer<CopyRenderer>(0, InsnMatcher,
2277                                                DstChild->getName());
2278         return Error::success();
2279       }
2280     }
2281 
2282     // Similarly, imm is an operator in TreePatternNode's view but must be
2283     // rendered as operands.
2284     // FIXME: The target should be able to choose sign-extended when appropriate
2285     //        (e.g. on Mips).
2286     if (DstChild->getOperator()->getName() == "imm") {
2287       DstMIBuilder.addRenderer<CopyConstantAsImmRenderer>(0,
2288                                                           DstChild->getName());
2289       return Error::success();
2290     } else if (DstChild->getOperator()->getName() == "fpimm") {
2291       DstMIBuilder.addRenderer<CopyFConstantAsFPImmRenderer>(
2292           0, DstChild->getName());
2293       return Error::success();
2294     }
2295 
2296     return failedImport("Dst pattern child isn't a leaf node or an MBB" + llvm::to_string(*DstChild));
2297   }
2298 
2299   // Otherwise, we're looking for a bog-standard RegisterClass operand.
2300   if (auto *ChildDefInit = dyn_cast<DefInit>(DstChild->getLeafValue())) {
2301     auto *ChildRec = ChildDefInit->getDef();
2302 
2303     ArrayRef<TypeSetByHwMode> ChildTypes = DstChild->getExtTypes();
2304     if (ChildTypes.size() != 1)
2305       return failedImport("Dst pattern child has multiple results");
2306 
2307     Optional<LLTCodeGen> OpTyOrNone = None;
2308     if (ChildTypes.front().isMachineValueType())
2309       OpTyOrNone = MVTToLLT(ChildTypes.front().getMachineValueType().SimpleTy);
2310     if (!OpTyOrNone)
2311       return failedImport("Dst operand has an unsupported type");
2312 
2313     if (ChildRec->isSubClassOf("Register")) {
2314       DstMIBuilder.addRenderer<AddRegisterRenderer>(0, ChildRec);
2315       return Error::success();
2316     }
2317 
2318     if (ChildRec->isSubClassOf("RegisterClass") ||
2319         ChildRec->isSubClassOf("RegisterOperand") ||
2320         ChildRec->isSubClassOf("ValueType")) {
2321       DstMIBuilder.addRenderer<CopyRenderer>(0, InsnMatcher,
2322                                              DstChild->getName());
2323       return Error::success();
2324     }
2325 
2326     if (ChildRec->isSubClassOf("ComplexPattern")) {
2327       const auto &ComplexPattern = ComplexPatternEquivs.find(ChildRec);
2328       if (ComplexPattern == ComplexPatternEquivs.end())
2329         return failedImport(
2330             "SelectionDAG ComplexPattern not mapped to GlobalISel");
2331 
2332       const OperandMatcher &OM = Rule.getOperandMatcher(DstChild->getName());
2333       DstMIBuilder.addRenderer<RenderComplexPatternOperand>(
2334           0, *ComplexPattern->second, DstChild->getName(),
2335           OM.getAllocatedTemporariesBaseID());
2336       return Error::success();
2337     }
2338 
2339     if (ChildRec->isSubClassOf("SDNodeXForm"))
2340       return failedImport("Dst pattern child def is an unsupported tablegen "
2341                           "class (SDNodeXForm)");
2342 
2343     return failedImport(
2344         "Dst pattern child def is an unsupported tablegen class");
2345   }
2346 
2347   return failedImport("Dst pattern child is an unsupported kind");
2348 }
2349 
2350 Expected<BuildMIAction &> GlobalISelEmitter::createAndImportInstructionRenderer(
2351     RuleMatcher &M, const TreePatternNode *Dst,
2352     const InstructionMatcher &InsnMatcher) {
2353   Record *DstOp = Dst->getOperator();
2354   if (!DstOp->isSubClassOf("Instruction")) {
2355     if (DstOp->isSubClassOf("ValueType"))
2356       return failedImport(
2357           "Pattern operator isn't an instruction (it's a ValueType)");
2358     return failedImport("Pattern operator isn't an instruction");
2359   }
2360   CodeGenInstruction *DstI = &Target.getInstruction(DstOp);
2361 
2362   unsigned DstINumUses = DstI->Operands.size() - DstI->Operands.NumDefs;
2363   unsigned ExpectedDstINumUses = Dst->getNumChildren();
2364   bool IsExtractSubReg = false;
2365 
2366   // COPY_TO_REGCLASS is just a copy with a ConstrainOperandToRegClassAction
2367   // attached. Similarly for EXTRACT_SUBREG except that's a subregister copy.
2368   if (DstI->TheDef->getName() == "COPY_TO_REGCLASS") {
2369     DstI = &Target.getInstruction(RK.getDef("COPY"));
2370     DstINumUses--; // Ignore the class constraint.
2371     ExpectedDstINumUses--;
2372   } else if (DstI->TheDef->getName() == "EXTRACT_SUBREG") {
2373     DstI = &Target.getInstruction(RK.getDef("COPY"));
2374     IsExtractSubReg = true;
2375   }
2376 
2377   auto &DstMIBuilder = M.addAction<BuildMIAction>(0, DstI, InsnMatcher);
2378 
2379   // Render the explicit defs.
2380   for (unsigned I = 0; I < DstI->Operands.NumDefs; ++I) {
2381     const CGIOperandList::OperandInfo &DstIOperand = DstI->Operands[I];
2382     DstMIBuilder.addRenderer<CopyRenderer>(0, InsnMatcher, DstIOperand.Name);
2383   }
2384 
2385   // EXTRACT_SUBREG needs to use a subregister COPY.
2386   if (IsExtractSubReg) {
2387     if (!Dst->getChild(0)->isLeaf())
2388       return failedImport("EXTRACT_SUBREG child #1 is not a leaf");
2389 
2390     if (DefInit *SubRegInit =
2391             dyn_cast<DefInit>(Dst->getChild(1)->getLeafValue())) {
2392       CodeGenRegisterClass *RC = CGRegs.getRegClass(
2393           getInitValueAsRegClass(Dst->getChild(0)->getLeafValue()));
2394       CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef());
2395 
2396       const auto &SrcRCDstRCPair =
2397           RC->getMatchingSubClassWithSubRegs(CGRegs, SubIdx);
2398       if (SrcRCDstRCPair.hasValue()) {
2399         assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
2400         if (SrcRCDstRCPair->first != RC)
2401           return failedImport("EXTRACT_SUBREG requires an additional COPY");
2402       }
2403 
2404       DstMIBuilder.addRenderer<CopySubRegRenderer>(
2405           0, InsnMatcher, Dst->getChild(0)->getName(), SubIdx);
2406       return DstMIBuilder;
2407     }
2408 
2409     return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
2410   }
2411 
2412   // Render the explicit uses.
2413   unsigned Child = 0;
2414   unsigned NumDefaultOps = 0;
2415   for (unsigned I = 0; I != DstINumUses; ++I) {
2416     const CGIOperandList::OperandInfo &DstIOperand =
2417         DstI->Operands[DstI->Operands.NumDefs + I];
2418 
2419     // If the operand has default values, introduce them now.
2420     // FIXME: Until we have a decent test case that dictates we should do
2421     // otherwise, we're going to assume that operands with default values cannot
2422     // be specified in the patterns. Therefore, adding them will not cause us to
2423     // end up with too many rendered operands.
2424     if (DstIOperand.Rec->isSubClassOf("OperandWithDefaultOps")) {
2425       DagInit *DefaultOps = DstIOperand.Rec->getValueAsDag("DefaultOps");
2426       if (auto Error = importDefaultOperandRenderers(DstMIBuilder, DefaultOps))
2427         return std::move(Error);
2428       ++NumDefaultOps;
2429       continue;
2430     }
2431 
2432     if (auto Error = importExplicitUseRenderer(
2433             M, DstMIBuilder, Dst->getChild(Child), InsnMatcher))
2434       return std::move(Error);
2435     ++Child;
2436   }
2437 
2438   if (NumDefaultOps + ExpectedDstINumUses != DstINumUses)
2439     return failedImport("Expected " + llvm::to_string(DstINumUses) +
2440                         " used operands but found " +
2441                         llvm::to_string(ExpectedDstINumUses) +
2442                         " explicit ones and " + llvm::to_string(NumDefaultOps) +
2443                         " default ones");
2444 
2445   return DstMIBuilder;
2446 }
2447 
2448 Error GlobalISelEmitter::importDefaultOperandRenderers(
2449     BuildMIAction &DstMIBuilder, DagInit *DefaultOps) const {
2450   for (const auto *DefaultOp : DefaultOps->getArgs()) {
2451     // Look through ValueType operators.
2452     if (const DagInit *DefaultDagOp = dyn_cast<DagInit>(DefaultOp)) {
2453       if (const DefInit *DefaultDagOperator =
2454               dyn_cast<DefInit>(DefaultDagOp->getOperator())) {
2455         if (DefaultDagOperator->getDef()->isSubClassOf("ValueType"))
2456           DefaultOp = DefaultDagOp->getArg(0);
2457       }
2458     }
2459 
2460     if (const DefInit *DefaultDefOp = dyn_cast<DefInit>(DefaultOp)) {
2461       DstMIBuilder.addRenderer<AddRegisterRenderer>(0, DefaultDefOp->getDef());
2462       continue;
2463     }
2464 
2465     if (const IntInit *DefaultIntOp = dyn_cast<IntInit>(DefaultOp)) {
2466       DstMIBuilder.addRenderer<ImmRenderer>(0, DefaultIntOp->getValue());
2467       continue;
2468     }
2469 
2470     return failedImport("Could not add default op");
2471   }
2472 
2473   return Error::success();
2474 }
2475 
2476 Error GlobalISelEmitter::importImplicitDefRenderers(
2477     BuildMIAction &DstMIBuilder,
2478     const std::vector<Record *> &ImplicitDefs) const {
2479   if (!ImplicitDefs.empty())
2480     return failedImport("Pattern defines a physical register");
2481   return Error::success();
2482 }
2483 
2484 Expected<RuleMatcher> GlobalISelEmitter::runOnPattern(const PatternToMatch &P) {
2485   // Keep track of the matchers and actions to emit.
2486   RuleMatcher M(P.getSrcRecord()->getLoc());
2487   M.addAction<DebugCommentAction>(P);
2488 
2489   if (auto Error = importRulePredicates(M, P.getPredicates()))
2490     return std::move(Error);
2491 
2492   // Next, analyze the pattern operators.
2493   TreePatternNode *Src = P.getSrcPattern();
2494   TreePatternNode *Dst = P.getDstPattern();
2495 
2496   // If the root of either pattern isn't a simple operator, ignore it.
2497   if (auto Err = isTrivialOperatorNode(Dst))
2498     return failedImport("Dst pattern root isn't a trivial operator (" +
2499                         toString(std::move(Err)) + ")");
2500   if (auto Err = isTrivialOperatorNode(Src))
2501     return failedImport("Src pattern root isn't a trivial operator (" +
2502                         toString(std::move(Err)) + ")");
2503 
2504   InstructionMatcher &InsnMatcherTemp = M.addInstructionMatcher(Src->getName());
2505   unsigned TempOpIdx = 0;
2506   auto InsnMatcherOrError =
2507       createAndImportSelDAGMatcher(InsnMatcherTemp, Src, TempOpIdx);
2508   if (auto Error = InsnMatcherOrError.takeError())
2509     return std::move(Error);
2510   InstructionMatcher &InsnMatcher = InsnMatcherOrError.get();
2511 
2512   if (Dst->isLeaf()) {
2513     Record *RCDef = getInitValueAsRegClass(Dst->getLeafValue());
2514 
2515     const CodeGenRegisterClass &RC = Target.getRegisterClass(RCDef);
2516     if (RCDef) {
2517       // We need to replace the def and all its uses with the specified
2518       // operand. However, we must also insert COPY's wherever needed.
2519       // For now, emit a copy and let the register allocator clean up.
2520       auto &DstI = Target.getInstruction(RK.getDef("COPY"));
2521       const auto &DstIOperand = DstI.Operands[0];
2522 
2523       OperandMatcher &OM0 = InsnMatcher.getOperand(0);
2524       OM0.setSymbolicName(DstIOperand.Name);
2525       M.defineOperand(OM0.getSymbolicName(), OM0);
2526       OM0.addPredicate<RegisterBankOperandMatcher>(RC);
2527 
2528       auto &DstMIBuilder = M.addAction<BuildMIAction>(0, &DstI, InsnMatcher);
2529       DstMIBuilder.addRenderer<CopyRenderer>(0, InsnMatcher, DstIOperand.Name);
2530       DstMIBuilder.addRenderer<CopyRenderer>(0, InsnMatcher, Dst->getName());
2531       M.addAction<ConstrainOperandToRegClassAction>(0, 0, RC);
2532 
2533       // We're done with this pattern!  It's eligible for GISel emission; return
2534       // it.
2535       ++NumPatternImported;
2536       return std::move(M);
2537     }
2538 
2539     return failedImport("Dst pattern root isn't a known leaf");
2540   }
2541 
2542   // Start with the defined operands (i.e., the results of the root operator).
2543   Record *DstOp = Dst->getOperator();
2544   if (!DstOp->isSubClassOf("Instruction"))
2545     return failedImport("Pattern operator isn't an instruction");
2546 
2547   auto &DstI = Target.getInstruction(DstOp);
2548   if (DstI.Operands.NumDefs != Src->getExtTypes().size())
2549     return failedImport("Src pattern results and dst MI defs are different (" +
2550                         to_string(Src->getExtTypes().size()) + " def(s) vs " +
2551                         to_string(DstI.Operands.NumDefs) + " def(s))");
2552 
2553   // The root of the match also has constraints on the register bank so that it
2554   // matches the result instruction.
2555   unsigned OpIdx = 0;
2556   for (const TypeSetByHwMode &VTy : Src->getExtTypes()) {
2557     (void)VTy;
2558 
2559     const auto &DstIOperand = DstI.Operands[OpIdx];
2560     Record *DstIOpRec = DstIOperand.Rec;
2561     if (DstI.TheDef->getName() == "COPY_TO_REGCLASS") {
2562       DstIOpRec = getInitValueAsRegClass(Dst->getChild(1)->getLeafValue());
2563 
2564       if (DstIOpRec == nullptr)
2565         return failedImport(
2566             "COPY_TO_REGCLASS operand #1 isn't a register class");
2567     } else if (DstI.TheDef->getName() == "EXTRACT_SUBREG") {
2568       if (!Dst->getChild(0)->isLeaf())
2569         return failedImport("EXTRACT_SUBREG operand #0 isn't a leaf");
2570 
2571       // We can assume that a subregister is in the same bank as it's super
2572       // register.
2573       DstIOpRec = getInitValueAsRegClass(Dst->getChild(0)->getLeafValue());
2574 
2575       if (DstIOpRec == nullptr)
2576         return failedImport(
2577             "EXTRACT_SUBREG operand #0 isn't a register class");
2578     } else if (DstIOpRec->isSubClassOf("RegisterOperand"))
2579       DstIOpRec = DstIOpRec->getValueAsDef("RegClass");
2580     else if (!DstIOpRec->isSubClassOf("RegisterClass"))
2581       return failedImport("Dst MI def isn't a register class" +
2582                           to_string(*Dst));
2583 
2584     OperandMatcher &OM = InsnMatcher.getOperand(OpIdx);
2585     OM.setSymbolicName(DstIOperand.Name);
2586     M.defineOperand(OM.getSymbolicName(), OM);
2587     OM.addPredicate<RegisterBankOperandMatcher>(
2588         Target.getRegisterClass(DstIOpRec));
2589     ++OpIdx;
2590   }
2591 
2592   auto DstMIBuilderOrError =
2593       createAndImportInstructionRenderer(M, Dst, InsnMatcher);
2594   if (auto Error = DstMIBuilderOrError.takeError())
2595     return std::move(Error);
2596   BuildMIAction &DstMIBuilder = DstMIBuilderOrError.get();
2597 
2598   // Render the implicit defs.
2599   // These are only added to the root of the result.
2600   if (auto Error = importImplicitDefRenderers(DstMIBuilder, P.getDstRegs()))
2601     return std::move(Error);
2602 
2603   // Constrain the registers to classes. This is normally derived from the
2604   // emitted instruction but a few instructions require special handling.
2605   if (DstI.TheDef->getName() == "COPY_TO_REGCLASS") {
2606     // COPY_TO_REGCLASS does not provide operand constraints itself but the
2607     // result is constrained to the class given by the second child.
2608     Record *DstIOpRec =
2609         getInitValueAsRegClass(Dst->getChild(1)->getLeafValue());
2610 
2611     if (DstIOpRec == nullptr)
2612       return failedImport("COPY_TO_REGCLASS operand #1 isn't a register class");
2613 
2614     M.addAction<ConstrainOperandToRegClassAction>(
2615         0, 0, Target.getRegisterClass(DstIOpRec));
2616 
2617     // We're done with this pattern!  It's eligible for GISel emission; return
2618     // it.
2619     ++NumPatternImported;
2620     return std::move(M);
2621   }
2622 
2623   if (DstI.TheDef->getName() == "EXTRACT_SUBREG") {
2624     // EXTRACT_SUBREG selects into a subregister COPY but unlike most
2625     // instructions, the result register class is controlled by the
2626     // subregisters of the operand. As a result, we must constrain the result
2627     // class rather than check that it's already the right one.
2628     if (!Dst->getChild(0)->isLeaf())
2629       return failedImport("EXTRACT_SUBREG child #1 is not a leaf");
2630 
2631     DefInit *SubRegInit = dyn_cast<DefInit>(Dst->getChild(1)->getLeafValue());
2632     if (!SubRegInit)
2633       return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
2634 
2635     // Constrain the result to the same register bank as the operand.
2636     Record *DstIOpRec =
2637         getInitValueAsRegClass(Dst->getChild(0)->getLeafValue());
2638 
2639     if (DstIOpRec == nullptr)
2640       return failedImport("EXTRACT_SUBREG operand #1 isn't a register class");
2641 
2642     CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef());
2643     CodeGenRegisterClass *SrcRC = CGRegs.getRegClass(DstIOpRec);
2644 
2645     // It would be nice to leave this constraint implicit but we're required
2646     // to pick a register class so constrain the result to a register class
2647     // that can hold the correct MVT.
2648     //
2649     // FIXME: This may introduce an extra copy if the chosen class doesn't
2650     //        actually contain the subregisters.
2651     assert(Src->getExtTypes().size() == 1 &&
2652              "Expected Src of EXTRACT_SUBREG to have one result type");
2653 
2654     const auto &SrcRCDstRCPair =
2655         SrcRC->getMatchingSubClassWithSubRegs(CGRegs, SubIdx);
2656     assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
2657     M.addAction<ConstrainOperandToRegClassAction>(0, 0, *SrcRCDstRCPair->second);
2658     M.addAction<ConstrainOperandToRegClassAction>(0, 1, *SrcRCDstRCPair->first);
2659 
2660     // We're done with this pattern!  It's eligible for GISel emission; return
2661     // it.
2662     ++NumPatternImported;
2663     return std::move(M);
2664   }
2665 
2666   M.addAction<ConstrainOperandsToDefinitionAction>(0);
2667 
2668   // We're done with this pattern!  It's eligible for GISel emission; return it.
2669   ++NumPatternImported;
2670   return std::move(M);
2671 }
2672 
2673 // Emit imm predicate table and an enum to reference them with.
2674 // The 'Predicate_' part of the name is redundant but eliminating it is more
2675 // trouble than it's worth.
2676 void GlobalISelEmitter::emitImmPredicates(
2677     raw_ostream &OS, StringRef TypeIdentifier, StringRef Type,
2678     std::function<bool(const Record *R)> Filter) {
2679   std::vector<const Record *> MatchedRecords;
2680   const auto &Defs = RK.getAllDerivedDefinitions("PatFrag");
2681   std::copy_if(Defs.begin(), Defs.end(), std::back_inserter(MatchedRecords),
2682                [&](Record *Record) {
2683                  return !Record->getValueAsString("ImmediateCode").empty() &&
2684                         Filter(Record);
2685                });
2686 
2687   if (!MatchedRecords.empty()) {
2688     OS << "// PatFrag predicates.\n"
2689        << "enum {\n";
2690     std::string EnumeratorSeparator =
2691         (" = GIPFP_" + TypeIdentifier + "_Invalid + 1,\n").str();
2692     for (const auto *Record : MatchedRecords) {
2693       OS << "  GIPFP_" << TypeIdentifier << "_Predicate_" << Record->getName()
2694          << EnumeratorSeparator;
2695       EnumeratorSeparator = ",\n";
2696     }
2697     OS << "};\n";
2698   }
2699 
2700   for (const auto *Record : MatchedRecords)
2701     OS << "static bool Predicate_" << Record->getName() << "(" << Type
2702        << " Imm) {" << Record->getValueAsString("ImmediateCode") << "}\n";
2703 
2704   OS << "static InstructionSelector::" << TypeIdentifier
2705      << "ImmediatePredicateFn " << TypeIdentifier << "ImmPredicateFns[] = {\n"
2706      << "  nullptr,\n";
2707   for (const auto *Record : MatchedRecords)
2708     OS << "  Predicate_" << Record->getName() << ",\n";
2709   OS << "};\n";
2710 }
2711 
2712 void GlobalISelEmitter::run(raw_ostream &OS) {
2713   // Track the GINodeEquiv definitions.
2714   gatherNodeEquivs();
2715 
2716   emitSourceFileHeader(("Global Instruction Selector for the " +
2717                        Target.getName() + " target").str(), OS);
2718   std::vector<RuleMatcher> Rules;
2719   // Look through the SelectionDAG patterns we found, possibly emitting some.
2720   for (const PatternToMatch &Pat : CGP.ptms()) {
2721     ++NumPatternTotal;
2722     auto MatcherOrErr = runOnPattern(Pat);
2723 
2724     // The pattern analysis can fail, indicating an unsupported pattern.
2725     // Report that if we've been asked to do so.
2726     if (auto Err = MatcherOrErr.takeError()) {
2727       if (WarnOnSkippedPatterns) {
2728         PrintWarning(Pat.getSrcRecord()->getLoc(),
2729                      "Skipped pattern: " + toString(std::move(Err)));
2730       } else {
2731         consumeError(std::move(Err));
2732       }
2733       ++NumPatternImportsSkipped;
2734       continue;
2735     }
2736 
2737     Rules.push_back(std::move(MatcherOrErr.get()));
2738   }
2739 
2740   std::stable_sort(Rules.begin(), Rules.end(),
2741             [&](const RuleMatcher &A, const RuleMatcher &B) {
2742               if (A.isHigherPriorityThan(B)) {
2743                 assert(!B.isHigherPriorityThan(A) && "Cannot be more important "
2744                                                      "and less important at "
2745                                                      "the same time");
2746                 return true;
2747               }
2748               return false;
2749             });
2750 
2751   std::vector<Record *> ComplexPredicates =
2752       RK.getAllDerivedDefinitions("GIComplexOperandMatcher");
2753   std::sort(ComplexPredicates.begin(), ComplexPredicates.end(),
2754             [](const Record *A, const Record *B) {
2755               if (A->getName() < B->getName())
2756                 return true;
2757               return false;
2758             });
2759   unsigned MaxTemporaries = 0;
2760   for (const auto &Rule : Rules)
2761     MaxTemporaries = std::max(MaxTemporaries, Rule.countRendererFns());
2762 
2763   OS << "#ifdef GET_GLOBALISEL_PREDICATE_BITSET\n"
2764      << "const unsigned MAX_SUBTARGET_PREDICATES = " << SubtargetFeatures.size()
2765      << ";\n"
2766      << "using PredicateBitset = "
2767         "llvm::PredicateBitsetImpl<MAX_SUBTARGET_PREDICATES>;\n"
2768      << "#endif // ifdef GET_GLOBALISEL_PREDICATE_BITSET\n\n";
2769 
2770   OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n"
2771      << "  mutable MatcherState State;\n"
2772      << "  typedef "
2773         "ComplexRendererFn("
2774      << Target.getName()
2775      << "InstructionSelector::*ComplexMatcherMemFn)(MachineOperand &) const;\n"
2776      << "const MatcherInfoTy<PredicateBitset, ComplexMatcherMemFn> "
2777         "MatcherInfo;\n"
2778      << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n\n";
2779 
2780   OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n"
2781      << ", State(" << MaxTemporaries << "),\n"
2782      << "MatcherInfo({TypeObjects, FeatureBitsets, I64ImmPredicateFns, "
2783         "APIntImmPredicateFns, APFloatImmPredicateFns, {\n"
2784      << "  nullptr, // GICP_Invalid\n";
2785   for (const auto &Record : ComplexPredicates)
2786     OS << "  &" << Target.getName()
2787        << "InstructionSelector::" << Record->getValueAsString("MatcherFn")
2788        << ", // " << Record->getName() << "\n";
2789   OS << "}})\n"
2790      << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n\n";
2791 
2792   OS << "#ifdef GET_GLOBALISEL_IMPL\n";
2793   SubtargetFeatureInfo::emitSubtargetFeatureBitEnumeration(SubtargetFeatures,
2794                                                            OS);
2795 
2796   // Separate subtarget features by how often they must be recomputed.
2797   SubtargetFeatureInfoMap ModuleFeatures;
2798   std::copy_if(SubtargetFeatures.begin(), SubtargetFeatures.end(),
2799                std::inserter(ModuleFeatures, ModuleFeatures.end()),
2800                [](const SubtargetFeatureInfoMap::value_type &X) {
2801                  return !X.second.mustRecomputePerFunction();
2802                });
2803   SubtargetFeatureInfoMap FunctionFeatures;
2804   std::copy_if(SubtargetFeatures.begin(), SubtargetFeatures.end(),
2805                std::inserter(FunctionFeatures, FunctionFeatures.end()),
2806                [](const SubtargetFeatureInfoMap::value_type &X) {
2807                  return X.second.mustRecomputePerFunction();
2808                });
2809 
2810   SubtargetFeatureInfo::emitComputeAvailableFeatures(
2811       Target.getName(), "InstructionSelector", "computeAvailableModuleFeatures",
2812       ModuleFeatures, OS);
2813   SubtargetFeatureInfo::emitComputeAvailableFeatures(
2814       Target.getName(), "InstructionSelector",
2815       "computeAvailableFunctionFeatures", FunctionFeatures, OS,
2816       "const MachineFunction *MF");
2817 
2818   // Emit a table containing the LLT objects needed by the matcher and an enum
2819   // for the matcher to reference them with.
2820   std::vector<LLTCodeGen> TypeObjects;
2821   for (const auto &Ty : LLTOperandMatcher::KnownTypes)
2822     TypeObjects.push_back(Ty);
2823   std::sort(TypeObjects.begin(), TypeObjects.end());
2824   OS << "// LLT Objects.\n"
2825      << "enum {\n";
2826   for (const auto &TypeObject : TypeObjects) {
2827     OS << "  ";
2828     TypeObject.emitCxxEnumValue(OS);
2829     OS << ",\n";
2830   }
2831   OS << "};\n"
2832      << "const static LLT TypeObjects[] = {\n";
2833   for (const auto &TypeObject : TypeObjects) {
2834     OS << "  ";
2835     TypeObject.emitCxxConstructorCall(OS);
2836     OS << ",\n";
2837   }
2838   OS << "};\n\n";
2839 
2840   // Emit a table containing the PredicateBitsets objects needed by the matcher
2841   // and an enum for the matcher to reference them with.
2842   std::vector<std::vector<Record *>> FeatureBitsets;
2843   for (auto &Rule : Rules)
2844     FeatureBitsets.push_back(Rule.getRequiredFeatures());
2845   std::sort(
2846       FeatureBitsets.begin(), FeatureBitsets.end(),
2847       [&](const std::vector<Record *> &A, const std::vector<Record *> &B) {
2848         if (A.size() < B.size())
2849           return true;
2850         if (A.size() > B.size())
2851           return false;
2852         for (const auto &Pair : zip(A, B)) {
2853           if (std::get<0>(Pair)->getName() < std::get<1>(Pair)->getName())
2854             return true;
2855           if (std::get<0>(Pair)->getName() > std::get<1>(Pair)->getName())
2856             return false;
2857         }
2858         return false;
2859       });
2860   FeatureBitsets.erase(
2861       std::unique(FeatureBitsets.begin(), FeatureBitsets.end()),
2862       FeatureBitsets.end());
2863   OS << "// Feature bitsets.\n"
2864      << "enum {\n"
2865      << "  GIFBS_Invalid,\n";
2866   for (const auto &FeatureBitset : FeatureBitsets) {
2867     if (FeatureBitset.empty())
2868       continue;
2869     OS << "  " << getNameForFeatureBitset(FeatureBitset) << ",\n";
2870   }
2871   OS << "};\n"
2872      << "const static PredicateBitset FeatureBitsets[] {\n"
2873      << "  {}, // GIFBS_Invalid\n";
2874   for (const auto &FeatureBitset : FeatureBitsets) {
2875     if (FeatureBitset.empty())
2876       continue;
2877     OS << "  {";
2878     for (const auto &Feature : FeatureBitset) {
2879       const auto &I = SubtargetFeatures.find(Feature);
2880       assert(I != SubtargetFeatures.end() && "Didn't import predicate?");
2881       OS << I->second.getEnumBitName() << ", ";
2882     }
2883     OS << "},\n";
2884   }
2885   OS << "};\n\n";
2886 
2887   // Emit complex predicate table and an enum to reference them with.
2888   OS << "// ComplexPattern predicates.\n"
2889      << "enum {\n"
2890      << "  GICP_Invalid,\n";
2891   for (const auto &Record : ComplexPredicates)
2892     OS << "  GICP_" << Record->getName() << ",\n";
2893   OS << "};\n"
2894      << "// See constructor for table contents\n\n";
2895 
2896   emitImmPredicates(OS, "I64", "int64_t", [](const Record *R) {
2897     bool Unset;
2898     return !R->getValueAsBitOrUnset("IsAPFloat", Unset) &&
2899            !R->getValueAsBit("IsAPInt");
2900   });
2901   emitImmPredicates(OS, "APFloat", "const APFloat &", [](const Record *R) {
2902     bool Unset;
2903     return R->getValueAsBitOrUnset("IsAPFloat", Unset);
2904   });
2905   emitImmPredicates(OS, "APInt", "const APInt &", [](const Record *R) {
2906     return R->getValueAsBit("IsAPInt");
2907   });
2908 
2909   OS << "bool " << Target.getName()
2910      << "InstructionSelector::selectImpl(MachineInstr &I) const {\n"
2911      << "  MachineFunction &MF = *I.getParent()->getParent();\n"
2912      << "  MachineRegisterInfo &MRI = MF.getRegInfo();\n"
2913      << "  // FIXME: This should be computed on a per-function basis rather "
2914         "than per-insn.\n"
2915      << "  AvailableFunctionFeatures = computeAvailableFunctionFeatures(&STI, "
2916         "&MF);\n"
2917      << "  const PredicateBitset AvailableFeatures = getAvailableFeatures();\n"
2918      << "  NewMIVector OutMIs;\n"
2919      << "  State.MIs.clear();\n"
2920      << "  State.MIs.push_back(&I);\n\n";
2921 
2922   MatchTable Table(0);
2923   for (auto &Rule : Rules) {
2924     Rule.emit(Table);
2925     ++NumPatternEmitted;
2926   }
2927   Table << MatchTable::Opcode("GIM_Reject") << MatchTable::LineBreak;
2928   Table.emitDeclaration(OS);
2929   OS << "  if (executeMatchTable(*this, OutMIs, State, MatcherInfo, ";
2930   Table.emitUse(OS);
2931   OS << ", TII, MRI, TRI, RBI, AvailableFeatures)) {\n"
2932      << "    return true;\n"
2933      << "  }\n\n";
2934 
2935   OS << "  return false;\n"
2936      << "}\n"
2937      << "#endif // ifdef GET_GLOBALISEL_IMPL\n";
2938 
2939   OS << "#ifdef GET_GLOBALISEL_PREDICATES_DECL\n"
2940      << "PredicateBitset AvailableModuleFeatures;\n"
2941      << "mutable PredicateBitset AvailableFunctionFeatures;\n"
2942      << "PredicateBitset getAvailableFeatures() const {\n"
2943      << "  return AvailableModuleFeatures | AvailableFunctionFeatures;\n"
2944      << "}\n"
2945      << "PredicateBitset\n"
2946      << "computeAvailableModuleFeatures(const " << Target.getName()
2947      << "Subtarget *Subtarget) const;\n"
2948      << "PredicateBitset\n"
2949      << "computeAvailableFunctionFeatures(const " << Target.getName()
2950      << "Subtarget *Subtarget,\n"
2951      << "                                 const MachineFunction *MF) const;\n"
2952      << "#endif // ifdef GET_GLOBALISEL_PREDICATES_DECL\n";
2953 
2954   OS << "#ifdef GET_GLOBALISEL_PREDICATES_INIT\n"
2955      << "AvailableModuleFeatures(computeAvailableModuleFeatures(&STI)),\n"
2956      << "AvailableFunctionFeatures()\n"
2957      << "#endif // ifdef GET_GLOBALISEL_PREDICATES_INIT\n";
2958 }
2959 
2960 void GlobalISelEmitter::declareSubtargetFeature(Record *Predicate) {
2961   if (SubtargetFeatures.count(Predicate) == 0)
2962     SubtargetFeatures.emplace(
2963         Predicate, SubtargetFeatureInfo(Predicate, SubtargetFeatures.size()));
2964 }
2965 
2966 } // end anonymous namespace
2967 
2968 //===----------------------------------------------------------------------===//
2969 
2970 namespace llvm {
2971 void EmitGlobalISel(RecordKeeper &RK, raw_ostream &OS) {
2972   GlobalISelEmitter(RK).run(OS);
2973 }
2974 } // End llvm namespace
2975