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