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