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