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