xref: /freebsd/contrib/llvm-project/llvm/utils/TableGen/GlobalISelEmitter.cpp (revision 972a253a57b6f144b0e4a3e2080a2a0076ec55a0)
1 //===- GlobalISelEmitter.cpp - Generate an instruction selector -----------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 /// \file
10 /// This tablegen backend emits code for use by the GlobalISel instruction
11 /// selector. See include/llvm/CodeGen/TargetGlobalISel.td.
12 ///
13 /// This file analyzes the patterns recognized by the SelectionDAGISel tablegen
14 /// backend, filters out the ones that are unsupported, maps
15 /// SelectionDAG-specific constructs to their GlobalISel counterpart
16 /// (when applicable: MVT to LLT;  SDNode to generic Instruction).
17 ///
18 /// Not all patterns are supported: pass the tablegen invocation
19 /// "-warn-on-skipped-patterns" to emit a warning when a pattern is skipped,
20 /// as well as why.
21 ///
22 /// The generated file defines a single method:
23 ///     bool <Target>InstructionSelector::selectImpl(MachineInstr &I) const;
24 /// intended to be used in InstructionSelector::select as the first-step
25 /// selector for the patterns that don't require complex C++.
26 ///
27 /// FIXME: We'll probably want to eventually define a base
28 /// "TargetGenInstructionSelector" class.
29 ///
30 //===----------------------------------------------------------------------===//
31 
32 #include "CodeGenDAGPatterns.h"
33 #include "CodeGenInstruction.h"
34 #include "SubtargetFeatureInfo.h"
35 #include "llvm/ADT/Optional.h"
36 #include "llvm/ADT/Statistic.h"
37 #include "llvm/Support/CodeGenCoverage.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/Error.h"
40 #include "llvm/Support/LowLevelTypeImpl.h"
41 #include "llvm/Support/MachineValueType.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 <numeric>
47 #include <string>
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(NumPatternsTested, "Number of patterns executed according to coverage information");
56 STATISTIC(NumPatternEmitted, "Number of patterns emitted");
57 
58 cl::OptionCategory GlobalISelEmitterCat("Options for -gen-global-isel");
59 
60 static cl::opt<bool> WarnOnSkippedPatterns(
61     "warn-on-skipped-patterns",
62     cl::desc("Explain why a pattern was skipped for inclusion "
63              "in the GlobalISel selector"),
64     cl::init(false), cl::cat(GlobalISelEmitterCat));
65 
66 static cl::opt<bool> GenerateCoverage(
67     "instrument-gisel-coverage",
68     cl::desc("Generate coverage instrumentation for GlobalISel"),
69     cl::init(false), cl::cat(GlobalISelEmitterCat));
70 
71 static cl::opt<std::string> UseCoverageFile(
72     "gisel-coverage-file", cl::init(""),
73     cl::desc("Specify file to retrieve coverage information from"),
74     cl::cat(GlobalISelEmitterCat));
75 
76 static cl::opt<bool> OptimizeMatchTable(
77     "optimize-match-table",
78     cl::desc("Generate an optimized version of the match table"),
79     cl::init(true), cl::cat(GlobalISelEmitterCat));
80 
81 namespace {
82 //===- Helper functions ---------------------------------------------------===//
83 
84 /// Get the name of the enum value used to number the predicate function.
85 std::string getEnumNameForPredicate(const TreePredicateFn &Predicate) {
86   if (Predicate.hasGISelPredicateCode())
87     return "GIPFP_MI_" + Predicate.getFnName();
88   return "GIPFP_" + Predicate.getImmTypeIdentifier().str() + "_" +
89          Predicate.getFnName();
90 }
91 
92 /// Get the opcode used to check this predicate.
93 std::string getMatchOpcodeForImmPredicate(const TreePredicateFn &Predicate) {
94   return "GIM_Check" + Predicate.getImmTypeIdentifier().str() + "ImmPredicate";
95 }
96 
97 /// This class stands in for LLT wherever we want to tablegen-erate an
98 /// equivalent at compiler run-time.
99 class LLTCodeGen {
100 private:
101   LLT Ty;
102 
103 public:
104   LLTCodeGen() = default;
105   LLTCodeGen(const LLT &Ty) : Ty(Ty) {}
106 
107   std::string getCxxEnumValue() const {
108     std::string Str;
109     raw_string_ostream OS(Str);
110 
111     emitCxxEnumValue(OS);
112     return Str;
113   }
114 
115   void emitCxxEnumValue(raw_ostream &OS) const {
116     if (Ty.isScalar()) {
117       OS << "GILLT_s" << Ty.getSizeInBits();
118       return;
119     }
120     if (Ty.isVector()) {
121       OS << (Ty.isScalable() ? "GILLT_nxv" : "GILLT_v")
122          << Ty.getElementCount().getKnownMinValue() << "s"
123          << Ty.getScalarSizeInBits();
124       return;
125     }
126     if (Ty.isPointer()) {
127       OS << "GILLT_p" << Ty.getAddressSpace();
128       if (Ty.getSizeInBits() > 0)
129         OS << "s" << Ty.getSizeInBits();
130       return;
131     }
132     llvm_unreachable("Unhandled LLT");
133   }
134 
135   void emitCxxConstructorCall(raw_ostream &OS) const {
136     if (Ty.isScalar()) {
137       OS << "LLT::scalar(" << Ty.getSizeInBits() << ")";
138       return;
139     }
140     if (Ty.isVector()) {
141       OS << "LLT::vector("
142          << (Ty.isScalable() ? "ElementCount::getScalable("
143                              : "ElementCount::getFixed(")
144          << Ty.getElementCount().getKnownMinValue() << "), "
145          << Ty.getScalarSizeInBits() << ")";
146       return;
147     }
148     if (Ty.isPointer() && Ty.getSizeInBits() > 0) {
149       OS << "LLT::pointer(" << Ty.getAddressSpace() << ", "
150          << Ty.getSizeInBits() << ")";
151       return;
152     }
153     llvm_unreachable("Unhandled LLT");
154   }
155 
156   const LLT &get() const { return Ty; }
157 
158   /// This ordering is used for std::unique() and llvm::sort(). There's no
159   /// particular logic behind the order but either A < B or B < A must be
160   /// true if A != B.
161   bool operator<(const LLTCodeGen &Other) const {
162     if (Ty.isValid() != Other.Ty.isValid())
163       return Ty.isValid() < Other.Ty.isValid();
164     if (!Ty.isValid())
165       return false;
166 
167     if (Ty.isVector() != Other.Ty.isVector())
168       return Ty.isVector() < Other.Ty.isVector();
169     if (Ty.isScalar() != Other.Ty.isScalar())
170       return Ty.isScalar() < Other.Ty.isScalar();
171     if (Ty.isPointer() != Other.Ty.isPointer())
172       return Ty.isPointer() < Other.Ty.isPointer();
173 
174     if (Ty.isPointer() && Ty.getAddressSpace() != Other.Ty.getAddressSpace())
175       return Ty.getAddressSpace() < Other.Ty.getAddressSpace();
176 
177     if (Ty.isVector() && Ty.getElementCount() != Other.Ty.getElementCount())
178       return std::make_tuple(Ty.isScalable(),
179                              Ty.getElementCount().getKnownMinValue()) <
180              std::make_tuple(Other.Ty.isScalable(),
181                              Other.Ty.getElementCount().getKnownMinValue());
182 
183     assert((!Ty.isVector() || Ty.isScalable() == Other.Ty.isScalable()) &&
184            "Unexpected mismatch of scalable property");
185     return Ty.isVector()
186                ? std::make_tuple(Ty.isScalable(),
187                                  Ty.getSizeInBits().getKnownMinSize()) <
188                      std::make_tuple(Other.Ty.isScalable(),
189                                      Other.Ty.getSizeInBits().getKnownMinSize())
190                : Ty.getSizeInBits().getFixedSize() <
191                      Other.Ty.getSizeInBits().getFixedSize();
192   }
193 
194   bool operator==(const LLTCodeGen &B) const { return Ty == B.Ty; }
195 };
196 
197 // Track all types that are used so we can emit the corresponding enum.
198 std::set<LLTCodeGen> KnownTypes;
199 
200 class InstructionMatcher;
201 /// Convert an MVT to an equivalent LLT if possible, or the invalid LLT() for
202 /// MVTs that don't map cleanly to an LLT (e.g., iPTR, *any, ...).
203 static Optional<LLTCodeGen> MVTToLLT(MVT::SimpleValueType SVT) {
204   MVT VT(SVT);
205 
206   if (VT.isVector() && !VT.getVectorElementCount().isScalar())
207     return LLTCodeGen(
208         LLT::vector(VT.getVectorElementCount(), VT.getScalarSizeInBits()));
209 
210   if (VT.isInteger() || VT.isFloatingPoint())
211     return LLTCodeGen(LLT::scalar(VT.getSizeInBits()));
212 
213   return None;
214 }
215 
216 static std::string explainPredicates(const TreePatternNode *N) {
217   std::string Explanation;
218   StringRef Separator = "";
219   for (const TreePredicateCall &Call : N->getPredicateCalls()) {
220     const TreePredicateFn &P = Call.Fn;
221     Explanation +=
222         (Separator + P.getOrigPatFragRecord()->getRecord()->getName()).str();
223     Separator = ", ";
224 
225     if (P.isAlwaysTrue())
226       Explanation += " always-true";
227     if (P.isImmediatePattern())
228       Explanation += " immediate";
229 
230     if (P.isUnindexed())
231       Explanation += " unindexed";
232 
233     if (P.isNonExtLoad())
234       Explanation += " non-extload";
235     if (P.isAnyExtLoad())
236       Explanation += " extload";
237     if (P.isSignExtLoad())
238       Explanation += " sextload";
239     if (P.isZeroExtLoad())
240       Explanation += " zextload";
241 
242     if (P.isNonTruncStore())
243       Explanation += " non-truncstore";
244     if (P.isTruncStore())
245       Explanation += " truncstore";
246 
247     if (Record *VT = P.getMemoryVT())
248       Explanation += (" MemVT=" + VT->getName()).str();
249     if (Record *VT = P.getScalarMemoryVT())
250       Explanation += (" ScalarVT(MemVT)=" + VT->getName()).str();
251 
252     if (ListInit *AddrSpaces = P.getAddressSpaces()) {
253       raw_string_ostream OS(Explanation);
254       OS << " AddressSpaces=[";
255 
256       StringRef AddrSpaceSeparator;
257       for (Init *Val : AddrSpaces->getValues()) {
258         IntInit *IntVal = dyn_cast<IntInit>(Val);
259         if (!IntVal)
260           continue;
261 
262         OS << AddrSpaceSeparator << IntVal->getValue();
263         AddrSpaceSeparator = ", ";
264       }
265 
266       OS << ']';
267     }
268 
269     int64_t MinAlign = P.getMinAlignment();
270     if (MinAlign > 0)
271       Explanation += " MinAlign=" + utostr(MinAlign);
272 
273     if (P.isAtomicOrderingMonotonic())
274       Explanation += " monotonic";
275     if (P.isAtomicOrderingAcquire())
276       Explanation += " acquire";
277     if (P.isAtomicOrderingRelease())
278       Explanation += " release";
279     if (P.isAtomicOrderingAcquireRelease())
280       Explanation += " acq_rel";
281     if (P.isAtomicOrderingSequentiallyConsistent())
282       Explanation += " seq_cst";
283     if (P.isAtomicOrderingAcquireOrStronger())
284       Explanation += " >=acquire";
285     if (P.isAtomicOrderingWeakerThanAcquire())
286       Explanation += " <acquire";
287     if (P.isAtomicOrderingReleaseOrStronger())
288       Explanation += " >=release";
289     if (P.isAtomicOrderingWeakerThanRelease())
290       Explanation += " <release";
291   }
292   return Explanation;
293 }
294 
295 std::string explainOperator(Record *Operator) {
296   if (Operator->isSubClassOf("SDNode"))
297     return (" (" + Operator->getValueAsString("Opcode") + ")").str();
298 
299   if (Operator->isSubClassOf("Intrinsic"))
300     return (" (Operator is an Intrinsic, " + Operator->getName() + ")").str();
301 
302   if (Operator->isSubClassOf("ComplexPattern"))
303     return (" (Operator is an unmapped ComplexPattern, " + Operator->getName() +
304             ")")
305         .str();
306 
307   if (Operator->isSubClassOf("SDNodeXForm"))
308     return (" (Operator is an unmapped SDNodeXForm, " + Operator->getName() +
309             ")")
310         .str();
311 
312   return (" (Operator " + Operator->getName() + " not understood)").str();
313 }
314 
315 /// Helper function to let the emitter report skip reason error messages.
316 static Error failedImport(const Twine &Reason) {
317   return make_error<StringError>(Reason, inconvertibleErrorCode());
318 }
319 
320 static Error isTrivialOperatorNode(const TreePatternNode *N) {
321   std::string Explanation;
322   std::string Separator;
323 
324   bool HasUnsupportedPredicate = false;
325   for (const TreePredicateCall &Call : N->getPredicateCalls()) {
326     const TreePredicateFn &Predicate = Call.Fn;
327 
328     if (Predicate.isAlwaysTrue())
329       continue;
330 
331     if (Predicate.isImmediatePattern())
332       continue;
333 
334     if (Predicate.hasNoUse())
335       continue;
336 
337     if (Predicate.isNonExtLoad() || Predicate.isAnyExtLoad() ||
338         Predicate.isSignExtLoad() || Predicate.isZeroExtLoad())
339       continue;
340 
341     if (Predicate.isNonTruncStore() || Predicate.isTruncStore())
342       continue;
343 
344     if (Predicate.isLoad() && Predicate.getMemoryVT())
345       continue;
346 
347     if (Predicate.isLoad() || Predicate.isStore()) {
348       if (Predicate.isUnindexed())
349         continue;
350     }
351 
352     if (Predicate.isLoad() || Predicate.isStore() || Predicate.isAtomic()) {
353       const ListInit *AddrSpaces = Predicate.getAddressSpaces();
354       if (AddrSpaces && !AddrSpaces->empty())
355         continue;
356 
357       if (Predicate.getMinAlignment() > 0)
358         continue;
359     }
360 
361     if (Predicate.isAtomic() && Predicate.getMemoryVT())
362       continue;
363 
364     if (Predicate.isAtomic() &&
365         (Predicate.isAtomicOrderingMonotonic() ||
366          Predicate.isAtomicOrderingAcquire() ||
367          Predicate.isAtomicOrderingRelease() ||
368          Predicate.isAtomicOrderingAcquireRelease() ||
369          Predicate.isAtomicOrderingSequentiallyConsistent() ||
370          Predicate.isAtomicOrderingAcquireOrStronger() ||
371          Predicate.isAtomicOrderingWeakerThanAcquire() ||
372          Predicate.isAtomicOrderingReleaseOrStronger() ||
373          Predicate.isAtomicOrderingWeakerThanRelease()))
374       continue;
375 
376     if (Predicate.hasGISelPredicateCode())
377       continue;
378 
379     HasUnsupportedPredicate = true;
380     Explanation = Separator + "Has a predicate (" + explainPredicates(N) + ")";
381     Separator = ", ";
382     Explanation += (Separator + "first-failing:" +
383                     Predicate.getOrigPatFragRecord()->getRecord()->getName())
384                        .str();
385     break;
386   }
387 
388   if (!HasUnsupportedPredicate)
389     return Error::success();
390 
391   return failedImport(Explanation);
392 }
393 
394 static Record *getInitValueAsRegClass(Init *V) {
395   if (DefInit *VDefInit = dyn_cast<DefInit>(V)) {
396     if (VDefInit->getDef()->isSubClassOf("RegisterOperand"))
397       return VDefInit->getDef()->getValueAsDef("RegClass");
398     if (VDefInit->getDef()->isSubClassOf("RegisterClass"))
399       return VDefInit->getDef();
400   }
401   return nullptr;
402 }
403 
404 std::string
405 getNameForFeatureBitset(const std::vector<Record *> &FeatureBitset) {
406   std::string Name = "GIFBS";
407   for (const auto &Feature : FeatureBitset)
408     Name += ("_" + Feature->getName()).str();
409   return Name;
410 }
411 
412 static std::string getScopedName(unsigned Scope, const std::string &Name) {
413   return ("pred:" + Twine(Scope) + ":" + Name).str();
414 }
415 
416 //===- MatchTable Helpers -------------------------------------------------===//
417 
418 class MatchTable;
419 
420 /// A record to be stored in a MatchTable.
421 ///
422 /// This class represents any and all output that may be required to emit the
423 /// MatchTable. Instances  are most often configured to represent an opcode or
424 /// value that will be emitted to the table with some formatting but it can also
425 /// represent commas, comments, and other formatting instructions.
426 struct MatchTableRecord {
427   enum RecordFlagsBits {
428     MTRF_None = 0x0,
429     /// Causes EmitStr to be formatted as comment when emitted.
430     MTRF_Comment = 0x1,
431     /// Causes the record value to be followed by a comma when emitted.
432     MTRF_CommaFollows = 0x2,
433     /// Causes the record value to be followed by a line break when emitted.
434     MTRF_LineBreakFollows = 0x4,
435     /// Indicates that the record defines a label and causes an additional
436     /// comment to be emitted containing the index of the label.
437     MTRF_Label = 0x8,
438     /// Causes the record to be emitted as the index of the label specified by
439     /// LabelID along with a comment indicating where that label is.
440     MTRF_JumpTarget = 0x10,
441     /// Causes the formatter to add a level of indentation before emitting the
442     /// record.
443     MTRF_Indent = 0x20,
444     /// Causes the formatter to remove a level of indentation after emitting the
445     /// record.
446     MTRF_Outdent = 0x40,
447   };
448 
449   /// When MTRF_Label or MTRF_JumpTarget is used, indicates a label id to
450   /// reference or define.
451   unsigned LabelID;
452   /// The string to emit. Depending on the MTRF_* flags it may be a comment, a
453   /// value, a label name.
454   std::string EmitStr;
455 
456 private:
457   /// The number of MatchTable elements described by this record. Comments are 0
458   /// while values are typically 1. Values >1 may occur when we need to emit
459   /// values that exceed the size of a MatchTable element.
460   unsigned NumElements;
461 
462 public:
463   /// A bitfield of RecordFlagsBits flags.
464   unsigned Flags;
465 
466   /// The actual run-time value, if known
467   int64_t RawValue;
468 
469   MatchTableRecord(Optional<unsigned> LabelID_, StringRef EmitStr,
470                    unsigned NumElements, unsigned Flags,
471                    int64_t RawValue = std::numeric_limits<int64_t>::min())
472       : LabelID(LabelID_.value_or(~0u)), EmitStr(EmitStr),
473         NumElements(NumElements), Flags(Flags), RawValue(RawValue) {
474     assert((!LabelID_ || LabelID != ~0u) &&
475            "This value is reserved for non-labels");
476   }
477   MatchTableRecord(const MatchTableRecord &Other) = default;
478   MatchTableRecord(MatchTableRecord &&Other) = default;
479 
480   /// Useful if a Match Table Record gets optimized out
481   void turnIntoComment() {
482     Flags |= MTRF_Comment;
483     Flags &= ~MTRF_CommaFollows;
484     NumElements = 0;
485   }
486 
487   /// For Jump Table generation purposes
488   bool operator<(const MatchTableRecord &Other) const {
489     return RawValue < Other.RawValue;
490   }
491   int64_t getRawValue() const { return RawValue; }
492 
493   void emit(raw_ostream &OS, bool LineBreakNextAfterThis,
494             const MatchTable &Table) const;
495   unsigned size() const { return NumElements; }
496 };
497 
498 class Matcher;
499 
500 /// Holds the contents of a generated MatchTable to enable formatting and the
501 /// necessary index tracking needed to support GIM_Try.
502 class MatchTable {
503   /// An unique identifier for the table. The generated table will be named
504   /// MatchTable${ID}.
505   unsigned ID;
506   /// The records that make up the table. Also includes comments describing the
507   /// values being emitted and line breaks to format it.
508   std::vector<MatchTableRecord> Contents;
509   /// The currently defined labels.
510   DenseMap<unsigned, unsigned> LabelMap;
511   /// Tracks the sum of MatchTableRecord::NumElements as the table is built.
512   unsigned CurrentSize = 0;
513   /// A unique identifier for a MatchTable label.
514   unsigned CurrentLabelID = 0;
515   /// Determines if the table should be instrumented for rule coverage tracking.
516   bool IsWithCoverage;
517 
518 public:
519   static MatchTableRecord LineBreak;
520   static MatchTableRecord Comment(StringRef Comment) {
521     return MatchTableRecord(None, Comment, 0, MatchTableRecord::MTRF_Comment);
522   }
523   static MatchTableRecord Opcode(StringRef Opcode, int IndentAdjust = 0) {
524     unsigned ExtraFlags = 0;
525     if (IndentAdjust > 0)
526       ExtraFlags |= MatchTableRecord::MTRF_Indent;
527     if (IndentAdjust < 0)
528       ExtraFlags |= MatchTableRecord::MTRF_Outdent;
529 
530     return MatchTableRecord(None, Opcode, 1,
531                             MatchTableRecord::MTRF_CommaFollows | ExtraFlags);
532   }
533   static MatchTableRecord NamedValue(StringRef NamedValue) {
534     return MatchTableRecord(None, NamedValue, 1,
535                             MatchTableRecord::MTRF_CommaFollows);
536   }
537   static MatchTableRecord NamedValue(StringRef NamedValue, int64_t RawValue) {
538     return MatchTableRecord(None, NamedValue, 1,
539                             MatchTableRecord::MTRF_CommaFollows, RawValue);
540   }
541   static MatchTableRecord NamedValue(StringRef Namespace,
542                                      StringRef NamedValue) {
543     return MatchTableRecord(None, (Namespace + "::" + NamedValue).str(), 1,
544                             MatchTableRecord::MTRF_CommaFollows);
545   }
546   static MatchTableRecord NamedValue(StringRef Namespace, StringRef NamedValue,
547                                      int64_t RawValue) {
548     return MatchTableRecord(None, (Namespace + "::" + NamedValue).str(), 1,
549                             MatchTableRecord::MTRF_CommaFollows, RawValue);
550   }
551   static MatchTableRecord IntValue(int64_t IntValue) {
552     return MatchTableRecord(None, llvm::to_string(IntValue), 1,
553                             MatchTableRecord::MTRF_CommaFollows);
554   }
555   static MatchTableRecord Label(unsigned LabelID) {
556     return MatchTableRecord(LabelID, "Label " + llvm::to_string(LabelID), 0,
557                             MatchTableRecord::MTRF_Label |
558                                 MatchTableRecord::MTRF_Comment |
559                                 MatchTableRecord::MTRF_LineBreakFollows);
560   }
561   static MatchTableRecord JumpTarget(unsigned LabelID) {
562     return MatchTableRecord(LabelID, "Label " + llvm::to_string(LabelID), 1,
563                             MatchTableRecord::MTRF_JumpTarget |
564                                 MatchTableRecord::MTRF_Comment |
565                                 MatchTableRecord::MTRF_CommaFollows);
566   }
567 
568   static MatchTable buildTable(ArrayRef<Matcher *> Rules, bool WithCoverage);
569 
570   MatchTable(bool WithCoverage, unsigned ID = 0)
571       : ID(ID), IsWithCoverage(WithCoverage) {}
572 
573   bool isWithCoverage() const { return IsWithCoverage; }
574 
575   void push_back(const MatchTableRecord &Value) {
576     if (Value.Flags & MatchTableRecord::MTRF_Label)
577       defineLabel(Value.LabelID);
578     Contents.push_back(Value);
579     CurrentSize += Value.size();
580   }
581 
582   unsigned allocateLabelID() { return CurrentLabelID++; }
583 
584   void defineLabel(unsigned LabelID) {
585     LabelMap.insert(std::make_pair(LabelID, CurrentSize));
586   }
587 
588   unsigned getLabelIndex(unsigned LabelID) const {
589     const auto I = LabelMap.find(LabelID);
590     assert(I != LabelMap.end() && "Use of undeclared label");
591     return I->second;
592   }
593 
594   void emitUse(raw_ostream &OS) const { OS << "MatchTable" << ID; }
595 
596   void emitDeclaration(raw_ostream &OS) const {
597     unsigned Indentation = 4;
598     OS << "  constexpr static int64_t MatchTable" << ID << "[] = {";
599     LineBreak.emit(OS, true, *this);
600     OS << std::string(Indentation, ' ');
601 
602     for (auto I = Contents.begin(), E = Contents.end(); I != E;
603          ++I) {
604       bool LineBreakIsNext = false;
605       const auto &NextI = std::next(I);
606 
607       if (NextI != E) {
608         if (NextI->EmitStr == "" &&
609             NextI->Flags == MatchTableRecord::MTRF_LineBreakFollows)
610           LineBreakIsNext = true;
611       }
612 
613       if (I->Flags & MatchTableRecord::MTRF_Indent)
614         Indentation += 2;
615 
616       I->emit(OS, LineBreakIsNext, *this);
617       if (I->Flags & MatchTableRecord::MTRF_LineBreakFollows)
618         OS << std::string(Indentation, ' ');
619 
620       if (I->Flags & MatchTableRecord::MTRF_Outdent)
621         Indentation -= 2;
622     }
623     OS << "};\n";
624   }
625 };
626 
627 MatchTableRecord MatchTable::LineBreak = {
628     None, "" /* Emit String */, 0 /* Elements */,
629     MatchTableRecord::MTRF_LineBreakFollows};
630 
631 void MatchTableRecord::emit(raw_ostream &OS, bool LineBreakIsNextAfterThis,
632                             const MatchTable &Table) const {
633   bool UseLineComment =
634       LineBreakIsNextAfterThis || (Flags & MTRF_LineBreakFollows);
635   if (Flags & (MTRF_JumpTarget | MTRF_CommaFollows))
636     UseLineComment = false;
637 
638   if (Flags & MTRF_Comment)
639     OS << (UseLineComment ? "// " : "/*");
640 
641   OS << EmitStr;
642   if (Flags & MTRF_Label)
643     OS << ": @" << Table.getLabelIndex(LabelID);
644 
645   if ((Flags & MTRF_Comment) && !UseLineComment)
646     OS << "*/";
647 
648   if (Flags & MTRF_JumpTarget) {
649     if (Flags & MTRF_Comment)
650       OS << " ";
651     OS << Table.getLabelIndex(LabelID);
652   }
653 
654   if (Flags & MTRF_CommaFollows) {
655     OS << ",";
656     if (!LineBreakIsNextAfterThis && !(Flags & MTRF_LineBreakFollows))
657       OS << " ";
658   }
659 
660   if (Flags & MTRF_LineBreakFollows)
661     OS << "\n";
662 }
663 
664 MatchTable &operator<<(MatchTable &Table, const MatchTableRecord &Value) {
665   Table.push_back(Value);
666   return Table;
667 }
668 
669 //===- Matchers -----------------------------------------------------------===//
670 
671 class OperandMatcher;
672 class MatchAction;
673 class PredicateMatcher;
674 
675 class Matcher {
676 public:
677   virtual ~Matcher() = default;
678   virtual void optimize() {}
679   virtual void emit(MatchTable &Table) = 0;
680 
681   virtual bool hasFirstCondition() const = 0;
682   virtual const PredicateMatcher &getFirstCondition() const = 0;
683   virtual std::unique_ptr<PredicateMatcher> popFirstCondition() = 0;
684 };
685 
686 MatchTable MatchTable::buildTable(ArrayRef<Matcher *> Rules,
687                                   bool WithCoverage) {
688   MatchTable Table(WithCoverage);
689   for (Matcher *Rule : Rules)
690     Rule->emit(Table);
691 
692   return Table << MatchTable::Opcode("GIM_Reject") << MatchTable::LineBreak;
693 }
694 
695 class GroupMatcher final : public Matcher {
696   /// Conditions that form a common prefix of all the matchers contained.
697   SmallVector<std::unique_ptr<PredicateMatcher>, 1> Conditions;
698 
699   /// All the nested matchers, sharing a common prefix.
700   std::vector<Matcher *> Matchers;
701 
702   /// An owning collection for any auxiliary matchers created while optimizing
703   /// nested matchers contained.
704   std::vector<std::unique_ptr<Matcher>> MatcherStorage;
705 
706 public:
707   /// Add a matcher to the collection of nested matchers if it meets the
708   /// requirements, and return true. If it doesn't, do nothing and return false.
709   ///
710   /// Expected to preserve its argument, so it could be moved out later on.
711   bool addMatcher(Matcher &Candidate);
712 
713   /// Mark the matcher as fully-built and ensure any invariants expected by both
714   /// optimize() and emit(...) methods. Generally, both sequences of calls
715   /// are expected to lead to a sensible result:
716   ///
717   /// addMatcher(...)*; finalize(); optimize(); emit(...); and
718   /// addMatcher(...)*; finalize(); emit(...);
719   ///
720   /// or generally
721   ///
722   /// addMatcher(...)*; finalize(); { optimize()*; emit(...); }*
723   ///
724   /// Multiple calls to optimize() are expected to be handled gracefully, though
725   /// optimize() is not expected to be idempotent. Multiple calls to finalize()
726   /// aren't generally supported. emit(...) is expected to be non-mutating and
727   /// producing the exact same results upon repeated calls.
728   ///
729   /// addMatcher() calls after the finalize() call are not supported.
730   ///
731   /// finalize() and optimize() are both allowed to mutate the contained
732   /// matchers, so moving them out after finalize() is not supported.
733   void finalize();
734   void optimize() override;
735   void emit(MatchTable &Table) override;
736 
737   /// Could be used to move out the matchers added previously, unless finalize()
738   /// has been already called. If any of the matchers are moved out, the group
739   /// becomes safe to destroy, but not safe to re-use for anything else.
740   iterator_range<std::vector<Matcher *>::iterator> matchers() {
741     return make_range(Matchers.begin(), Matchers.end());
742   }
743   size_t size() const { return Matchers.size(); }
744   bool empty() const { return Matchers.empty(); }
745 
746   std::unique_ptr<PredicateMatcher> popFirstCondition() override {
747     assert(!Conditions.empty() &&
748            "Trying to pop a condition from a condition-less group");
749     std::unique_ptr<PredicateMatcher> P = std::move(Conditions.front());
750     Conditions.erase(Conditions.begin());
751     return P;
752   }
753   const PredicateMatcher &getFirstCondition() const override {
754     assert(!Conditions.empty() &&
755            "Trying to get a condition from a condition-less group");
756     return *Conditions.front();
757   }
758   bool hasFirstCondition() const override { return !Conditions.empty(); }
759 
760 private:
761   /// See if a candidate matcher could be added to this group solely by
762   /// analyzing its first condition.
763   bool candidateConditionMatches(const PredicateMatcher &Predicate) const;
764 };
765 
766 class SwitchMatcher : public Matcher {
767   /// All the nested matchers, representing distinct switch-cases. The first
768   /// conditions (as Matcher::getFirstCondition() reports) of all the nested
769   /// matchers must share the same type and path to a value they check, in other
770   /// words, be isIdenticalDownToValue, but have different values they check
771   /// against.
772   std::vector<Matcher *> Matchers;
773 
774   /// The representative condition, with a type and a path (InsnVarID and OpIdx
775   /// in most cases)  shared by all the matchers contained.
776   std::unique_ptr<PredicateMatcher> Condition = nullptr;
777 
778   /// Temporary set used to check that the case values don't repeat within the
779   /// same switch.
780   std::set<MatchTableRecord> Values;
781 
782   /// An owning collection for any auxiliary matchers created while optimizing
783   /// nested matchers contained.
784   std::vector<std::unique_ptr<Matcher>> MatcherStorage;
785 
786 public:
787   bool addMatcher(Matcher &Candidate);
788 
789   void finalize();
790   void emit(MatchTable &Table) override;
791 
792   iterator_range<std::vector<Matcher *>::iterator> matchers() {
793     return make_range(Matchers.begin(), Matchers.end());
794   }
795   size_t size() const { return Matchers.size(); }
796   bool empty() const { return Matchers.empty(); }
797 
798   std::unique_ptr<PredicateMatcher> popFirstCondition() override {
799     // SwitchMatcher doesn't have a common first condition for its cases, as all
800     // the cases only share a kind of a value (a type and a path to it) they
801     // match, but deliberately differ in the actual value they match.
802     llvm_unreachable("Trying to pop a condition from a condition-less group");
803   }
804   const PredicateMatcher &getFirstCondition() const override {
805     llvm_unreachable("Trying to pop a condition from a condition-less group");
806   }
807   bool hasFirstCondition() const override { return false; }
808 
809 private:
810   /// See if the predicate type has a Switch-implementation for it.
811   static bool isSupportedPredicateType(const PredicateMatcher &Predicate);
812 
813   bool candidateConditionMatches(const PredicateMatcher &Predicate) const;
814 
815   /// emit()-helper
816   static void emitPredicateSpecificOpcodes(const PredicateMatcher &P,
817                                            MatchTable &Table);
818 };
819 
820 /// Generates code to check that a match rule matches.
821 class RuleMatcher : public Matcher {
822 public:
823   using ActionList = std::list<std::unique_ptr<MatchAction>>;
824   using action_iterator = ActionList::iterator;
825 
826 protected:
827   /// A list of matchers that all need to succeed for the current rule to match.
828   /// FIXME: This currently supports a single match position but could be
829   /// extended to support multiple positions to support div/rem fusion or
830   /// load-multiple instructions.
831   using MatchersTy = std::vector<std::unique_ptr<InstructionMatcher>> ;
832   MatchersTy Matchers;
833 
834   /// A list of actions that need to be taken when all predicates in this rule
835   /// have succeeded.
836   ActionList Actions;
837 
838   using DefinedInsnVariablesMap = std::map<InstructionMatcher *, unsigned>;
839 
840   /// A map of instruction matchers to the local variables
841   DefinedInsnVariablesMap InsnVariableIDs;
842 
843   using MutatableInsnSet = SmallPtrSet<InstructionMatcher *, 4>;
844 
845   // The set of instruction matchers that have not yet been claimed for mutation
846   // by a BuildMI.
847   MutatableInsnSet MutatableInsns;
848 
849   /// A map of named operands defined by the matchers that may be referenced by
850   /// the renderers.
851   StringMap<OperandMatcher *> DefinedOperands;
852 
853   /// A map of anonymous physical register operands defined by the matchers that
854   /// may be referenced by the renderers.
855   DenseMap<Record *, OperandMatcher *> PhysRegOperands;
856 
857   /// ID for the next instruction variable defined with implicitlyDefineInsnVar()
858   unsigned NextInsnVarID;
859 
860   /// ID for the next output instruction allocated with allocateOutputInsnID()
861   unsigned NextOutputInsnID;
862 
863   /// ID for the next temporary register ID allocated with allocateTempRegID()
864   unsigned NextTempRegID;
865 
866   std::vector<Record *> RequiredFeatures;
867   std::vector<std::unique_ptr<PredicateMatcher>> EpilogueMatchers;
868 
869   ArrayRef<SMLoc> SrcLoc;
870 
871   typedef std::tuple<Record *, unsigned, unsigned>
872       DefinedComplexPatternSubOperand;
873   typedef StringMap<DefinedComplexPatternSubOperand>
874       DefinedComplexPatternSubOperandMap;
875   /// A map of Symbolic Names to ComplexPattern sub-operands.
876   DefinedComplexPatternSubOperandMap ComplexSubOperands;
877   /// A map used to for multiple referenced error check of ComplexSubOperand.
878   /// ComplexSubOperand can't be referenced multiple from different operands,
879   /// however multiple references from same operand are allowed since that is
880   /// how 'same operand checks' are generated.
881   StringMap<std::string> ComplexSubOperandsParentName;
882 
883   uint64_t RuleID;
884   static uint64_t NextRuleID;
885 
886 public:
887   RuleMatcher(ArrayRef<SMLoc> SrcLoc)
888       : NextInsnVarID(0), NextOutputInsnID(0), NextTempRegID(0), SrcLoc(SrcLoc),
889         RuleID(NextRuleID++) {}
890   RuleMatcher(RuleMatcher &&Other) = default;
891   RuleMatcher &operator=(RuleMatcher &&Other) = default;
892 
893   uint64_t getRuleID() const { return RuleID; }
894 
895   InstructionMatcher &addInstructionMatcher(StringRef SymbolicName);
896   void addRequiredFeature(Record *Feature);
897   const std::vector<Record *> &getRequiredFeatures() const;
898 
899   template <class Kind, class... Args> Kind &addAction(Args &&... args);
900   template <class Kind, class... Args>
901   action_iterator insertAction(action_iterator InsertPt, Args &&... args);
902 
903   /// Define an instruction without emitting any code to do so.
904   unsigned implicitlyDefineInsnVar(InstructionMatcher &Matcher);
905 
906   unsigned getInsnVarID(InstructionMatcher &InsnMatcher) const;
907   DefinedInsnVariablesMap::const_iterator defined_insn_vars_begin() const {
908     return InsnVariableIDs.begin();
909   }
910   DefinedInsnVariablesMap::const_iterator defined_insn_vars_end() const {
911     return InsnVariableIDs.end();
912   }
913   iterator_range<typename DefinedInsnVariablesMap::const_iterator>
914   defined_insn_vars() const {
915     return make_range(defined_insn_vars_begin(), defined_insn_vars_end());
916   }
917 
918   MutatableInsnSet::const_iterator mutatable_insns_begin() const {
919     return MutatableInsns.begin();
920   }
921   MutatableInsnSet::const_iterator mutatable_insns_end() const {
922     return MutatableInsns.end();
923   }
924   iterator_range<typename MutatableInsnSet::const_iterator>
925   mutatable_insns() const {
926     return make_range(mutatable_insns_begin(), mutatable_insns_end());
927   }
928   void reserveInsnMatcherForMutation(InstructionMatcher *InsnMatcher) {
929     bool R = MutatableInsns.erase(InsnMatcher);
930     assert(R && "Reserving a mutatable insn that isn't available");
931     (void)R;
932   }
933 
934   action_iterator actions_begin() { return Actions.begin(); }
935   action_iterator actions_end() { return Actions.end(); }
936   iterator_range<action_iterator> actions() {
937     return make_range(actions_begin(), actions_end());
938   }
939 
940   void defineOperand(StringRef SymbolicName, OperandMatcher &OM);
941 
942   void definePhysRegOperand(Record *Reg, OperandMatcher &OM);
943 
944   Error defineComplexSubOperand(StringRef SymbolicName, Record *ComplexPattern,
945                                 unsigned RendererID, unsigned SubOperandID,
946                                 StringRef ParentSymbolicName) {
947     std::string ParentName(ParentSymbolicName);
948     if (ComplexSubOperands.count(SymbolicName)) {
949       const std::string &RecordedParentName =
950           ComplexSubOperandsParentName[SymbolicName];
951       if (RecordedParentName != ParentName)
952         return failedImport("Error: Complex suboperand " + SymbolicName +
953                             " referenced by different operands: " +
954                             RecordedParentName + " and " + ParentName + ".");
955       // Complex suboperand referenced more than once from same the operand is
956       // used to generate 'same operand check'. Emitting of
957       // GIR_ComplexSubOperandRenderer for them is already handled.
958       return Error::success();
959     }
960 
961     ComplexSubOperands[SymbolicName] =
962         std::make_tuple(ComplexPattern, RendererID, SubOperandID);
963     ComplexSubOperandsParentName[SymbolicName] = ParentName;
964 
965     return Error::success();
966   }
967 
968   Optional<DefinedComplexPatternSubOperand>
969   getComplexSubOperand(StringRef SymbolicName) const {
970     const auto &I = ComplexSubOperands.find(SymbolicName);
971     if (I == ComplexSubOperands.end())
972       return None;
973     return I->second;
974   }
975 
976   InstructionMatcher &getInstructionMatcher(StringRef SymbolicName) const;
977   const OperandMatcher &getOperandMatcher(StringRef Name) const;
978   const OperandMatcher &getPhysRegOperandMatcher(Record *) const;
979 
980   void optimize() override;
981   void emit(MatchTable &Table) override;
982 
983   /// Compare the priority of this object and B.
984   ///
985   /// Returns true if this object is more important than B.
986   bool isHigherPriorityThan(const RuleMatcher &B) const;
987 
988   /// Report the maximum number of temporary operands needed by the rule
989   /// matcher.
990   unsigned countRendererFns() const;
991 
992   std::unique_ptr<PredicateMatcher> popFirstCondition() override;
993   const PredicateMatcher &getFirstCondition() const override;
994   LLTCodeGen getFirstConditionAsRootType();
995   bool hasFirstCondition() const override;
996   unsigned getNumOperands() const;
997   StringRef getOpcode() const;
998 
999   // FIXME: Remove this as soon as possible
1000   InstructionMatcher &insnmatchers_front() const { return *Matchers.front(); }
1001 
1002   unsigned allocateOutputInsnID() { return NextOutputInsnID++; }
1003   unsigned allocateTempRegID() { return NextTempRegID++; }
1004 
1005   iterator_range<MatchersTy::iterator> insnmatchers() {
1006     return make_range(Matchers.begin(), Matchers.end());
1007   }
1008   bool insnmatchers_empty() const { return Matchers.empty(); }
1009   void insnmatchers_pop_front() { Matchers.erase(Matchers.begin()); }
1010 };
1011 
1012 uint64_t RuleMatcher::NextRuleID = 0;
1013 
1014 using action_iterator = RuleMatcher::action_iterator;
1015 
1016 template <class PredicateTy> class PredicateListMatcher {
1017 private:
1018   /// Template instantiations should specialize this to return a string to use
1019   /// for the comment emitted when there are no predicates.
1020   std::string getNoPredicateComment() const;
1021 
1022 protected:
1023   using PredicatesTy = std::deque<std::unique_ptr<PredicateTy>>;
1024   PredicatesTy Predicates;
1025 
1026   /// Track if the list of predicates was manipulated by one of the optimization
1027   /// methods.
1028   bool Optimized = false;
1029 
1030 public:
1031   typename PredicatesTy::iterator predicates_begin() {
1032     return Predicates.begin();
1033   }
1034   typename PredicatesTy::iterator predicates_end() {
1035     return Predicates.end();
1036   }
1037   iterator_range<typename PredicatesTy::iterator> predicates() {
1038     return make_range(predicates_begin(), predicates_end());
1039   }
1040   typename PredicatesTy::size_type predicates_size() const {
1041     return Predicates.size();
1042   }
1043   bool predicates_empty() const { return Predicates.empty(); }
1044 
1045   std::unique_ptr<PredicateTy> predicates_pop_front() {
1046     std::unique_ptr<PredicateTy> Front = std::move(Predicates.front());
1047     Predicates.pop_front();
1048     Optimized = true;
1049     return Front;
1050   }
1051 
1052   void prependPredicate(std::unique_ptr<PredicateTy> &&Predicate) {
1053     Predicates.push_front(std::move(Predicate));
1054   }
1055 
1056   void eraseNullPredicates() {
1057     const auto NewEnd =
1058         std::stable_partition(Predicates.begin(), Predicates.end(),
1059                               std::logical_not<std::unique_ptr<PredicateTy>>());
1060     if (NewEnd != Predicates.begin()) {
1061       Predicates.erase(Predicates.begin(), NewEnd);
1062       Optimized = true;
1063     }
1064   }
1065 
1066   /// Emit MatchTable opcodes that tests whether all the predicates are met.
1067   template <class... Args>
1068   void emitPredicateListOpcodes(MatchTable &Table, Args &&... args) {
1069     if (Predicates.empty() && !Optimized) {
1070       Table << MatchTable::Comment(getNoPredicateComment())
1071             << MatchTable::LineBreak;
1072       return;
1073     }
1074 
1075     for (const auto &Predicate : predicates())
1076       Predicate->emitPredicateOpcodes(Table, std::forward<Args>(args)...);
1077   }
1078 
1079   /// Provide a function to avoid emitting certain predicates. This is used to
1080   /// defer some predicate checks until after others
1081   using PredicateFilterFunc = std::function<bool(const PredicateTy&)>;
1082 
1083   /// Emit MatchTable opcodes for predicates which satisfy \p
1084   /// ShouldEmitPredicate. This should be called multiple times to ensure all
1085   /// predicates are eventually added to the match table.
1086   template <class... Args>
1087   void emitFilteredPredicateListOpcodes(PredicateFilterFunc ShouldEmitPredicate,
1088                                         MatchTable &Table, Args &&... args) {
1089     if (Predicates.empty() && !Optimized) {
1090       Table << MatchTable::Comment(getNoPredicateComment())
1091             << MatchTable::LineBreak;
1092       return;
1093     }
1094 
1095     for (const auto &Predicate : predicates()) {
1096       if (ShouldEmitPredicate(*Predicate))
1097         Predicate->emitPredicateOpcodes(Table, std::forward<Args>(args)...);
1098     }
1099   }
1100 };
1101 
1102 class PredicateMatcher {
1103 public:
1104   /// This enum is used for RTTI and also defines the priority that is given to
1105   /// the predicate when generating the matcher code. Kinds with higher priority
1106   /// must be tested first.
1107   ///
1108   /// The relative priority of OPM_LLT, OPM_RegBank, and OPM_MBB do not matter
1109   /// but OPM_Int must have priority over OPM_RegBank since constant integers
1110   /// are represented by a virtual register defined by a G_CONSTANT instruction.
1111   ///
1112   /// Note: The relative priority between IPM_ and OPM_ does not matter, they
1113   /// are currently not compared between each other.
1114   enum PredicateKind {
1115     IPM_Opcode,
1116     IPM_NumOperands,
1117     IPM_ImmPredicate,
1118     IPM_Imm,
1119     IPM_AtomicOrderingMMO,
1120     IPM_MemoryLLTSize,
1121     IPM_MemoryVsLLTSize,
1122     IPM_MemoryAddressSpace,
1123     IPM_MemoryAlignment,
1124     IPM_VectorSplatImm,
1125     IPM_NoUse,
1126     IPM_GenericPredicate,
1127     OPM_SameOperand,
1128     OPM_ComplexPattern,
1129     OPM_IntrinsicID,
1130     OPM_CmpPredicate,
1131     OPM_Instruction,
1132     OPM_Int,
1133     OPM_LiteralInt,
1134     OPM_LLT,
1135     OPM_PointerToAny,
1136     OPM_RegBank,
1137     OPM_MBB,
1138     OPM_RecordNamedOperand,
1139   };
1140 
1141 protected:
1142   PredicateKind Kind;
1143   unsigned InsnVarID;
1144   unsigned OpIdx;
1145 
1146 public:
1147   PredicateMatcher(PredicateKind Kind, unsigned InsnVarID, unsigned OpIdx = ~0)
1148       : Kind(Kind), InsnVarID(InsnVarID), OpIdx(OpIdx) {}
1149 
1150   unsigned getInsnVarID() const { return InsnVarID; }
1151   unsigned getOpIdx() const { return OpIdx; }
1152 
1153   virtual ~PredicateMatcher() = default;
1154   /// Emit MatchTable opcodes that check the predicate for the given operand.
1155   virtual void emitPredicateOpcodes(MatchTable &Table,
1156                                     RuleMatcher &Rule) const = 0;
1157 
1158   PredicateKind getKind() const { return Kind; }
1159 
1160   bool dependsOnOperands() const {
1161     // Custom predicates really depend on the context pattern of the
1162     // instruction, not just the individual instruction. This therefore
1163     // implicitly depends on all other pattern constraints.
1164     return Kind == IPM_GenericPredicate;
1165   }
1166 
1167   virtual bool isIdentical(const PredicateMatcher &B) const {
1168     return B.getKind() == getKind() && InsnVarID == B.InsnVarID &&
1169            OpIdx == B.OpIdx;
1170   }
1171 
1172   virtual bool isIdenticalDownToValue(const PredicateMatcher &B) const {
1173     return hasValue() && PredicateMatcher::isIdentical(B);
1174   }
1175 
1176   virtual MatchTableRecord getValue() const {
1177     assert(hasValue() && "Can not get a value of a value-less predicate!");
1178     llvm_unreachable("Not implemented yet");
1179   }
1180   virtual bool hasValue() const { return false; }
1181 
1182   /// Report the maximum number of temporary operands needed by the predicate
1183   /// matcher.
1184   virtual unsigned countRendererFns() const { return 0; }
1185 };
1186 
1187 /// Generates code to check a predicate of an operand.
1188 ///
1189 /// Typical predicates include:
1190 /// * Operand is a particular register.
1191 /// * Operand is assigned a particular register bank.
1192 /// * Operand is an MBB.
1193 class OperandPredicateMatcher : public PredicateMatcher {
1194 public:
1195   OperandPredicateMatcher(PredicateKind Kind, unsigned InsnVarID,
1196                           unsigned OpIdx)
1197       : PredicateMatcher(Kind, InsnVarID, OpIdx) {}
1198   virtual ~OperandPredicateMatcher() {}
1199 
1200   /// Compare the priority of this object and B.
1201   ///
1202   /// Returns true if this object is more important than B.
1203   virtual bool isHigherPriorityThan(const OperandPredicateMatcher &B) const;
1204 };
1205 
1206 template <>
1207 std::string
1208 PredicateListMatcher<OperandPredicateMatcher>::getNoPredicateComment() const {
1209   return "No operand predicates";
1210 }
1211 
1212 /// Generates code to check that a register operand is defined by the same exact
1213 /// one as another.
1214 class SameOperandMatcher : public OperandPredicateMatcher {
1215   std::string MatchingName;
1216   unsigned OrigOpIdx;
1217 
1218 public:
1219   SameOperandMatcher(unsigned InsnVarID, unsigned OpIdx, StringRef MatchingName,
1220                      unsigned OrigOpIdx)
1221       : OperandPredicateMatcher(OPM_SameOperand, InsnVarID, OpIdx),
1222         MatchingName(MatchingName), OrigOpIdx(OrigOpIdx) {}
1223 
1224   static bool classof(const PredicateMatcher *P) {
1225     return P->getKind() == OPM_SameOperand;
1226   }
1227 
1228   void emitPredicateOpcodes(MatchTable &Table,
1229                             RuleMatcher &Rule) const override;
1230 
1231   bool isIdentical(const PredicateMatcher &B) const override {
1232     return OperandPredicateMatcher::isIdentical(B) &&
1233            OrigOpIdx == cast<SameOperandMatcher>(&B)->OrigOpIdx &&
1234            MatchingName == cast<SameOperandMatcher>(&B)->MatchingName;
1235   }
1236 };
1237 
1238 /// Generates code to check that an operand is a particular LLT.
1239 class LLTOperandMatcher : public OperandPredicateMatcher {
1240 protected:
1241   LLTCodeGen Ty;
1242 
1243 public:
1244   static std::map<LLTCodeGen, unsigned> TypeIDValues;
1245 
1246   static void initTypeIDValuesMap() {
1247     TypeIDValues.clear();
1248 
1249     unsigned ID = 0;
1250     for (const LLTCodeGen &LLTy : KnownTypes)
1251       TypeIDValues[LLTy] = ID++;
1252   }
1253 
1254   LLTOperandMatcher(unsigned InsnVarID, unsigned OpIdx, const LLTCodeGen &Ty)
1255       : OperandPredicateMatcher(OPM_LLT, InsnVarID, OpIdx), Ty(Ty) {
1256     KnownTypes.insert(Ty);
1257   }
1258 
1259   static bool classof(const PredicateMatcher *P) {
1260     return P->getKind() == OPM_LLT;
1261   }
1262   bool isIdentical(const PredicateMatcher &B) const override {
1263     return OperandPredicateMatcher::isIdentical(B) &&
1264            Ty == cast<LLTOperandMatcher>(&B)->Ty;
1265   }
1266   MatchTableRecord getValue() const override {
1267     const auto VI = TypeIDValues.find(Ty);
1268     if (VI == TypeIDValues.end())
1269       return MatchTable::NamedValue(getTy().getCxxEnumValue());
1270     return MatchTable::NamedValue(getTy().getCxxEnumValue(), VI->second);
1271   }
1272   bool hasValue() const override {
1273     if (TypeIDValues.size() != KnownTypes.size())
1274       initTypeIDValuesMap();
1275     return TypeIDValues.count(Ty);
1276   }
1277 
1278   LLTCodeGen getTy() const { return Ty; }
1279 
1280   void emitPredicateOpcodes(MatchTable &Table,
1281                             RuleMatcher &Rule) const override {
1282     Table << MatchTable::Opcode("GIM_CheckType") << MatchTable::Comment("MI")
1283           << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Op")
1284           << MatchTable::IntValue(OpIdx) << MatchTable::Comment("Type")
1285           << getValue() << MatchTable::LineBreak;
1286   }
1287 };
1288 
1289 std::map<LLTCodeGen, unsigned> LLTOperandMatcher::TypeIDValues;
1290 
1291 /// Generates code to check that an operand is a pointer to any address space.
1292 ///
1293 /// In SelectionDAG, the types did not describe pointers or address spaces. As a
1294 /// result, iN is used to describe a pointer of N bits to any address space and
1295 /// PatFrag predicates are typically used to constrain the address space. There's
1296 /// no reliable means to derive the missing type information from the pattern so
1297 /// imported rules must test the components of a pointer separately.
1298 ///
1299 /// If SizeInBits is zero, then the pointer size will be obtained from the
1300 /// subtarget.
1301 class PointerToAnyOperandMatcher : public OperandPredicateMatcher {
1302 protected:
1303   unsigned SizeInBits;
1304 
1305 public:
1306   PointerToAnyOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
1307                              unsigned SizeInBits)
1308       : OperandPredicateMatcher(OPM_PointerToAny, InsnVarID, OpIdx),
1309         SizeInBits(SizeInBits) {}
1310 
1311   static bool classof(const PredicateMatcher *P) {
1312     return P->getKind() == OPM_PointerToAny;
1313   }
1314 
1315   bool isIdentical(const PredicateMatcher &B) const override {
1316     return OperandPredicateMatcher::isIdentical(B) &&
1317            SizeInBits == cast<PointerToAnyOperandMatcher>(&B)->SizeInBits;
1318   }
1319 
1320   void emitPredicateOpcodes(MatchTable &Table,
1321                             RuleMatcher &Rule) const override {
1322     Table << MatchTable::Opcode("GIM_CheckPointerToAny")
1323           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1324           << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1325           << MatchTable::Comment("SizeInBits")
1326           << MatchTable::IntValue(SizeInBits) << MatchTable::LineBreak;
1327   }
1328 };
1329 
1330 /// Generates code to record named operand in RecordedOperands list at StoreIdx.
1331 /// Predicates with 'let PredicateCodeUsesOperands = 1' get RecordedOperands as
1332 /// an argument to predicate's c++ code once all operands have been matched.
1333 class RecordNamedOperandMatcher : public OperandPredicateMatcher {
1334 protected:
1335   unsigned StoreIdx;
1336   std::string Name;
1337 
1338 public:
1339   RecordNamedOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
1340                             unsigned StoreIdx, StringRef Name)
1341       : OperandPredicateMatcher(OPM_RecordNamedOperand, InsnVarID, OpIdx),
1342         StoreIdx(StoreIdx), Name(Name) {}
1343 
1344   static bool classof(const PredicateMatcher *P) {
1345     return P->getKind() == OPM_RecordNamedOperand;
1346   }
1347 
1348   bool isIdentical(const PredicateMatcher &B) const override {
1349     return OperandPredicateMatcher::isIdentical(B) &&
1350            StoreIdx == cast<RecordNamedOperandMatcher>(&B)->StoreIdx &&
1351            Name == cast<RecordNamedOperandMatcher>(&B)->Name;
1352   }
1353 
1354   void emitPredicateOpcodes(MatchTable &Table,
1355                             RuleMatcher &Rule) const override {
1356     Table << MatchTable::Opcode("GIM_RecordNamedOperand")
1357           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1358           << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1359           << MatchTable::Comment("StoreIdx") << MatchTable::IntValue(StoreIdx)
1360           << MatchTable::Comment("Name : " + Name) << MatchTable::LineBreak;
1361   }
1362 };
1363 
1364 /// Generates code to check that an operand is a particular target constant.
1365 class ComplexPatternOperandMatcher : public OperandPredicateMatcher {
1366 protected:
1367   const OperandMatcher &Operand;
1368   const Record &TheDef;
1369 
1370   unsigned getAllocatedTemporariesBaseID() const;
1371 
1372 public:
1373   bool isIdentical(const PredicateMatcher &B) const override { return false; }
1374 
1375   ComplexPatternOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
1376                                const OperandMatcher &Operand,
1377                                const Record &TheDef)
1378       : OperandPredicateMatcher(OPM_ComplexPattern, InsnVarID, OpIdx),
1379         Operand(Operand), TheDef(TheDef) {}
1380 
1381   static bool classof(const PredicateMatcher *P) {
1382     return P->getKind() == OPM_ComplexPattern;
1383   }
1384 
1385   void emitPredicateOpcodes(MatchTable &Table,
1386                             RuleMatcher &Rule) const override {
1387     unsigned ID = getAllocatedTemporariesBaseID();
1388     Table << MatchTable::Opcode("GIM_CheckComplexPattern")
1389           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1390           << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1391           << MatchTable::Comment("Renderer") << MatchTable::IntValue(ID)
1392           << MatchTable::NamedValue(("GICP_" + TheDef.getName()).str())
1393           << MatchTable::LineBreak;
1394   }
1395 
1396   unsigned countRendererFns() const override {
1397     return 1;
1398   }
1399 };
1400 
1401 /// Generates code to check that an operand is in a particular register bank.
1402 class RegisterBankOperandMatcher : public OperandPredicateMatcher {
1403 protected:
1404   const CodeGenRegisterClass &RC;
1405 
1406 public:
1407   RegisterBankOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
1408                              const CodeGenRegisterClass &RC)
1409       : OperandPredicateMatcher(OPM_RegBank, InsnVarID, OpIdx), RC(RC) {}
1410 
1411   bool isIdentical(const PredicateMatcher &B) const override {
1412     return OperandPredicateMatcher::isIdentical(B) &&
1413            RC.getDef() == cast<RegisterBankOperandMatcher>(&B)->RC.getDef();
1414   }
1415 
1416   static bool classof(const PredicateMatcher *P) {
1417     return P->getKind() == OPM_RegBank;
1418   }
1419 
1420   void emitPredicateOpcodes(MatchTable &Table,
1421                             RuleMatcher &Rule) const override {
1422     Table << MatchTable::Opcode("GIM_CheckRegBankForClass")
1423           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1424           << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1425           << MatchTable::Comment("RC")
1426           << MatchTable::NamedValue(RC.getQualifiedName() + "RegClassID")
1427           << MatchTable::LineBreak;
1428   }
1429 };
1430 
1431 /// Generates code to check that an operand is a basic block.
1432 class MBBOperandMatcher : public OperandPredicateMatcher {
1433 public:
1434   MBBOperandMatcher(unsigned InsnVarID, unsigned OpIdx)
1435       : OperandPredicateMatcher(OPM_MBB, InsnVarID, OpIdx) {}
1436 
1437   static bool classof(const PredicateMatcher *P) {
1438     return P->getKind() == OPM_MBB;
1439   }
1440 
1441   void emitPredicateOpcodes(MatchTable &Table,
1442                             RuleMatcher &Rule) const override {
1443     Table << MatchTable::Opcode("GIM_CheckIsMBB") << MatchTable::Comment("MI")
1444           << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Op")
1445           << MatchTable::IntValue(OpIdx) << MatchTable::LineBreak;
1446   }
1447 };
1448 
1449 class ImmOperandMatcher : public OperandPredicateMatcher {
1450 public:
1451   ImmOperandMatcher(unsigned InsnVarID, unsigned OpIdx)
1452       : OperandPredicateMatcher(IPM_Imm, InsnVarID, OpIdx) {}
1453 
1454   static bool classof(const PredicateMatcher *P) {
1455     return P->getKind() == IPM_Imm;
1456   }
1457 
1458   void emitPredicateOpcodes(MatchTable &Table,
1459                             RuleMatcher &Rule) const override {
1460     Table << MatchTable::Opcode("GIM_CheckIsImm") << MatchTable::Comment("MI")
1461           << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Op")
1462           << MatchTable::IntValue(OpIdx) << MatchTable::LineBreak;
1463   }
1464 };
1465 
1466 /// Generates code to check that an operand is a G_CONSTANT with a particular
1467 /// int.
1468 class ConstantIntOperandMatcher : public OperandPredicateMatcher {
1469 protected:
1470   int64_t Value;
1471 
1472 public:
1473   ConstantIntOperandMatcher(unsigned InsnVarID, unsigned OpIdx, int64_t Value)
1474       : OperandPredicateMatcher(OPM_Int, InsnVarID, OpIdx), Value(Value) {}
1475 
1476   bool isIdentical(const PredicateMatcher &B) const override {
1477     return OperandPredicateMatcher::isIdentical(B) &&
1478            Value == cast<ConstantIntOperandMatcher>(&B)->Value;
1479   }
1480 
1481   static bool classof(const PredicateMatcher *P) {
1482     return P->getKind() == OPM_Int;
1483   }
1484 
1485   void emitPredicateOpcodes(MatchTable &Table,
1486                             RuleMatcher &Rule) const override {
1487     Table << MatchTable::Opcode("GIM_CheckConstantInt")
1488           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1489           << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1490           << MatchTable::IntValue(Value) << MatchTable::LineBreak;
1491   }
1492 };
1493 
1494 /// Generates code to check that an operand is a raw int (where MO.isImm() or
1495 /// MO.isCImm() is true).
1496 class LiteralIntOperandMatcher : public OperandPredicateMatcher {
1497 protected:
1498   int64_t Value;
1499 
1500 public:
1501   LiteralIntOperandMatcher(unsigned InsnVarID, unsigned OpIdx, int64_t Value)
1502       : OperandPredicateMatcher(OPM_LiteralInt, InsnVarID, OpIdx),
1503         Value(Value) {}
1504 
1505   bool isIdentical(const PredicateMatcher &B) const override {
1506     return OperandPredicateMatcher::isIdentical(B) &&
1507            Value == cast<LiteralIntOperandMatcher>(&B)->Value;
1508   }
1509 
1510   static bool classof(const PredicateMatcher *P) {
1511     return P->getKind() == OPM_LiteralInt;
1512   }
1513 
1514   void emitPredicateOpcodes(MatchTable &Table,
1515                             RuleMatcher &Rule) const override {
1516     Table << MatchTable::Opcode("GIM_CheckLiteralInt")
1517           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1518           << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1519           << MatchTable::IntValue(Value) << MatchTable::LineBreak;
1520   }
1521 };
1522 
1523 /// Generates code to check that an operand is an CmpInst predicate
1524 class CmpPredicateOperandMatcher : public OperandPredicateMatcher {
1525 protected:
1526   std::string PredName;
1527 
1528 public:
1529   CmpPredicateOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
1530                              std::string P)
1531     : OperandPredicateMatcher(OPM_CmpPredicate, InsnVarID, OpIdx), PredName(P) {}
1532 
1533   bool isIdentical(const PredicateMatcher &B) const override {
1534     return OperandPredicateMatcher::isIdentical(B) &&
1535            PredName == cast<CmpPredicateOperandMatcher>(&B)->PredName;
1536   }
1537 
1538   static bool classof(const PredicateMatcher *P) {
1539     return P->getKind() == OPM_CmpPredicate;
1540   }
1541 
1542   void emitPredicateOpcodes(MatchTable &Table,
1543                             RuleMatcher &Rule) const override {
1544     Table << MatchTable::Opcode("GIM_CheckCmpPredicate")
1545           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1546           << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1547           << MatchTable::Comment("Predicate")
1548           << MatchTable::NamedValue("CmpInst", PredName)
1549           << MatchTable::LineBreak;
1550   }
1551 };
1552 
1553 /// Generates code to check that an operand is an intrinsic ID.
1554 class IntrinsicIDOperandMatcher : public OperandPredicateMatcher {
1555 protected:
1556   const CodeGenIntrinsic *II;
1557 
1558 public:
1559   IntrinsicIDOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
1560                             const CodeGenIntrinsic *II)
1561       : OperandPredicateMatcher(OPM_IntrinsicID, InsnVarID, OpIdx), II(II) {}
1562 
1563   bool isIdentical(const PredicateMatcher &B) const override {
1564     return OperandPredicateMatcher::isIdentical(B) &&
1565            II == cast<IntrinsicIDOperandMatcher>(&B)->II;
1566   }
1567 
1568   static bool classof(const PredicateMatcher *P) {
1569     return P->getKind() == OPM_IntrinsicID;
1570   }
1571 
1572   void emitPredicateOpcodes(MatchTable &Table,
1573                             RuleMatcher &Rule) const override {
1574     Table << MatchTable::Opcode("GIM_CheckIntrinsicID")
1575           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1576           << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1577           << MatchTable::NamedValue("Intrinsic::" + II->EnumName)
1578           << MatchTable::LineBreak;
1579   }
1580 };
1581 
1582 /// Generates code to check that this operand is an immediate whose value meets
1583 /// an immediate predicate.
1584 class OperandImmPredicateMatcher : public OperandPredicateMatcher {
1585 protected:
1586   TreePredicateFn Predicate;
1587 
1588 public:
1589   OperandImmPredicateMatcher(unsigned InsnVarID, unsigned OpIdx,
1590                              const TreePredicateFn &Predicate)
1591       : OperandPredicateMatcher(IPM_ImmPredicate, InsnVarID, OpIdx),
1592         Predicate(Predicate) {}
1593 
1594   bool isIdentical(const PredicateMatcher &B) const override {
1595     return OperandPredicateMatcher::isIdentical(B) &&
1596            Predicate.getOrigPatFragRecord() ==
1597                cast<OperandImmPredicateMatcher>(&B)
1598                    ->Predicate.getOrigPatFragRecord();
1599   }
1600 
1601   static bool classof(const PredicateMatcher *P) {
1602     return P->getKind() == IPM_ImmPredicate;
1603   }
1604 
1605   void emitPredicateOpcodes(MatchTable &Table,
1606                             RuleMatcher &Rule) const override {
1607     Table << MatchTable::Opcode("GIM_CheckImmOperandPredicate")
1608           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1609           << MatchTable::Comment("MO") << MatchTable::IntValue(OpIdx)
1610           << MatchTable::Comment("Predicate")
1611           << MatchTable::NamedValue(getEnumNameForPredicate(Predicate))
1612           << MatchTable::LineBreak;
1613   }
1614 };
1615 
1616 /// Generates code to check that a set of predicates match for a particular
1617 /// operand.
1618 class OperandMatcher : public PredicateListMatcher<OperandPredicateMatcher> {
1619 protected:
1620   InstructionMatcher &Insn;
1621   unsigned OpIdx;
1622   std::string SymbolicName;
1623 
1624   /// The index of the first temporary variable allocated to this operand. The
1625   /// number of allocated temporaries can be found with
1626   /// countRendererFns().
1627   unsigned AllocatedTemporariesBaseID;
1628 
1629 public:
1630   OperandMatcher(InstructionMatcher &Insn, unsigned OpIdx,
1631                  const std::string &SymbolicName,
1632                  unsigned AllocatedTemporariesBaseID)
1633       : Insn(Insn), OpIdx(OpIdx), SymbolicName(SymbolicName),
1634         AllocatedTemporariesBaseID(AllocatedTemporariesBaseID) {}
1635 
1636   bool hasSymbolicName() const { return !SymbolicName.empty(); }
1637   StringRef getSymbolicName() const { return SymbolicName; }
1638   void setSymbolicName(StringRef Name) {
1639     assert(SymbolicName.empty() && "Operand already has a symbolic name");
1640     SymbolicName = std::string(Name);
1641   }
1642 
1643   /// Construct a new operand predicate and add it to the matcher.
1644   template <class Kind, class... Args>
1645   Optional<Kind *> addPredicate(Args &&... args) {
1646     if (isSameAsAnotherOperand())
1647       return None;
1648     Predicates.emplace_back(std::make_unique<Kind>(
1649         getInsnVarID(), getOpIdx(), std::forward<Args>(args)...));
1650     return static_cast<Kind *>(Predicates.back().get());
1651   }
1652 
1653   unsigned getOpIdx() const { return OpIdx; }
1654   unsigned getInsnVarID() const;
1655 
1656   std::string getOperandExpr(unsigned InsnVarID) const {
1657     return "State.MIs[" + llvm::to_string(InsnVarID) + "]->getOperand(" +
1658            llvm::to_string(OpIdx) + ")";
1659   }
1660 
1661   InstructionMatcher &getInstructionMatcher() const { return Insn; }
1662 
1663   Error addTypeCheckPredicate(const TypeSetByHwMode &VTy,
1664                               bool OperandIsAPointer);
1665 
1666   /// Emit MatchTable opcodes that test whether the instruction named in
1667   /// InsnVarID matches all the predicates and all the operands.
1668   void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule) {
1669     if (!Optimized) {
1670       std::string Comment;
1671       raw_string_ostream CommentOS(Comment);
1672       CommentOS << "MIs[" << getInsnVarID() << "] ";
1673       if (SymbolicName.empty())
1674         CommentOS << "Operand " << OpIdx;
1675       else
1676         CommentOS << SymbolicName;
1677       Table << MatchTable::Comment(Comment) << MatchTable::LineBreak;
1678     }
1679 
1680     emitPredicateListOpcodes(Table, Rule);
1681   }
1682 
1683   /// Compare the priority of this object and B.
1684   ///
1685   /// Returns true if this object is more important than B.
1686   bool isHigherPriorityThan(OperandMatcher &B) {
1687     // Operand matchers involving more predicates have higher priority.
1688     if (predicates_size() > B.predicates_size())
1689       return true;
1690     if (predicates_size() < B.predicates_size())
1691       return false;
1692 
1693     // This assumes that predicates are added in a consistent order.
1694     for (auto &&Predicate : zip(predicates(), B.predicates())) {
1695       if (std::get<0>(Predicate)->isHigherPriorityThan(*std::get<1>(Predicate)))
1696         return true;
1697       if (std::get<1>(Predicate)->isHigherPriorityThan(*std::get<0>(Predicate)))
1698         return false;
1699     }
1700 
1701     return false;
1702   };
1703 
1704   /// Report the maximum number of temporary operands needed by the operand
1705   /// matcher.
1706   unsigned countRendererFns() {
1707     return std::accumulate(
1708         predicates().begin(), predicates().end(), 0,
1709         [](unsigned A,
1710            const std::unique_ptr<OperandPredicateMatcher> &Predicate) {
1711           return A + Predicate->countRendererFns();
1712         });
1713   }
1714 
1715   unsigned getAllocatedTemporariesBaseID() const {
1716     return AllocatedTemporariesBaseID;
1717   }
1718 
1719   bool isSameAsAnotherOperand() {
1720     for (const auto &Predicate : predicates())
1721       if (isa<SameOperandMatcher>(Predicate))
1722         return true;
1723     return false;
1724   }
1725 };
1726 
1727 Error OperandMatcher::addTypeCheckPredicate(const TypeSetByHwMode &VTy,
1728                                             bool OperandIsAPointer) {
1729   if (!VTy.isMachineValueType())
1730     return failedImport("unsupported typeset");
1731 
1732   if (VTy.getMachineValueType() == MVT::iPTR && OperandIsAPointer) {
1733     addPredicate<PointerToAnyOperandMatcher>(0);
1734     return Error::success();
1735   }
1736 
1737   auto OpTyOrNone = MVTToLLT(VTy.getMachineValueType().SimpleTy);
1738   if (!OpTyOrNone)
1739     return failedImport("unsupported type");
1740 
1741   if (OperandIsAPointer)
1742     addPredicate<PointerToAnyOperandMatcher>(OpTyOrNone->get().getSizeInBits());
1743   else if (VTy.isPointer())
1744     addPredicate<LLTOperandMatcher>(LLT::pointer(VTy.getPtrAddrSpace(),
1745                                                  OpTyOrNone->get().getSizeInBits()));
1746   else
1747     addPredicate<LLTOperandMatcher>(*OpTyOrNone);
1748   return Error::success();
1749 }
1750 
1751 unsigned ComplexPatternOperandMatcher::getAllocatedTemporariesBaseID() const {
1752   return Operand.getAllocatedTemporariesBaseID();
1753 }
1754 
1755 /// Generates code to check a predicate on an instruction.
1756 ///
1757 /// Typical predicates include:
1758 /// * The opcode of the instruction is a particular value.
1759 /// * The nsw/nuw flag is/isn't set.
1760 class InstructionPredicateMatcher : public PredicateMatcher {
1761 public:
1762   InstructionPredicateMatcher(PredicateKind Kind, unsigned InsnVarID)
1763       : PredicateMatcher(Kind, InsnVarID) {}
1764   virtual ~InstructionPredicateMatcher() {}
1765 
1766   /// Compare the priority of this object and B.
1767   ///
1768   /// Returns true if this object is more important than B.
1769   virtual bool
1770   isHigherPriorityThan(const InstructionPredicateMatcher &B) const {
1771     return Kind < B.Kind;
1772   };
1773 };
1774 
1775 template <>
1776 std::string
1777 PredicateListMatcher<PredicateMatcher>::getNoPredicateComment() const {
1778   return "No instruction predicates";
1779 }
1780 
1781 /// Generates code to check the opcode of an instruction.
1782 class InstructionOpcodeMatcher : public InstructionPredicateMatcher {
1783 protected:
1784   // Allow matching one to several, similar opcodes that share properties. This
1785   // is to handle patterns where one SelectionDAG operation maps to multiple
1786   // GlobalISel ones (e.g. G_BUILD_VECTOR and G_BUILD_VECTOR_TRUNC). The first
1787   // is treated as the canonical opcode.
1788   SmallVector<const CodeGenInstruction *, 2> Insts;
1789 
1790   static DenseMap<const CodeGenInstruction *, unsigned> OpcodeValues;
1791 
1792 
1793   MatchTableRecord getInstValue(const CodeGenInstruction *I) const {
1794     const auto VI = OpcodeValues.find(I);
1795     if (VI != OpcodeValues.end())
1796       return MatchTable::NamedValue(I->Namespace, I->TheDef->getName(),
1797                                     VI->second);
1798     return MatchTable::NamedValue(I->Namespace, I->TheDef->getName());
1799   }
1800 
1801 public:
1802   static void initOpcodeValuesMap(const CodeGenTarget &Target) {
1803     OpcodeValues.clear();
1804 
1805     unsigned OpcodeValue = 0;
1806     for (const CodeGenInstruction *I : Target.getInstructionsByEnumValue())
1807       OpcodeValues[I] = OpcodeValue++;
1808   }
1809 
1810   InstructionOpcodeMatcher(unsigned InsnVarID,
1811                            ArrayRef<const CodeGenInstruction *> I)
1812       : InstructionPredicateMatcher(IPM_Opcode, InsnVarID),
1813         Insts(I.begin(), I.end()) {
1814     assert((Insts.size() == 1 || Insts.size() == 2) &&
1815            "unexpected number of opcode alternatives");
1816   }
1817 
1818   static bool classof(const PredicateMatcher *P) {
1819     return P->getKind() == IPM_Opcode;
1820   }
1821 
1822   bool isIdentical(const PredicateMatcher &B) const override {
1823     return InstructionPredicateMatcher::isIdentical(B) &&
1824            Insts == cast<InstructionOpcodeMatcher>(&B)->Insts;
1825   }
1826 
1827   bool hasValue() const override {
1828     return Insts.size() == 1 && OpcodeValues.count(Insts[0]);
1829   }
1830 
1831   // TODO: This is used for the SwitchMatcher optimization. We should be able to
1832   // return a list of the opcodes to match.
1833   MatchTableRecord getValue() const override {
1834     assert(Insts.size() == 1);
1835 
1836     const CodeGenInstruction *I = Insts[0];
1837     const auto VI = OpcodeValues.find(I);
1838     if (VI != OpcodeValues.end())
1839       return MatchTable::NamedValue(I->Namespace, I->TheDef->getName(),
1840                                     VI->second);
1841     return MatchTable::NamedValue(I->Namespace, I->TheDef->getName());
1842   }
1843 
1844   void emitPredicateOpcodes(MatchTable &Table,
1845                             RuleMatcher &Rule) const override {
1846     StringRef CheckType = Insts.size() == 1 ?
1847                           "GIM_CheckOpcode" : "GIM_CheckOpcodeIsEither";
1848     Table << MatchTable::Opcode(CheckType) << MatchTable::Comment("MI")
1849           << MatchTable::IntValue(InsnVarID);
1850 
1851     for (const CodeGenInstruction *I : Insts)
1852       Table << getInstValue(I);
1853     Table << MatchTable::LineBreak;
1854   }
1855 
1856   /// Compare the priority of this object and B.
1857   ///
1858   /// Returns true if this object is more important than B.
1859   bool
1860   isHigherPriorityThan(const InstructionPredicateMatcher &B) const override {
1861     if (InstructionPredicateMatcher::isHigherPriorityThan(B))
1862       return true;
1863     if (B.InstructionPredicateMatcher::isHigherPriorityThan(*this))
1864       return false;
1865 
1866     // Prioritize opcodes for cosmetic reasons in the generated source. Although
1867     // this is cosmetic at the moment, we may want to drive a similar ordering
1868     // using instruction frequency information to improve compile time.
1869     if (const InstructionOpcodeMatcher *BO =
1870             dyn_cast<InstructionOpcodeMatcher>(&B))
1871       return Insts[0]->TheDef->getName() < BO->Insts[0]->TheDef->getName();
1872 
1873     return false;
1874   };
1875 
1876   bool isConstantInstruction() const {
1877     return Insts.size() == 1 && Insts[0]->TheDef->getName() == "G_CONSTANT";
1878   }
1879 
1880   // The first opcode is the canonical opcode, and later are alternatives.
1881   StringRef getOpcode() const {
1882     return Insts[0]->TheDef->getName();
1883   }
1884 
1885   ArrayRef<const CodeGenInstruction *> getAlternativeOpcodes() {
1886     return Insts;
1887   }
1888 
1889   bool isVariadicNumOperands() const {
1890     // If one is variadic, they all should be.
1891     return Insts[0]->Operands.isVariadic;
1892   }
1893 
1894   StringRef getOperandType(unsigned OpIdx) const {
1895     // Types expected to be uniform for all alternatives.
1896     return Insts[0]->Operands[OpIdx].OperandType;
1897   }
1898 };
1899 
1900 DenseMap<const CodeGenInstruction *, unsigned>
1901     InstructionOpcodeMatcher::OpcodeValues;
1902 
1903 class InstructionNumOperandsMatcher final : public InstructionPredicateMatcher {
1904   unsigned NumOperands = 0;
1905 
1906 public:
1907   InstructionNumOperandsMatcher(unsigned InsnVarID, unsigned NumOperands)
1908       : InstructionPredicateMatcher(IPM_NumOperands, InsnVarID),
1909         NumOperands(NumOperands) {}
1910 
1911   static bool classof(const PredicateMatcher *P) {
1912     return P->getKind() == IPM_NumOperands;
1913   }
1914 
1915   bool isIdentical(const PredicateMatcher &B) const override {
1916     return InstructionPredicateMatcher::isIdentical(B) &&
1917            NumOperands == cast<InstructionNumOperandsMatcher>(&B)->NumOperands;
1918   }
1919 
1920   void emitPredicateOpcodes(MatchTable &Table,
1921                             RuleMatcher &Rule) const override {
1922     Table << MatchTable::Opcode("GIM_CheckNumOperands")
1923           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1924           << MatchTable::Comment("Expected")
1925           << MatchTable::IntValue(NumOperands) << MatchTable::LineBreak;
1926   }
1927 };
1928 
1929 /// Generates code to check that this instruction is a constant whose value
1930 /// meets an immediate predicate.
1931 ///
1932 /// Immediates are slightly odd since they are typically used like an operand
1933 /// but are represented as an operator internally. We typically write simm8:$src
1934 /// in a tablegen pattern, but this is just syntactic sugar for
1935 /// (imm:i32)<<P:Predicate_simm8>>:$imm which more directly describes the nodes
1936 /// that will be matched and the predicate (which is attached to the imm
1937 /// operator) that will be tested. In SelectionDAG this describes a
1938 /// ConstantSDNode whose internal value will be tested using the simm8 predicate.
1939 ///
1940 /// The corresponding GlobalISel representation is %1 = G_CONSTANT iN Value. In
1941 /// this representation, the immediate could be tested with an
1942 /// InstructionMatcher, InstructionOpcodeMatcher, OperandMatcher, and a
1943 /// OperandPredicateMatcher-subclass to check the Value meets the predicate but
1944 /// there are two implementation issues with producing that matcher
1945 /// configuration from the SelectionDAG pattern:
1946 /// * ImmLeaf is a PatFrag whose root is an InstructionMatcher. This means that
1947 ///   were we to sink the immediate predicate to the operand we would have to
1948 ///   have two partial implementations of PatFrag support, one for immediates
1949 ///   and one for non-immediates.
1950 /// * At the point we handle the predicate, the OperandMatcher hasn't been
1951 ///   created yet. If we were to sink the predicate to the OperandMatcher we
1952 ///   would also have to complicate (or duplicate) the code that descends and
1953 ///   creates matchers for the subtree.
1954 /// Overall, it's simpler to handle it in the place it was found.
1955 class InstructionImmPredicateMatcher : public InstructionPredicateMatcher {
1956 protected:
1957   TreePredicateFn Predicate;
1958 
1959 public:
1960   InstructionImmPredicateMatcher(unsigned InsnVarID,
1961                                  const TreePredicateFn &Predicate)
1962       : InstructionPredicateMatcher(IPM_ImmPredicate, InsnVarID),
1963         Predicate(Predicate) {}
1964 
1965   bool isIdentical(const PredicateMatcher &B) const override {
1966     return InstructionPredicateMatcher::isIdentical(B) &&
1967            Predicate.getOrigPatFragRecord() ==
1968                cast<InstructionImmPredicateMatcher>(&B)
1969                    ->Predicate.getOrigPatFragRecord();
1970   }
1971 
1972   static bool classof(const PredicateMatcher *P) {
1973     return P->getKind() == IPM_ImmPredicate;
1974   }
1975 
1976   void emitPredicateOpcodes(MatchTable &Table,
1977                             RuleMatcher &Rule) const override {
1978     Table << MatchTable::Opcode(getMatchOpcodeForImmPredicate(Predicate))
1979           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1980           << MatchTable::Comment("Predicate")
1981           << MatchTable::NamedValue(getEnumNameForPredicate(Predicate))
1982           << MatchTable::LineBreak;
1983   }
1984 };
1985 
1986 /// Generates code to check that a memory instruction has a atomic ordering
1987 /// MachineMemoryOperand.
1988 class AtomicOrderingMMOPredicateMatcher : public InstructionPredicateMatcher {
1989 public:
1990   enum AOComparator {
1991     AO_Exactly,
1992     AO_OrStronger,
1993     AO_WeakerThan,
1994   };
1995 
1996 protected:
1997   StringRef Order;
1998   AOComparator Comparator;
1999 
2000 public:
2001   AtomicOrderingMMOPredicateMatcher(unsigned InsnVarID, StringRef Order,
2002                                     AOComparator Comparator = AO_Exactly)
2003       : InstructionPredicateMatcher(IPM_AtomicOrderingMMO, InsnVarID),
2004         Order(Order), Comparator(Comparator) {}
2005 
2006   static bool classof(const PredicateMatcher *P) {
2007     return P->getKind() == IPM_AtomicOrderingMMO;
2008   }
2009 
2010   bool isIdentical(const PredicateMatcher &B) const override {
2011     if (!InstructionPredicateMatcher::isIdentical(B))
2012       return false;
2013     const auto &R = *cast<AtomicOrderingMMOPredicateMatcher>(&B);
2014     return Order == R.Order && Comparator == R.Comparator;
2015   }
2016 
2017   void emitPredicateOpcodes(MatchTable &Table,
2018                             RuleMatcher &Rule) const override {
2019     StringRef Opcode = "GIM_CheckAtomicOrdering";
2020 
2021     if (Comparator == AO_OrStronger)
2022       Opcode = "GIM_CheckAtomicOrderingOrStrongerThan";
2023     if (Comparator == AO_WeakerThan)
2024       Opcode = "GIM_CheckAtomicOrderingWeakerThan";
2025 
2026     Table << MatchTable::Opcode(Opcode) << MatchTable::Comment("MI")
2027           << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Order")
2028           << MatchTable::NamedValue(("(int64_t)AtomicOrdering::" + Order).str())
2029           << MatchTable::LineBreak;
2030   }
2031 };
2032 
2033 /// Generates code to check that the size of an MMO is exactly N bytes.
2034 class MemorySizePredicateMatcher : public InstructionPredicateMatcher {
2035 protected:
2036   unsigned MMOIdx;
2037   uint64_t Size;
2038 
2039 public:
2040   MemorySizePredicateMatcher(unsigned InsnVarID, unsigned MMOIdx, unsigned Size)
2041       : InstructionPredicateMatcher(IPM_MemoryLLTSize, InsnVarID),
2042         MMOIdx(MMOIdx), Size(Size) {}
2043 
2044   static bool classof(const PredicateMatcher *P) {
2045     return P->getKind() == IPM_MemoryLLTSize;
2046   }
2047   bool isIdentical(const PredicateMatcher &B) const override {
2048     return InstructionPredicateMatcher::isIdentical(B) &&
2049            MMOIdx == cast<MemorySizePredicateMatcher>(&B)->MMOIdx &&
2050            Size == cast<MemorySizePredicateMatcher>(&B)->Size;
2051   }
2052 
2053   void emitPredicateOpcodes(MatchTable &Table,
2054                             RuleMatcher &Rule) const override {
2055     Table << MatchTable::Opcode("GIM_CheckMemorySizeEqualTo")
2056           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
2057           << MatchTable::Comment("MMO") << MatchTable::IntValue(MMOIdx)
2058           << MatchTable::Comment("Size") << MatchTable::IntValue(Size)
2059           << MatchTable::LineBreak;
2060   }
2061 };
2062 
2063 class MemoryAddressSpacePredicateMatcher : public InstructionPredicateMatcher {
2064 protected:
2065   unsigned MMOIdx;
2066   SmallVector<unsigned, 4> AddrSpaces;
2067 
2068 public:
2069   MemoryAddressSpacePredicateMatcher(unsigned InsnVarID, unsigned MMOIdx,
2070                                      ArrayRef<unsigned> AddrSpaces)
2071       : InstructionPredicateMatcher(IPM_MemoryAddressSpace, InsnVarID),
2072         MMOIdx(MMOIdx), AddrSpaces(AddrSpaces.begin(), AddrSpaces.end()) {}
2073 
2074   static bool classof(const PredicateMatcher *P) {
2075     return P->getKind() == IPM_MemoryAddressSpace;
2076   }
2077   bool isIdentical(const PredicateMatcher &B) const override {
2078     if (!InstructionPredicateMatcher::isIdentical(B))
2079       return false;
2080     auto *Other = cast<MemoryAddressSpacePredicateMatcher>(&B);
2081     return MMOIdx == Other->MMOIdx && AddrSpaces == Other->AddrSpaces;
2082   }
2083 
2084   void emitPredicateOpcodes(MatchTable &Table,
2085                             RuleMatcher &Rule) const override {
2086     Table << MatchTable::Opcode("GIM_CheckMemoryAddressSpace")
2087           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
2088           << MatchTable::Comment("MMO") << MatchTable::IntValue(MMOIdx)
2089         // Encode number of address spaces to expect.
2090           << MatchTable::Comment("NumAddrSpace")
2091           << MatchTable::IntValue(AddrSpaces.size());
2092     for (unsigned AS : AddrSpaces)
2093       Table << MatchTable::Comment("AddrSpace") << MatchTable::IntValue(AS);
2094 
2095     Table << MatchTable::LineBreak;
2096   }
2097 };
2098 
2099 class MemoryAlignmentPredicateMatcher : public InstructionPredicateMatcher {
2100 protected:
2101   unsigned MMOIdx;
2102   int MinAlign;
2103 
2104 public:
2105   MemoryAlignmentPredicateMatcher(unsigned InsnVarID, unsigned MMOIdx,
2106                                   int MinAlign)
2107       : InstructionPredicateMatcher(IPM_MemoryAlignment, InsnVarID),
2108         MMOIdx(MMOIdx), MinAlign(MinAlign) {
2109     assert(MinAlign > 0);
2110   }
2111 
2112   static bool classof(const PredicateMatcher *P) {
2113     return P->getKind() == IPM_MemoryAlignment;
2114   }
2115 
2116   bool isIdentical(const PredicateMatcher &B) const override {
2117     if (!InstructionPredicateMatcher::isIdentical(B))
2118       return false;
2119     auto *Other = cast<MemoryAlignmentPredicateMatcher>(&B);
2120     return MMOIdx == Other->MMOIdx && MinAlign == Other->MinAlign;
2121   }
2122 
2123   void emitPredicateOpcodes(MatchTable &Table,
2124                             RuleMatcher &Rule) const override {
2125     Table << MatchTable::Opcode("GIM_CheckMemoryAlignment")
2126           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
2127           << MatchTable::Comment("MMO") << MatchTable::IntValue(MMOIdx)
2128           << MatchTable::Comment("MinAlign") << MatchTable::IntValue(MinAlign)
2129           << MatchTable::LineBreak;
2130   }
2131 };
2132 
2133 /// Generates code to check that the size of an MMO is less-than, equal-to, or
2134 /// greater than a given LLT.
2135 class MemoryVsLLTSizePredicateMatcher : public InstructionPredicateMatcher {
2136 public:
2137   enum RelationKind {
2138     GreaterThan,
2139     EqualTo,
2140     LessThan,
2141   };
2142 
2143 protected:
2144   unsigned MMOIdx;
2145   RelationKind Relation;
2146   unsigned OpIdx;
2147 
2148 public:
2149   MemoryVsLLTSizePredicateMatcher(unsigned InsnVarID, unsigned MMOIdx,
2150                                   enum RelationKind Relation,
2151                                   unsigned OpIdx)
2152       : InstructionPredicateMatcher(IPM_MemoryVsLLTSize, InsnVarID),
2153         MMOIdx(MMOIdx), Relation(Relation), OpIdx(OpIdx) {}
2154 
2155   static bool classof(const PredicateMatcher *P) {
2156     return P->getKind() == IPM_MemoryVsLLTSize;
2157   }
2158   bool isIdentical(const PredicateMatcher &B) const override {
2159     return InstructionPredicateMatcher::isIdentical(B) &&
2160            MMOIdx == cast<MemoryVsLLTSizePredicateMatcher>(&B)->MMOIdx &&
2161            Relation == cast<MemoryVsLLTSizePredicateMatcher>(&B)->Relation &&
2162            OpIdx == cast<MemoryVsLLTSizePredicateMatcher>(&B)->OpIdx;
2163   }
2164 
2165   void emitPredicateOpcodes(MatchTable &Table,
2166                             RuleMatcher &Rule) const override {
2167     Table << MatchTable::Opcode(Relation == EqualTo
2168                                     ? "GIM_CheckMemorySizeEqualToLLT"
2169                                     : Relation == GreaterThan
2170                                           ? "GIM_CheckMemorySizeGreaterThanLLT"
2171                                           : "GIM_CheckMemorySizeLessThanLLT")
2172           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
2173           << MatchTable::Comment("MMO") << MatchTable::IntValue(MMOIdx)
2174           << MatchTable::Comment("OpIdx") << MatchTable::IntValue(OpIdx)
2175           << MatchTable::LineBreak;
2176   }
2177 };
2178 
2179 // Matcher for immAllOnesV/immAllZerosV
2180 class VectorSplatImmPredicateMatcher : public InstructionPredicateMatcher {
2181 public:
2182   enum SplatKind {
2183     AllZeros,
2184     AllOnes
2185   };
2186 
2187 private:
2188   SplatKind Kind;
2189 
2190 public:
2191   VectorSplatImmPredicateMatcher(unsigned InsnVarID, SplatKind K)
2192       : InstructionPredicateMatcher(IPM_VectorSplatImm, InsnVarID), Kind(K) {}
2193 
2194   static bool classof(const PredicateMatcher *P) {
2195     return P->getKind() == IPM_VectorSplatImm;
2196   }
2197 
2198   bool isIdentical(const PredicateMatcher &B) const override {
2199     return InstructionPredicateMatcher::isIdentical(B) &&
2200            Kind == static_cast<const VectorSplatImmPredicateMatcher &>(B).Kind;
2201   }
2202 
2203   void emitPredicateOpcodes(MatchTable &Table,
2204                             RuleMatcher &Rule) const override {
2205     if (Kind == AllOnes)
2206       Table << MatchTable::Opcode("GIM_CheckIsBuildVectorAllOnes");
2207     else
2208       Table << MatchTable::Opcode("GIM_CheckIsBuildVectorAllZeros");
2209 
2210     Table << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID);
2211     Table << MatchTable::LineBreak;
2212   }
2213 };
2214 
2215 /// Generates code to check an arbitrary C++ instruction predicate.
2216 class GenericInstructionPredicateMatcher : public InstructionPredicateMatcher {
2217 protected:
2218   TreePredicateFn Predicate;
2219 
2220 public:
2221   GenericInstructionPredicateMatcher(unsigned InsnVarID,
2222                                      TreePredicateFn Predicate)
2223       : InstructionPredicateMatcher(IPM_GenericPredicate, InsnVarID),
2224         Predicate(Predicate) {}
2225 
2226   static bool classof(const InstructionPredicateMatcher *P) {
2227     return P->getKind() == IPM_GenericPredicate;
2228   }
2229   bool isIdentical(const PredicateMatcher &B) const override {
2230     return InstructionPredicateMatcher::isIdentical(B) &&
2231            Predicate ==
2232                static_cast<const GenericInstructionPredicateMatcher &>(B)
2233                    .Predicate;
2234   }
2235   void emitPredicateOpcodes(MatchTable &Table,
2236                             RuleMatcher &Rule) const override {
2237     Table << MatchTable::Opcode("GIM_CheckCxxInsnPredicate")
2238           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
2239           << MatchTable::Comment("FnId")
2240           << MatchTable::NamedValue(getEnumNameForPredicate(Predicate))
2241           << MatchTable::LineBreak;
2242   }
2243 };
2244 
2245 /// Generates code to check for the absence of use of the result.
2246 // TODO? Generalize this to support checking for one use.
2247 class NoUsePredicateMatcher : public InstructionPredicateMatcher {
2248 public:
2249   NoUsePredicateMatcher(unsigned InsnVarID)
2250       : InstructionPredicateMatcher(IPM_NoUse, InsnVarID) {}
2251 
2252   static bool classof(const PredicateMatcher *P) {
2253     return P->getKind() == IPM_NoUse;
2254   }
2255 
2256   bool isIdentical(const PredicateMatcher &B) const override {
2257     return InstructionPredicateMatcher::isIdentical(B);
2258   }
2259 
2260   void emitPredicateOpcodes(MatchTable &Table,
2261                             RuleMatcher &Rule) const override {
2262     Table << MatchTable::Opcode("GIM_CheckHasNoUse")
2263           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
2264           << MatchTable::LineBreak;
2265   }
2266 };
2267 
2268 /// Generates code to check that a set of predicates and operands match for a
2269 /// particular instruction.
2270 ///
2271 /// Typical predicates include:
2272 /// * Has a specific opcode.
2273 /// * Has an nsw/nuw flag or doesn't.
2274 class InstructionMatcher final : public PredicateListMatcher<PredicateMatcher> {
2275 protected:
2276   typedef std::vector<std::unique_ptr<OperandMatcher>> OperandVec;
2277 
2278   RuleMatcher &Rule;
2279 
2280   /// The operands to match. All rendered operands must be present even if the
2281   /// condition is always true.
2282   OperandVec Operands;
2283   bool NumOperandsCheck = true;
2284 
2285   std::string SymbolicName;
2286   unsigned InsnVarID;
2287 
2288   /// PhysRegInputs - List list has an entry for each explicitly specified
2289   /// physreg input to the pattern.  The first elt is the Register node, the
2290   /// second is the recorded slot number the input pattern match saved it in.
2291   SmallVector<std::pair<Record *, unsigned>, 2> PhysRegInputs;
2292 
2293 public:
2294   InstructionMatcher(RuleMatcher &Rule, StringRef SymbolicName,
2295                      bool NumOpsCheck = true)
2296       : Rule(Rule), NumOperandsCheck(NumOpsCheck), SymbolicName(SymbolicName) {
2297     // We create a new instruction matcher.
2298     // Get a new ID for that instruction.
2299     InsnVarID = Rule.implicitlyDefineInsnVar(*this);
2300   }
2301 
2302   /// Construct a new instruction predicate and add it to the matcher.
2303   template <class Kind, class... Args>
2304   Optional<Kind *> addPredicate(Args &&... args) {
2305     Predicates.emplace_back(
2306         std::make_unique<Kind>(getInsnVarID(), std::forward<Args>(args)...));
2307     return static_cast<Kind *>(Predicates.back().get());
2308   }
2309 
2310   RuleMatcher &getRuleMatcher() const { return Rule; }
2311 
2312   unsigned getInsnVarID() const { return InsnVarID; }
2313 
2314   /// Add an operand to the matcher.
2315   OperandMatcher &addOperand(unsigned OpIdx, const std::string &SymbolicName,
2316                              unsigned AllocatedTemporariesBaseID) {
2317     Operands.emplace_back(new OperandMatcher(*this, OpIdx, SymbolicName,
2318                                              AllocatedTemporariesBaseID));
2319     if (!SymbolicName.empty())
2320       Rule.defineOperand(SymbolicName, *Operands.back());
2321 
2322     return *Operands.back();
2323   }
2324 
2325   OperandMatcher &getOperand(unsigned OpIdx) {
2326     auto I = llvm::find_if(Operands,
2327                            [&OpIdx](const std::unique_ptr<OperandMatcher> &X) {
2328                              return X->getOpIdx() == OpIdx;
2329                            });
2330     if (I != Operands.end())
2331       return **I;
2332     llvm_unreachable("Failed to lookup operand");
2333   }
2334 
2335   OperandMatcher &addPhysRegInput(Record *Reg, unsigned OpIdx,
2336                                   unsigned TempOpIdx) {
2337     assert(SymbolicName.empty());
2338     OperandMatcher *OM = new OperandMatcher(*this, OpIdx, "", TempOpIdx);
2339     Operands.emplace_back(OM);
2340     Rule.definePhysRegOperand(Reg, *OM);
2341     PhysRegInputs.emplace_back(Reg, OpIdx);
2342     return *OM;
2343   }
2344 
2345   ArrayRef<std::pair<Record *, unsigned>> getPhysRegInputs() const {
2346     return PhysRegInputs;
2347   }
2348 
2349   StringRef getSymbolicName() const { return SymbolicName; }
2350   unsigned getNumOperands() const { return Operands.size(); }
2351   OperandVec::iterator operands_begin() { return Operands.begin(); }
2352   OperandVec::iterator operands_end() { return Operands.end(); }
2353   iterator_range<OperandVec::iterator> operands() {
2354     return make_range(operands_begin(), operands_end());
2355   }
2356   OperandVec::const_iterator operands_begin() const { return Operands.begin(); }
2357   OperandVec::const_iterator operands_end() const { return Operands.end(); }
2358   iterator_range<OperandVec::const_iterator> operands() const {
2359     return make_range(operands_begin(), operands_end());
2360   }
2361   bool operands_empty() const { return Operands.empty(); }
2362 
2363   void pop_front() { Operands.erase(Operands.begin()); }
2364 
2365   void optimize();
2366 
2367   /// Emit MatchTable opcodes that test whether the instruction named in
2368   /// InsnVarName matches all the predicates and all the operands.
2369   void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule) {
2370     if (NumOperandsCheck)
2371       InstructionNumOperandsMatcher(InsnVarID, getNumOperands())
2372           .emitPredicateOpcodes(Table, Rule);
2373 
2374     // First emit all instruction level predicates need to be verified before we
2375     // can verify operands.
2376     emitFilteredPredicateListOpcodes(
2377       [](const PredicateMatcher &P) {
2378         return !P.dependsOnOperands();
2379       }, Table, Rule);
2380 
2381     // Emit all operand constraints.
2382     for (const auto &Operand : Operands)
2383       Operand->emitPredicateOpcodes(Table, Rule);
2384 
2385     // All of the tablegen defined predicates should now be matched. Now emit
2386     // any custom predicates that rely on all generated checks.
2387     emitFilteredPredicateListOpcodes(
2388       [](const PredicateMatcher &P) {
2389         return P.dependsOnOperands();
2390       }, Table, Rule);
2391   }
2392 
2393   /// Compare the priority of this object and B.
2394   ///
2395   /// Returns true if this object is more important than B.
2396   bool isHigherPriorityThan(InstructionMatcher &B) {
2397     // Instruction matchers involving more operands have higher priority.
2398     if (Operands.size() > B.Operands.size())
2399       return true;
2400     if (Operands.size() < B.Operands.size())
2401       return false;
2402 
2403     for (auto &&P : zip(predicates(), B.predicates())) {
2404       auto L = static_cast<InstructionPredicateMatcher *>(std::get<0>(P).get());
2405       auto R = static_cast<InstructionPredicateMatcher *>(std::get<1>(P).get());
2406       if (L->isHigherPriorityThan(*R))
2407         return true;
2408       if (R->isHigherPriorityThan(*L))
2409         return false;
2410     }
2411 
2412     for (auto Operand : zip(Operands, B.Operands)) {
2413       if (std::get<0>(Operand)->isHigherPriorityThan(*std::get<1>(Operand)))
2414         return true;
2415       if (std::get<1>(Operand)->isHigherPriorityThan(*std::get<0>(Operand)))
2416         return false;
2417     }
2418 
2419     return false;
2420   };
2421 
2422   /// Report the maximum number of temporary operands needed by the instruction
2423   /// matcher.
2424   unsigned countRendererFns() {
2425     return std::accumulate(
2426                predicates().begin(), predicates().end(), 0,
2427                [](unsigned A,
2428                   const std::unique_ptr<PredicateMatcher> &Predicate) {
2429                  return A + Predicate->countRendererFns();
2430                }) +
2431            std::accumulate(
2432                Operands.begin(), Operands.end(), 0,
2433                [](unsigned A, const std::unique_ptr<OperandMatcher> &Operand) {
2434                  return A + Operand->countRendererFns();
2435                });
2436   }
2437 
2438   InstructionOpcodeMatcher &getOpcodeMatcher() {
2439     for (auto &P : predicates())
2440       if (auto *OpMatcher = dyn_cast<InstructionOpcodeMatcher>(P.get()))
2441         return *OpMatcher;
2442     llvm_unreachable("Didn't find an opcode matcher");
2443   }
2444 
2445   bool isConstantInstruction() {
2446     return getOpcodeMatcher().isConstantInstruction();
2447   }
2448 
2449   StringRef getOpcode() { return getOpcodeMatcher().getOpcode(); }
2450 };
2451 
2452 StringRef RuleMatcher::getOpcode() const {
2453   return Matchers.front()->getOpcode();
2454 }
2455 
2456 unsigned RuleMatcher::getNumOperands() const {
2457   return Matchers.front()->getNumOperands();
2458 }
2459 
2460 LLTCodeGen RuleMatcher::getFirstConditionAsRootType() {
2461   InstructionMatcher &InsnMatcher = *Matchers.front();
2462   if (!InsnMatcher.predicates_empty())
2463     if (const auto *TM =
2464             dyn_cast<LLTOperandMatcher>(&**InsnMatcher.predicates_begin()))
2465       if (TM->getInsnVarID() == 0 && TM->getOpIdx() == 0)
2466         return TM->getTy();
2467   return {};
2468 }
2469 
2470 /// Generates code to check that the operand is a register defined by an
2471 /// instruction that matches the given instruction matcher.
2472 ///
2473 /// For example, the pattern:
2474 ///   (set $dst, (G_MUL (G_ADD $src1, $src2), $src3))
2475 /// would use an InstructionOperandMatcher for operand 1 of the G_MUL to match
2476 /// the:
2477 ///   (G_ADD $src1, $src2)
2478 /// subpattern.
2479 class InstructionOperandMatcher : public OperandPredicateMatcher {
2480 protected:
2481   std::unique_ptr<InstructionMatcher> InsnMatcher;
2482 
2483 public:
2484   InstructionOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
2485                             RuleMatcher &Rule, StringRef SymbolicName,
2486                             bool NumOpsCheck = true)
2487       : OperandPredicateMatcher(OPM_Instruction, InsnVarID, OpIdx),
2488         InsnMatcher(new InstructionMatcher(Rule, SymbolicName, NumOpsCheck)) {}
2489 
2490   static bool classof(const PredicateMatcher *P) {
2491     return P->getKind() == OPM_Instruction;
2492   }
2493 
2494   InstructionMatcher &getInsnMatcher() const { return *InsnMatcher; }
2495 
2496   void emitCaptureOpcodes(MatchTable &Table, RuleMatcher &Rule) const {
2497     const unsigned NewInsnVarID = InsnMatcher->getInsnVarID();
2498     Table << MatchTable::Opcode("GIM_RecordInsn")
2499           << MatchTable::Comment("DefineMI")
2500           << MatchTable::IntValue(NewInsnVarID) << MatchTable::Comment("MI")
2501           << MatchTable::IntValue(getInsnVarID())
2502           << MatchTable::Comment("OpIdx") << MatchTable::IntValue(getOpIdx())
2503           << MatchTable::Comment("MIs[" + llvm::to_string(NewInsnVarID) + "]")
2504           << MatchTable::LineBreak;
2505   }
2506 
2507   void emitPredicateOpcodes(MatchTable &Table,
2508                             RuleMatcher &Rule) const override {
2509     emitCaptureOpcodes(Table, Rule);
2510     InsnMatcher->emitPredicateOpcodes(Table, Rule);
2511   }
2512 
2513   bool isHigherPriorityThan(const OperandPredicateMatcher &B) const override {
2514     if (OperandPredicateMatcher::isHigherPriorityThan(B))
2515       return true;
2516     if (B.OperandPredicateMatcher::isHigherPriorityThan(*this))
2517       return false;
2518 
2519     if (const InstructionOperandMatcher *BP =
2520             dyn_cast<InstructionOperandMatcher>(&B))
2521       if (InsnMatcher->isHigherPriorityThan(*BP->InsnMatcher))
2522         return true;
2523     return false;
2524   }
2525 };
2526 
2527 void InstructionMatcher::optimize() {
2528   SmallVector<std::unique_ptr<PredicateMatcher>, 8> Stash;
2529   const auto &OpcMatcher = getOpcodeMatcher();
2530 
2531   Stash.push_back(predicates_pop_front());
2532   if (Stash.back().get() == &OpcMatcher) {
2533     if (NumOperandsCheck && OpcMatcher.isVariadicNumOperands())
2534       Stash.emplace_back(
2535           new InstructionNumOperandsMatcher(InsnVarID, getNumOperands()));
2536     NumOperandsCheck = false;
2537 
2538     for (auto &OM : Operands)
2539       for (auto &OP : OM->predicates())
2540         if (isa<IntrinsicIDOperandMatcher>(OP)) {
2541           Stash.push_back(std::move(OP));
2542           OM->eraseNullPredicates();
2543           break;
2544         }
2545   }
2546 
2547   if (InsnVarID > 0) {
2548     assert(!Operands.empty() && "Nested instruction is expected to def a vreg");
2549     for (auto &OP : Operands[0]->predicates())
2550       OP.reset();
2551     Operands[0]->eraseNullPredicates();
2552   }
2553   for (auto &OM : Operands) {
2554     for (auto &OP : OM->predicates())
2555       if (isa<LLTOperandMatcher>(OP))
2556         Stash.push_back(std::move(OP));
2557     OM->eraseNullPredicates();
2558   }
2559   while (!Stash.empty())
2560     prependPredicate(Stash.pop_back_val());
2561 }
2562 
2563 //===- Actions ------------------------------------------------------------===//
2564 class OperandRenderer {
2565 public:
2566   enum RendererKind {
2567     OR_Copy,
2568     OR_CopyOrAddZeroReg,
2569     OR_CopySubReg,
2570     OR_CopyPhysReg,
2571     OR_CopyConstantAsImm,
2572     OR_CopyFConstantAsFPImm,
2573     OR_Imm,
2574     OR_SubRegIndex,
2575     OR_Register,
2576     OR_TempRegister,
2577     OR_ComplexPattern,
2578     OR_Custom,
2579     OR_CustomOperand
2580   };
2581 
2582 protected:
2583   RendererKind Kind;
2584 
2585 public:
2586   OperandRenderer(RendererKind Kind) : Kind(Kind) {}
2587   virtual ~OperandRenderer() {}
2588 
2589   RendererKind getKind() const { return Kind; }
2590 
2591   virtual void emitRenderOpcodes(MatchTable &Table,
2592                                  RuleMatcher &Rule) const = 0;
2593 };
2594 
2595 /// A CopyRenderer emits code to copy a single operand from an existing
2596 /// instruction to the one being built.
2597 class CopyRenderer : public OperandRenderer {
2598 protected:
2599   unsigned NewInsnID;
2600   /// The name of the operand.
2601   const StringRef SymbolicName;
2602 
2603 public:
2604   CopyRenderer(unsigned NewInsnID, StringRef SymbolicName)
2605       : OperandRenderer(OR_Copy), NewInsnID(NewInsnID),
2606         SymbolicName(SymbolicName) {
2607     assert(!SymbolicName.empty() && "Cannot copy from an unspecified source");
2608   }
2609 
2610   static bool classof(const OperandRenderer *R) {
2611     return R->getKind() == OR_Copy;
2612   }
2613 
2614   StringRef getSymbolicName() const { return SymbolicName; }
2615 
2616   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2617     const OperandMatcher &Operand = Rule.getOperandMatcher(SymbolicName);
2618     unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
2619     Table << MatchTable::Opcode("GIR_Copy") << MatchTable::Comment("NewInsnID")
2620           << MatchTable::IntValue(NewInsnID) << MatchTable::Comment("OldInsnID")
2621           << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
2622           << MatchTable::IntValue(Operand.getOpIdx())
2623           << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2624   }
2625 };
2626 
2627 /// A CopyRenderer emits code to copy a virtual register to a specific physical
2628 /// register.
2629 class CopyPhysRegRenderer : public OperandRenderer {
2630 protected:
2631   unsigned NewInsnID;
2632   Record *PhysReg;
2633 
2634 public:
2635   CopyPhysRegRenderer(unsigned NewInsnID, Record *Reg)
2636       : OperandRenderer(OR_CopyPhysReg), NewInsnID(NewInsnID),
2637         PhysReg(Reg) {
2638     assert(PhysReg);
2639   }
2640 
2641   static bool classof(const OperandRenderer *R) {
2642     return R->getKind() == OR_CopyPhysReg;
2643   }
2644 
2645   Record *getPhysReg() const { return PhysReg; }
2646 
2647   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2648     const OperandMatcher &Operand = Rule.getPhysRegOperandMatcher(PhysReg);
2649     unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
2650     Table << MatchTable::Opcode("GIR_Copy") << MatchTable::Comment("NewInsnID")
2651           << MatchTable::IntValue(NewInsnID) << MatchTable::Comment("OldInsnID")
2652           << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
2653           << MatchTable::IntValue(Operand.getOpIdx())
2654           << MatchTable::Comment(PhysReg->getName())
2655           << MatchTable::LineBreak;
2656   }
2657 };
2658 
2659 /// A CopyOrAddZeroRegRenderer emits code to copy a single operand from an
2660 /// existing instruction to the one being built. If the operand turns out to be
2661 /// a 'G_CONSTANT 0' then it replaces the operand with a zero register.
2662 class CopyOrAddZeroRegRenderer : public OperandRenderer {
2663 protected:
2664   unsigned NewInsnID;
2665   /// The name of the operand.
2666   const StringRef SymbolicName;
2667   const Record *ZeroRegisterDef;
2668 
2669 public:
2670   CopyOrAddZeroRegRenderer(unsigned NewInsnID,
2671                            StringRef SymbolicName, Record *ZeroRegisterDef)
2672       : OperandRenderer(OR_CopyOrAddZeroReg), NewInsnID(NewInsnID),
2673         SymbolicName(SymbolicName), ZeroRegisterDef(ZeroRegisterDef) {
2674     assert(!SymbolicName.empty() && "Cannot copy from an unspecified source");
2675   }
2676 
2677   static bool classof(const OperandRenderer *R) {
2678     return R->getKind() == OR_CopyOrAddZeroReg;
2679   }
2680 
2681   StringRef getSymbolicName() const { return SymbolicName; }
2682 
2683   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2684     const OperandMatcher &Operand = Rule.getOperandMatcher(SymbolicName);
2685     unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
2686     Table << MatchTable::Opcode("GIR_CopyOrAddZeroReg")
2687           << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
2688           << MatchTable::Comment("OldInsnID")
2689           << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
2690           << MatchTable::IntValue(Operand.getOpIdx())
2691           << MatchTable::NamedValue(
2692                  (ZeroRegisterDef->getValue("Namespace")
2693                       ? ZeroRegisterDef->getValueAsString("Namespace")
2694                       : ""),
2695                  ZeroRegisterDef->getName())
2696           << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2697   }
2698 };
2699 
2700 /// A CopyConstantAsImmRenderer emits code to render a G_CONSTANT instruction to
2701 /// an extended immediate operand.
2702 class CopyConstantAsImmRenderer : public OperandRenderer {
2703 protected:
2704   unsigned NewInsnID;
2705   /// The name of the operand.
2706   const std::string SymbolicName;
2707   bool Signed;
2708 
2709 public:
2710   CopyConstantAsImmRenderer(unsigned NewInsnID, StringRef SymbolicName)
2711       : OperandRenderer(OR_CopyConstantAsImm), NewInsnID(NewInsnID),
2712         SymbolicName(SymbolicName), Signed(true) {}
2713 
2714   static bool classof(const OperandRenderer *R) {
2715     return R->getKind() == OR_CopyConstantAsImm;
2716   }
2717 
2718   StringRef getSymbolicName() const { return SymbolicName; }
2719 
2720   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2721     InstructionMatcher &InsnMatcher = Rule.getInstructionMatcher(SymbolicName);
2722     unsigned OldInsnVarID = Rule.getInsnVarID(InsnMatcher);
2723     Table << MatchTable::Opcode(Signed ? "GIR_CopyConstantAsSImm"
2724                                        : "GIR_CopyConstantAsUImm")
2725           << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
2726           << MatchTable::Comment("OldInsnID")
2727           << MatchTable::IntValue(OldInsnVarID)
2728           << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2729   }
2730 };
2731 
2732 /// A CopyFConstantAsFPImmRenderer emits code to render a G_FCONSTANT
2733 /// instruction to an extended immediate operand.
2734 class CopyFConstantAsFPImmRenderer : public OperandRenderer {
2735 protected:
2736   unsigned NewInsnID;
2737   /// The name of the operand.
2738   const std::string SymbolicName;
2739 
2740 public:
2741   CopyFConstantAsFPImmRenderer(unsigned NewInsnID, StringRef SymbolicName)
2742       : OperandRenderer(OR_CopyFConstantAsFPImm), NewInsnID(NewInsnID),
2743         SymbolicName(SymbolicName) {}
2744 
2745   static bool classof(const OperandRenderer *R) {
2746     return R->getKind() == OR_CopyFConstantAsFPImm;
2747   }
2748 
2749   StringRef getSymbolicName() const { return SymbolicName; }
2750 
2751   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2752     InstructionMatcher &InsnMatcher = Rule.getInstructionMatcher(SymbolicName);
2753     unsigned OldInsnVarID = Rule.getInsnVarID(InsnMatcher);
2754     Table << MatchTable::Opcode("GIR_CopyFConstantAsFPImm")
2755           << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
2756           << MatchTable::Comment("OldInsnID")
2757           << MatchTable::IntValue(OldInsnVarID)
2758           << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2759   }
2760 };
2761 
2762 /// A CopySubRegRenderer emits code to copy a single register operand from an
2763 /// existing instruction to the one being built and indicate that only a
2764 /// subregister should be copied.
2765 class CopySubRegRenderer : public OperandRenderer {
2766 protected:
2767   unsigned NewInsnID;
2768   /// The name of the operand.
2769   const StringRef SymbolicName;
2770   /// The subregister to extract.
2771   const CodeGenSubRegIndex *SubReg;
2772 
2773 public:
2774   CopySubRegRenderer(unsigned NewInsnID, StringRef SymbolicName,
2775                      const CodeGenSubRegIndex *SubReg)
2776       : OperandRenderer(OR_CopySubReg), NewInsnID(NewInsnID),
2777         SymbolicName(SymbolicName), SubReg(SubReg) {}
2778 
2779   static bool classof(const OperandRenderer *R) {
2780     return R->getKind() == OR_CopySubReg;
2781   }
2782 
2783   StringRef getSymbolicName() const { return SymbolicName; }
2784 
2785   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2786     const OperandMatcher &Operand = Rule.getOperandMatcher(SymbolicName);
2787     unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
2788     Table << MatchTable::Opcode("GIR_CopySubReg")
2789           << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
2790           << MatchTable::Comment("OldInsnID")
2791           << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
2792           << MatchTable::IntValue(Operand.getOpIdx())
2793           << MatchTable::Comment("SubRegIdx")
2794           << MatchTable::IntValue(SubReg->EnumValue)
2795           << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2796   }
2797 };
2798 
2799 /// Adds a specific physical register to the instruction being built.
2800 /// This is typically useful for WZR/XZR on AArch64.
2801 class AddRegisterRenderer : public OperandRenderer {
2802 protected:
2803   unsigned InsnID;
2804   const Record *RegisterDef;
2805   bool IsDef;
2806   const CodeGenTarget &Target;
2807 
2808 public:
2809   AddRegisterRenderer(unsigned InsnID, const CodeGenTarget &Target,
2810                       const Record *RegisterDef, bool IsDef = false)
2811       : OperandRenderer(OR_Register), InsnID(InsnID), RegisterDef(RegisterDef),
2812         IsDef(IsDef), Target(Target) {}
2813 
2814   static bool classof(const OperandRenderer *R) {
2815     return R->getKind() == OR_Register;
2816   }
2817 
2818   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2819     Table << MatchTable::Opcode("GIR_AddRegister")
2820           << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID);
2821     if (RegisterDef->getName() != "zero_reg") {
2822       Table << MatchTable::NamedValue(
2823                    (RegisterDef->getValue("Namespace")
2824                         ? RegisterDef->getValueAsString("Namespace")
2825                         : ""),
2826                    RegisterDef->getName());
2827     } else {
2828       Table << MatchTable::NamedValue(Target.getRegNamespace(), "NoRegister");
2829     }
2830     Table << MatchTable::Comment("AddRegisterRegFlags");
2831 
2832     // TODO: This is encoded as a 64-bit element, but only 16 or 32-bits are
2833     // really needed for a physical register reference. We can pack the
2834     // register and flags in a single field.
2835     if (IsDef)
2836       Table << MatchTable::NamedValue("RegState::Define");
2837     else
2838       Table << MatchTable::IntValue(0);
2839     Table << MatchTable::LineBreak;
2840   }
2841 };
2842 
2843 /// Adds a specific temporary virtual register to the instruction being built.
2844 /// This is used to chain instructions together when emitting multiple
2845 /// instructions.
2846 class TempRegRenderer : public OperandRenderer {
2847 protected:
2848   unsigned InsnID;
2849   unsigned TempRegID;
2850   const CodeGenSubRegIndex *SubRegIdx;
2851   bool IsDef;
2852   bool IsDead;
2853 
2854 public:
2855   TempRegRenderer(unsigned InsnID, unsigned TempRegID, bool IsDef = false,
2856                   const CodeGenSubRegIndex *SubReg = nullptr,
2857                   bool IsDead = false)
2858       : OperandRenderer(OR_Register), InsnID(InsnID), TempRegID(TempRegID),
2859         SubRegIdx(SubReg), IsDef(IsDef), IsDead(IsDead) {}
2860 
2861   static bool classof(const OperandRenderer *R) {
2862     return R->getKind() == OR_TempRegister;
2863   }
2864 
2865   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2866     if (SubRegIdx) {
2867       assert(!IsDef);
2868       Table << MatchTable::Opcode("GIR_AddTempSubRegister");
2869     } else
2870       Table << MatchTable::Opcode("GIR_AddTempRegister");
2871 
2872     Table << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2873           << MatchTable::Comment("TempRegID") << MatchTable::IntValue(TempRegID)
2874           << MatchTable::Comment("TempRegFlags");
2875 
2876     if (IsDef) {
2877       SmallString<32> RegFlags;
2878       RegFlags += "RegState::Define";
2879       if (IsDead)
2880         RegFlags += "|RegState::Dead";
2881       Table << MatchTable::NamedValue(RegFlags);
2882     } else
2883       Table << MatchTable::IntValue(0);
2884 
2885     if (SubRegIdx)
2886       Table << MatchTable::NamedValue(SubRegIdx->getQualifiedName());
2887     Table << MatchTable::LineBreak;
2888   }
2889 };
2890 
2891 /// Adds a specific immediate to the instruction being built.
2892 class ImmRenderer : public OperandRenderer {
2893 protected:
2894   unsigned InsnID;
2895   int64_t Imm;
2896 
2897 public:
2898   ImmRenderer(unsigned InsnID, int64_t Imm)
2899       : OperandRenderer(OR_Imm), InsnID(InsnID), Imm(Imm) {}
2900 
2901   static bool classof(const OperandRenderer *R) {
2902     return R->getKind() == OR_Imm;
2903   }
2904 
2905   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2906     Table << MatchTable::Opcode("GIR_AddImm") << MatchTable::Comment("InsnID")
2907           << MatchTable::IntValue(InsnID) << MatchTable::Comment("Imm")
2908           << MatchTable::IntValue(Imm) << MatchTable::LineBreak;
2909   }
2910 };
2911 
2912 /// Adds an enum value for a subreg index to the instruction being built.
2913 class SubRegIndexRenderer : public OperandRenderer {
2914 protected:
2915   unsigned InsnID;
2916   const CodeGenSubRegIndex *SubRegIdx;
2917 
2918 public:
2919   SubRegIndexRenderer(unsigned InsnID, const CodeGenSubRegIndex *SRI)
2920       : OperandRenderer(OR_SubRegIndex), InsnID(InsnID), SubRegIdx(SRI) {}
2921 
2922   static bool classof(const OperandRenderer *R) {
2923     return R->getKind() == OR_SubRegIndex;
2924   }
2925 
2926   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2927     Table << MatchTable::Opcode("GIR_AddImm") << MatchTable::Comment("InsnID")
2928           << MatchTable::IntValue(InsnID) << MatchTable::Comment("SubRegIndex")
2929           << MatchTable::IntValue(SubRegIdx->EnumValue)
2930           << MatchTable::LineBreak;
2931   }
2932 };
2933 
2934 /// Adds operands by calling a renderer function supplied by the ComplexPattern
2935 /// matcher function.
2936 class RenderComplexPatternOperand : public OperandRenderer {
2937 private:
2938   unsigned InsnID;
2939   const Record &TheDef;
2940   /// The name of the operand.
2941   const StringRef SymbolicName;
2942   /// The renderer number. This must be unique within a rule since it's used to
2943   /// identify a temporary variable to hold the renderer function.
2944   unsigned RendererID;
2945   /// When provided, this is the suboperand of the ComplexPattern operand to
2946   /// render. Otherwise all the suboperands will be rendered.
2947   Optional<unsigned> SubOperand;
2948 
2949   unsigned getNumOperands() const {
2950     return TheDef.getValueAsDag("Operands")->getNumArgs();
2951   }
2952 
2953 public:
2954   RenderComplexPatternOperand(unsigned InsnID, const Record &TheDef,
2955                               StringRef SymbolicName, unsigned RendererID,
2956                               Optional<unsigned> SubOperand = None)
2957       : OperandRenderer(OR_ComplexPattern), InsnID(InsnID), TheDef(TheDef),
2958         SymbolicName(SymbolicName), RendererID(RendererID),
2959         SubOperand(SubOperand) {}
2960 
2961   static bool classof(const OperandRenderer *R) {
2962     return R->getKind() == OR_ComplexPattern;
2963   }
2964 
2965   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2966     Table << MatchTable::Opcode(SubOperand ? "GIR_ComplexSubOperandRenderer"
2967                                            : "GIR_ComplexRenderer")
2968           << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2969           << MatchTable::Comment("RendererID")
2970           << MatchTable::IntValue(RendererID);
2971     if (SubOperand)
2972       Table << MatchTable::Comment("SubOperand")
2973             << MatchTable::IntValue(SubOperand.value());
2974     Table << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2975   }
2976 };
2977 
2978 class CustomRenderer : public OperandRenderer {
2979 protected:
2980   unsigned InsnID;
2981   const Record &Renderer;
2982   /// The name of the operand.
2983   const std::string SymbolicName;
2984 
2985 public:
2986   CustomRenderer(unsigned InsnID, const Record &Renderer,
2987                  StringRef SymbolicName)
2988       : OperandRenderer(OR_Custom), InsnID(InsnID), Renderer(Renderer),
2989         SymbolicName(SymbolicName) {}
2990 
2991   static bool classof(const OperandRenderer *R) {
2992     return R->getKind() == OR_Custom;
2993   }
2994 
2995   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2996     InstructionMatcher &InsnMatcher = Rule.getInstructionMatcher(SymbolicName);
2997     unsigned OldInsnVarID = Rule.getInsnVarID(InsnMatcher);
2998     Table << MatchTable::Opcode("GIR_CustomRenderer")
2999           << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
3000           << MatchTable::Comment("OldInsnID")
3001           << MatchTable::IntValue(OldInsnVarID)
3002           << MatchTable::Comment("Renderer")
3003           << MatchTable::NamedValue(
3004                  "GICR_" + Renderer.getValueAsString("RendererFn").str())
3005           << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
3006   }
3007 };
3008 
3009 class CustomOperandRenderer : public OperandRenderer {
3010 protected:
3011   unsigned InsnID;
3012   const Record &Renderer;
3013   /// The name of the operand.
3014   const std::string SymbolicName;
3015 
3016 public:
3017   CustomOperandRenderer(unsigned InsnID, const Record &Renderer,
3018                         StringRef SymbolicName)
3019       : OperandRenderer(OR_CustomOperand), InsnID(InsnID), Renderer(Renderer),
3020         SymbolicName(SymbolicName) {}
3021 
3022   static bool classof(const OperandRenderer *R) {
3023     return R->getKind() == OR_CustomOperand;
3024   }
3025 
3026   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
3027     const OperandMatcher &OpdMatcher = Rule.getOperandMatcher(SymbolicName);
3028     Table << MatchTable::Opcode("GIR_CustomOperandRenderer")
3029           << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
3030           << MatchTable::Comment("OldInsnID")
3031           << MatchTable::IntValue(OpdMatcher.getInsnVarID())
3032           << MatchTable::Comment("OpIdx")
3033           << MatchTable::IntValue(OpdMatcher.getOpIdx())
3034           << MatchTable::Comment("OperandRenderer")
3035           << MatchTable::NamedValue(
3036             "GICR_" + Renderer.getValueAsString("RendererFn").str())
3037           << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
3038   }
3039 };
3040 
3041 /// An action taken when all Matcher predicates succeeded for a parent rule.
3042 ///
3043 /// Typical actions include:
3044 /// * Changing the opcode of an instruction.
3045 /// * Adding an operand to an instruction.
3046 class MatchAction {
3047 public:
3048   virtual ~MatchAction() {}
3049 
3050   /// Emit the MatchTable opcodes to implement the action.
3051   virtual void emitActionOpcodes(MatchTable &Table,
3052                                  RuleMatcher &Rule) const = 0;
3053 };
3054 
3055 /// Generates a comment describing the matched rule being acted upon.
3056 class DebugCommentAction : public MatchAction {
3057 private:
3058   std::string S;
3059 
3060 public:
3061   DebugCommentAction(StringRef S) : S(std::string(S)) {}
3062 
3063   void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
3064     Table << MatchTable::Comment(S) << MatchTable::LineBreak;
3065   }
3066 };
3067 
3068 /// Generates code to build an instruction or mutate an existing instruction
3069 /// into the desired instruction when this is possible.
3070 class BuildMIAction : public MatchAction {
3071 private:
3072   unsigned InsnID;
3073   const CodeGenInstruction *I;
3074   InstructionMatcher *Matched;
3075   std::vector<std::unique_ptr<OperandRenderer>> OperandRenderers;
3076 
3077   /// True if the instruction can be built solely by mutating the opcode.
3078   bool canMutate(RuleMatcher &Rule, const InstructionMatcher *Insn) const {
3079     if (!Insn)
3080       return false;
3081 
3082     if (OperandRenderers.size() != Insn->getNumOperands())
3083       return false;
3084 
3085     for (const auto &Renderer : enumerate(OperandRenderers)) {
3086       if (const auto *Copy = dyn_cast<CopyRenderer>(&*Renderer.value())) {
3087         const OperandMatcher &OM = Rule.getOperandMatcher(Copy->getSymbolicName());
3088         if (Insn != &OM.getInstructionMatcher() ||
3089             OM.getOpIdx() != Renderer.index())
3090           return false;
3091       } else
3092         return false;
3093     }
3094 
3095     return true;
3096   }
3097 
3098 public:
3099   BuildMIAction(unsigned InsnID, const CodeGenInstruction *I)
3100       : InsnID(InsnID), I(I), Matched(nullptr) {}
3101 
3102   unsigned getInsnID() const { return InsnID; }
3103   const CodeGenInstruction *getCGI() const { return I; }
3104 
3105   void chooseInsnToMutate(RuleMatcher &Rule) {
3106     for (auto *MutateCandidate : Rule.mutatable_insns()) {
3107       if (canMutate(Rule, MutateCandidate)) {
3108         // Take the first one we're offered that we're able to mutate.
3109         Rule.reserveInsnMatcherForMutation(MutateCandidate);
3110         Matched = MutateCandidate;
3111         return;
3112       }
3113     }
3114   }
3115 
3116   template <class Kind, class... Args>
3117   Kind &addRenderer(Args&&... args) {
3118     OperandRenderers.emplace_back(
3119         std::make_unique<Kind>(InsnID, std::forward<Args>(args)...));
3120     return *static_cast<Kind *>(OperandRenderers.back().get());
3121   }
3122 
3123   void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
3124     if (Matched) {
3125       assert(canMutate(Rule, Matched) &&
3126              "Arranged to mutate an insn that isn't mutatable");
3127 
3128       unsigned RecycleInsnID = Rule.getInsnVarID(*Matched);
3129       Table << MatchTable::Opcode("GIR_MutateOpcode")
3130             << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
3131             << MatchTable::Comment("RecycleInsnID")
3132             << MatchTable::IntValue(RecycleInsnID)
3133             << MatchTable::Comment("Opcode")
3134             << MatchTable::NamedValue(I->Namespace, I->TheDef->getName())
3135             << MatchTable::LineBreak;
3136 
3137       if (!I->ImplicitDefs.empty() || !I->ImplicitUses.empty()) {
3138         for (auto Def : I->ImplicitDefs) {
3139           auto Namespace = Def->getValue("Namespace")
3140                                ? Def->getValueAsString("Namespace")
3141                                : "";
3142           Table << MatchTable::Opcode("GIR_AddImplicitDef")
3143                 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
3144                 << MatchTable::NamedValue(Namespace, Def->getName())
3145                 << MatchTable::LineBreak;
3146         }
3147         for (auto Use : I->ImplicitUses) {
3148           auto Namespace = Use->getValue("Namespace")
3149                                ? Use->getValueAsString("Namespace")
3150                                : "";
3151           Table << MatchTable::Opcode("GIR_AddImplicitUse")
3152                 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
3153                 << MatchTable::NamedValue(Namespace, Use->getName())
3154                 << MatchTable::LineBreak;
3155         }
3156       }
3157       return;
3158     }
3159 
3160     // TODO: Simple permutation looks like it could be almost as common as
3161     //       mutation due to commutative operations.
3162 
3163     Table << MatchTable::Opcode("GIR_BuildMI") << MatchTable::Comment("InsnID")
3164           << MatchTable::IntValue(InsnID) << MatchTable::Comment("Opcode")
3165           << MatchTable::NamedValue(I->Namespace, I->TheDef->getName())
3166           << MatchTable::LineBreak;
3167     for (const auto &Renderer : OperandRenderers)
3168       Renderer->emitRenderOpcodes(Table, Rule);
3169 
3170     if (I->mayLoad || I->mayStore) {
3171       Table << MatchTable::Opcode("GIR_MergeMemOperands")
3172             << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
3173             << MatchTable::Comment("MergeInsnID's");
3174       // Emit the ID's for all the instructions that are matched by this rule.
3175       // TODO: Limit this to matched instructions that mayLoad/mayStore or have
3176       //       some other means of having a memoperand. Also limit this to
3177       //       emitted instructions that expect to have a memoperand too. For
3178       //       example, (G_SEXT (G_LOAD x)) that results in separate load and
3179       //       sign-extend instructions shouldn't put the memoperand on the
3180       //       sign-extend since it has no effect there.
3181       std::vector<unsigned> MergeInsnIDs;
3182       for (const auto &IDMatcherPair : Rule.defined_insn_vars())
3183         MergeInsnIDs.push_back(IDMatcherPair.second);
3184       llvm::sort(MergeInsnIDs);
3185       for (const auto &MergeInsnID : MergeInsnIDs)
3186         Table << MatchTable::IntValue(MergeInsnID);
3187       Table << MatchTable::NamedValue("GIU_MergeMemOperands_EndOfList")
3188             << MatchTable::LineBreak;
3189     }
3190 
3191     // FIXME: This is a hack but it's sufficient for ISel. We'll need to do
3192     //        better for combines. Particularly when there are multiple match
3193     //        roots.
3194     if (InsnID == 0)
3195       Table << MatchTable::Opcode("GIR_EraseFromParent")
3196             << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
3197             << MatchTable::LineBreak;
3198   }
3199 };
3200 
3201 /// Generates code to constrain the operands of an output instruction to the
3202 /// register classes specified by the definition of that instruction.
3203 class ConstrainOperandsToDefinitionAction : public MatchAction {
3204   unsigned InsnID;
3205 
3206 public:
3207   ConstrainOperandsToDefinitionAction(unsigned InsnID) : InsnID(InsnID) {}
3208 
3209   void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
3210     Table << MatchTable::Opcode("GIR_ConstrainSelectedInstOperands")
3211           << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
3212           << MatchTable::LineBreak;
3213   }
3214 };
3215 
3216 /// Generates code to constrain the specified operand of an output instruction
3217 /// to the specified register class.
3218 class ConstrainOperandToRegClassAction : public MatchAction {
3219   unsigned InsnID;
3220   unsigned OpIdx;
3221   const CodeGenRegisterClass &RC;
3222 
3223 public:
3224   ConstrainOperandToRegClassAction(unsigned InsnID, unsigned OpIdx,
3225                                    const CodeGenRegisterClass &RC)
3226       : InsnID(InsnID), OpIdx(OpIdx), RC(RC) {}
3227 
3228   void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
3229     Table << MatchTable::Opcode("GIR_ConstrainOperandRC")
3230           << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
3231           << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
3232           << MatchTable::NamedValue(RC.getQualifiedName() + "RegClassID")
3233           << MatchTable::LineBreak;
3234   }
3235 };
3236 
3237 /// Generates code to create a temporary register which can be used to chain
3238 /// instructions together.
3239 class MakeTempRegisterAction : public MatchAction {
3240 private:
3241   LLTCodeGen Ty;
3242   unsigned TempRegID;
3243 
3244 public:
3245   MakeTempRegisterAction(const LLTCodeGen &Ty, unsigned TempRegID)
3246       : Ty(Ty), TempRegID(TempRegID) {
3247     KnownTypes.insert(Ty);
3248   }
3249 
3250   void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
3251     Table << MatchTable::Opcode("GIR_MakeTempReg")
3252           << MatchTable::Comment("TempRegID") << MatchTable::IntValue(TempRegID)
3253           << MatchTable::Comment("TypeID")
3254           << MatchTable::NamedValue(Ty.getCxxEnumValue())
3255           << MatchTable::LineBreak;
3256   }
3257 };
3258 
3259 InstructionMatcher &RuleMatcher::addInstructionMatcher(StringRef SymbolicName) {
3260   Matchers.emplace_back(new InstructionMatcher(*this, SymbolicName));
3261   MutatableInsns.insert(Matchers.back().get());
3262   return *Matchers.back();
3263 }
3264 
3265 void RuleMatcher::addRequiredFeature(Record *Feature) {
3266   RequiredFeatures.push_back(Feature);
3267 }
3268 
3269 const std::vector<Record *> &RuleMatcher::getRequiredFeatures() const {
3270   return RequiredFeatures;
3271 }
3272 
3273 // Emplaces an action of the specified Kind at the end of the action list.
3274 //
3275 // Returns a reference to the newly created action.
3276 //
3277 // Like std::vector::emplace_back(), may invalidate all iterators if the new
3278 // size exceeds the capacity. Otherwise, only invalidates the past-the-end
3279 // iterator.
3280 template <class Kind, class... Args>
3281 Kind &RuleMatcher::addAction(Args &&... args) {
3282   Actions.emplace_back(std::make_unique<Kind>(std::forward<Args>(args)...));
3283   return *static_cast<Kind *>(Actions.back().get());
3284 }
3285 
3286 // Emplaces an action of the specified Kind before the given insertion point.
3287 //
3288 // Returns an iterator pointing at the newly created instruction.
3289 //
3290 // Like std::vector::insert(), may invalidate all iterators if the new size
3291 // exceeds the capacity. Otherwise, only invalidates the iterators from the
3292 // insertion point onwards.
3293 template <class Kind, class... Args>
3294 action_iterator RuleMatcher::insertAction(action_iterator InsertPt,
3295                                           Args &&... args) {
3296   return Actions.emplace(InsertPt,
3297                          std::make_unique<Kind>(std::forward<Args>(args)...));
3298 }
3299 
3300 unsigned RuleMatcher::implicitlyDefineInsnVar(InstructionMatcher &Matcher) {
3301   unsigned NewInsnVarID = NextInsnVarID++;
3302   InsnVariableIDs[&Matcher] = NewInsnVarID;
3303   return NewInsnVarID;
3304 }
3305 
3306 unsigned RuleMatcher::getInsnVarID(InstructionMatcher &InsnMatcher) const {
3307   const auto &I = InsnVariableIDs.find(&InsnMatcher);
3308   if (I != InsnVariableIDs.end())
3309     return I->second;
3310   llvm_unreachable("Matched Insn was not captured in a local variable");
3311 }
3312 
3313 void RuleMatcher::defineOperand(StringRef SymbolicName, OperandMatcher &OM) {
3314   if (DefinedOperands.find(SymbolicName) == DefinedOperands.end()) {
3315     DefinedOperands[SymbolicName] = &OM;
3316     return;
3317   }
3318 
3319   // If the operand is already defined, then we must ensure both references in
3320   // the matcher have the exact same node.
3321   OM.addPredicate<SameOperandMatcher>(
3322       OM.getSymbolicName(), getOperandMatcher(OM.getSymbolicName()).getOpIdx());
3323 }
3324 
3325 void RuleMatcher::definePhysRegOperand(Record *Reg, OperandMatcher &OM) {
3326   if (PhysRegOperands.find(Reg) == PhysRegOperands.end()) {
3327     PhysRegOperands[Reg] = &OM;
3328     return;
3329   }
3330 }
3331 
3332 InstructionMatcher &
3333 RuleMatcher::getInstructionMatcher(StringRef SymbolicName) const {
3334   for (const auto &I : InsnVariableIDs)
3335     if (I.first->getSymbolicName() == SymbolicName)
3336       return *I.first;
3337   llvm_unreachable(
3338       ("Failed to lookup instruction " + SymbolicName).str().c_str());
3339 }
3340 
3341 const OperandMatcher &
3342 RuleMatcher::getPhysRegOperandMatcher(Record *Reg) const {
3343   const auto &I = PhysRegOperands.find(Reg);
3344 
3345   if (I == PhysRegOperands.end()) {
3346     PrintFatalError(SrcLoc, "Register " + Reg->getName() +
3347                     " was not declared in matcher");
3348   }
3349 
3350   return *I->second;
3351 }
3352 
3353 const OperandMatcher &
3354 RuleMatcher::getOperandMatcher(StringRef Name) const {
3355   const auto &I = DefinedOperands.find(Name);
3356 
3357   if (I == DefinedOperands.end())
3358     PrintFatalError(SrcLoc, "Operand " + Name + " was not declared in matcher");
3359 
3360   return *I->second;
3361 }
3362 
3363 void RuleMatcher::emit(MatchTable &Table) {
3364   if (Matchers.empty())
3365     llvm_unreachable("Unexpected empty matcher!");
3366 
3367   // The representation supports rules that require multiple roots such as:
3368   //    %ptr(p0) = ...
3369   //    %elt0(s32) = G_LOAD %ptr
3370   //    %1(p0) = G_ADD %ptr, 4
3371   //    %elt1(s32) = G_LOAD p0 %1
3372   // which could be usefully folded into:
3373   //    %ptr(p0) = ...
3374   //    %elt0(s32), %elt1(s32) = TGT_LOAD_PAIR %ptr
3375   // on some targets but we don't need to make use of that yet.
3376   assert(Matchers.size() == 1 && "Cannot handle multi-root matchers yet");
3377 
3378   unsigned LabelID = Table.allocateLabelID();
3379   Table << MatchTable::Opcode("GIM_Try", +1)
3380         << MatchTable::Comment("On fail goto")
3381         << MatchTable::JumpTarget(LabelID)
3382         << MatchTable::Comment(("Rule ID " + Twine(RuleID) + " //").str())
3383         << MatchTable::LineBreak;
3384 
3385   if (!RequiredFeatures.empty()) {
3386     Table << MatchTable::Opcode("GIM_CheckFeatures")
3387           << MatchTable::NamedValue(getNameForFeatureBitset(RequiredFeatures))
3388           << MatchTable::LineBreak;
3389   }
3390 
3391   Matchers.front()->emitPredicateOpcodes(Table, *this);
3392 
3393   // We must also check if it's safe to fold the matched instructions.
3394   if (InsnVariableIDs.size() >= 2) {
3395     // Invert the map to create stable ordering (by var names)
3396     SmallVector<unsigned, 2> InsnIDs;
3397     for (const auto &Pair : InsnVariableIDs) {
3398       // Skip the root node since it isn't moving anywhere. Everything else is
3399       // sinking to meet it.
3400       if (Pair.first == Matchers.front().get())
3401         continue;
3402 
3403       InsnIDs.push_back(Pair.second);
3404     }
3405     llvm::sort(InsnIDs);
3406 
3407     for (const auto &InsnID : InsnIDs) {
3408       // Reject the difficult cases until we have a more accurate check.
3409       Table << MatchTable::Opcode("GIM_CheckIsSafeToFold")
3410             << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
3411             << MatchTable::LineBreak;
3412 
3413       // FIXME: Emit checks to determine it's _actually_ safe to fold and/or
3414       //        account for unsafe cases.
3415       //
3416       //        Example:
3417       //          MI1--> %0 = ...
3418       //                 %1 = ... %0
3419       //          MI0--> %2 = ... %0
3420       //          It's not safe to erase MI1. We currently handle this by not
3421       //          erasing %0 (even when it's dead).
3422       //
3423       //        Example:
3424       //          MI1--> %0 = load volatile @a
3425       //                 %1 = load volatile @a
3426       //          MI0--> %2 = ... %0
3427       //          It's not safe to sink %0's def past %1. We currently handle
3428       //          this by rejecting all loads.
3429       //
3430       //        Example:
3431       //          MI1--> %0 = load @a
3432       //                 %1 = store @a
3433       //          MI0--> %2 = ... %0
3434       //          It's not safe to sink %0's def past %1. We currently handle
3435       //          this by rejecting all loads.
3436       //
3437       //        Example:
3438       //                   G_CONDBR %cond, @BB1
3439       //                 BB0:
3440       //          MI1-->   %0 = load @a
3441       //                   G_BR @BB1
3442       //                 BB1:
3443       //          MI0-->   %2 = ... %0
3444       //          It's not always safe to sink %0 across control flow. In this
3445       //          case it may introduce a memory fault. We currentl handle this
3446       //          by rejecting all loads.
3447     }
3448   }
3449 
3450   for (const auto &PM : EpilogueMatchers)
3451     PM->emitPredicateOpcodes(Table, *this);
3452 
3453   for (const auto &MA : Actions)
3454     MA->emitActionOpcodes(Table, *this);
3455 
3456   if (Table.isWithCoverage())
3457     Table << MatchTable::Opcode("GIR_Coverage") << MatchTable::IntValue(RuleID)
3458           << MatchTable::LineBreak;
3459   else
3460     Table << MatchTable::Comment(("GIR_Coverage, " + Twine(RuleID) + ",").str())
3461           << MatchTable::LineBreak;
3462 
3463   Table << MatchTable::Opcode("GIR_Done", -1) << MatchTable::LineBreak
3464         << MatchTable::Label(LabelID);
3465   ++NumPatternEmitted;
3466 }
3467 
3468 bool RuleMatcher::isHigherPriorityThan(const RuleMatcher &B) const {
3469   // Rules involving more match roots have higher priority.
3470   if (Matchers.size() > B.Matchers.size())
3471     return true;
3472   if (Matchers.size() < B.Matchers.size())
3473     return false;
3474 
3475   for (auto Matcher : zip(Matchers, B.Matchers)) {
3476     if (std::get<0>(Matcher)->isHigherPriorityThan(*std::get<1>(Matcher)))
3477       return true;
3478     if (std::get<1>(Matcher)->isHigherPriorityThan(*std::get<0>(Matcher)))
3479       return false;
3480   }
3481 
3482   return false;
3483 }
3484 
3485 unsigned RuleMatcher::countRendererFns() const {
3486   return std::accumulate(
3487       Matchers.begin(), Matchers.end(), 0,
3488       [](unsigned A, const std::unique_ptr<InstructionMatcher> &Matcher) {
3489         return A + Matcher->countRendererFns();
3490       });
3491 }
3492 
3493 bool OperandPredicateMatcher::isHigherPriorityThan(
3494     const OperandPredicateMatcher &B) const {
3495   // Generally speaking, an instruction is more important than an Int or a
3496   // LiteralInt because it can cover more nodes but theres an exception to
3497   // this. G_CONSTANT's are less important than either of those two because they
3498   // are more permissive.
3499 
3500   const InstructionOperandMatcher *AOM =
3501       dyn_cast<InstructionOperandMatcher>(this);
3502   const InstructionOperandMatcher *BOM =
3503       dyn_cast<InstructionOperandMatcher>(&B);
3504   bool AIsConstantInsn = AOM && AOM->getInsnMatcher().isConstantInstruction();
3505   bool BIsConstantInsn = BOM && BOM->getInsnMatcher().isConstantInstruction();
3506 
3507   if (AOM && BOM) {
3508     // The relative priorities between a G_CONSTANT and any other instruction
3509     // don't actually matter but this code is needed to ensure a strict weak
3510     // ordering. This is particularly important on Windows where the rules will
3511     // be incorrectly sorted without it.
3512     if (AIsConstantInsn != BIsConstantInsn)
3513       return AIsConstantInsn < BIsConstantInsn;
3514     return false;
3515   }
3516 
3517   if (AOM && AIsConstantInsn && (B.Kind == OPM_Int || B.Kind == OPM_LiteralInt))
3518     return false;
3519   if (BOM && BIsConstantInsn && (Kind == OPM_Int || Kind == OPM_LiteralInt))
3520     return true;
3521 
3522   return Kind < B.Kind;
3523 }
3524 
3525 void SameOperandMatcher::emitPredicateOpcodes(MatchTable &Table,
3526                                               RuleMatcher &Rule) const {
3527   const OperandMatcher &OtherOM = Rule.getOperandMatcher(MatchingName);
3528   unsigned OtherInsnVarID = Rule.getInsnVarID(OtherOM.getInstructionMatcher());
3529   assert(OtherInsnVarID == OtherOM.getInstructionMatcher().getInsnVarID());
3530 
3531   Table << MatchTable::Opcode("GIM_CheckIsSameOperand")
3532         << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
3533         << MatchTable::Comment("OpIdx") << MatchTable::IntValue(OpIdx)
3534         << MatchTable::Comment("OtherMI")
3535         << MatchTable::IntValue(OtherInsnVarID)
3536         << MatchTable::Comment("OtherOpIdx")
3537         << MatchTable::IntValue(OtherOM.getOpIdx())
3538         << MatchTable::LineBreak;
3539 }
3540 
3541 //===- GlobalISelEmitter class --------------------------------------------===//
3542 
3543 static Expected<LLTCodeGen> getInstResultType(const TreePatternNode *Dst) {
3544   ArrayRef<TypeSetByHwMode> ChildTypes = Dst->getExtTypes();
3545   if (ChildTypes.size() != 1)
3546     return failedImport("Dst pattern child has multiple results");
3547 
3548   Optional<LLTCodeGen> MaybeOpTy;
3549   if (ChildTypes.front().isMachineValueType()) {
3550     MaybeOpTy =
3551       MVTToLLT(ChildTypes.front().getMachineValueType().SimpleTy);
3552   }
3553 
3554   if (!MaybeOpTy)
3555     return failedImport("Dst operand has an unsupported type");
3556   return *MaybeOpTy;
3557 }
3558 
3559 class GlobalISelEmitter {
3560 public:
3561   explicit GlobalISelEmitter(RecordKeeper &RK);
3562   void run(raw_ostream &OS);
3563 
3564 private:
3565   const RecordKeeper &RK;
3566   const CodeGenDAGPatterns CGP;
3567   const CodeGenTarget &Target;
3568   CodeGenRegBank &CGRegs;
3569 
3570   /// Keep track of the equivalence between SDNodes and Instruction by mapping
3571   /// SDNodes to the GINodeEquiv mapping. We need to map to the GINodeEquiv to
3572   /// check for attributes on the relation such as CheckMMOIsNonAtomic.
3573   /// This is defined using 'GINodeEquiv' in the target description.
3574   DenseMap<Record *, Record *> NodeEquivs;
3575 
3576   /// Keep track of the equivalence between ComplexPattern's and
3577   /// GIComplexOperandMatcher. Map entries are specified by subclassing
3578   /// GIComplexPatternEquiv.
3579   DenseMap<const Record *, const Record *> ComplexPatternEquivs;
3580 
3581   /// Keep track of the equivalence between SDNodeXForm's and
3582   /// GICustomOperandRenderer. Map entries are specified by subclassing
3583   /// GISDNodeXFormEquiv.
3584   DenseMap<const Record *, const Record *> SDNodeXFormEquivs;
3585 
3586   /// Keep track of Scores of PatternsToMatch similar to how the DAG does.
3587   /// This adds compatibility for RuleMatchers to use this for ordering rules.
3588   DenseMap<uint64_t, int> RuleMatcherScores;
3589 
3590   // Map of predicates to their subtarget features.
3591   SubtargetFeatureInfoMap SubtargetFeatures;
3592 
3593   // Rule coverage information.
3594   Optional<CodeGenCoverage> RuleCoverage;
3595 
3596   /// Variables used to help with collecting of named operands for predicates
3597   /// with 'let PredicateCodeUsesOperands = 1'. WaitingForNamedOperands is set
3598   /// to the number of named operands that predicate expects. Store locations in
3599   /// StoreIdxForName correspond to the order in which operand names appear in
3600   /// predicate's argument list.
3601   /// When we visit named leaf operand and WaitingForNamedOperands is not zero,
3602   /// add matcher that will record operand and decrease counter.
3603   unsigned WaitingForNamedOperands = 0;
3604   StringMap<unsigned> StoreIdxForName;
3605 
3606   void gatherOpcodeValues();
3607   void gatherTypeIDValues();
3608   void gatherNodeEquivs();
3609 
3610   Record *findNodeEquiv(Record *N) const;
3611   const CodeGenInstruction *getEquivNode(Record &Equiv,
3612                                          const TreePatternNode *N) const;
3613 
3614   Error importRulePredicates(RuleMatcher &M, ArrayRef<Record *> Predicates);
3615   Expected<InstructionMatcher &>
3616   createAndImportSelDAGMatcher(RuleMatcher &Rule,
3617                                InstructionMatcher &InsnMatcher,
3618                                const TreePatternNode *Src, unsigned &TempOpIdx);
3619   Error importComplexPatternOperandMatcher(OperandMatcher &OM, Record *R,
3620                                            unsigned &TempOpIdx) const;
3621   Error importChildMatcher(RuleMatcher &Rule, InstructionMatcher &InsnMatcher,
3622                            const TreePatternNode *SrcChild,
3623                            bool OperandIsAPointer, bool OperandIsImmArg,
3624                            unsigned OpIdx, unsigned &TempOpIdx);
3625 
3626   Expected<BuildMIAction &> createAndImportInstructionRenderer(
3627       RuleMatcher &M, InstructionMatcher &InsnMatcher,
3628       const TreePatternNode *Src, const TreePatternNode *Dst);
3629   Expected<action_iterator> createAndImportSubInstructionRenderer(
3630       action_iterator InsertPt, RuleMatcher &M, const TreePatternNode *Dst,
3631       unsigned TempReg);
3632   Expected<action_iterator>
3633   createInstructionRenderer(action_iterator InsertPt, RuleMatcher &M,
3634                             const TreePatternNode *Dst);
3635 
3636   Expected<action_iterator>
3637   importExplicitDefRenderers(action_iterator InsertPt, RuleMatcher &M,
3638                              BuildMIAction &DstMIBuilder,
3639                              const TreePatternNode *Dst);
3640 
3641   Expected<action_iterator>
3642   importExplicitUseRenderers(action_iterator InsertPt, RuleMatcher &M,
3643                              BuildMIAction &DstMIBuilder,
3644                              const llvm::TreePatternNode *Dst);
3645   Expected<action_iterator>
3646   importExplicitUseRenderer(action_iterator InsertPt, RuleMatcher &Rule,
3647                             BuildMIAction &DstMIBuilder,
3648                             TreePatternNode *DstChild);
3649   Error importDefaultOperandRenderers(action_iterator InsertPt, RuleMatcher &M,
3650                                       BuildMIAction &DstMIBuilder,
3651                                       DagInit *DefaultOps) const;
3652   Error
3653   importImplicitDefRenderers(BuildMIAction &DstMIBuilder,
3654                              const std::vector<Record *> &ImplicitDefs) const;
3655 
3656   void emitCxxPredicateFns(raw_ostream &OS, StringRef CodeFieldName,
3657                            StringRef TypeIdentifier, StringRef ArgType,
3658                            StringRef ArgName, StringRef AdditionalArgs,
3659                            StringRef AdditionalDeclarations,
3660                            std::function<bool(const Record *R)> Filter);
3661   void emitImmPredicateFns(raw_ostream &OS, StringRef TypeIdentifier,
3662                            StringRef ArgType,
3663                            std::function<bool(const Record *R)> Filter);
3664   void emitMIPredicateFns(raw_ostream &OS);
3665 
3666   /// Analyze pattern \p P, returning a matcher for it if possible.
3667   /// Otherwise, return an Error explaining why we don't support it.
3668   Expected<RuleMatcher> runOnPattern(const PatternToMatch &P);
3669 
3670   void declareSubtargetFeature(Record *Predicate);
3671 
3672   MatchTable buildMatchTable(MutableArrayRef<RuleMatcher> Rules, bool Optimize,
3673                              bool WithCoverage);
3674 
3675   /// Infer a CodeGenRegisterClass for the type of \p SuperRegNode. The returned
3676   /// CodeGenRegisterClass will support the CodeGenRegisterClass of
3677   /// \p SubRegNode, and the subregister index defined by \p SubRegIdxNode.
3678   /// If no register class is found, return None.
3679   Optional<const CodeGenRegisterClass *>
3680   inferSuperRegisterClassForNode(const TypeSetByHwMode &Ty,
3681                                  TreePatternNode *SuperRegNode,
3682                                  TreePatternNode *SubRegIdxNode);
3683   Optional<CodeGenSubRegIndex *>
3684   inferSubRegIndexForNode(TreePatternNode *SubRegIdxNode);
3685 
3686   /// Infer a CodeGenRegisterClass which suppoorts \p Ty and \p SubRegIdxNode.
3687   /// Return None if no such class exists.
3688   Optional<const CodeGenRegisterClass *>
3689   inferSuperRegisterClass(const TypeSetByHwMode &Ty,
3690                           TreePatternNode *SubRegIdxNode);
3691 
3692   /// Return the CodeGenRegisterClass associated with \p Leaf if it has one.
3693   Optional<const CodeGenRegisterClass *>
3694   getRegClassFromLeaf(TreePatternNode *Leaf);
3695 
3696   /// Return a CodeGenRegisterClass for \p N if one can be found. Return None
3697   /// otherwise.
3698   Optional<const CodeGenRegisterClass *>
3699   inferRegClassFromPattern(TreePatternNode *N);
3700 
3701   /// Return the size of the MemoryVT in this predicate, if possible.
3702   Optional<unsigned>
3703   getMemSizeBitsFromPredicate(const TreePredicateFn &Predicate);
3704 
3705   // Add builtin predicates.
3706   Expected<InstructionMatcher &>
3707   addBuiltinPredicates(const Record *SrcGIEquivOrNull,
3708                        const TreePredicateFn &Predicate,
3709                        InstructionMatcher &InsnMatcher, bool &HasAddedMatcher);
3710 
3711 public:
3712   /// Takes a sequence of \p Rules and group them based on the predicates
3713   /// they share. \p MatcherStorage is used as a memory container
3714   /// for the group that are created as part of this process.
3715   ///
3716   /// What this optimization does looks like if GroupT = GroupMatcher:
3717   /// Output without optimization:
3718   /// \verbatim
3719   /// # R1
3720   ///  # predicate A
3721   ///  # predicate B
3722   ///  ...
3723   /// # R2
3724   ///  # predicate A // <-- effectively this is going to be checked twice.
3725   ///                //     Once in R1 and once in R2.
3726   ///  # predicate C
3727   /// \endverbatim
3728   /// Output with optimization:
3729   /// \verbatim
3730   /// # Group1_2
3731   ///  # predicate A // <-- Check is now shared.
3732   ///  # R1
3733   ///   # predicate B
3734   ///  # R2
3735   ///   # predicate C
3736   /// \endverbatim
3737   template <class GroupT>
3738   static std::vector<Matcher *> optimizeRules(
3739       ArrayRef<Matcher *> Rules,
3740       std::vector<std::unique_ptr<Matcher>> &MatcherStorage);
3741 };
3742 
3743 void GlobalISelEmitter::gatherOpcodeValues() {
3744   InstructionOpcodeMatcher::initOpcodeValuesMap(Target);
3745 }
3746 
3747 void GlobalISelEmitter::gatherTypeIDValues() {
3748   LLTOperandMatcher::initTypeIDValuesMap();
3749 }
3750 
3751 void GlobalISelEmitter::gatherNodeEquivs() {
3752   assert(NodeEquivs.empty());
3753   for (Record *Equiv : RK.getAllDerivedDefinitions("GINodeEquiv"))
3754     NodeEquivs[Equiv->getValueAsDef("Node")] = Equiv;
3755 
3756   assert(ComplexPatternEquivs.empty());
3757   for (Record *Equiv : RK.getAllDerivedDefinitions("GIComplexPatternEquiv")) {
3758     Record *SelDAGEquiv = Equiv->getValueAsDef("SelDAGEquivalent");
3759     if (!SelDAGEquiv)
3760       continue;
3761     ComplexPatternEquivs[SelDAGEquiv] = Equiv;
3762  }
3763 
3764  assert(SDNodeXFormEquivs.empty());
3765  for (Record *Equiv : RK.getAllDerivedDefinitions("GISDNodeXFormEquiv")) {
3766    Record *SelDAGEquiv = Equiv->getValueAsDef("SelDAGEquivalent");
3767    if (!SelDAGEquiv)
3768      continue;
3769    SDNodeXFormEquivs[SelDAGEquiv] = Equiv;
3770  }
3771 }
3772 
3773 Record *GlobalISelEmitter::findNodeEquiv(Record *N) const {
3774   return NodeEquivs.lookup(N);
3775 }
3776 
3777 const CodeGenInstruction *
3778 GlobalISelEmitter::getEquivNode(Record &Equiv, const TreePatternNode *N) const {
3779   if (N->getNumChildren() >= 1) {
3780     // setcc operation maps to two different G_* instructions based on the type.
3781     if (!Equiv.isValueUnset("IfFloatingPoint") &&
3782         MVT(N->getChild(0)->getSimpleType(0)).isFloatingPoint())
3783       return &Target.getInstruction(Equiv.getValueAsDef("IfFloatingPoint"));
3784   }
3785 
3786   for (const TreePredicateCall &Call : N->getPredicateCalls()) {
3787     const TreePredicateFn &Predicate = Call.Fn;
3788     if (!Equiv.isValueUnset("IfSignExtend") &&
3789         (Predicate.isLoad() || Predicate.isAtomic()) &&
3790         Predicate.isSignExtLoad())
3791       return &Target.getInstruction(Equiv.getValueAsDef("IfSignExtend"));
3792     if (!Equiv.isValueUnset("IfZeroExtend") &&
3793         (Predicate.isLoad() || Predicate.isAtomic()) &&
3794         Predicate.isZeroExtLoad())
3795       return &Target.getInstruction(Equiv.getValueAsDef("IfZeroExtend"));
3796   }
3797 
3798   return &Target.getInstruction(Equiv.getValueAsDef("I"));
3799 }
3800 
3801 GlobalISelEmitter::GlobalISelEmitter(RecordKeeper &RK)
3802     : RK(RK), CGP(RK), Target(CGP.getTargetInfo()),
3803       CGRegs(Target.getRegBank()) {}
3804 
3805 //===- Emitter ------------------------------------------------------------===//
3806 
3807 Error GlobalISelEmitter::importRulePredicates(RuleMatcher &M,
3808                                               ArrayRef<Record *> Predicates) {
3809   for (Record *Pred : Predicates) {
3810     if (Pred->getValueAsString("CondString").empty())
3811       continue;
3812     declareSubtargetFeature(Pred);
3813     M.addRequiredFeature(Pred);
3814   }
3815 
3816   return Error::success();
3817 }
3818 
3819 Optional<unsigned> GlobalISelEmitter::getMemSizeBitsFromPredicate(const TreePredicateFn &Predicate) {
3820   Optional<LLTCodeGen> MemTyOrNone =
3821       MVTToLLT(getValueType(Predicate.getMemoryVT()));
3822 
3823   if (!MemTyOrNone)
3824     return None;
3825 
3826   // Align so unusual types like i1 don't get rounded down.
3827   return llvm::alignTo(
3828       static_cast<unsigned>(MemTyOrNone->get().getSizeInBits()), 8);
3829 }
3830 
3831 Expected<InstructionMatcher &> GlobalISelEmitter::addBuiltinPredicates(
3832     const Record *SrcGIEquivOrNull, const TreePredicateFn &Predicate,
3833     InstructionMatcher &InsnMatcher, bool &HasAddedMatcher) {
3834   if (Predicate.isLoad() || Predicate.isStore() || Predicate.isAtomic()) {
3835     if (const ListInit *AddrSpaces = Predicate.getAddressSpaces()) {
3836       SmallVector<unsigned, 4> ParsedAddrSpaces;
3837 
3838       for (Init *Val : AddrSpaces->getValues()) {
3839         IntInit *IntVal = dyn_cast<IntInit>(Val);
3840         if (!IntVal)
3841           return failedImport("Address space is not an integer");
3842         ParsedAddrSpaces.push_back(IntVal->getValue());
3843       }
3844 
3845       if (!ParsedAddrSpaces.empty()) {
3846         InsnMatcher.addPredicate<MemoryAddressSpacePredicateMatcher>(
3847             0, ParsedAddrSpaces);
3848         return InsnMatcher;
3849       }
3850     }
3851 
3852     int64_t MinAlign = Predicate.getMinAlignment();
3853     if (MinAlign > 0) {
3854       InsnMatcher.addPredicate<MemoryAlignmentPredicateMatcher>(0, MinAlign);
3855       return InsnMatcher;
3856     }
3857   }
3858 
3859   // G_LOAD is used for both non-extending and any-extending loads.
3860   if (Predicate.isLoad() && Predicate.isNonExtLoad()) {
3861     InsnMatcher.addPredicate<MemoryVsLLTSizePredicateMatcher>(
3862         0, MemoryVsLLTSizePredicateMatcher::EqualTo, 0);
3863     return InsnMatcher;
3864   }
3865   if (Predicate.isLoad() && Predicate.isAnyExtLoad()) {
3866     InsnMatcher.addPredicate<MemoryVsLLTSizePredicateMatcher>(
3867         0, MemoryVsLLTSizePredicateMatcher::LessThan, 0);
3868     return InsnMatcher;
3869   }
3870 
3871   if (Predicate.isStore()) {
3872     if (Predicate.isTruncStore()) {
3873       if (Predicate.getMemoryVT() != nullptr) {
3874         // FIXME: If MemoryVT is set, we end up with 2 checks for the MMO size.
3875         auto MemSizeInBits = getMemSizeBitsFromPredicate(Predicate);
3876         if (!MemSizeInBits)
3877           return failedImport("MemVT could not be converted to LLT");
3878 
3879         InsnMatcher.addPredicate<MemorySizePredicateMatcher>(0, *MemSizeInBits /
3880                                                                     8);
3881       } else {
3882         InsnMatcher.addPredicate<MemoryVsLLTSizePredicateMatcher>(
3883             0, MemoryVsLLTSizePredicateMatcher::LessThan, 0);
3884       }
3885       return InsnMatcher;
3886     }
3887     if (Predicate.isNonTruncStore()) {
3888       // We need to check the sizes match here otherwise we could incorrectly
3889       // match truncating stores with non-truncating ones.
3890       InsnMatcher.addPredicate<MemoryVsLLTSizePredicateMatcher>(
3891           0, MemoryVsLLTSizePredicateMatcher::EqualTo, 0);
3892     }
3893   }
3894 
3895   // No check required. We already did it by swapping the opcode.
3896   if (!SrcGIEquivOrNull->isValueUnset("IfSignExtend") &&
3897       Predicate.isSignExtLoad())
3898     return InsnMatcher;
3899 
3900   // No check required. We already did it by swapping the opcode.
3901   if (!SrcGIEquivOrNull->isValueUnset("IfZeroExtend") &&
3902       Predicate.isZeroExtLoad())
3903     return InsnMatcher;
3904 
3905   // No check required. G_STORE by itself is a non-extending store.
3906   if (Predicate.isNonTruncStore())
3907     return InsnMatcher;
3908 
3909   if (Predicate.isLoad() || Predicate.isStore() || Predicate.isAtomic()) {
3910     if (Predicate.getMemoryVT() != nullptr) {
3911       auto MemSizeInBits = getMemSizeBitsFromPredicate(Predicate);
3912       if (!MemSizeInBits)
3913         return failedImport("MemVT could not be converted to LLT");
3914 
3915       InsnMatcher.addPredicate<MemorySizePredicateMatcher>(0,
3916                                                            *MemSizeInBits / 8);
3917       return InsnMatcher;
3918     }
3919   }
3920 
3921   if (Predicate.isLoad() || Predicate.isStore()) {
3922     // No check required. A G_LOAD/G_STORE is an unindexed load.
3923     if (Predicate.isUnindexed())
3924       return InsnMatcher;
3925   }
3926 
3927   if (Predicate.isAtomic()) {
3928     if (Predicate.isAtomicOrderingMonotonic()) {
3929       InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>("Monotonic");
3930       return InsnMatcher;
3931     }
3932     if (Predicate.isAtomicOrderingAcquire()) {
3933       InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>("Acquire");
3934       return InsnMatcher;
3935     }
3936     if (Predicate.isAtomicOrderingRelease()) {
3937       InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>("Release");
3938       return InsnMatcher;
3939     }
3940     if (Predicate.isAtomicOrderingAcquireRelease()) {
3941       InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3942           "AcquireRelease");
3943       return InsnMatcher;
3944     }
3945     if (Predicate.isAtomicOrderingSequentiallyConsistent()) {
3946       InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3947           "SequentiallyConsistent");
3948       return InsnMatcher;
3949     }
3950   }
3951 
3952   if (Predicate.isAtomicOrderingAcquireOrStronger()) {
3953     InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3954         "Acquire", AtomicOrderingMMOPredicateMatcher::AO_OrStronger);
3955     return InsnMatcher;
3956   }
3957   if (Predicate.isAtomicOrderingWeakerThanAcquire()) {
3958     InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3959         "Acquire", AtomicOrderingMMOPredicateMatcher::AO_WeakerThan);
3960     return InsnMatcher;
3961   }
3962 
3963   if (Predicate.isAtomicOrderingReleaseOrStronger()) {
3964     InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3965         "Release", AtomicOrderingMMOPredicateMatcher::AO_OrStronger);
3966     return InsnMatcher;
3967   }
3968   if (Predicate.isAtomicOrderingWeakerThanRelease()) {
3969     InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3970         "Release", AtomicOrderingMMOPredicateMatcher::AO_WeakerThan);
3971     return InsnMatcher;
3972   }
3973   HasAddedMatcher = false;
3974   return InsnMatcher;
3975 }
3976 
3977 Expected<InstructionMatcher &> GlobalISelEmitter::createAndImportSelDAGMatcher(
3978     RuleMatcher &Rule, InstructionMatcher &InsnMatcher,
3979     const TreePatternNode *Src, unsigned &TempOpIdx) {
3980   Record *SrcGIEquivOrNull = nullptr;
3981   const CodeGenInstruction *SrcGIOrNull = nullptr;
3982 
3983   // Start with the defined operands (i.e., the results of the root operator).
3984   if (Src->getExtTypes().size() > 1)
3985     return failedImport("Src pattern has multiple results");
3986 
3987   if (Src->isLeaf()) {
3988     Init *SrcInit = Src->getLeafValue();
3989     if (isa<IntInit>(SrcInit)) {
3990       InsnMatcher.addPredicate<InstructionOpcodeMatcher>(
3991           &Target.getInstruction(RK.getDef("G_CONSTANT")));
3992     } else
3993       return failedImport(
3994           "Unable to deduce gMIR opcode to handle Src (which is a leaf)");
3995   } else {
3996     SrcGIEquivOrNull = findNodeEquiv(Src->getOperator());
3997     if (!SrcGIEquivOrNull)
3998       return failedImport("Pattern operator lacks an equivalent Instruction" +
3999                           explainOperator(Src->getOperator()));
4000     SrcGIOrNull = getEquivNode(*SrcGIEquivOrNull, Src);
4001 
4002     // The operators look good: match the opcode
4003     InsnMatcher.addPredicate<InstructionOpcodeMatcher>(SrcGIOrNull);
4004   }
4005 
4006   unsigned OpIdx = 0;
4007   for (const TypeSetByHwMode &VTy : Src->getExtTypes()) {
4008     // Results don't have a name unless they are the root node. The caller will
4009     // set the name if appropriate.
4010     OperandMatcher &OM = InsnMatcher.addOperand(OpIdx++, "", TempOpIdx);
4011     if (auto Error = OM.addTypeCheckPredicate(VTy, false /* OperandIsAPointer */))
4012       return failedImport(toString(std::move(Error)) +
4013                           " for result of Src pattern operator");
4014   }
4015 
4016   for (const TreePredicateCall &Call : Src->getPredicateCalls()) {
4017     const TreePredicateFn &Predicate = Call.Fn;
4018     bool HasAddedBuiltinMatcher = true;
4019     if (Predicate.isAlwaysTrue())
4020       continue;
4021 
4022     if (Predicate.isImmediatePattern()) {
4023       InsnMatcher.addPredicate<InstructionImmPredicateMatcher>(Predicate);
4024       continue;
4025     }
4026 
4027     auto InsnMatcherOrError = addBuiltinPredicates(
4028         SrcGIEquivOrNull, Predicate, InsnMatcher, HasAddedBuiltinMatcher);
4029     if (auto Error = InsnMatcherOrError.takeError())
4030       return std::move(Error);
4031 
4032     // FIXME: This should be part of addBuiltinPredicates(). If we add this at
4033     // the start of addBuiltinPredicates() without returning, then there might
4034     // be cases where we hit the last return before which the
4035     // HasAddedBuiltinMatcher will be set to false. The predicate could be
4036     // missed if we add it in the middle or at the end due to return statements
4037     // after the addPredicate<>() calls.
4038     if (Predicate.hasNoUse()) {
4039       InsnMatcher.addPredicate<NoUsePredicateMatcher>();
4040       HasAddedBuiltinMatcher = true;
4041     }
4042 
4043     if (Predicate.hasGISelPredicateCode()) {
4044       if (Predicate.usesOperands()) {
4045         assert(WaitingForNamedOperands == 0 &&
4046                "previous predicate didn't find all operands or "
4047                "nested predicate that uses operands");
4048         TreePattern *TP = Predicate.getOrigPatFragRecord();
4049         WaitingForNamedOperands = TP->getNumArgs();
4050         for (unsigned i = 0; i < WaitingForNamedOperands; ++i)
4051           StoreIdxForName[getScopedName(Call.Scope, TP->getArgName(i))] = i;
4052       }
4053       InsnMatcher.addPredicate<GenericInstructionPredicateMatcher>(Predicate);
4054       continue;
4055     }
4056     if (!HasAddedBuiltinMatcher) {
4057       return failedImport("Src pattern child has predicate (" +
4058                           explainPredicates(Src) + ")");
4059     }
4060   }
4061 
4062   bool IsAtomic = false;
4063   if (SrcGIEquivOrNull && SrcGIEquivOrNull->getValueAsBit("CheckMMOIsNonAtomic"))
4064     InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>("NotAtomic");
4065   else if (SrcGIEquivOrNull && SrcGIEquivOrNull->getValueAsBit("CheckMMOIsAtomic")) {
4066     IsAtomic = true;
4067     InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
4068       "Unordered", AtomicOrderingMMOPredicateMatcher::AO_OrStronger);
4069   }
4070 
4071   if (Src->isLeaf()) {
4072     Init *SrcInit = Src->getLeafValue();
4073     if (IntInit *SrcIntInit = dyn_cast<IntInit>(SrcInit)) {
4074       OperandMatcher &OM =
4075           InsnMatcher.addOperand(OpIdx++, Src->getName(), TempOpIdx);
4076       OM.addPredicate<LiteralIntOperandMatcher>(SrcIntInit->getValue());
4077     } else
4078       return failedImport(
4079           "Unable to deduce gMIR opcode to handle Src (which is a leaf)");
4080   } else {
4081     assert(SrcGIOrNull &&
4082            "Expected to have already found an equivalent Instruction");
4083     if (SrcGIOrNull->TheDef->getName() == "G_CONSTANT" ||
4084         SrcGIOrNull->TheDef->getName() == "G_FCONSTANT") {
4085       // imm/fpimm still have operands but we don't need to do anything with it
4086       // here since we don't support ImmLeaf predicates yet. However, we still
4087       // need to note the hidden operand to get GIM_CheckNumOperands correct.
4088       InsnMatcher.addOperand(OpIdx++, "", TempOpIdx);
4089       return InsnMatcher;
4090     }
4091 
4092     // Special case because the operand order is changed from setcc. The
4093     // predicate operand needs to be swapped from the last operand to the first
4094     // source.
4095 
4096     unsigned NumChildren = Src->getNumChildren();
4097     bool IsFCmp = SrcGIOrNull->TheDef->getName() == "G_FCMP";
4098 
4099     if (IsFCmp || SrcGIOrNull->TheDef->getName() == "G_ICMP") {
4100       TreePatternNode *SrcChild = Src->getChild(NumChildren - 1);
4101       if (SrcChild->isLeaf()) {
4102         DefInit *DI = dyn_cast<DefInit>(SrcChild->getLeafValue());
4103         Record *CCDef = DI ? DI->getDef() : nullptr;
4104         if (!CCDef || !CCDef->isSubClassOf("CondCode"))
4105           return failedImport("Unable to handle CondCode");
4106 
4107         OperandMatcher &OM =
4108           InsnMatcher.addOperand(OpIdx++, SrcChild->getName(), TempOpIdx);
4109         StringRef PredType = IsFCmp ? CCDef->getValueAsString("FCmpPredicate") :
4110                                       CCDef->getValueAsString("ICmpPredicate");
4111 
4112         if (!PredType.empty()) {
4113           OM.addPredicate<CmpPredicateOperandMatcher>(std::string(PredType));
4114           // Process the other 2 operands normally.
4115           --NumChildren;
4116         }
4117       }
4118     }
4119 
4120     // Hack around an unfortunate mistake in how atomic store (and really
4121     // atomicrmw in general) operands were ordered. A ISD::STORE used the order
4122     // <stored value>, <pointer> order. ISD::ATOMIC_STORE used the opposite,
4123     // <pointer>, <stored value>. In GlobalISel there's just the one store
4124     // opcode, so we need to swap the operands here to get the right type check.
4125     if (IsAtomic && SrcGIOrNull->TheDef->getName() == "G_STORE") {
4126       assert(NumChildren == 2 && "wrong operands for atomic store");
4127 
4128       TreePatternNode *PtrChild = Src->getChild(0);
4129       TreePatternNode *ValueChild = Src->getChild(1);
4130 
4131       if (auto Error = importChildMatcher(Rule, InsnMatcher, PtrChild, true,
4132                                           false, 1, TempOpIdx))
4133         return std::move(Error);
4134 
4135       if (auto Error = importChildMatcher(Rule, InsnMatcher, ValueChild, false,
4136                                           false, 0, TempOpIdx))
4137         return std::move(Error);
4138       return InsnMatcher;
4139     }
4140 
4141     // Match the used operands (i.e. the children of the operator).
4142     bool IsIntrinsic =
4143         SrcGIOrNull->TheDef->getName() == "G_INTRINSIC" ||
4144         SrcGIOrNull->TheDef->getName() == "G_INTRINSIC_W_SIDE_EFFECTS";
4145     const CodeGenIntrinsic *II = Src->getIntrinsicInfo(CGP);
4146     if (IsIntrinsic && !II)
4147       return failedImport("Expected IntInit containing intrinsic ID)");
4148 
4149     for (unsigned i = 0; i != NumChildren; ++i) {
4150       TreePatternNode *SrcChild = Src->getChild(i);
4151 
4152       // We need to determine the meaning of a literal integer based on the
4153       // context. If this is a field required to be an immediate (such as an
4154       // immarg intrinsic argument), the required predicates are different than
4155       // a constant which may be materialized in a register. If we have an
4156       // argument that is required to be an immediate, we should not emit an LLT
4157       // type check, and should not be looking for a G_CONSTANT defined
4158       // register.
4159       bool OperandIsImmArg = SrcGIOrNull->isOperandImmArg(i);
4160 
4161       // SelectionDAG allows pointers to be represented with iN since it doesn't
4162       // distinguish between pointers and integers but they are different types in GlobalISel.
4163       // Coerce integers to pointers to address space 0 if the context indicates a pointer.
4164       //
4165       bool OperandIsAPointer = SrcGIOrNull->isOperandAPointer(i);
4166 
4167       if (IsIntrinsic) {
4168         // For G_INTRINSIC/G_INTRINSIC_W_SIDE_EFFECTS, the operand immediately
4169         // following the defs is an intrinsic ID.
4170         if (i == 0) {
4171           OperandMatcher &OM =
4172               InsnMatcher.addOperand(OpIdx++, SrcChild->getName(), TempOpIdx);
4173           OM.addPredicate<IntrinsicIDOperandMatcher>(II);
4174           continue;
4175         }
4176 
4177         // We have to check intrinsics for llvm_anyptr_ty and immarg parameters.
4178         //
4179         // Note that we have to look at the i-1th parameter, because we don't
4180         // have the intrinsic ID in the intrinsic's parameter list.
4181         OperandIsAPointer |= II->isParamAPointer(i - 1);
4182         OperandIsImmArg |= II->isParamImmArg(i - 1);
4183       }
4184 
4185       if (auto Error =
4186               importChildMatcher(Rule, InsnMatcher, SrcChild, OperandIsAPointer,
4187                                  OperandIsImmArg, OpIdx++, TempOpIdx))
4188         return std::move(Error);
4189     }
4190   }
4191 
4192   return InsnMatcher;
4193 }
4194 
4195 Error GlobalISelEmitter::importComplexPatternOperandMatcher(
4196     OperandMatcher &OM, Record *R, unsigned &TempOpIdx) const {
4197   const auto &ComplexPattern = ComplexPatternEquivs.find(R);
4198   if (ComplexPattern == ComplexPatternEquivs.end())
4199     return failedImport("SelectionDAG ComplexPattern (" + R->getName() +
4200                         ") not mapped to GlobalISel");
4201 
4202   OM.addPredicate<ComplexPatternOperandMatcher>(OM, *ComplexPattern->second);
4203   TempOpIdx++;
4204   return Error::success();
4205 }
4206 
4207 // Get the name to use for a pattern operand. For an anonymous physical register
4208 // input, this should use the register name.
4209 static StringRef getSrcChildName(const TreePatternNode *SrcChild,
4210                                  Record *&PhysReg) {
4211   StringRef SrcChildName = SrcChild->getName();
4212   if (SrcChildName.empty() && SrcChild->isLeaf()) {
4213     if (auto *ChildDefInit = dyn_cast<DefInit>(SrcChild->getLeafValue())) {
4214       auto *ChildRec = ChildDefInit->getDef();
4215       if (ChildRec->isSubClassOf("Register")) {
4216         SrcChildName = ChildRec->getName();
4217         PhysReg = ChildRec;
4218       }
4219     }
4220   }
4221 
4222   return SrcChildName;
4223 }
4224 
4225 Error GlobalISelEmitter::importChildMatcher(
4226     RuleMatcher &Rule, InstructionMatcher &InsnMatcher,
4227     const TreePatternNode *SrcChild, bool OperandIsAPointer,
4228     bool OperandIsImmArg, unsigned OpIdx, unsigned &TempOpIdx) {
4229 
4230   Record *PhysReg = nullptr;
4231   std::string SrcChildName = std::string(getSrcChildName(SrcChild, PhysReg));
4232   if (!SrcChild->isLeaf() &&
4233       SrcChild->getOperator()->isSubClassOf("ComplexPattern")) {
4234     // The "name" of a non-leaf complex pattern (MY_PAT $op1, $op2) is
4235     // "MY_PAT:op1:op2" and the ones with same "name" represent same operand.
4236     std::string PatternName = std::string(SrcChild->getOperator()->getName());
4237     for (unsigned i = 0; i < SrcChild->getNumChildren(); ++i) {
4238       PatternName += ":";
4239       PatternName += SrcChild->getChild(i)->getName();
4240     }
4241     SrcChildName = PatternName;
4242   }
4243 
4244   OperandMatcher &OM =
4245       PhysReg ? InsnMatcher.addPhysRegInput(PhysReg, OpIdx, TempOpIdx)
4246               : InsnMatcher.addOperand(OpIdx, SrcChildName, TempOpIdx);
4247   if (OM.isSameAsAnotherOperand())
4248     return Error::success();
4249 
4250   ArrayRef<TypeSetByHwMode> ChildTypes = SrcChild->getExtTypes();
4251   if (ChildTypes.size() != 1)
4252     return failedImport("Src pattern child has multiple results");
4253 
4254   // Check MBB's before the type check since they are not a known type.
4255   if (!SrcChild->isLeaf()) {
4256     if (SrcChild->getOperator()->isSubClassOf("SDNode")) {
4257       auto &ChildSDNI = CGP.getSDNodeInfo(SrcChild->getOperator());
4258       if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") {
4259         OM.addPredicate<MBBOperandMatcher>();
4260         return Error::success();
4261       }
4262       if (SrcChild->getOperator()->getName() == "timm") {
4263         OM.addPredicate<ImmOperandMatcher>();
4264 
4265         // Add predicates, if any
4266         for (const TreePredicateCall &Call : SrcChild->getPredicateCalls()) {
4267           const TreePredicateFn &Predicate = Call.Fn;
4268 
4269           // Only handle immediate patterns for now
4270           if (Predicate.isImmediatePattern()) {
4271             OM.addPredicate<OperandImmPredicateMatcher>(Predicate);
4272           }
4273         }
4274 
4275         return Error::success();
4276       }
4277     }
4278   }
4279 
4280   // Immediate arguments have no meaningful type to check as they don't have
4281   // registers.
4282   if (!OperandIsImmArg) {
4283     if (auto Error =
4284             OM.addTypeCheckPredicate(ChildTypes.front(), OperandIsAPointer))
4285       return failedImport(toString(std::move(Error)) + " for Src operand (" +
4286                           to_string(*SrcChild) + ")");
4287   }
4288 
4289   // Check for nested instructions.
4290   if (!SrcChild->isLeaf()) {
4291     if (SrcChild->getOperator()->isSubClassOf("ComplexPattern")) {
4292       // When a ComplexPattern is used as an operator, it should do the same
4293       // thing as when used as a leaf. However, the children of the operator
4294       // name the sub-operands that make up the complex operand and we must
4295       // prepare to reference them in the renderer too.
4296       unsigned RendererID = TempOpIdx;
4297       if (auto Error = importComplexPatternOperandMatcher(
4298               OM, SrcChild->getOperator(), TempOpIdx))
4299         return Error;
4300 
4301       for (unsigned i = 0, e = SrcChild->getNumChildren(); i != e; ++i) {
4302         auto *SubOperand = SrcChild->getChild(i);
4303         if (!SubOperand->getName().empty()) {
4304           if (auto Error = Rule.defineComplexSubOperand(
4305                   SubOperand->getName(), SrcChild->getOperator(), RendererID, i,
4306                   SrcChildName))
4307             return Error;
4308         }
4309       }
4310 
4311       return Error::success();
4312     }
4313 
4314     auto MaybeInsnOperand = OM.addPredicate<InstructionOperandMatcher>(
4315         InsnMatcher.getRuleMatcher(), SrcChild->getName());
4316     if (!MaybeInsnOperand) {
4317       // This isn't strictly true. If the user were to provide exactly the same
4318       // matchers as the original operand then we could allow it. However, it's
4319       // simpler to not permit the redundant specification.
4320       return failedImport("Nested instruction cannot be the same as another operand");
4321     }
4322 
4323     // Map the node to a gMIR instruction.
4324     InstructionOperandMatcher &InsnOperand = **MaybeInsnOperand;
4325     auto InsnMatcherOrError = createAndImportSelDAGMatcher(
4326         Rule, InsnOperand.getInsnMatcher(), SrcChild, TempOpIdx);
4327     if (auto Error = InsnMatcherOrError.takeError())
4328       return Error;
4329 
4330     return Error::success();
4331   }
4332 
4333   if (SrcChild->hasAnyPredicate())
4334     return failedImport("Src pattern child has unsupported predicate");
4335 
4336   // Check for constant immediates.
4337   if (auto *ChildInt = dyn_cast<IntInit>(SrcChild->getLeafValue())) {
4338     if (OperandIsImmArg) {
4339       // Checks for argument directly in operand list
4340       OM.addPredicate<LiteralIntOperandMatcher>(ChildInt->getValue());
4341     } else {
4342       // Checks for materialized constant
4343       OM.addPredicate<ConstantIntOperandMatcher>(ChildInt->getValue());
4344     }
4345     return Error::success();
4346   }
4347 
4348   // Check for def's like register classes or ComplexPattern's.
4349   if (auto *ChildDefInit = dyn_cast<DefInit>(SrcChild->getLeafValue())) {
4350     auto *ChildRec = ChildDefInit->getDef();
4351 
4352     if (WaitingForNamedOperands) {
4353       auto PA = SrcChild->getNamesAsPredicateArg().begin();
4354       std::string Name = getScopedName(PA->getScope(), PA->getIdentifier());
4355       OM.addPredicate<RecordNamedOperandMatcher>(StoreIdxForName[Name], Name);
4356       --WaitingForNamedOperands;
4357     }
4358 
4359     // Check for register classes.
4360     if (ChildRec->isSubClassOf("RegisterClass") ||
4361         ChildRec->isSubClassOf("RegisterOperand")) {
4362       OM.addPredicate<RegisterBankOperandMatcher>(
4363           Target.getRegisterClass(getInitValueAsRegClass(ChildDefInit)));
4364       return Error::success();
4365     }
4366 
4367     if (ChildRec->isSubClassOf("Register")) {
4368       // This just be emitted as a copy to the specific register.
4369       ValueTypeByHwMode VT = ChildTypes.front().getValueTypeByHwMode();
4370       const CodeGenRegisterClass *RC
4371         = CGRegs.getMinimalPhysRegClass(ChildRec, &VT);
4372       if (!RC) {
4373         return failedImport(
4374           "Could not determine physical register class of pattern source");
4375       }
4376 
4377       OM.addPredicate<RegisterBankOperandMatcher>(*RC);
4378       return Error::success();
4379     }
4380 
4381     // Check for ValueType.
4382     if (ChildRec->isSubClassOf("ValueType")) {
4383       // We already added a type check as standard practice so this doesn't need
4384       // to do anything.
4385       return Error::success();
4386     }
4387 
4388     // Check for ComplexPattern's.
4389     if (ChildRec->isSubClassOf("ComplexPattern"))
4390       return importComplexPatternOperandMatcher(OM, ChildRec, TempOpIdx);
4391 
4392     if (ChildRec->isSubClassOf("ImmLeaf")) {
4393       return failedImport(
4394           "Src pattern child def is an unsupported tablegen class (ImmLeaf)");
4395     }
4396 
4397     // Place holder for SRCVALUE nodes. Nothing to do here.
4398     if (ChildRec->getName() == "srcvalue")
4399       return Error::success();
4400 
4401     const bool ImmAllOnesV = ChildRec->getName() == "immAllOnesV";
4402     if (ImmAllOnesV || ChildRec->getName() == "immAllZerosV") {
4403       auto MaybeInsnOperand = OM.addPredicate<InstructionOperandMatcher>(
4404           InsnMatcher.getRuleMatcher(), SrcChild->getName(), false);
4405       InstructionOperandMatcher &InsnOperand = **MaybeInsnOperand;
4406 
4407       ValueTypeByHwMode VTy = ChildTypes.front().getValueTypeByHwMode();
4408 
4409       const CodeGenInstruction &BuildVector
4410         = Target.getInstruction(RK.getDef("G_BUILD_VECTOR"));
4411       const CodeGenInstruction &BuildVectorTrunc
4412         = Target.getInstruction(RK.getDef("G_BUILD_VECTOR_TRUNC"));
4413 
4414       // Treat G_BUILD_VECTOR as the canonical opcode, and G_BUILD_VECTOR_TRUNC
4415       // as an alternative.
4416       InsnOperand.getInsnMatcher().addPredicate<InstructionOpcodeMatcher>(
4417       makeArrayRef({&BuildVector, &BuildVectorTrunc}));
4418 
4419       // TODO: Handle both G_BUILD_VECTOR and G_BUILD_VECTOR_TRUNC We could
4420       // theoretically not emit any opcode check, but getOpcodeMatcher currently
4421       // has to succeed.
4422       OperandMatcher &OM =
4423           InsnOperand.getInsnMatcher().addOperand(0, "", TempOpIdx);
4424       if (auto Error =
4425               OM.addTypeCheckPredicate(VTy, false /* OperandIsAPointer */))
4426         return failedImport(toString(std::move(Error)) +
4427                             " for result of Src pattern operator");
4428 
4429       InsnOperand.getInsnMatcher().addPredicate<VectorSplatImmPredicateMatcher>(
4430           ImmAllOnesV ? VectorSplatImmPredicateMatcher::AllOnes
4431                       : VectorSplatImmPredicateMatcher::AllZeros);
4432       return Error::success();
4433     }
4434 
4435     return failedImport(
4436         "Src pattern child def is an unsupported tablegen class");
4437   }
4438 
4439   return failedImport("Src pattern child is an unsupported kind");
4440 }
4441 
4442 Expected<action_iterator> GlobalISelEmitter::importExplicitUseRenderer(
4443     action_iterator InsertPt, RuleMatcher &Rule, BuildMIAction &DstMIBuilder,
4444     TreePatternNode *DstChild) {
4445 
4446   const auto &SubOperand = Rule.getComplexSubOperand(DstChild->getName());
4447   if (SubOperand) {
4448     DstMIBuilder.addRenderer<RenderComplexPatternOperand>(
4449         *std::get<0>(*SubOperand), DstChild->getName(),
4450         std::get<1>(*SubOperand), std::get<2>(*SubOperand));
4451     return InsertPt;
4452   }
4453 
4454   if (!DstChild->isLeaf()) {
4455     if (DstChild->getOperator()->isSubClassOf("SDNodeXForm")) {
4456       auto Child = DstChild->getChild(0);
4457       auto I = SDNodeXFormEquivs.find(DstChild->getOperator());
4458       if (I != SDNodeXFormEquivs.end()) {
4459         Record *XFormOpc = DstChild->getOperator()->getValueAsDef("Opcode");
4460         if (XFormOpc->getName() == "timm") {
4461           // If this is a TargetConstant, there won't be a corresponding
4462           // instruction to transform. Instead, this will refer directly to an
4463           // operand in an instruction's operand list.
4464           DstMIBuilder.addRenderer<CustomOperandRenderer>(*I->second,
4465                                                           Child->getName());
4466         } else {
4467           DstMIBuilder.addRenderer<CustomRenderer>(*I->second,
4468                                                    Child->getName());
4469         }
4470 
4471         return InsertPt;
4472       }
4473       return failedImport("SDNodeXForm " + Child->getName() +
4474                           " has no custom renderer");
4475     }
4476 
4477     // We accept 'bb' here. It's an operator because BasicBlockSDNode isn't
4478     // inline, but in MI it's just another operand.
4479     if (DstChild->getOperator()->isSubClassOf("SDNode")) {
4480       auto &ChildSDNI = CGP.getSDNodeInfo(DstChild->getOperator());
4481       if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") {
4482         DstMIBuilder.addRenderer<CopyRenderer>(DstChild->getName());
4483         return InsertPt;
4484       }
4485     }
4486 
4487     // Similarly, imm is an operator in TreePatternNode's view but must be
4488     // rendered as operands.
4489     // FIXME: The target should be able to choose sign-extended when appropriate
4490     //        (e.g. on Mips).
4491     if (DstChild->getOperator()->getName() == "timm") {
4492       DstMIBuilder.addRenderer<CopyRenderer>(DstChild->getName());
4493       return InsertPt;
4494     } else if (DstChild->getOperator()->getName() == "imm") {
4495       DstMIBuilder.addRenderer<CopyConstantAsImmRenderer>(DstChild->getName());
4496       return InsertPt;
4497     } else if (DstChild->getOperator()->getName() == "fpimm") {
4498       DstMIBuilder.addRenderer<CopyFConstantAsFPImmRenderer>(
4499           DstChild->getName());
4500       return InsertPt;
4501     }
4502 
4503     if (DstChild->getOperator()->isSubClassOf("Instruction")) {
4504       auto OpTy = getInstResultType(DstChild);
4505       if (!OpTy)
4506         return OpTy.takeError();
4507 
4508       unsigned TempRegID = Rule.allocateTempRegID();
4509       InsertPt = Rule.insertAction<MakeTempRegisterAction>(
4510           InsertPt, *OpTy, TempRegID);
4511       DstMIBuilder.addRenderer<TempRegRenderer>(TempRegID);
4512 
4513       auto InsertPtOrError = createAndImportSubInstructionRenderer(
4514           ++InsertPt, Rule, DstChild, TempRegID);
4515       if (auto Error = InsertPtOrError.takeError())
4516         return std::move(Error);
4517       return InsertPtOrError.get();
4518     }
4519 
4520     return failedImport("Dst pattern child isn't a leaf node or an MBB" + llvm::to_string(*DstChild));
4521   }
4522 
4523   // It could be a specific immediate in which case we should just check for
4524   // that immediate.
4525   if (const IntInit *ChildIntInit =
4526           dyn_cast<IntInit>(DstChild->getLeafValue())) {
4527     DstMIBuilder.addRenderer<ImmRenderer>(ChildIntInit->getValue());
4528     return InsertPt;
4529   }
4530 
4531   // Otherwise, we're looking for a bog-standard RegisterClass operand.
4532   if (auto *ChildDefInit = dyn_cast<DefInit>(DstChild->getLeafValue())) {
4533     auto *ChildRec = ChildDefInit->getDef();
4534 
4535     ArrayRef<TypeSetByHwMode> ChildTypes = DstChild->getExtTypes();
4536     if (ChildTypes.size() != 1)
4537       return failedImport("Dst pattern child has multiple results");
4538 
4539     Optional<LLTCodeGen> OpTyOrNone = None;
4540     if (ChildTypes.front().isMachineValueType())
4541       OpTyOrNone = MVTToLLT(ChildTypes.front().getMachineValueType().SimpleTy);
4542     if (!OpTyOrNone)
4543       return failedImport("Dst operand has an unsupported type");
4544 
4545     if (ChildRec->isSubClassOf("Register")) {
4546       DstMIBuilder.addRenderer<AddRegisterRenderer>(Target, ChildRec);
4547       return InsertPt;
4548     }
4549 
4550     if (ChildRec->isSubClassOf("RegisterClass") ||
4551         ChildRec->isSubClassOf("RegisterOperand") ||
4552         ChildRec->isSubClassOf("ValueType")) {
4553       if (ChildRec->isSubClassOf("RegisterOperand") &&
4554           !ChildRec->isValueUnset("GIZeroRegister")) {
4555         DstMIBuilder.addRenderer<CopyOrAddZeroRegRenderer>(
4556             DstChild->getName(), ChildRec->getValueAsDef("GIZeroRegister"));
4557         return InsertPt;
4558       }
4559 
4560       DstMIBuilder.addRenderer<CopyRenderer>(DstChild->getName());
4561       return InsertPt;
4562     }
4563 
4564     if (ChildRec->isSubClassOf("SubRegIndex")) {
4565       CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(ChildRec);
4566       DstMIBuilder.addRenderer<ImmRenderer>(SubIdx->EnumValue);
4567       return InsertPt;
4568     }
4569 
4570     if (ChildRec->isSubClassOf("ComplexPattern")) {
4571       const auto &ComplexPattern = ComplexPatternEquivs.find(ChildRec);
4572       if (ComplexPattern == ComplexPatternEquivs.end())
4573         return failedImport(
4574             "SelectionDAG ComplexPattern not mapped to GlobalISel");
4575 
4576       const OperandMatcher &OM = Rule.getOperandMatcher(DstChild->getName());
4577       DstMIBuilder.addRenderer<RenderComplexPatternOperand>(
4578           *ComplexPattern->second, DstChild->getName(),
4579           OM.getAllocatedTemporariesBaseID());
4580       return InsertPt;
4581     }
4582 
4583     return failedImport(
4584         "Dst pattern child def is an unsupported tablegen class");
4585   }
4586   return failedImport("Dst pattern child is an unsupported kind");
4587 }
4588 
4589 Expected<BuildMIAction &> GlobalISelEmitter::createAndImportInstructionRenderer(
4590     RuleMatcher &M, InstructionMatcher &InsnMatcher, const TreePatternNode *Src,
4591     const TreePatternNode *Dst) {
4592   auto InsertPtOrError = createInstructionRenderer(M.actions_end(), M, Dst);
4593   if (auto Error = InsertPtOrError.takeError())
4594     return std::move(Error);
4595 
4596   action_iterator InsertPt = InsertPtOrError.get();
4597   BuildMIAction &DstMIBuilder = *static_cast<BuildMIAction *>(InsertPt->get());
4598 
4599   for (auto PhysInput : InsnMatcher.getPhysRegInputs()) {
4600     InsertPt = M.insertAction<BuildMIAction>(
4601         InsertPt, M.allocateOutputInsnID(),
4602         &Target.getInstruction(RK.getDef("COPY")));
4603     BuildMIAction &CopyToPhysRegMIBuilder =
4604         *static_cast<BuildMIAction *>(InsertPt->get());
4605     CopyToPhysRegMIBuilder.addRenderer<AddRegisterRenderer>(Target,
4606                                                             PhysInput.first,
4607                                                             true);
4608     CopyToPhysRegMIBuilder.addRenderer<CopyPhysRegRenderer>(PhysInput.first);
4609   }
4610 
4611   if (auto Error = importExplicitDefRenderers(InsertPt, M, DstMIBuilder, Dst)
4612                        .takeError())
4613     return std::move(Error);
4614 
4615   if (auto Error = importExplicitUseRenderers(InsertPt, M, DstMIBuilder, Dst)
4616                        .takeError())
4617     return std::move(Error);
4618 
4619   return DstMIBuilder;
4620 }
4621 
4622 Expected<action_iterator>
4623 GlobalISelEmitter::createAndImportSubInstructionRenderer(
4624     const action_iterator InsertPt, RuleMatcher &M, const TreePatternNode *Dst,
4625     unsigned TempRegID) {
4626   auto InsertPtOrError = createInstructionRenderer(InsertPt, M, Dst);
4627 
4628   // TODO: Assert there's exactly one result.
4629 
4630   if (auto Error = InsertPtOrError.takeError())
4631     return std::move(Error);
4632 
4633   BuildMIAction &DstMIBuilder =
4634       *static_cast<BuildMIAction *>(InsertPtOrError.get()->get());
4635 
4636   // Assign the result to TempReg.
4637   DstMIBuilder.addRenderer<TempRegRenderer>(TempRegID, true);
4638 
4639   InsertPtOrError =
4640       importExplicitUseRenderers(InsertPtOrError.get(), M, DstMIBuilder, Dst);
4641   if (auto Error = InsertPtOrError.takeError())
4642     return std::move(Error);
4643 
4644   // We need to make sure that when we import an INSERT_SUBREG as a
4645   // subinstruction that it ends up being constrained to the correct super
4646   // register and subregister classes.
4647   auto OpName = Target.getInstruction(Dst->getOperator()).TheDef->getName();
4648   if (OpName == "INSERT_SUBREG") {
4649     auto SubClass = inferRegClassFromPattern(Dst->getChild(1));
4650     if (!SubClass)
4651       return failedImport(
4652           "Cannot infer register class from INSERT_SUBREG operand #1");
4653     Optional<const CodeGenRegisterClass *> SuperClass =
4654         inferSuperRegisterClassForNode(Dst->getExtType(0), Dst->getChild(0),
4655                                        Dst->getChild(2));
4656     if (!SuperClass)
4657       return failedImport(
4658           "Cannot infer register class for INSERT_SUBREG operand #0");
4659     // The destination and the super register source of an INSERT_SUBREG must
4660     // be the same register class.
4661     M.insertAction<ConstrainOperandToRegClassAction>(
4662         InsertPt, DstMIBuilder.getInsnID(), 0, **SuperClass);
4663     M.insertAction<ConstrainOperandToRegClassAction>(
4664         InsertPt, DstMIBuilder.getInsnID(), 1, **SuperClass);
4665     M.insertAction<ConstrainOperandToRegClassAction>(
4666         InsertPt, DstMIBuilder.getInsnID(), 2, **SubClass);
4667     return InsertPtOrError.get();
4668   }
4669 
4670   if (OpName == "EXTRACT_SUBREG") {
4671     // EXTRACT_SUBREG selects into a subregister COPY but unlike most
4672     // instructions, the result register class is controlled by the
4673     // subregisters of the operand. As a result, we must constrain the result
4674     // class rather than check that it's already the right one.
4675     auto SuperClass = inferRegClassFromPattern(Dst->getChild(0));
4676     if (!SuperClass)
4677       return failedImport(
4678         "Cannot infer register class from EXTRACT_SUBREG operand #0");
4679 
4680     auto SubIdx = inferSubRegIndexForNode(Dst->getChild(1));
4681     if (!SubIdx)
4682       return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
4683 
4684     const auto SrcRCDstRCPair =
4685       (*SuperClass)->getMatchingSubClassWithSubRegs(CGRegs, *SubIdx);
4686     assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
4687     M.insertAction<ConstrainOperandToRegClassAction>(
4688       InsertPt, DstMIBuilder.getInsnID(), 0, *SrcRCDstRCPair->second);
4689     M.insertAction<ConstrainOperandToRegClassAction>(
4690       InsertPt, DstMIBuilder.getInsnID(), 1, *SrcRCDstRCPair->first);
4691 
4692     // We're done with this pattern!  It's eligible for GISel emission; return
4693     // it.
4694     return InsertPtOrError.get();
4695   }
4696 
4697   // Similar to INSERT_SUBREG, we also have to handle SUBREG_TO_REG as a
4698   // subinstruction.
4699   if (OpName == "SUBREG_TO_REG") {
4700     auto SubClass = inferRegClassFromPattern(Dst->getChild(1));
4701     if (!SubClass)
4702       return failedImport(
4703         "Cannot infer register class from SUBREG_TO_REG child #1");
4704     auto SuperClass = inferSuperRegisterClass(Dst->getExtType(0),
4705                                               Dst->getChild(2));
4706     if (!SuperClass)
4707       return failedImport(
4708         "Cannot infer register class for SUBREG_TO_REG operand #0");
4709     M.insertAction<ConstrainOperandToRegClassAction>(
4710       InsertPt, DstMIBuilder.getInsnID(), 0, **SuperClass);
4711     M.insertAction<ConstrainOperandToRegClassAction>(
4712       InsertPt, DstMIBuilder.getInsnID(), 2, **SubClass);
4713     return InsertPtOrError.get();
4714   }
4715 
4716   if (OpName == "REG_SEQUENCE") {
4717     auto SuperClass = inferRegClassFromPattern(Dst->getChild(0));
4718     M.insertAction<ConstrainOperandToRegClassAction>(
4719       InsertPt, DstMIBuilder.getInsnID(), 0, **SuperClass);
4720 
4721     unsigned Num = Dst->getNumChildren();
4722     for (unsigned I = 1; I != Num; I += 2) {
4723       TreePatternNode *SubRegChild = Dst->getChild(I + 1);
4724 
4725       auto SubIdx = inferSubRegIndexForNode(SubRegChild);
4726       if (!SubIdx)
4727         return failedImport("REG_SEQUENCE child is not a subreg index");
4728 
4729       const auto SrcRCDstRCPair =
4730         (*SuperClass)->getMatchingSubClassWithSubRegs(CGRegs, *SubIdx);
4731       assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
4732       M.insertAction<ConstrainOperandToRegClassAction>(
4733         InsertPt, DstMIBuilder.getInsnID(), I, *SrcRCDstRCPair->second);
4734     }
4735 
4736     return InsertPtOrError.get();
4737   }
4738 
4739   M.insertAction<ConstrainOperandsToDefinitionAction>(InsertPt,
4740                                                       DstMIBuilder.getInsnID());
4741   return InsertPtOrError.get();
4742 }
4743 
4744 Expected<action_iterator> GlobalISelEmitter::createInstructionRenderer(
4745     action_iterator InsertPt, RuleMatcher &M, const TreePatternNode *Dst) {
4746   Record *DstOp = Dst->getOperator();
4747   if (!DstOp->isSubClassOf("Instruction")) {
4748     if (DstOp->isSubClassOf("ValueType"))
4749       return failedImport(
4750           "Pattern operator isn't an instruction (it's a ValueType)");
4751     return failedImport("Pattern operator isn't an instruction");
4752   }
4753   CodeGenInstruction *DstI = &Target.getInstruction(DstOp);
4754 
4755   // COPY_TO_REGCLASS is just a copy with a ConstrainOperandToRegClassAction
4756   // attached. Similarly for EXTRACT_SUBREG except that's a subregister copy.
4757   StringRef Name = DstI->TheDef->getName();
4758   if (Name == "COPY_TO_REGCLASS" || Name == "EXTRACT_SUBREG")
4759     DstI = &Target.getInstruction(RK.getDef("COPY"));
4760 
4761   return M.insertAction<BuildMIAction>(InsertPt, M.allocateOutputInsnID(),
4762                                        DstI);
4763 }
4764 
4765 Expected<action_iterator> GlobalISelEmitter::importExplicitDefRenderers(
4766     action_iterator InsertPt, RuleMatcher &M, BuildMIAction &DstMIBuilder,
4767     const TreePatternNode *Dst) {
4768   const CodeGenInstruction *DstI = DstMIBuilder.getCGI();
4769   const unsigned NumDefs = DstI->Operands.NumDefs;
4770   if (NumDefs == 0)
4771     return InsertPt;
4772 
4773   DstMIBuilder.addRenderer<CopyRenderer>(DstI->Operands[0].Name);
4774 
4775   // Some instructions have multiple defs, but are missing a type entry
4776   // (e.g. s_cc_out operands).
4777   if (Dst->getExtTypes().size() < NumDefs)
4778     return failedImport("unhandled discarded def");
4779 
4780   // Patterns only handle a single result, so any result after the first is an
4781   // implicitly dead def.
4782   for (unsigned I = 1; I < NumDefs; ++I) {
4783     const TypeSetByHwMode &ExtTy = Dst->getExtType(I);
4784     if (!ExtTy.isMachineValueType())
4785       return failedImport("unsupported typeset");
4786 
4787     auto OpTy = MVTToLLT(ExtTy.getMachineValueType().SimpleTy);
4788     if (!OpTy)
4789       return failedImport("unsupported type");
4790 
4791     unsigned TempRegID = M.allocateTempRegID();
4792     InsertPt =
4793       M.insertAction<MakeTempRegisterAction>(InsertPt, *OpTy, TempRegID);
4794     DstMIBuilder.addRenderer<TempRegRenderer>(TempRegID, true, nullptr, true);
4795   }
4796 
4797   return InsertPt;
4798 }
4799 
4800 Expected<action_iterator> GlobalISelEmitter::importExplicitUseRenderers(
4801     action_iterator InsertPt, RuleMatcher &M, BuildMIAction &DstMIBuilder,
4802     const llvm::TreePatternNode *Dst) {
4803   const CodeGenInstruction *DstI = DstMIBuilder.getCGI();
4804   CodeGenInstruction *OrigDstI = &Target.getInstruction(Dst->getOperator());
4805 
4806   StringRef Name = OrigDstI->TheDef->getName();
4807   unsigned ExpectedDstINumUses = Dst->getNumChildren();
4808 
4809   // EXTRACT_SUBREG needs to use a subregister COPY.
4810   if (Name == "EXTRACT_SUBREG") {
4811     if (!Dst->getChild(1)->isLeaf())
4812       return failedImport("EXTRACT_SUBREG child #1 is not a leaf");
4813     DefInit *SubRegInit = dyn_cast<DefInit>(Dst->getChild(1)->getLeafValue());
4814     if (!SubRegInit)
4815       return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
4816 
4817     CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef());
4818     TreePatternNode *ValChild = Dst->getChild(0);
4819     if (!ValChild->isLeaf()) {
4820       // We really have to handle the source instruction, and then insert a
4821       // copy from the subregister.
4822       auto ExtractSrcTy = getInstResultType(ValChild);
4823       if (!ExtractSrcTy)
4824         return ExtractSrcTy.takeError();
4825 
4826       unsigned TempRegID = M.allocateTempRegID();
4827       InsertPt = M.insertAction<MakeTempRegisterAction>(
4828         InsertPt, *ExtractSrcTy, TempRegID);
4829 
4830       auto InsertPtOrError = createAndImportSubInstructionRenderer(
4831         ++InsertPt, M, ValChild, TempRegID);
4832       if (auto Error = InsertPtOrError.takeError())
4833         return std::move(Error);
4834 
4835       DstMIBuilder.addRenderer<TempRegRenderer>(TempRegID, false, SubIdx);
4836       return InsertPt;
4837     }
4838 
4839     // If this is a source operand, this is just a subregister copy.
4840     Record *RCDef = getInitValueAsRegClass(ValChild->getLeafValue());
4841     if (!RCDef)
4842       return failedImport("EXTRACT_SUBREG child #0 could not "
4843                           "be coerced to a register class");
4844 
4845     CodeGenRegisterClass *RC = CGRegs.getRegClass(RCDef);
4846 
4847     const auto SrcRCDstRCPair =
4848       RC->getMatchingSubClassWithSubRegs(CGRegs, SubIdx);
4849     if (SrcRCDstRCPair) {
4850       assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
4851       if (SrcRCDstRCPair->first != RC)
4852         return failedImport("EXTRACT_SUBREG requires an additional COPY");
4853     }
4854 
4855     DstMIBuilder.addRenderer<CopySubRegRenderer>(Dst->getChild(0)->getName(),
4856                                                  SubIdx);
4857     return InsertPt;
4858   }
4859 
4860   if (Name == "REG_SEQUENCE") {
4861     if (!Dst->getChild(0)->isLeaf())
4862       return failedImport("REG_SEQUENCE child #0 is not a leaf");
4863 
4864     Record *RCDef = getInitValueAsRegClass(Dst->getChild(0)->getLeafValue());
4865     if (!RCDef)
4866       return failedImport("REG_SEQUENCE child #0 could not "
4867                           "be coerced to a register class");
4868 
4869     if ((ExpectedDstINumUses - 1) % 2 != 0)
4870       return failedImport("Malformed REG_SEQUENCE");
4871 
4872     for (unsigned I = 1; I != ExpectedDstINumUses; I += 2) {
4873       TreePatternNode *ValChild = Dst->getChild(I);
4874       TreePatternNode *SubRegChild = Dst->getChild(I + 1);
4875 
4876       if (DefInit *SubRegInit =
4877               dyn_cast<DefInit>(SubRegChild->getLeafValue())) {
4878         CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef());
4879 
4880         auto InsertPtOrError =
4881             importExplicitUseRenderer(InsertPt, M, DstMIBuilder, ValChild);
4882         if (auto Error = InsertPtOrError.takeError())
4883           return std::move(Error);
4884         InsertPt = InsertPtOrError.get();
4885         DstMIBuilder.addRenderer<SubRegIndexRenderer>(SubIdx);
4886       }
4887     }
4888 
4889     return InsertPt;
4890   }
4891 
4892   // Render the explicit uses.
4893   unsigned DstINumUses = OrigDstI->Operands.size() - OrigDstI->Operands.NumDefs;
4894   if (Name == "COPY_TO_REGCLASS") {
4895     DstINumUses--; // Ignore the class constraint.
4896     ExpectedDstINumUses--;
4897   }
4898 
4899   // NumResults - This is the number of results produced by the instruction in
4900   // the "outs" list.
4901   unsigned NumResults = OrigDstI->Operands.NumDefs;
4902 
4903   // Number of operands we know the output instruction must have. If it is
4904   // variadic, we could have more operands.
4905   unsigned NumFixedOperands = DstI->Operands.size();
4906 
4907   // Loop over all of the fixed operands of the instruction pattern, emitting
4908   // code to fill them all in. The node 'N' usually has number children equal to
4909   // the number of input operands of the instruction.  However, in cases where
4910   // there are predicate operands for an instruction, we need to fill in the
4911   // 'execute always' values. Match up the node operands to the instruction
4912   // operands to do this.
4913   unsigned Child = 0;
4914 
4915   // Similarly to the code in TreePatternNode::ApplyTypeConstraints, count the
4916   // number of operands at the end of the list which have default values.
4917   // Those can come from the pattern if it provides enough arguments, or be
4918   // filled in with the default if the pattern hasn't provided them. But any
4919   // operand with a default value _before_ the last mandatory one will be
4920   // filled in with their defaults unconditionally.
4921   unsigned NonOverridableOperands = NumFixedOperands;
4922   while (NonOverridableOperands > NumResults &&
4923          CGP.operandHasDefault(DstI->Operands[NonOverridableOperands - 1].Rec))
4924     --NonOverridableOperands;
4925 
4926   unsigned NumDefaultOps = 0;
4927   for (unsigned I = 0; I != DstINumUses; ++I) {
4928     unsigned InstOpNo = DstI->Operands.NumDefs + I;
4929 
4930     // Determine what to emit for this operand.
4931     Record *OperandNode = DstI->Operands[InstOpNo].Rec;
4932 
4933     // If the operand has default values, introduce them now.
4934     if (CGP.operandHasDefault(OperandNode) &&
4935         (InstOpNo < NonOverridableOperands || Child >= Dst->getNumChildren())) {
4936       // This is a predicate or optional def operand which the pattern has not
4937       // overridden, or which we aren't letting it override; emit the 'default
4938       // ops' operands.
4939 
4940       const CGIOperandList::OperandInfo &DstIOperand = DstI->Operands[InstOpNo];
4941       DagInit *DefaultOps = DstIOperand.Rec->getValueAsDag("DefaultOps");
4942       if (auto Error = importDefaultOperandRenderers(
4943             InsertPt, M, DstMIBuilder, DefaultOps))
4944         return std::move(Error);
4945       ++NumDefaultOps;
4946       continue;
4947     }
4948 
4949     auto InsertPtOrError = importExplicitUseRenderer(InsertPt, M, DstMIBuilder,
4950                                                      Dst->getChild(Child));
4951     if (auto Error = InsertPtOrError.takeError())
4952       return std::move(Error);
4953     InsertPt = InsertPtOrError.get();
4954     ++Child;
4955   }
4956 
4957   if (NumDefaultOps + ExpectedDstINumUses != DstINumUses)
4958     return failedImport("Expected " + llvm::to_string(DstINumUses) +
4959                         " used operands but found " +
4960                         llvm::to_string(ExpectedDstINumUses) +
4961                         " explicit ones and " + llvm::to_string(NumDefaultOps) +
4962                         " default ones");
4963 
4964   return InsertPt;
4965 }
4966 
4967 Error GlobalISelEmitter::importDefaultOperandRenderers(
4968     action_iterator InsertPt, RuleMatcher &M, BuildMIAction &DstMIBuilder,
4969     DagInit *DefaultOps) const {
4970   for (const auto *DefaultOp : DefaultOps->getArgs()) {
4971     Optional<LLTCodeGen> OpTyOrNone = None;
4972 
4973     // Look through ValueType operators.
4974     if (const DagInit *DefaultDagOp = dyn_cast<DagInit>(DefaultOp)) {
4975       if (const DefInit *DefaultDagOperator =
4976               dyn_cast<DefInit>(DefaultDagOp->getOperator())) {
4977         if (DefaultDagOperator->getDef()->isSubClassOf("ValueType")) {
4978           OpTyOrNone = MVTToLLT(getValueType(
4979                                   DefaultDagOperator->getDef()));
4980           DefaultOp = DefaultDagOp->getArg(0);
4981         }
4982       }
4983     }
4984 
4985     if (const DefInit *DefaultDefOp = dyn_cast<DefInit>(DefaultOp)) {
4986       auto Def = DefaultDefOp->getDef();
4987       if (Def->getName() == "undef_tied_input") {
4988         unsigned TempRegID = M.allocateTempRegID();
4989         M.insertAction<MakeTempRegisterAction>(InsertPt, OpTyOrNone.value(),
4990                                                TempRegID);
4991         InsertPt = M.insertAction<BuildMIAction>(
4992           InsertPt, M.allocateOutputInsnID(),
4993           &Target.getInstruction(RK.getDef("IMPLICIT_DEF")));
4994         BuildMIAction &IDMIBuilder = *static_cast<BuildMIAction *>(
4995           InsertPt->get());
4996         IDMIBuilder.addRenderer<TempRegRenderer>(TempRegID);
4997         DstMIBuilder.addRenderer<TempRegRenderer>(TempRegID);
4998       } else {
4999         DstMIBuilder.addRenderer<AddRegisterRenderer>(Target, Def);
5000       }
5001       continue;
5002     }
5003 
5004     if (const IntInit *DefaultIntOp = dyn_cast<IntInit>(DefaultOp)) {
5005       DstMIBuilder.addRenderer<ImmRenderer>(DefaultIntOp->getValue());
5006       continue;
5007     }
5008 
5009     return failedImport("Could not add default op");
5010   }
5011 
5012   return Error::success();
5013 }
5014 
5015 Error GlobalISelEmitter::importImplicitDefRenderers(
5016     BuildMIAction &DstMIBuilder,
5017     const std::vector<Record *> &ImplicitDefs) const {
5018   if (!ImplicitDefs.empty())
5019     return failedImport("Pattern defines a physical register");
5020   return Error::success();
5021 }
5022 
5023 Optional<const CodeGenRegisterClass *>
5024 GlobalISelEmitter::getRegClassFromLeaf(TreePatternNode *Leaf) {
5025   assert(Leaf && "Expected node?");
5026   assert(Leaf->isLeaf() && "Expected leaf?");
5027   Record *RCRec = getInitValueAsRegClass(Leaf->getLeafValue());
5028   if (!RCRec)
5029     return None;
5030   CodeGenRegisterClass *RC = CGRegs.getRegClass(RCRec);
5031   if (!RC)
5032     return None;
5033   return RC;
5034 }
5035 
5036 Optional<const CodeGenRegisterClass *>
5037 GlobalISelEmitter::inferRegClassFromPattern(TreePatternNode *N) {
5038   if (!N)
5039     return None;
5040 
5041   if (N->isLeaf())
5042     return getRegClassFromLeaf(N);
5043 
5044   // We don't have a leaf node, so we have to try and infer something. Check
5045   // that we have an instruction that we an infer something from.
5046 
5047   // Only handle things that produce a single type.
5048   if (N->getNumTypes() != 1)
5049     return None;
5050   Record *OpRec = N->getOperator();
5051 
5052   // We only want instructions.
5053   if (!OpRec->isSubClassOf("Instruction"))
5054     return None;
5055 
5056   // Don't want to try and infer things when there could potentially be more
5057   // than one candidate register class.
5058   auto &Inst = Target.getInstruction(OpRec);
5059   if (Inst.Operands.NumDefs > 1)
5060     return None;
5061 
5062   // Handle any special-case instructions which we can safely infer register
5063   // classes from.
5064   StringRef InstName = Inst.TheDef->getName();
5065   bool IsRegSequence = InstName == "REG_SEQUENCE";
5066   if (IsRegSequence || InstName == "COPY_TO_REGCLASS") {
5067     // If we have a COPY_TO_REGCLASS, then we need to handle it specially. It
5068     // has the desired register class as the first child.
5069     TreePatternNode *RCChild = N->getChild(IsRegSequence ? 0 : 1);
5070     if (!RCChild->isLeaf())
5071       return None;
5072     return getRegClassFromLeaf(RCChild);
5073   }
5074   if (InstName == "INSERT_SUBREG") {
5075     TreePatternNode *Child0 = N->getChild(0);
5076     assert(Child0->getNumTypes() == 1 && "Unexpected number of types!");
5077     const TypeSetByHwMode &VTy = Child0->getExtType(0);
5078     return inferSuperRegisterClassForNode(VTy, Child0, N->getChild(2));
5079   }
5080   if (InstName == "EXTRACT_SUBREG") {
5081     assert(N->getNumTypes() == 1 && "Unexpected number of types!");
5082     const TypeSetByHwMode &VTy = N->getExtType(0);
5083     return inferSuperRegisterClass(VTy, N->getChild(1));
5084   }
5085 
5086   // Handle destination record types that we can safely infer a register class
5087   // from.
5088   const auto &DstIOperand = Inst.Operands[0];
5089   Record *DstIOpRec = DstIOperand.Rec;
5090   if (DstIOpRec->isSubClassOf("RegisterOperand")) {
5091     DstIOpRec = DstIOpRec->getValueAsDef("RegClass");
5092     const CodeGenRegisterClass &RC = Target.getRegisterClass(DstIOpRec);
5093     return &RC;
5094   }
5095 
5096   if (DstIOpRec->isSubClassOf("RegisterClass")) {
5097     const CodeGenRegisterClass &RC = Target.getRegisterClass(DstIOpRec);
5098     return &RC;
5099   }
5100 
5101   return None;
5102 }
5103 
5104 Optional<const CodeGenRegisterClass *>
5105 GlobalISelEmitter::inferSuperRegisterClass(const TypeSetByHwMode &Ty,
5106                                            TreePatternNode *SubRegIdxNode) {
5107   assert(SubRegIdxNode && "Expected subregister index node!");
5108   // We need a ValueTypeByHwMode for getSuperRegForSubReg.
5109   if (!Ty.isValueTypeByHwMode(false))
5110     return None;
5111   if (!SubRegIdxNode->isLeaf())
5112     return None;
5113   DefInit *SubRegInit = dyn_cast<DefInit>(SubRegIdxNode->getLeafValue());
5114   if (!SubRegInit)
5115     return None;
5116   CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef());
5117 
5118   // Use the information we found above to find a minimal register class which
5119   // supports the subregister and type we want.
5120   auto RC =
5121       Target.getSuperRegForSubReg(Ty.getValueTypeByHwMode(), CGRegs, SubIdx,
5122                                   /* MustBeAllocatable */ true);
5123   if (!RC)
5124     return None;
5125   return *RC;
5126 }
5127 
5128 Optional<const CodeGenRegisterClass *>
5129 GlobalISelEmitter::inferSuperRegisterClassForNode(
5130     const TypeSetByHwMode &Ty, TreePatternNode *SuperRegNode,
5131     TreePatternNode *SubRegIdxNode) {
5132   assert(SuperRegNode && "Expected super register node!");
5133   // Check if we already have a defined register class for the super register
5134   // node. If we do, then we should preserve that rather than inferring anything
5135   // from the subregister index node. We can assume that whoever wrote the
5136   // pattern in the first place made sure that the super register and
5137   // subregister are compatible.
5138   if (Optional<const CodeGenRegisterClass *> SuperRegisterClass =
5139           inferRegClassFromPattern(SuperRegNode))
5140     return *SuperRegisterClass;
5141   return inferSuperRegisterClass(Ty, SubRegIdxNode);
5142 }
5143 
5144 Optional<CodeGenSubRegIndex *>
5145 GlobalISelEmitter::inferSubRegIndexForNode(TreePatternNode *SubRegIdxNode) {
5146   if (!SubRegIdxNode->isLeaf())
5147     return None;
5148 
5149   DefInit *SubRegInit = dyn_cast<DefInit>(SubRegIdxNode->getLeafValue());
5150   if (!SubRegInit)
5151     return None;
5152   return CGRegs.getSubRegIdx(SubRegInit->getDef());
5153 }
5154 
5155 Expected<RuleMatcher> GlobalISelEmitter::runOnPattern(const PatternToMatch &P) {
5156   // Keep track of the matchers and actions to emit.
5157   int Score = P.getPatternComplexity(CGP);
5158   RuleMatcher M(P.getSrcRecord()->getLoc());
5159   RuleMatcherScores[M.getRuleID()] = Score;
5160   M.addAction<DebugCommentAction>(llvm::to_string(*P.getSrcPattern()) +
5161                                   "  =>  " +
5162                                   llvm::to_string(*P.getDstPattern()));
5163 
5164   SmallVector<Record *, 4> Predicates;
5165   P.getPredicateRecords(Predicates);
5166   if (auto Error = importRulePredicates(M, Predicates))
5167     return std::move(Error);
5168 
5169   // Next, analyze the pattern operators.
5170   TreePatternNode *Src = P.getSrcPattern();
5171   TreePatternNode *Dst = P.getDstPattern();
5172 
5173   // If the root of either pattern isn't a simple operator, ignore it.
5174   if (auto Err = isTrivialOperatorNode(Dst))
5175     return failedImport("Dst pattern root isn't a trivial operator (" +
5176                         toString(std::move(Err)) + ")");
5177   if (auto Err = isTrivialOperatorNode(Src))
5178     return failedImport("Src pattern root isn't a trivial operator (" +
5179                         toString(std::move(Err)) + ")");
5180 
5181   // The different predicates and matchers created during
5182   // addInstructionMatcher use the RuleMatcher M to set up their
5183   // instruction ID (InsnVarID) that are going to be used when
5184   // M is going to be emitted.
5185   // However, the code doing the emission still relies on the IDs
5186   // returned during that process by the RuleMatcher when issuing
5187   // the recordInsn opcodes.
5188   // Because of that:
5189   // 1. The order in which we created the predicates
5190   //    and such must be the same as the order in which we emit them,
5191   //    and
5192   // 2. We need to reset the generation of the IDs in M somewhere between
5193   //    addInstructionMatcher and emit
5194   //
5195   // FIXME: Long term, we don't want to have to rely on this implicit
5196   // naming being the same. One possible solution would be to have
5197   // explicit operator for operation capture and reference those.
5198   // The plus side is that it would expose opportunities to share
5199   // the capture accross rules. The downside is that it would
5200   // introduce a dependency between predicates (captures must happen
5201   // before their first use.)
5202   InstructionMatcher &InsnMatcherTemp = M.addInstructionMatcher(Src->getName());
5203   unsigned TempOpIdx = 0;
5204   auto InsnMatcherOrError =
5205       createAndImportSelDAGMatcher(M, InsnMatcherTemp, Src, TempOpIdx);
5206   if (auto Error = InsnMatcherOrError.takeError())
5207     return std::move(Error);
5208   InstructionMatcher &InsnMatcher = InsnMatcherOrError.get();
5209 
5210   if (Dst->isLeaf()) {
5211     Record *RCDef = getInitValueAsRegClass(Dst->getLeafValue());
5212     if (RCDef) {
5213       const CodeGenRegisterClass &RC = Target.getRegisterClass(RCDef);
5214 
5215       // We need to replace the def and all its uses with the specified
5216       // operand. However, we must also insert COPY's wherever needed.
5217       // For now, emit a copy and let the register allocator clean up.
5218       auto &DstI = Target.getInstruction(RK.getDef("COPY"));
5219       const auto &DstIOperand = DstI.Operands[0];
5220 
5221       OperandMatcher &OM0 = InsnMatcher.getOperand(0);
5222       OM0.setSymbolicName(DstIOperand.Name);
5223       M.defineOperand(OM0.getSymbolicName(), OM0);
5224       OM0.addPredicate<RegisterBankOperandMatcher>(RC);
5225 
5226       auto &DstMIBuilder =
5227           M.addAction<BuildMIAction>(M.allocateOutputInsnID(), &DstI);
5228       DstMIBuilder.addRenderer<CopyRenderer>(DstIOperand.Name);
5229       DstMIBuilder.addRenderer<CopyRenderer>(Dst->getName());
5230       M.addAction<ConstrainOperandToRegClassAction>(0, 0, RC);
5231 
5232       // We're done with this pattern!  It's eligible for GISel emission; return
5233       // it.
5234       ++NumPatternImported;
5235       return std::move(M);
5236     }
5237 
5238     return failedImport("Dst pattern root isn't a known leaf");
5239   }
5240 
5241   // Start with the defined operands (i.e., the results of the root operator).
5242   Record *DstOp = Dst->getOperator();
5243   if (!DstOp->isSubClassOf("Instruction"))
5244     return failedImport("Pattern operator isn't an instruction");
5245 
5246   auto &DstI = Target.getInstruction(DstOp);
5247   StringRef DstIName = DstI.TheDef->getName();
5248 
5249   unsigned DstNumDefs = DstI.Operands.NumDefs,
5250            SrcNumDefs = Src->getExtTypes().size();
5251   if (DstNumDefs < SrcNumDefs) {
5252     if (DstNumDefs != 0)
5253       return failedImport("Src pattern result has more defs than dst MI (" +
5254                           to_string(SrcNumDefs) + " def(s) vs " +
5255                           to_string(DstNumDefs) + " def(s))");
5256 
5257     bool FoundNoUsePred = false;
5258     for (const auto &Pred : InsnMatcher.predicates()) {
5259       if ((FoundNoUsePred = isa<NoUsePredicateMatcher>(Pred.get())))
5260         break;
5261     }
5262     if (!FoundNoUsePred)
5263       return failedImport("Src pattern result has " + to_string(SrcNumDefs) +
5264                           " def(s) without the HasNoUse predicate set to true "
5265                           "but Dst MI has no def");
5266   }
5267 
5268   // The root of the match also has constraints on the register bank so that it
5269   // matches the result instruction.
5270   unsigned OpIdx = 0;
5271   unsigned N = std::min(DstNumDefs, SrcNumDefs);
5272   for (unsigned I = 0; I < N; ++I) {
5273     const TypeSetByHwMode &VTy = Src->getExtType(I);
5274 
5275     const auto &DstIOperand = DstI.Operands[OpIdx];
5276     Record *DstIOpRec = DstIOperand.Rec;
5277     if (DstIName == "COPY_TO_REGCLASS") {
5278       DstIOpRec = getInitValueAsRegClass(Dst->getChild(1)->getLeafValue());
5279 
5280       if (DstIOpRec == nullptr)
5281         return failedImport(
5282             "COPY_TO_REGCLASS operand #1 isn't a register class");
5283     } else if (DstIName == "REG_SEQUENCE") {
5284       DstIOpRec = getInitValueAsRegClass(Dst->getChild(0)->getLeafValue());
5285       if (DstIOpRec == nullptr)
5286         return failedImport("REG_SEQUENCE operand #0 isn't a register class");
5287     } else if (DstIName == "EXTRACT_SUBREG") {
5288       auto InferredClass = inferRegClassFromPattern(Dst->getChild(0));
5289       if (!InferredClass)
5290         return failedImport("Could not infer class for EXTRACT_SUBREG operand #0");
5291 
5292       // We can assume that a subregister is in the same bank as it's super
5293       // register.
5294       DstIOpRec = (*InferredClass)->getDef();
5295     } else if (DstIName == "INSERT_SUBREG") {
5296       auto MaybeSuperClass = inferSuperRegisterClassForNode(
5297           VTy, Dst->getChild(0), Dst->getChild(2));
5298       if (!MaybeSuperClass)
5299         return failedImport(
5300             "Cannot infer register class for INSERT_SUBREG operand #0");
5301       // Move to the next pattern here, because the register class we found
5302       // doesn't necessarily have a record associated with it. So, we can't
5303       // set DstIOpRec using this.
5304       OperandMatcher &OM = InsnMatcher.getOperand(OpIdx);
5305       OM.setSymbolicName(DstIOperand.Name);
5306       M.defineOperand(OM.getSymbolicName(), OM);
5307       OM.addPredicate<RegisterBankOperandMatcher>(**MaybeSuperClass);
5308       ++OpIdx;
5309       continue;
5310     } else if (DstIName == "SUBREG_TO_REG") {
5311       auto MaybeRegClass = inferSuperRegisterClass(VTy, Dst->getChild(2));
5312       if (!MaybeRegClass)
5313         return failedImport(
5314             "Cannot infer register class for SUBREG_TO_REG operand #0");
5315       OperandMatcher &OM = InsnMatcher.getOperand(OpIdx);
5316       OM.setSymbolicName(DstIOperand.Name);
5317       M.defineOperand(OM.getSymbolicName(), OM);
5318       OM.addPredicate<RegisterBankOperandMatcher>(**MaybeRegClass);
5319       ++OpIdx;
5320       continue;
5321     } else if (DstIOpRec->isSubClassOf("RegisterOperand"))
5322       DstIOpRec = DstIOpRec->getValueAsDef("RegClass");
5323     else if (!DstIOpRec->isSubClassOf("RegisterClass"))
5324       return failedImport("Dst MI def isn't a register class" +
5325                           to_string(*Dst));
5326 
5327     OperandMatcher &OM = InsnMatcher.getOperand(OpIdx);
5328     OM.setSymbolicName(DstIOperand.Name);
5329     M.defineOperand(OM.getSymbolicName(), OM);
5330     OM.addPredicate<RegisterBankOperandMatcher>(
5331         Target.getRegisterClass(DstIOpRec));
5332     ++OpIdx;
5333   }
5334 
5335   auto DstMIBuilderOrError =
5336       createAndImportInstructionRenderer(M, InsnMatcher, Src, Dst);
5337   if (auto Error = DstMIBuilderOrError.takeError())
5338     return std::move(Error);
5339   BuildMIAction &DstMIBuilder = DstMIBuilderOrError.get();
5340 
5341   // Render the implicit defs.
5342   // These are only added to the root of the result.
5343   if (auto Error = importImplicitDefRenderers(DstMIBuilder, P.getDstRegs()))
5344     return std::move(Error);
5345 
5346   DstMIBuilder.chooseInsnToMutate(M);
5347 
5348   // Constrain the registers to classes. This is normally derived from the
5349   // emitted instruction but a few instructions require special handling.
5350   if (DstIName == "COPY_TO_REGCLASS") {
5351     // COPY_TO_REGCLASS does not provide operand constraints itself but the
5352     // result is constrained to the class given by the second child.
5353     Record *DstIOpRec =
5354         getInitValueAsRegClass(Dst->getChild(1)->getLeafValue());
5355 
5356     if (DstIOpRec == nullptr)
5357       return failedImport("COPY_TO_REGCLASS operand #1 isn't a register class");
5358 
5359     M.addAction<ConstrainOperandToRegClassAction>(
5360         0, 0, Target.getRegisterClass(DstIOpRec));
5361 
5362     // We're done with this pattern!  It's eligible for GISel emission; return
5363     // it.
5364     ++NumPatternImported;
5365     return std::move(M);
5366   }
5367 
5368   if (DstIName == "EXTRACT_SUBREG") {
5369     auto SuperClass = inferRegClassFromPattern(Dst->getChild(0));
5370     if (!SuperClass)
5371       return failedImport(
5372         "Cannot infer register class from EXTRACT_SUBREG operand #0");
5373 
5374     auto SubIdx = inferSubRegIndexForNode(Dst->getChild(1));
5375     if (!SubIdx)
5376       return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
5377 
5378     // It would be nice to leave this constraint implicit but we're required
5379     // to pick a register class so constrain the result to a register class
5380     // that can hold the correct MVT.
5381     //
5382     // FIXME: This may introduce an extra copy if the chosen class doesn't
5383     //        actually contain the subregisters.
5384     assert(Src->getExtTypes().size() == 1 &&
5385              "Expected Src of EXTRACT_SUBREG to have one result type");
5386 
5387     const auto SrcRCDstRCPair =
5388       (*SuperClass)->getMatchingSubClassWithSubRegs(CGRegs, *SubIdx);
5389     if (!SrcRCDstRCPair) {
5390       return failedImport("subreg index is incompatible "
5391                           "with inferred reg class");
5392     }
5393 
5394     assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
5395     M.addAction<ConstrainOperandToRegClassAction>(0, 0, *SrcRCDstRCPair->second);
5396     M.addAction<ConstrainOperandToRegClassAction>(0, 1, *SrcRCDstRCPair->first);
5397 
5398     // We're done with this pattern!  It's eligible for GISel emission; return
5399     // it.
5400     ++NumPatternImported;
5401     return std::move(M);
5402   }
5403 
5404   if (DstIName == "INSERT_SUBREG") {
5405     assert(Src->getExtTypes().size() == 1 &&
5406            "Expected Src of INSERT_SUBREG to have one result type");
5407     // We need to constrain the destination, a super regsister source, and a
5408     // subregister source.
5409     auto SubClass = inferRegClassFromPattern(Dst->getChild(1));
5410     if (!SubClass)
5411       return failedImport(
5412           "Cannot infer register class from INSERT_SUBREG operand #1");
5413     auto SuperClass = inferSuperRegisterClassForNode(
5414         Src->getExtType(0), Dst->getChild(0), Dst->getChild(2));
5415     if (!SuperClass)
5416       return failedImport(
5417           "Cannot infer register class for INSERT_SUBREG operand #0");
5418     M.addAction<ConstrainOperandToRegClassAction>(0, 0, **SuperClass);
5419     M.addAction<ConstrainOperandToRegClassAction>(0, 1, **SuperClass);
5420     M.addAction<ConstrainOperandToRegClassAction>(0, 2, **SubClass);
5421     ++NumPatternImported;
5422     return std::move(M);
5423   }
5424 
5425   if (DstIName == "SUBREG_TO_REG") {
5426     // We need to constrain the destination and subregister source.
5427     assert(Src->getExtTypes().size() == 1 &&
5428            "Expected Src of SUBREG_TO_REG to have one result type");
5429 
5430     // Attempt to infer the subregister source from the first child. If it has
5431     // an explicitly given register class, we'll use that. Otherwise, we will
5432     // fail.
5433     auto SubClass = inferRegClassFromPattern(Dst->getChild(1));
5434     if (!SubClass)
5435       return failedImport(
5436           "Cannot infer register class from SUBREG_TO_REG child #1");
5437     // We don't have a child to look at that might have a super register node.
5438     auto SuperClass =
5439         inferSuperRegisterClass(Src->getExtType(0), Dst->getChild(2));
5440     if (!SuperClass)
5441       return failedImport(
5442           "Cannot infer register class for SUBREG_TO_REG operand #0");
5443     M.addAction<ConstrainOperandToRegClassAction>(0, 0, **SuperClass);
5444     M.addAction<ConstrainOperandToRegClassAction>(0, 2, **SubClass);
5445     ++NumPatternImported;
5446     return std::move(M);
5447   }
5448 
5449   if (DstIName == "REG_SEQUENCE") {
5450     auto SuperClass = inferRegClassFromPattern(Dst->getChild(0));
5451 
5452     M.addAction<ConstrainOperandToRegClassAction>(0, 0, **SuperClass);
5453 
5454     unsigned Num = Dst->getNumChildren();
5455     for (unsigned I = 1; I != Num; I += 2) {
5456       TreePatternNode *SubRegChild = Dst->getChild(I + 1);
5457 
5458       auto SubIdx = inferSubRegIndexForNode(SubRegChild);
5459       if (!SubIdx)
5460         return failedImport("REG_SEQUENCE child is not a subreg index");
5461 
5462       const auto SrcRCDstRCPair =
5463         (*SuperClass)->getMatchingSubClassWithSubRegs(CGRegs, *SubIdx);
5464 
5465       M.addAction<ConstrainOperandToRegClassAction>(0, I,
5466                                                     *SrcRCDstRCPair->second);
5467     }
5468 
5469     ++NumPatternImported;
5470     return std::move(M);
5471   }
5472 
5473   M.addAction<ConstrainOperandsToDefinitionAction>(0);
5474 
5475   // We're done with this pattern!  It's eligible for GISel emission; return it.
5476   ++NumPatternImported;
5477   return std::move(M);
5478 }
5479 
5480 // Emit imm predicate table and an enum to reference them with.
5481 // The 'Predicate_' part of the name is redundant but eliminating it is more
5482 // trouble than it's worth.
5483 void GlobalISelEmitter::emitCxxPredicateFns(
5484     raw_ostream &OS, StringRef CodeFieldName, StringRef TypeIdentifier,
5485     StringRef ArgType, StringRef ArgName, StringRef AdditionalArgs,
5486     StringRef AdditionalDeclarations,
5487     std::function<bool(const Record *R)> Filter) {
5488   std::vector<const Record *> MatchedRecords;
5489   const auto &Defs = RK.getAllDerivedDefinitions("PatFrags");
5490   std::copy_if(Defs.begin(), Defs.end(), std::back_inserter(MatchedRecords),
5491                [&](Record *Record) {
5492                  return !Record->getValueAsString(CodeFieldName).empty() &&
5493                         Filter(Record);
5494                });
5495 
5496   if (!MatchedRecords.empty()) {
5497     OS << "// PatFrag predicates.\n"
5498        << "enum {\n";
5499     std::string EnumeratorSeparator =
5500         (" = GIPFP_" + TypeIdentifier + "_Invalid + 1,\n").str();
5501     for (const auto *Record : MatchedRecords) {
5502       OS << "  GIPFP_" << TypeIdentifier << "_Predicate_" << Record->getName()
5503          << EnumeratorSeparator;
5504       EnumeratorSeparator = ",\n";
5505     }
5506     OS << "};\n";
5507   }
5508 
5509   OS << "bool " << Target.getName() << "InstructionSelector::test" << ArgName
5510      << "Predicate_" << TypeIdentifier << "(unsigned PredicateID, " << ArgType << " "
5511      << ArgName << AdditionalArgs <<") const {\n"
5512      << AdditionalDeclarations;
5513   if (!AdditionalDeclarations.empty())
5514     OS << "\n";
5515   if (!MatchedRecords.empty())
5516     OS << "  switch (PredicateID) {\n";
5517   for (const auto *Record : MatchedRecords) {
5518     OS << "  case GIPFP_" << TypeIdentifier << "_Predicate_"
5519        << Record->getName() << ": {\n"
5520        << "    " << Record->getValueAsString(CodeFieldName) << "\n"
5521        << "    llvm_unreachable(\"" << CodeFieldName
5522        << " should have returned\");\n"
5523        << "    return false;\n"
5524        << "  }\n";
5525   }
5526   if (!MatchedRecords.empty())
5527     OS << "  }\n";
5528   OS << "  llvm_unreachable(\"Unknown predicate\");\n"
5529      << "  return false;\n"
5530      << "}\n";
5531 }
5532 
5533 void GlobalISelEmitter::emitImmPredicateFns(
5534     raw_ostream &OS, StringRef TypeIdentifier, StringRef ArgType,
5535     std::function<bool(const Record *R)> Filter) {
5536   return emitCxxPredicateFns(OS, "ImmediateCode", TypeIdentifier, ArgType,
5537                              "Imm", "", "", Filter);
5538 }
5539 
5540 void GlobalISelEmitter::emitMIPredicateFns(raw_ostream &OS) {
5541   return emitCxxPredicateFns(
5542       OS, "GISelPredicateCode", "MI", "const MachineInstr &", "MI",
5543       ", const std::array<const MachineOperand *, 3> &Operands",
5544       "  const MachineFunction &MF = *MI.getParent()->getParent();\n"
5545       "  const MachineRegisterInfo &MRI = MF.getRegInfo();\n"
5546       "  (void)MRI;",
5547       [](const Record *R) { return true; });
5548 }
5549 
5550 template <class GroupT>
5551 std::vector<Matcher *> GlobalISelEmitter::optimizeRules(
5552     ArrayRef<Matcher *> Rules,
5553     std::vector<std::unique_ptr<Matcher>> &MatcherStorage) {
5554 
5555   std::vector<Matcher *> OptRules;
5556   std::unique_ptr<GroupT> CurrentGroup = std::make_unique<GroupT>();
5557   assert(CurrentGroup->empty() && "Newly created group isn't empty!");
5558   unsigned NumGroups = 0;
5559 
5560   auto ProcessCurrentGroup = [&]() {
5561     if (CurrentGroup->empty())
5562       // An empty group is good to be reused:
5563       return;
5564 
5565     // If the group isn't large enough to provide any benefit, move all the
5566     // added rules out of it and make sure to re-create the group to properly
5567     // re-initialize it:
5568     if (CurrentGroup->size() < 2)
5569       append_range(OptRules, CurrentGroup->matchers());
5570     else {
5571       CurrentGroup->finalize();
5572       OptRules.push_back(CurrentGroup.get());
5573       MatcherStorage.emplace_back(std::move(CurrentGroup));
5574       ++NumGroups;
5575     }
5576     CurrentGroup = std::make_unique<GroupT>();
5577   };
5578   for (Matcher *Rule : Rules) {
5579     // Greedily add as many matchers as possible to the current group:
5580     if (CurrentGroup->addMatcher(*Rule))
5581       continue;
5582 
5583     ProcessCurrentGroup();
5584     assert(CurrentGroup->empty() && "A group wasn't properly re-initialized");
5585 
5586     // Try to add the pending matcher to a newly created empty group:
5587     if (!CurrentGroup->addMatcher(*Rule))
5588       // If we couldn't add the matcher to an empty group, that group type
5589       // doesn't support that kind of matchers at all, so just skip it:
5590       OptRules.push_back(Rule);
5591   }
5592   ProcessCurrentGroup();
5593 
5594   LLVM_DEBUG(dbgs() << "NumGroups: " << NumGroups << "\n");
5595   (void) NumGroups;
5596   assert(CurrentGroup->empty() && "The last group wasn't properly processed");
5597   return OptRules;
5598 }
5599 
5600 MatchTable
5601 GlobalISelEmitter::buildMatchTable(MutableArrayRef<RuleMatcher> Rules,
5602                                    bool Optimize, bool WithCoverage) {
5603   std::vector<Matcher *> InputRules;
5604   for (Matcher &Rule : Rules)
5605     InputRules.push_back(&Rule);
5606 
5607   if (!Optimize)
5608     return MatchTable::buildTable(InputRules, WithCoverage);
5609 
5610   unsigned CurrentOrdering = 0;
5611   StringMap<unsigned> OpcodeOrder;
5612   for (RuleMatcher &Rule : Rules) {
5613     const StringRef Opcode = Rule.getOpcode();
5614     assert(!Opcode.empty() && "Didn't expect an undefined opcode");
5615     if (OpcodeOrder.count(Opcode) == 0)
5616       OpcodeOrder[Opcode] = CurrentOrdering++;
5617   }
5618 
5619   llvm::stable_sort(InputRules, [&OpcodeOrder](const Matcher *A,
5620                                                const Matcher *B) {
5621     auto *L = static_cast<const RuleMatcher *>(A);
5622     auto *R = static_cast<const RuleMatcher *>(B);
5623     return std::make_tuple(OpcodeOrder[L->getOpcode()], L->getNumOperands()) <
5624            std::make_tuple(OpcodeOrder[R->getOpcode()], R->getNumOperands());
5625   });
5626 
5627   for (Matcher *Rule : InputRules)
5628     Rule->optimize();
5629 
5630   std::vector<std::unique_ptr<Matcher>> MatcherStorage;
5631   std::vector<Matcher *> OptRules =
5632       optimizeRules<GroupMatcher>(InputRules, MatcherStorage);
5633 
5634   for (Matcher *Rule : OptRules)
5635     Rule->optimize();
5636 
5637   OptRules = optimizeRules<SwitchMatcher>(OptRules, MatcherStorage);
5638 
5639   return MatchTable::buildTable(OptRules, WithCoverage);
5640 }
5641 
5642 void GroupMatcher::optimize() {
5643   // Make sure we only sort by a specific predicate within a range of rules that
5644   // all have that predicate checked against a specific value (not a wildcard):
5645   auto F = Matchers.begin();
5646   auto T = F;
5647   auto E = Matchers.end();
5648   while (T != E) {
5649     while (T != E) {
5650       auto *R = static_cast<RuleMatcher *>(*T);
5651       if (!R->getFirstConditionAsRootType().get().isValid())
5652         break;
5653       ++T;
5654     }
5655     std::stable_sort(F, T, [](Matcher *A, Matcher *B) {
5656       auto *L = static_cast<RuleMatcher *>(A);
5657       auto *R = static_cast<RuleMatcher *>(B);
5658       return L->getFirstConditionAsRootType() <
5659              R->getFirstConditionAsRootType();
5660     });
5661     if (T != E)
5662       F = ++T;
5663   }
5664   GlobalISelEmitter::optimizeRules<GroupMatcher>(Matchers, MatcherStorage)
5665       .swap(Matchers);
5666   GlobalISelEmitter::optimizeRules<SwitchMatcher>(Matchers, MatcherStorage)
5667       .swap(Matchers);
5668 }
5669 
5670 void GlobalISelEmitter::run(raw_ostream &OS) {
5671   if (!UseCoverageFile.empty()) {
5672     RuleCoverage = CodeGenCoverage();
5673     auto RuleCoverageBufOrErr = MemoryBuffer::getFile(UseCoverageFile);
5674     if (!RuleCoverageBufOrErr) {
5675       PrintWarning(SMLoc(), "Missing rule coverage data");
5676       RuleCoverage = None;
5677     } else {
5678       if (!RuleCoverage->parse(*RuleCoverageBufOrErr.get(), Target.getName())) {
5679         PrintWarning(SMLoc(), "Ignoring invalid or missing rule coverage data");
5680         RuleCoverage = None;
5681       }
5682     }
5683   }
5684 
5685   // Track the run-time opcode values
5686   gatherOpcodeValues();
5687   // Track the run-time LLT ID values
5688   gatherTypeIDValues();
5689 
5690   // Track the GINodeEquiv definitions.
5691   gatherNodeEquivs();
5692 
5693   emitSourceFileHeader(("Global Instruction Selector for the " +
5694                        Target.getName() + " target").str(), OS);
5695   std::vector<RuleMatcher> Rules;
5696   // Look through the SelectionDAG patterns we found, possibly emitting some.
5697   for (const PatternToMatch &Pat : CGP.ptms()) {
5698     ++NumPatternTotal;
5699 
5700     auto MatcherOrErr = runOnPattern(Pat);
5701 
5702     // The pattern analysis can fail, indicating an unsupported pattern.
5703     // Report that if we've been asked to do so.
5704     if (auto Err = MatcherOrErr.takeError()) {
5705       if (WarnOnSkippedPatterns) {
5706         PrintWarning(Pat.getSrcRecord()->getLoc(),
5707                      "Skipped pattern: " + toString(std::move(Err)));
5708       } else {
5709         consumeError(std::move(Err));
5710       }
5711       ++NumPatternImportsSkipped;
5712       continue;
5713     }
5714 
5715     if (RuleCoverage) {
5716       if (RuleCoverage->isCovered(MatcherOrErr->getRuleID()))
5717         ++NumPatternsTested;
5718       else
5719         PrintWarning(Pat.getSrcRecord()->getLoc(),
5720                      "Pattern is not covered by a test");
5721     }
5722     Rules.push_back(std::move(MatcherOrErr.get()));
5723   }
5724 
5725   // Comparison function to order records by name.
5726   auto orderByName = [](const Record *A, const Record *B) {
5727     return A->getName() < B->getName();
5728   };
5729 
5730   std::vector<Record *> ComplexPredicates =
5731       RK.getAllDerivedDefinitions("GIComplexOperandMatcher");
5732   llvm::sort(ComplexPredicates, orderByName);
5733 
5734   std::vector<StringRef> CustomRendererFns;
5735   transform(RK.getAllDerivedDefinitions("GICustomOperandRenderer"),
5736             std::back_inserter(CustomRendererFns), [](const auto &Record) {
5737               return Record->getValueAsString("RendererFn");
5738             });
5739   // Sort and remove duplicates to get a list of unique renderer functions, in
5740   // case some were mentioned more than once.
5741   llvm::sort(CustomRendererFns);
5742   CustomRendererFns.erase(
5743       std::unique(CustomRendererFns.begin(), CustomRendererFns.end()),
5744       CustomRendererFns.end());
5745 
5746   unsigned MaxTemporaries = 0;
5747   for (const auto &Rule : Rules)
5748     MaxTemporaries = std::max(MaxTemporaries, Rule.countRendererFns());
5749 
5750   OS << "#ifdef GET_GLOBALISEL_PREDICATE_BITSET\n"
5751      << "const unsigned MAX_SUBTARGET_PREDICATES = " << SubtargetFeatures.size()
5752      << ";\n"
5753      << "using PredicateBitset = "
5754         "llvm::PredicateBitsetImpl<MAX_SUBTARGET_PREDICATES>;\n"
5755      << "#endif // ifdef GET_GLOBALISEL_PREDICATE_BITSET\n\n";
5756 
5757   OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n"
5758      << "  mutable MatcherState State;\n"
5759      << "  typedef "
5760         "ComplexRendererFns("
5761      << Target.getName()
5762      << "InstructionSelector::*ComplexMatcherMemFn)(MachineOperand &) const;\n"
5763 
5764      << "  typedef void(" << Target.getName()
5765      << "InstructionSelector::*CustomRendererFn)(MachineInstrBuilder &, const "
5766         "MachineInstr &, int) "
5767         "const;\n"
5768      << "  const ISelInfoTy<PredicateBitset, ComplexMatcherMemFn, "
5769         "CustomRendererFn> "
5770         "ISelInfo;\n";
5771   OS << "  static " << Target.getName()
5772      << "InstructionSelector::ComplexMatcherMemFn ComplexPredicateFns[];\n"
5773      << "  static " << Target.getName()
5774      << "InstructionSelector::CustomRendererFn CustomRenderers[];\n"
5775      << "  bool testImmPredicate_I64(unsigned PredicateID, int64_t Imm) const "
5776         "override;\n"
5777      << "  bool testImmPredicate_APInt(unsigned PredicateID, const APInt &Imm) "
5778         "const override;\n"
5779      << "  bool testImmPredicate_APFloat(unsigned PredicateID, const APFloat "
5780         "&Imm) const override;\n"
5781      << "  const int64_t *getMatchTable() const override;\n"
5782      << "  bool testMIPredicate_MI(unsigned PredicateID, const MachineInstr &MI"
5783         ", const std::array<const MachineOperand *, 3> &Operands) "
5784         "const override;\n"
5785      << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n\n";
5786 
5787   OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n"
5788      << ", State(" << MaxTemporaries << "),\n"
5789      << "ISelInfo(TypeObjects, NumTypeObjects, FeatureBitsets"
5790      << ", ComplexPredicateFns, CustomRenderers)\n"
5791      << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n\n";
5792 
5793   OS << "#ifdef GET_GLOBALISEL_IMPL\n";
5794   SubtargetFeatureInfo::emitSubtargetFeatureBitEnumeration(SubtargetFeatures,
5795                                                            OS);
5796 
5797   // Separate subtarget features by how often they must be recomputed.
5798   SubtargetFeatureInfoMap ModuleFeatures;
5799   std::copy_if(SubtargetFeatures.begin(), SubtargetFeatures.end(),
5800                std::inserter(ModuleFeatures, ModuleFeatures.end()),
5801                [](const SubtargetFeatureInfoMap::value_type &X) {
5802                  return !X.second.mustRecomputePerFunction();
5803                });
5804   SubtargetFeatureInfoMap FunctionFeatures;
5805   std::copy_if(SubtargetFeatures.begin(), SubtargetFeatures.end(),
5806                std::inserter(FunctionFeatures, FunctionFeatures.end()),
5807                [](const SubtargetFeatureInfoMap::value_type &X) {
5808                  return X.second.mustRecomputePerFunction();
5809                });
5810 
5811   SubtargetFeatureInfo::emitComputeAvailableFeatures(
5812     Target.getName(), "InstructionSelector", "computeAvailableModuleFeatures",
5813       ModuleFeatures, OS);
5814 
5815 
5816   OS << "void " << Target.getName() << "InstructionSelector"
5817     "::setupGeneratedPerFunctionState(MachineFunction &MF) {\n"
5818     "  AvailableFunctionFeatures = computeAvailableFunctionFeatures("
5819     "(const " << Target.getName() << "Subtarget *)&MF.getSubtarget(), &MF);\n"
5820     "}\n";
5821 
5822   SubtargetFeatureInfo::emitComputeAvailableFeatures(
5823       Target.getName(), "InstructionSelector",
5824       "computeAvailableFunctionFeatures", FunctionFeatures, OS,
5825       "const MachineFunction *MF");
5826 
5827   // Emit a table containing the LLT objects needed by the matcher and an enum
5828   // for the matcher to reference them with.
5829   std::vector<LLTCodeGen> TypeObjects;
5830   append_range(TypeObjects, KnownTypes);
5831   llvm::sort(TypeObjects);
5832   OS << "// LLT Objects.\n"
5833      << "enum {\n";
5834   for (const auto &TypeObject : TypeObjects) {
5835     OS << "  ";
5836     TypeObject.emitCxxEnumValue(OS);
5837     OS << ",\n";
5838   }
5839   OS << "};\n";
5840   OS << "const static size_t NumTypeObjects = " << TypeObjects.size() << ";\n"
5841      << "const static LLT TypeObjects[] = {\n";
5842   for (const auto &TypeObject : TypeObjects) {
5843     OS << "  ";
5844     TypeObject.emitCxxConstructorCall(OS);
5845     OS << ",\n";
5846   }
5847   OS << "};\n\n";
5848 
5849   // Emit a table containing the PredicateBitsets objects needed by the matcher
5850   // and an enum for the matcher to reference them with.
5851   std::vector<std::vector<Record *>> FeatureBitsets;
5852   for (auto &Rule : Rules)
5853     FeatureBitsets.push_back(Rule.getRequiredFeatures());
5854   llvm::sort(FeatureBitsets, [&](const std::vector<Record *> &A,
5855                                  const std::vector<Record *> &B) {
5856     if (A.size() < B.size())
5857       return true;
5858     if (A.size() > B.size())
5859       return false;
5860     for (auto Pair : zip(A, B)) {
5861       if (std::get<0>(Pair)->getName() < std::get<1>(Pair)->getName())
5862         return true;
5863       if (std::get<0>(Pair)->getName() > std::get<1>(Pair)->getName())
5864         return false;
5865     }
5866     return false;
5867   });
5868   FeatureBitsets.erase(
5869       std::unique(FeatureBitsets.begin(), FeatureBitsets.end()),
5870       FeatureBitsets.end());
5871   OS << "// Feature bitsets.\n"
5872      << "enum {\n"
5873      << "  GIFBS_Invalid,\n";
5874   for (const auto &FeatureBitset : FeatureBitsets) {
5875     if (FeatureBitset.empty())
5876       continue;
5877     OS << "  " << getNameForFeatureBitset(FeatureBitset) << ",\n";
5878   }
5879   OS << "};\n"
5880      << "const static PredicateBitset FeatureBitsets[] {\n"
5881      << "  {}, // GIFBS_Invalid\n";
5882   for (const auto &FeatureBitset : FeatureBitsets) {
5883     if (FeatureBitset.empty())
5884       continue;
5885     OS << "  {";
5886     for (const auto &Feature : FeatureBitset) {
5887       const auto &I = SubtargetFeatures.find(Feature);
5888       assert(I != SubtargetFeatures.end() && "Didn't import predicate?");
5889       OS << I->second.getEnumBitName() << ", ";
5890     }
5891     OS << "},\n";
5892   }
5893   OS << "};\n\n";
5894 
5895   // Emit complex predicate table and an enum to reference them with.
5896   OS << "// ComplexPattern predicates.\n"
5897      << "enum {\n"
5898      << "  GICP_Invalid,\n";
5899   for (const auto &Record : ComplexPredicates)
5900     OS << "  GICP_" << Record->getName() << ",\n";
5901   OS << "};\n"
5902      << "// See constructor for table contents\n\n";
5903 
5904   emitImmPredicateFns(OS, "I64", "int64_t", [](const Record *R) {
5905     bool Unset;
5906     return !R->getValueAsBitOrUnset("IsAPFloat", Unset) &&
5907            !R->getValueAsBit("IsAPInt");
5908   });
5909   emitImmPredicateFns(OS, "APFloat", "const APFloat &", [](const Record *R) {
5910     bool Unset;
5911     return R->getValueAsBitOrUnset("IsAPFloat", Unset);
5912   });
5913   emitImmPredicateFns(OS, "APInt", "const APInt &", [](const Record *R) {
5914     return R->getValueAsBit("IsAPInt");
5915   });
5916   emitMIPredicateFns(OS);
5917   OS << "\n";
5918 
5919   OS << Target.getName() << "InstructionSelector::ComplexMatcherMemFn\n"
5920      << Target.getName() << "InstructionSelector::ComplexPredicateFns[] = {\n"
5921      << "  nullptr, // GICP_Invalid\n";
5922   for (const auto &Record : ComplexPredicates)
5923     OS << "  &" << Target.getName()
5924        << "InstructionSelector::" << Record->getValueAsString("MatcherFn")
5925        << ", // " << Record->getName() << "\n";
5926   OS << "};\n\n";
5927 
5928   OS << "// Custom renderers.\n"
5929      << "enum {\n"
5930      << "  GICR_Invalid,\n";
5931   for (const auto &Fn : CustomRendererFns)
5932     OS << "  GICR_" << Fn << ",\n";
5933   OS << "};\n";
5934 
5935   OS << Target.getName() << "InstructionSelector::CustomRendererFn\n"
5936      << Target.getName() << "InstructionSelector::CustomRenderers[] = {\n"
5937      << "  nullptr, // GICR_Invalid\n";
5938   for (const auto &Fn : CustomRendererFns)
5939     OS << "  &" << Target.getName() << "InstructionSelector::" << Fn << ",\n";
5940   OS << "};\n\n";
5941 
5942   llvm::stable_sort(Rules, [&](const RuleMatcher &A, const RuleMatcher &B) {
5943     int ScoreA = RuleMatcherScores[A.getRuleID()];
5944     int ScoreB = RuleMatcherScores[B.getRuleID()];
5945     if (ScoreA > ScoreB)
5946       return true;
5947     if (ScoreB > ScoreA)
5948       return false;
5949     if (A.isHigherPriorityThan(B)) {
5950       assert(!B.isHigherPriorityThan(A) && "Cannot be more important "
5951                                            "and less important at "
5952                                            "the same time");
5953       return true;
5954     }
5955     return false;
5956   });
5957 
5958   OS << "bool " << Target.getName()
5959      << "InstructionSelector::selectImpl(MachineInstr &I, CodeGenCoverage "
5960         "&CoverageInfo) const {\n"
5961      << "  MachineFunction &MF = *I.getParent()->getParent();\n"
5962      << "  MachineRegisterInfo &MRI = MF.getRegInfo();\n"
5963      << "  const PredicateBitset AvailableFeatures = getAvailableFeatures();\n"
5964      << "  NewMIVector OutMIs;\n"
5965      << "  State.MIs.clear();\n"
5966      << "  State.MIs.push_back(&I);\n\n"
5967      << "  if (executeMatchTable(*this, OutMIs, State, ISelInfo"
5968      << ", getMatchTable(), TII, MRI, TRI, RBI, AvailableFeatures"
5969      << ", CoverageInfo)) {\n"
5970      << "    return true;\n"
5971      << "  }\n\n"
5972      << "  return false;\n"
5973      << "}\n\n";
5974 
5975   const MatchTable Table =
5976       buildMatchTable(Rules, OptimizeMatchTable, GenerateCoverage);
5977   OS << "const int64_t *" << Target.getName()
5978      << "InstructionSelector::getMatchTable() const {\n";
5979   Table.emitDeclaration(OS);
5980   OS << "  return ";
5981   Table.emitUse(OS);
5982   OS << ";\n}\n";
5983   OS << "#endif // ifdef GET_GLOBALISEL_IMPL\n";
5984 
5985   OS << "#ifdef GET_GLOBALISEL_PREDICATES_DECL\n"
5986      << "PredicateBitset AvailableModuleFeatures;\n"
5987      << "mutable PredicateBitset AvailableFunctionFeatures;\n"
5988      << "PredicateBitset getAvailableFeatures() const {\n"
5989      << "  return AvailableModuleFeatures | AvailableFunctionFeatures;\n"
5990      << "}\n"
5991      << "PredicateBitset\n"
5992      << "computeAvailableModuleFeatures(const " << Target.getName()
5993      << "Subtarget *Subtarget) const;\n"
5994      << "PredicateBitset\n"
5995      << "computeAvailableFunctionFeatures(const " << Target.getName()
5996      << "Subtarget *Subtarget,\n"
5997      << "                                 const MachineFunction *MF) const;\n"
5998      << "void setupGeneratedPerFunctionState(MachineFunction &MF) override;\n"
5999      << "#endif // ifdef GET_GLOBALISEL_PREDICATES_DECL\n";
6000 
6001   OS << "#ifdef GET_GLOBALISEL_PREDICATES_INIT\n"
6002      << "AvailableModuleFeatures(computeAvailableModuleFeatures(&STI)),\n"
6003      << "AvailableFunctionFeatures()\n"
6004      << "#endif // ifdef GET_GLOBALISEL_PREDICATES_INIT\n";
6005 }
6006 
6007 void GlobalISelEmitter::declareSubtargetFeature(Record *Predicate) {
6008   if (SubtargetFeatures.count(Predicate) == 0)
6009     SubtargetFeatures.emplace(
6010         Predicate, SubtargetFeatureInfo(Predicate, SubtargetFeatures.size()));
6011 }
6012 
6013 void RuleMatcher::optimize() {
6014   for (auto &Item : InsnVariableIDs) {
6015     InstructionMatcher &InsnMatcher = *Item.first;
6016     for (auto &OM : InsnMatcher.operands()) {
6017       // Complex Patterns are usually expensive and they relatively rarely fail
6018       // on their own: more often we end up throwing away all the work done by a
6019       // matching part of a complex pattern because some other part of the
6020       // enclosing pattern didn't match. All of this makes it beneficial to
6021       // delay complex patterns until the very end of the rule matching,
6022       // especially for targets having lots of complex patterns.
6023       for (auto &OP : OM->predicates())
6024         if (isa<ComplexPatternOperandMatcher>(OP))
6025           EpilogueMatchers.emplace_back(std::move(OP));
6026       OM->eraseNullPredicates();
6027     }
6028     InsnMatcher.optimize();
6029   }
6030   llvm::sort(EpilogueMatchers, [](const std::unique_ptr<PredicateMatcher> &L,
6031                                   const std::unique_ptr<PredicateMatcher> &R) {
6032     return std::make_tuple(L->getKind(), L->getInsnVarID(), L->getOpIdx()) <
6033            std::make_tuple(R->getKind(), R->getInsnVarID(), R->getOpIdx());
6034   });
6035 }
6036 
6037 bool RuleMatcher::hasFirstCondition() const {
6038   if (insnmatchers_empty())
6039     return false;
6040   InstructionMatcher &Matcher = insnmatchers_front();
6041   if (!Matcher.predicates_empty())
6042     return true;
6043   for (auto &OM : Matcher.operands())
6044     for (auto &OP : OM->predicates())
6045       if (!isa<InstructionOperandMatcher>(OP))
6046         return true;
6047   return false;
6048 }
6049 
6050 const PredicateMatcher &RuleMatcher::getFirstCondition() const {
6051   assert(!insnmatchers_empty() &&
6052          "Trying to get a condition from an empty RuleMatcher");
6053 
6054   InstructionMatcher &Matcher = insnmatchers_front();
6055   if (!Matcher.predicates_empty())
6056     return **Matcher.predicates_begin();
6057   // If there is no more predicate on the instruction itself, look at its
6058   // operands.
6059   for (auto &OM : Matcher.operands())
6060     for (auto &OP : OM->predicates())
6061       if (!isa<InstructionOperandMatcher>(OP))
6062         return *OP;
6063 
6064   llvm_unreachable("Trying to get a condition from an InstructionMatcher with "
6065                    "no conditions");
6066 }
6067 
6068 std::unique_ptr<PredicateMatcher> RuleMatcher::popFirstCondition() {
6069   assert(!insnmatchers_empty() &&
6070          "Trying to pop a condition from an empty RuleMatcher");
6071 
6072   InstructionMatcher &Matcher = insnmatchers_front();
6073   if (!Matcher.predicates_empty())
6074     return Matcher.predicates_pop_front();
6075   // If there is no more predicate on the instruction itself, look at its
6076   // operands.
6077   for (auto &OM : Matcher.operands())
6078     for (auto &OP : OM->predicates())
6079       if (!isa<InstructionOperandMatcher>(OP)) {
6080         std::unique_ptr<PredicateMatcher> Result = std::move(OP);
6081         OM->eraseNullPredicates();
6082         return Result;
6083       }
6084 
6085   llvm_unreachable("Trying to pop a condition from an InstructionMatcher with "
6086                    "no conditions");
6087 }
6088 
6089 bool GroupMatcher::candidateConditionMatches(
6090     const PredicateMatcher &Predicate) const {
6091 
6092   if (empty()) {
6093     // Sharing predicates for nested instructions is not supported yet as we
6094     // currently don't hoist the GIM_RecordInsn's properly, therefore we can
6095     // only work on the original root instruction (InsnVarID == 0):
6096     if (Predicate.getInsnVarID() != 0)
6097       return false;
6098     // ... otherwise an empty group can handle any predicate with no specific
6099     // requirements:
6100     return true;
6101   }
6102 
6103   const Matcher &Representative = **Matchers.begin();
6104   const auto &RepresentativeCondition = Representative.getFirstCondition();
6105   // ... if not empty, the group can only accomodate matchers with the exact
6106   // same first condition:
6107   return Predicate.isIdentical(RepresentativeCondition);
6108 }
6109 
6110 bool GroupMatcher::addMatcher(Matcher &Candidate) {
6111   if (!Candidate.hasFirstCondition())
6112     return false;
6113 
6114   const PredicateMatcher &Predicate = Candidate.getFirstCondition();
6115   if (!candidateConditionMatches(Predicate))
6116     return false;
6117 
6118   Matchers.push_back(&Candidate);
6119   return true;
6120 }
6121 
6122 void GroupMatcher::finalize() {
6123   assert(Conditions.empty() && "Already finalized?");
6124   if (empty())
6125     return;
6126 
6127   Matcher &FirstRule = **Matchers.begin();
6128   for (;;) {
6129     // All the checks are expected to succeed during the first iteration:
6130     for (const auto &Rule : Matchers)
6131       if (!Rule->hasFirstCondition())
6132         return;
6133     const auto &FirstCondition = FirstRule.getFirstCondition();
6134     for (unsigned I = 1, E = Matchers.size(); I < E; ++I)
6135       if (!Matchers[I]->getFirstCondition().isIdentical(FirstCondition))
6136         return;
6137 
6138     Conditions.push_back(FirstRule.popFirstCondition());
6139     for (unsigned I = 1, E = Matchers.size(); I < E; ++I)
6140       Matchers[I]->popFirstCondition();
6141   }
6142 }
6143 
6144 void GroupMatcher::emit(MatchTable &Table) {
6145   unsigned LabelID = ~0U;
6146   if (!Conditions.empty()) {
6147     LabelID = Table.allocateLabelID();
6148     Table << MatchTable::Opcode("GIM_Try", +1)
6149           << MatchTable::Comment("On fail goto")
6150           << MatchTable::JumpTarget(LabelID) << MatchTable::LineBreak;
6151   }
6152   for (auto &Condition : Conditions)
6153     Condition->emitPredicateOpcodes(
6154         Table, *static_cast<RuleMatcher *>(*Matchers.begin()));
6155 
6156   for (const auto &M : Matchers)
6157     M->emit(Table);
6158 
6159   // Exit the group
6160   if (!Conditions.empty())
6161     Table << MatchTable::Opcode("GIM_Reject", -1) << MatchTable::LineBreak
6162           << MatchTable::Label(LabelID);
6163 }
6164 
6165 bool SwitchMatcher::isSupportedPredicateType(const PredicateMatcher &P) {
6166   return isa<InstructionOpcodeMatcher>(P) || isa<LLTOperandMatcher>(P);
6167 }
6168 
6169 bool SwitchMatcher::candidateConditionMatches(
6170     const PredicateMatcher &Predicate) const {
6171 
6172   if (empty()) {
6173     // Sharing predicates for nested instructions is not supported yet as we
6174     // currently don't hoist the GIM_RecordInsn's properly, therefore we can
6175     // only work on the original root instruction (InsnVarID == 0):
6176     if (Predicate.getInsnVarID() != 0)
6177       return false;
6178     // ... while an attempt to add even a root matcher to an empty SwitchMatcher
6179     // could fail as not all the types of conditions are supported:
6180     if (!isSupportedPredicateType(Predicate))
6181       return false;
6182     // ... or the condition might not have a proper implementation of
6183     // getValue() / isIdenticalDownToValue() yet:
6184     if (!Predicate.hasValue())
6185       return false;
6186     // ... otherwise an empty Switch can accomodate the condition with no
6187     // further requirements:
6188     return true;
6189   }
6190 
6191   const Matcher &CaseRepresentative = **Matchers.begin();
6192   const auto &RepresentativeCondition = CaseRepresentative.getFirstCondition();
6193   // Switch-cases must share the same kind of condition and path to the value it
6194   // checks:
6195   if (!Predicate.isIdenticalDownToValue(RepresentativeCondition))
6196     return false;
6197 
6198   const auto Value = Predicate.getValue();
6199   // ... but be unique with respect to the actual value they check:
6200   return Values.count(Value) == 0;
6201 }
6202 
6203 bool SwitchMatcher::addMatcher(Matcher &Candidate) {
6204   if (!Candidate.hasFirstCondition())
6205     return false;
6206 
6207   const PredicateMatcher &Predicate = Candidate.getFirstCondition();
6208   if (!candidateConditionMatches(Predicate))
6209     return false;
6210   const auto Value = Predicate.getValue();
6211   Values.insert(Value);
6212 
6213   Matchers.push_back(&Candidate);
6214   return true;
6215 }
6216 
6217 void SwitchMatcher::finalize() {
6218   assert(Condition == nullptr && "Already finalized");
6219   assert(Values.size() == Matchers.size() && "Broken SwitchMatcher");
6220   if (empty())
6221     return;
6222 
6223   llvm::stable_sort(Matchers, [](const Matcher *L, const Matcher *R) {
6224     return L->getFirstCondition().getValue() <
6225            R->getFirstCondition().getValue();
6226   });
6227   Condition = Matchers[0]->popFirstCondition();
6228   for (unsigned I = 1, E = Values.size(); I < E; ++I)
6229     Matchers[I]->popFirstCondition();
6230 }
6231 
6232 void SwitchMatcher::emitPredicateSpecificOpcodes(const PredicateMatcher &P,
6233                                                  MatchTable &Table) {
6234   assert(isSupportedPredicateType(P) && "Predicate type is not supported");
6235 
6236   if (const auto *Condition = dyn_cast<InstructionOpcodeMatcher>(&P)) {
6237     Table << MatchTable::Opcode("GIM_SwitchOpcode") << MatchTable::Comment("MI")
6238           << MatchTable::IntValue(Condition->getInsnVarID());
6239     return;
6240   }
6241   if (const auto *Condition = dyn_cast<LLTOperandMatcher>(&P)) {
6242     Table << MatchTable::Opcode("GIM_SwitchType") << MatchTable::Comment("MI")
6243           << MatchTable::IntValue(Condition->getInsnVarID())
6244           << MatchTable::Comment("Op")
6245           << MatchTable::IntValue(Condition->getOpIdx());
6246     return;
6247   }
6248 
6249   llvm_unreachable("emitPredicateSpecificOpcodes is broken: can not handle a "
6250                    "predicate type that is claimed to be supported");
6251 }
6252 
6253 void SwitchMatcher::emit(MatchTable &Table) {
6254   assert(Values.size() == Matchers.size() && "Broken SwitchMatcher");
6255   if (empty())
6256     return;
6257   assert(Condition != nullptr &&
6258          "Broken SwitchMatcher, hasn't been finalized?");
6259 
6260   std::vector<unsigned> LabelIDs(Values.size());
6261   std::generate(LabelIDs.begin(), LabelIDs.end(),
6262                 [&Table]() { return Table.allocateLabelID(); });
6263   const unsigned Default = Table.allocateLabelID();
6264 
6265   const int64_t LowerBound = Values.begin()->getRawValue();
6266   const int64_t UpperBound = Values.rbegin()->getRawValue() + 1;
6267 
6268   emitPredicateSpecificOpcodes(*Condition, Table);
6269 
6270   Table << MatchTable::Comment("[") << MatchTable::IntValue(LowerBound)
6271         << MatchTable::IntValue(UpperBound) << MatchTable::Comment(")")
6272         << MatchTable::Comment("default:") << MatchTable::JumpTarget(Default);
6273 
6274   int64_t J = LowerBound;
6275   auto VI = Values.begin();
6276   for (unsigned I = 0, E = Values.size(); I < E; ++I) {
6277     auto V = *VI++;
6278     while (J++ < V.getRawValue())
6279       Table << MatchTable::IntValue(0);
6280     V.turnIntoComment();
6281     Table << MatchTable::LineBreak << V << MatchTable::JumpTarget(LabelIDs[I]);
6282   }
6283   Table << MatchTable::LineBreak;
6284 
6285   for (unsigned I = 0, E = Values.size(); I < E; ++I) {
6286     Table << MatchTable::Label(LabelIDs[I]);
6287     Matchers[I]->emit(Table);
6288     Table << MatchTable::Opcode("GIM_Reject") << MatchTable::LineBreak;
6289   }
6290   Table << MatchTable::Label(Default);
6291 }
6292 
6293 unsigned OperandMatcher::getInsnVarID() const { return Insn.getInsnVarID(); }
6294 
6295 } // end anonymous namespace
6296 
6297 //===----------------------------------------------------------------------===//
6298 
6299 namespace llvm {
6300 void EmitGlobalISel(RecordKeeper &RK, raw_ostream &OS) {
6301   GlobalISelEmitter(RK).run(OS);
6302 }
6303 } // End llvm namespace
6304