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/CommandLine.h"
40 #include "llvm/Support/Error.h"
41 #include "llvm/Support/LowLevelTypeImpl.h"
42 #include "llvm/Support/ScopedPrinter.h"
43 #include "llvm/TableGen/Error.h"
44 #include "llvm/TableGen/Record.h"
45 #include "llvm/TableGen/TableGenBackend.h"
46 #include <string>
47 #include <numeric>
48 using namespace llvm;
49 
50 #define DEBUG_TYPE "gisel-emitter"
51 
52 STATISTIC(NumPatternTotal, "Total number of patterns");
53 STATISTIC(NumPatternImported, "Number of patterns imported from SelectionDAG");
54 STATISTIC(NumPatternImportsSkipped, "Number of SelectionDAG imports skipped");
55 STATISTIC(NumPatternEmitted, "Number of patterns emitted");
56 
57 cl::OptionCategory GlobalISelEmitterCat("Options for -gen-global-isel");
58 
59 static cl::opt<bool> WarnOnSkippedPatterns(
60     "warn-on-skipped-patterns",
61     cl::desc("Explain why a pattern was skipped for inclusion "
62              "in the GlobalISel selector"),
63     cl::init(false), cl::cat(GlobalISelEmitterCat));
64 
65 namespace {
66 //===- Helper functions ---------------------------------------------------===//
67 
68 /// This class stands in for LLT wherever we want to tablegen-erate an
69 /// equivalent at compiler run-time.
70 class LLTCodeGen {
71 private:
72   LLT Ty;
73 
74 public:
75   LLTCodeGen(const LLT &Ty) : Ty(Ty) {}
76 
77   std::string getCxxEnumValue() const {
78     std::string Str;
79     raw_string_ostream OS(Str);
80 
81     emitCxxEnumValue(OS);
82     return OS.str();
83   }
84 
85   void emitCxxEnumValue(raw_ostream &OS) const {
86     if (Ty.isScalar()) {
87       OS << "GILLT_s" << Ty.getSizeInBits();
88       return;
89     }
90     if (Ty.isVector()) {
91       OS << "GILLT_v" << Ty.getNumElements() << "s" << Ty.getScalarSizeInBits();
92       return;
93     }
94     llvm_unreachable("Unhandled LLT");
95   }
96 
97   void emitCxxConstructorCall(raw_ostream &OS) const {
98     if (Ty.isScalar()) {
99       OS << "LLT::scalar(" << Ty.getSizeInBits() << ")";
100       return;
101     }
102     if (Ty.isVector()) {
103       OS << "LLT::vector(" << Ty.getNumElements() << ", "
104          << Ty.getScalarSizeInBits() << ")";
105       return;
106     }
107     llvm_unreachable("Unhandled LLT");
108   }
109 
110   const LLT &get() const { return Ty; }
111 
112   /// This ordering is used for std::unique() and std::sort(). There's no
113   /// particular logic behind the order.
114   bool operator<(const LLTCodeGen &Other) const {
115     if (!Ty.isValid())
116       return Other.Ty.isValid();
117     if (Ty.isScalar()) {
118       if (!Other.Ty.isValid())
119         return false;
120       if (Other.Ty.isScalar())
121         return Ty.getSizeInBits() < Other.Ty.getSizeInBits();
122       return false;
123     }
124     if (Ty.isVector()) {
125       if (!Other.Ty.isValid() || Other.Ty.isScalar())
126         return false;
127       if (Other.Ty.isVector()) {
128         if (Ty.getNumElements() < Other.Ty.getNumElements())
129           return true;
130         if (Ty.getNumElements() > Other.Ty.getNumElements())
131           return false;
132         return Ty.getSizeInBits() < Other.Ty.getSizeInBits();
133       }
134       return false;
135     }
136     llvm_unreachable("Unhandled LLT");
137   }
138 };
139 
140 class InstructionMatcher;
141 /// Convert an MVT to an equivalent LLT if possible, or the invalid LLT() for
142 /// MVTs that don't map cleanly to an LLT (e.g., iPTR, *any, ...).
143 static Optional<LLTCodeGen> MVTToLLT(MVT::SimpleValueType SVT) {
144   MVT VT(SVT);
145   if (VT.isVector() && VT.getVectorNumElements() != 1)
146     return LLTCodeGen(
147         LLT::vector(VT.getVectorNumElements(), VT.getScalarSizeInBits()));
148   if (VT.isInteger() || VT.isFloatingPoint())
149     return LLTCodeGen(LLT::scalar(VT.getSizeInBits()));
150   return None;
151 }
152 
153 static std::string explainPredicates(const TreePatternNode *N) {
154   std::string Explanation = "";
155   StringRef Separator = "";
156   for (const auto &P : N->getPredicateFns()) {
157     Explanation +=
158         (Separator + P.getOrigPatFragRecord()->getRecord()->getName()).str();
159     if (P.isAlwaysTrue())
160       Explanation += " always-true";
161     if (P.isImmediatePattern())
162       Explanation += " immediate";
163   }
164   return Explanation;
165 }
166 
167 std::string explainOperator(Record *Operator) {
168   if (Operator->isSubClassOf("SDNode"))
169     return (" (" + Operator->getValueAsString("Opcode") + ")").str();
170 
171   if (Operator->isSubClassOf("Intrinsic"))
172     return (" (Operator is an Intrinsic, " + Operator->getName() + ")").str();
173 
174   return " (Operator not understood)";
175 }
176 
177 /// Helper function to let the emitter report skip reason error messages.
178 static Error failedImport(const Twine &Reason) {
179   return make_error<StringError>(Reason, inconvertibleErrorCode());
180 }
181 
182 static Error isTrivialOperatorNode(const TreePatternNode *N) {
183   std::string Explanation = "";
184   std::string Separator = "";
185   if (N->isLeaf()) {
186     if (isa<IntInit>(N->getLeafValue()))
187       return Error::success();
188 
189     Explanation = "Is a leaf";
190     Separator = ", ";
191   }
192 
193   if (N->hasAnyPredicate()) {
194     Explanation = Separator + "Has a predicate (" + explainPredicates(N) + ")";
195     Separator = ", ";
196   }
197 
198   if (N->getTransformFn()) {
199     Explanation += Separator + "Has a transform function";
200     Separator = ", ";
201   }
202 
203   if (!N->isLeaf() && !N->hasAnyPredicate() && !N->getTransformFn())
204     return Error::success();
205 
206   return failedImport(Explanation);
207 }
208 
209 static Record *getInitValueAsRegClass(Init *V) {
210   if (DefInit *VDefInit = dyn_cast<DefInit>(V)) {
211     if (VDefInit->getDef()->isSubClassOf("RegisterOperand"))
212       return VDefInit->getDef()->getValueAsDef("RegClass");
213     if (VDefInit->getDef()->isSubClassOf("RegisterClass"))
214       return VDefInit->getDef();
215   }
216   return nullptr;
217 }
218 
219 std::string
220 getNameForFeatureBitset(const std::vector<Record *> &FeatureBitset) {
221   std::string Name = "GIFBS";
222   for (const auto &Feature : FeatureBitset)
223     Name += ("_" + Feature->getName()).str();
224   return Name;
225 }
226 
227 //===- MatchTable Helpers -------------------------------------------------===//
228 
229 class MatchTable;
230 
231 /// A record to be stored in a MatchTable.
232 ///
233 /// This class represents any and all output that may be required to emit the
234 /// MatchTable. Instances  are most often configured to represent an opcode or
235 /// value that will be emitted to the table with some formatting but it can also
236 /// represent commas, comments, and other formatting instructions.
237 struct MatchTableRecord {
238   enum RecordFlagsBits {
239     MTRF_None = 0x0,
240     /// Causes EmitStr to be formatted as comment when emitted.
241     MTRF_Comment = 0x1,
242     /// Causes the record value to be followed by a comma when emitted.
243     MTRF_CommaFollows = 0x2,
244     /// Causes the record value to be followed by a line break when emitted.
245     MTRF_LineBreakFollows = 0x4,
246     /// Indicates that the record defines a label and causes an additional
247     /// comment to be emitted containing the index of the label.
248     MTRF_Label = 0x8,
249     /// Causes the record to be emitted as the index of the label specified by
250     /// LabelID along with a comment indicating where that label is.
251     MTRF_JumpTarget = 0x10,
252     /// Causes the formatter to add a level of indentation before emitting the
253     /// record.
254     MTRF_Indent = 0x20,
255     /// Causes the formatter to remove a level of indentation after emitting the
256     /// record.
257     MTRF_Outdent = 0x40,
258   };
259 
260   /// When MTRF_Label or MTRF_JumpTarget is used, indicates a label id to
261   /// reference or define.
262   unsigned LabelID;
263   /// The string to emit. Depending on the MTRF_* flags it may be a comment, a
264   /// value, a label name.
265   std::string EmitStr;
266 
267 private:
268   /// The number of MatchTable elements described by this record. Comments are 0
269   /// while values are typically 1. Values >1 may occur when we need to emit
270   /// values that exceed the size of a MatchTable element.
271   unsigned NumElements;
272 
273 public:
274   /// A bitfield of RecordFlagsBits flags.
275   unsigned Flags;
276 
277   MatchTableRecord(Optional<unsigned> LabelID_, StringRef EmitStr,
278                    unsigned NumElements, unsigned Flags)
279       : LabelID(LabelID_.hasValue() ? LabelID_.getValue() : ~0u),
280         EmitStr(EmitStr), NumElements(NumElements), Flags(Flags) {
281     assert((!LabelID_.hasValue() || LabelID != ~0u) &&
282            "This value is reserved for non-labels");
283   }
284 
285   void emit(raw_ostream &OS, bool LineBreakNextAfterThis,
286             const MatchTable &Table) const;
287   unsigned size() const { return NumElements; }
288 };
289 
290 /// Holds the contents of a generated MatchTable to enable formatting and the
291 /// necessary index tracking needed to support GIM_Try.
292 class MatchTable {
293   /// An unique identifier for the table. The generated table will be named
294   /// MatchTable${ID}.
295   unsigned ID;
296   /// The records that make up the table. Also includes comments describing the
297   /// values being emitted and line breaks to format it.
298   std::vector<MatchTableRecord> Contents;
299   /// The currently defined labels.
300   DenseMap<unsigned, unsigned> LabelMap;
301   /// Tracks the sum of MatchTableRecord::NumElements as the table is built.
302   unsigned CurrentSize;
303 
304   /// A unique identifier for a MatchTable label.
305   static unsigned CurrentLabelID;
306 
307 public:
308   static MatchTableRecord LineBreak;
309   static MatchTableRecord Comment(StringRef Comment) {
310     return MatchTableRecord(None, Comment, 0, MatchTableRecord::MTRF_Comment);
311   }
312   static MatchTableRecord Opcode(StringRef Opcode, int IndentAdjust = 0) {
313     unsigned ExtraFlags = 0;
314     if (IndentAdjust > 0)
315       ExtraFlags |= MatchTableRecord::MTRF_Indent;
316     if (IndentAdjust < 0)
317       ExtraFlags |= MatchTableRecord::MTRF_Outdent;
318 
319     return MatchTableRecord(None, Opcode, 1,
320                             MatchTableRecord::MTRF_CommaFollows | ExtraFlags);
321   }
322   static MatchTableRecord NamedValue(StringRef NamedValue) {
323     return MatchTableRecord(None, NamedValue, 1,
324                             MatchTableRecord::MTRF_CommaFollows);
325   }
326   static MatchTableRecord NamedValue(StringRef Namespace,
327                                      StringRef NamedValue) {
328     return MatchTableRecord(None, (Namespace + "::" + NamedValue).str(), 1,
329                             MatchTableRecord::MTRF_CommaFollows);
330   }
331   static MatchTableRecord IntValue(int64_t IntValue) {
332     return MatchTableRecord(None, llvm::to_string(IntValue), 1,
333                             MatchTableRecord::MTRF_CommaFollows);
334   }
335   static MatchTableRecord Label(unsigned LabelID) {
336     return MatchTableRecord(LabelID, "Label " + llvm::to_string(LabelID), 0,
337                             MatchTableRecord::MTRF_Label |
338                                 MatchTableRecord::MTRF_Comment |
339                                 MatchTableRecord::MTRF_LineBreakFollows);
340   }
341   static MatchTableRecord JumpTarget(unsigned LabelID) {
342     return MatchTableRecord(LabelID, "Label " + llvm::to_string(LabelID), 1,
343                             MatchTableRecord::MTRF_JumpTarget |
344                                 MatchTableRecord::MTRF_Comment |
345                                 MatchTableRecord::MTRF_CommaFollows);
346   }
347 
348   MatchTable(unsigned ID) : ID(ID), CurrentSize(0) {}
349 
350   void push_back(const MatchTableRecord &Value) {
351     if (Value.Flags & MatchTableRecord::MTRF_Label)
352       defineLabel(Value.LabelID);
353     Contents.push_back(Value);
354     CurrentSize += Value.size();
355   }
356 
357   unsigned allocateLabelID() const { return CurrentLabelID++; }
358 
359   void defineLabel(unsigned LabelID) {
360     LabelMap.insert(std::make_pair(LabelID, CurrentSize));
361   }
362 
363   unsigned getLabelIndex(unsigned LabelID) const {
364     const auto I = LabelMap.find(LabelID);
365     assert(I != LabelMap.end() && "Use of undeclared label");
366     return I->second;
367   }
368 
369   void emitUse(raw_ostream &OS) const { OS << "MatchTable" << ID; }
370 
371   void emitDeclaration(raw_ostream &OS) const {
372     unsigned Indentation = 4;
373     OS << "  constexpr static int64_t MatchTable" << ID << "[] = {";
374     LineBreak.emit(OS, true, *this);
375     OS << std::string(Indentation, ' ');
376 
377     for (auto I = Contents.begin(), E = Contents.end(); I != E;
378          ++I) {
379       bool LineBreakIsNext = false;
380       const auto &NextI = std::next(I);
381 
382       if (NextI != E) {
383         if (NextI->EmitStr == "" &&
384             NextI->Flags == MatchTableRecord::MTRF_LineBreakFollows)
385           LineBreakIsNext = true;
386       }
387 
388       if (I->Flags & MatchTableRecord::MTRF_Indent)
389         Indentation += 2;
390 
391       I->emit(OS, LineBreakIsNext, *this);
392       if (I->Flags & MatchTableRecord::MTRF_LineBreakFollows)
393         OS << std::string(Indentation, ' ');
394 
395       if (I->Flags & MatchTableRecord::MTRF_Outdent)
396         Indentation -= 2;
397     }
398     OS << "};\n";
399   }
400 };
401 
402 unsigned MatchTable::CurrentLabelID = 0;
403 
404 MatchTableRecord MatchTable::LineBreak = {
405     None, "" /* Emit String */, 0 /* Elements */,
406     MatchTableRecord::MTRF_LineBreakFollows};
407 
408 void MatchTableRecord::emit(raw_ostream &OS, bool LineBreakIsNextAfterThis,
409                             const MatchTable &Table) const {
410   bool UseLineComment =
411       LineBreakIsNextAfterThis | (Flags & MTRF_LineBreakFollows);
412   if (Flags & (MTRF_JumpTarget | MTRF_CommaFollows))
413     UseLineComment = false;
414 
415   if (Flags & MTRF_Comment)
416     OS << (UseLineComment ? "// " : "/*");
417 
418   OS << EmitStr;
419   if (Flags & MTRF_Label)
420     OS << ": @" << Table.getLabelIndex(LabelID);
421 
422   if (Flags & MTRF_Comment && !UseLineComment)
423     OS << "*/";
424 
425   if (Flags & MTRF_JumpTarget) {
426     if (Flags & MTRF_Comment)
427       OS << " ";
428     OS << Table.getLabelIndex(LabelID);
429   }
430 
431   if (Flags & MTRF_CommaFollows) {
432     OS << ",";
433     if (!LineBreakIsNextAfterThis && !(Flags & MTRF_LineBreakFollows))
434       OS << " ";
435   }
436 
437   if (Flags & MTRF_LineBreakFollows)
438     OS << "\n";
439 }
440 
441 MatchTable &operator<<(MatchTable &Table, const MatchTableRecord &Value) {
442   Table.push_back(Value);
443   return Table;
444 }
445 
446 //===- Matchers -----------------------------------------------------------===//
447 
448 class OperandMatcher;
449 class MatchAction;
450 
451 /// Generates code to check that a match rule matches.
452 class RuleMatcher {
453   /// A list of matchers that all need to succeed for the current rule to match.
454   /// FIXME: This currently supports a single match position but could be
455   /// extended to support multiple positions to support div/rem fusion or
456   /// load-multiple instructions.
457   std::vector<std::unique_ptr<InstructionMatcher>> Matchers;
458 
459   /// A list of actions that need to be taken when all predicates in this rule
460   /// have succeeded.
461   std::vector<std::unique_ptr<MatchAction>> Actions;
462 
463   /// A map of instruction matchers to the local variables created by
464   /// emitCaptureOpcodes().
465   std::map<const InstructionMatcher *, unsigned> InsnVariableIDs;
466 
467   /// ID for the next instruction variable defined with defineInsnVar()
468   unsigned NextInsnVarID;
469 
470   std::vector<Record *> RequiredFeatures;
471 
472 public:
473   RuleMatcher()
474       : Matchers(), Actions(), InsnVariableIDs(), NextInsnVarID(0) {}
475   RuleMatcher(RuleMatcher &&Other) = default;
476   RuleMatcher &operator=(RuleMatcher &&Other) = default;
477 
478   InstructionMatcher &addInstructionMatcher();
479   void addRequiredFeature(Record *Feature);
480   const std::vector<Record *> &getRequiredFeatures() const;
481 
482   template <class Kind, class... Args> Kind &addAction(Args &&... args);
483 
484   /// Define an instruction without emitting any code to do so.
485   /// This is used for the root of the match.
486   unsigned implicitlyDefineInsnVar(const InstructionMatcher &Matcher);
487   /// Define an instruction and emit corresponding state-machine opcodes.
488   unsigned defineInsnVar(MatchTable &Table, const InstructionMatcher &Matcher,
489                          unsigned InsnVarID, unsigned OpIdx);
490   unsigned getInsnVarID(const InstructionMatcher &InsnMatcher) const;
491 
492   void emitCaptureOpcodes(MatchTable &Table);
493 
494   void emit(MatchTable &Table);
495 
496   /// Compare the priority of this object and B.
497   ///
498   /// Returns true if this object is more important than B.
499   bool isHigherPriorityThan(const RuleMatcher &B) const;
500 
501   /// Report the maximum number of temporary operands needed by the rule
502   /// matcher.
503   unsigned countRendererFns() const;
504 
505   // FIXME: Remove this as soon as possible
506   InstructionMatcher &insnmatcher_front() const { return *Matchers.front(); }
507 };
508 
509 template <class PredicateTy> class PredicateListMatcher {
510 private:
511   typedef std::vector<std::unique_ptr<PredicateTy>> PredicateVec;
512   PredicateVec Predicates;
513 
514 public:
515   /// Construct a new operand predicate and add it to the matcher.
516   template <class Kind, class... Args>
517   Kind &addPredicate(Args&&... args) {
518     Predicates.emplace_back(
519         llvm::make_unique<Kind>(std::forward<Args>(args)...));
520     return *static_cast<Kind *>(Predicates.back().get());
521   }
522 
523   typename PredicateVec::const_iterator predicates_begin() const {
524     return Predicates.begin();
525   }
526   typename PredicateVec::const_iterator predicates_end() const {
527     return Predicates.end();
528   }
529   iterator_range<typename PredicateVec::const_iterator> predicates() const {
530     return make_range(predicates_begin(), predicates_end());
531   }
532   typename PredicateVec::size_type predicates_size() const {
533     return Predicates.size();
534   }
535 
536   /// Emit MatchTable opcodes that tests whether all the predicates are met.
537   template <class... Args>
538   void emitPredicateListOpcodes(MatchTable &Table, Args &&... args) const {
539     if (Predicates.empty()) {
540       Table << MatchTable::Comment("No predicates") << MatchTable::LineBreak;
541       return;
542     }
543 
544     for (const auto &Predicate : predicates())
545       Predicate->emitPredicateOpcodes(Table, std::forward<Args>(args)...);
546   }
547 };
548 
549 /// Generates code to check a predicate of an operand.
550 ///
551 /// Typical predicates include:
552 /// * Operand is a particular register.
553 /// * Operand is assigned a particular register bank.
554 /// * Operand is an MBB.
555 class OperandPredicateMatcher {
556 public:
557   /// This enum is used for RTTI and also defines the priority that is given to
558   /// the predicate when generating the matcher code. Kinds with higher priority
559   /// must be tested first.
560   ///
561   /// The relative priority of OPM_LLT, OPM_RegBank, and OPM_MBB do not matter
562   /// but OPM_Int must have priority over OPM_RegBank since constant integers
563   /// are represented by a virtual register defined by a G_CONSTANT instruction.
564   enum PredicateKind {
565     OPM_ComplexPattern,
566     OPM_Instruction,
567     OPM_IntrinsicID,
568     OPM_Int,
569     OPM_LiteralInt,
570     OPM_LLT,
571     OPM_RegBank,
572     OPM_MBB,
573   };
574 
575 protected:
576   PredicateKind Kind;
577 
578 public:
579   OperandPredicateMatcher(PredicateKind Kind) : Kind(Kind) {}
580   virtual ~OperandPredicateMatcher() {}
581 
582   PredicateKind getKind() const { return Kind; }
583 
584   /// Return the OperandMatcher for the specified operand or nullptr if there
585   /// isn't one by that name in this operand predicate matcher.
586   ///
587   /// InstructionOperandMatcher is the only subclass that can return non-null
588   /// for this.
589   virtual Optional<const OperandMatcher *>
590   getOptionalOperand(StringRef SymbolicName) const {
591     assert(!SymbolicName.empty() && "Cannot lookup unnamed operand");
592     return None;
593   }
594 
595   /// Emit MatchTable opcodes to capture instructions into the MIs table.
596   ///
597   /// Only InstructionOperandMatcher needs to do anything for this method the
598   /// rest just walk the tree.
599   virtual void emitCaptureOpcodes(MatchTable &Table, RuleMatcher &Rule,
600                                   unsigned InsnVarID, unsigned OpIdx) const {}
601 
602   /// Emit MatchTable opcodes that check the predicate for the given operand.
603   virtual void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
604                                     unsigned InsnVarID,
605                                     unsigned OpIdx) const = 0;
606 
607   /// Compare the priority of this object and B.
608   ///
609   /// Returns true if this object is more important than B.
610   virtual bool isHigherPriorityThan(const OperandPredicateMatcher &B) const {
611     return Kind < B.Kind;
612   };
613 
614   /// Report the maximum number of temporary operands needed by the predicate
615   /// matcher.
616   virtual unsigned countRendererFns() const { return 0; }
617 };
618 
619 /// Generates code to check that an operand is a particular LLT.
620 class LLTOperandMatcher : public OperandPredicateMatcher {
621 protected:
622   LLTCodeGen Ty;
623 
624 public:
625   LLTOperandMatcher(const LLTCodeGen &Ty)
626       : OperandPredicateMatcher(OPM_LLT), Ty(Ty) {}
627 
628   static bool classof(const OperandPredicateMatcher *P) {
629     return P->getKind() == OPM_LLT;
630   }
631 
632   void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
633                             unsigned InsnVarID, unsigned OpIdx) const override {
634     Table << MatchTable::Opcode("GIM_CheckType") << MatchTable::Comment("MI")
635           << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Op")
636           << MatchTable::IntValue(OpIdx) << MatchTable::Comment("Type")
637           << MatchTable::NamedValue(Ty.getCxxEnumValue())
638           << MatchTable::LineBreak;
639   }
640 };
641 
642 /// Generates code to check that an operand is a particular target constant.
643 class ComplexPatternOperandMatcher : public OperandPredicateMatcher {
644 protected:
645   const OperandMatcher &Operand;
646   const Record &TheDef;
647 
648   unsigned getAllocatedTemporariesBaseID() const;
649 
650 public:
651   ComplexPatternOperandMatcher(const OperandMatcher &Operand,
652                                const Record &TheDef)
653       : OperandPredicateMatcher(OPM_ComplexPattern), Operand(Operand),
654         TheDef(TheDef) {}
655 
656   static bool classof(const OperandPredicateMatcher *P) {
657     return P->getKind() == OPM_ComplexPattern;
658   }
659 
660   void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
661                             unsigned InsnVarID, unsigned OpIdx) const override {
662     unsigned ID = getAllocatedTemporariesBaseID();
663     Table << MatchTable::Opcode("GIM_CheckComplexPattern")
664           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
665           << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
666           << MatchTable::Comment("Renderer") << MatchTable::IntValue(ID)
667           << MatchTable::NamedValue(("GICP_" + TheDef.getName()).str())
668           << MatchTable::LineBreak;
669   }
670 
671   unsigned countRendererFns() const override {
672     return 1;
673   }
674 };
675 
676 /// Generates code to check that an operand is in a particular register bank.
677 class RegisterBankOperandMatcher : public OperandPredicateMatcher {
678 protected:
679   const CodeGenRegisterClass &RC;
680 
681 public:
682   RegisterBankOperandMatcher(const CodeGenRegisterClass &RC)
683       : OperandPredicateMatcher(OPM_RegBank), RC(RC) {}
684 
685   static bool classof(const OperandPredicateMatcher *P) {
686     return P->getKind() == OPM_RegBank;
687   }
688 
689   void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
690                             unsigned InsnVarID, unsigned OpIdx) const override {
691     Table << MatchTable::Opcode("GIM_CheckRegBankForClass")
692           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
693           << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
694           << MatchTable::Comment("RC")
695           << MatchTable::NamedValue(RC.getQualifiedName() + "RegClassID")
696           << MatchTable::LineBreak;
697   }
698 };
699 
700 /// Generates code to check that an operand is a basic block.
701 class MBBOperandMatcher : public OperandPredicateMatcher {
702 public:
703   MBBOperandMatcher() : OperandPredicateMatcher(OPM_MBB) {}
704 
705   static bool classof(const OperandPredicateMatcher *P) {
706     return P->getKind() == OPM_MBB;
707   }
708 
709   void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
710                             unsigned InsnVarID, unsigned OpIdx) const override {
711     Table << MatchTable::Opcode("GIM_CheckIsMBB") << MatchTable::Comment("MI")
712           << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Op")
713           << MatchTable::IntValue(OpIdx) << MatchTable::LineBreak;
714   }
715 };
716 
717 /// Generates code to check that an operand is a G_CONSTANT with a particular
718 /// int.
719 class ConstantIntOperandMatcher : public OperandPredicateMatcher {
720 protected:
721   int64_t Value;
722 
723 public:
724   ConstantIntOperandMatcher(int64_t Value)
725       : OperandPredicateMatcher(OPM_Int), Value(Value) {}
726 
727   static bool classof(const OperandPredicateMatcher *P) {
728     return P->getKind() == OPM_Int;
729   }
730 
731   void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
732                             unsigned InsnVarID, unsigned OpIdx) const override {
733     Table << MatchTable::Opcode("GIM_CheckConstantInt")
734           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
735           << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
736           << MatchTable::IntValue(Value) << MatchTable::LineBreak;
737   }
738 };
739 
740 /// Generates code to check that an operand is a raw int (where MO.isImm() or
741 /// MO.isCImm() is true).
742 class LiteralIntOperandMatcher : public OperandPredicateMatcher {
743 protected:
744   int64_t Value;
745 
746 public:
747   LiteralIntOperandMatcher(int64_t Value)
748       : OperandPredicateMatcher(OPM_LiteralInt), Value(Value) {}
749 
750   static bool classof(const OperandPredicateMatcher *P) {
751     return P->getKind() == OPM_LiteralInt;
752   }
753 
754   void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
755                             unsigned InsnVarID, unsigned OpIdx) const override {
756     Table << MatchTable::Opcode("GIM_CheckLiteralInt")
757           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
758           << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
759           << MatchTable::IntValue(Value) << MatchTable::LineBreak;
760   }
761 };
762 
763 /// Generates code to check that an operand is an intrinsic ID.
764 class IntrinsicIDOperandMatcher : public OperandPredicateMatcher {
765 protected:
766   const CodeGenIntrinsic *II;
767 
768 public:
769   IntrinsicIDOperandMatcher(const CodeGenIntrinsic *II)
770       : OperandPredicateMatcher(OPM_IntrinsicID), II(II) {}
771 
772   static bool classof(const OperandPredicateMatcher *P) {
773     return P->getKind() == OPM_IntrinsicID;
774   }
775 
776   void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
777                             unsigned InsnVarID, unsigned OpIdx) const override {
778     Table << MatchTable::Opcode("GIM_CheckIntrinsicID")
779           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
780           << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
781           << MatchTable::NamedValue("Intrinsic::" + II->EnumName)
782           << MatchTable::LineBreak;
783   }
784 };
785 
786 /// Generates code to check that a set of predicates match for a particular
787 /// operand.
788 class OperandMatcher : public PredicateListMatcher<OperandPredicateMatcher> {
789 protected:
790   InstructionMatcher &Insn;
791   unsigned OpIdx;
792   std::string SymbolicName;
793 
794   /// The index of the first temporary variable allocated to this operand. The
795   /// number of allocated temporaries can be found with
796   /// countRendererFns().
797   unsigned AllocatedTemporariesBaseID;
798 
799 public:
800   OperandMatcher(InstructionMatcher &Insn, unsigned OpIdx,
801                  const std::string &SymbolicName,
802                  unsigned AllocatedTemporariesBaseID)
803       : Insn(Insn), OpIdx(OpIdx), SymbolicName(SymbolicName),
804         AllocatedTemporariesBaseID(AllocatedTemporariesBaseID) {}
805 
806   bool hasSymbolicName() const { return !SymbolicName.empty(); }
807   const StringRef getSymbolicName() const { return SymbolicName; }
808   void setSymbolicName(StringRef Name) {
809     assert(SymbolicName.empty() && "Operand already has a symbolic name");
810     SymbolicName = Name;
811   }
812   unsigned getOperandIndex() const { return OpIdx; }
813 
814   std::string getOperandExpr(unsigned InsnVarID) const {
815     return "State.MIs[" + llvm::to_string(InsnVarID) + "]->getOperand(" +
816            llvm::to_string(OpIdx) + ")";
817   }
818 
819   Optional<const OperandMatcher *>
820   getOptionalOperand(StringRef DesiredSymbolicName) const {
821     assert(!DesiredSymbolicName.empty() && "Cannot lookup unnamed operand");
822     if (DesiredSymbolicName == SymbolicName)
823       return this;
824     for (const auto &OP : predicates()) {
825       const auto &MaybeOperand = OP->getOptionalOperand(DesiredSymbolicName);
826       if (MaybeOperand.hasValue())
827         return MaybeOperand.getValue();
828     }
829     return None;
830   }
831 
832   InstructionMatcher &getInstructionMatcher() const { return Insn; }
833 
834   /// Emit MatchTable opcodes to capture instructions into the MIs table.
835   void emitCaptureOpcodes(MatchTable &Table, RuleMatcher &Rule,
836                           unsigned InsnVarID) const {
837     for (const auto &Predicate : predicates())
838       Predicate->emitCaptureOpcodes(Table, Rule, InsnVarID, OpIdx);
839   }
840 
841   /// Emit MatchTable opcodes that test whether the instruction named in
842   /// InsnVarID matches all the predicates and all the operands.
843   void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
844                             unsigned InsnVarID) const {
845     std::string Comment;
846     raw_string_ostream CommentOS(Comment);
847     CommentOS << "MIs[" << InsnVarID << "] ";
848     if (SymbolicName.empty())
849       CommentOS << "Operand " << OpIdx;
850     else
851       CommentOS << SymbolicName;
852     Table << MatchTable::Comment(CommentOS.str()) << MatchTable::LineBreak;
853 
854     emitPredicateListOpcodes(Table, Rule, InsnVarID, OpIdx);
855   }
856 
857   /// Compare the priority of this object and B.
858   ///
859   /// Returns true if this object is more important than B.
860   bool isHigherPriorityThan(const OperandMatcher &B) const {
861     // Operand matchers involving more predicates have higher priority.
862     if (predicates_size() > B.predicates_size())
863       return true;
864     if (predicates_size() < B.predicates_size())
865       return false;
866 
867     // This assumes that predicates are added in a consistent order.
868     for (const auto &Predicate : zip(predicates(), B.predicates())) {
869       if (std::get<0>(Predicate)->isHigherPriorityThan(*std::get<1>(Predicate)))
870         return true;
871       if (std::get<1>(Predicate)->isHigherPriorityThan(*std::get<0>(Predicate)))
872         return false;
873     }
874 
875     return false;
876   };
877 
878   /// Report the maximum number of temporary operands needed by the operand
879   /// matcher.
880   unsigned countRendererFns() const {
881     return std::accumulate(
882         predicates().begin(), predicates().end(), 0,
883         [](unsigned A,
884            const std::unique_ptr<OperandPredicateMatcher> &Predicate) {
885           return A + Predicate->countRendererFns();
886         });
887   }
888 
889   unsigned getAllocatedTemporariesBaseID() const {
890     return AllocatedTemporariesBaseID;
891   }
892 };
893 
894 unsigned ComplexPatternOperandMatcher::getAllocatedTemporariesBaseID() const {
895   return Operand.getAllocatedTemporariesBaseID();
896 }
897 
898 /// Generates code to check a predicate on an instruction.
899 ///
900 /// Typical predicates include:
901 /// * The opcode of the instruction is a particular value.
902 /// * The nsw/nuw flag is/isn't set.
903 class InstructionPredicateMatcher {
904 protected:
905   /// This enum is used for RTTI and also defines the priority that is given to
906   /// the predicate when generating the matcher code. Kinds with higher priority
907   /// must be tested first.
908   enum PredicateKind {
909     IPM_Opcode,
910   };
911 
912   PredicateKind Kind;
913 
914 public:
915   InstructionPredicateMatcher(PredicateKind Kind) : Kind(Kind) {}
916   virtual ~InstructionPredicateMatcher() {}
917 
918   PredicateKind getKind() const { return Kind; }
919 
920   /// Emit MatchTable opcodes that test whether the instruction named in
921   /// InsnVarID matches the predicate.
922   virtual void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
923                                     unsigned InsnVarID) const = 0;
924 
925   /// Compare the priority of this object and B.
926   ///
927   /// Returns true if this object is more important than B.
928   virtual bool
929   isHigherPriorityThan(const InstructionPredicateMatcher &B) const {
930     return Kind < B.Kind;
931   };
932 
933   /// Report the maximum number of temporary operands needed by the predicate
934   /// matcher.
935   virtual unsigned countRendererFns() const { return 0; }
936 };
937 
938 /// Generates code to check the opcode of an instruction.
939 class InstructionOpcodeMatcher : public InstructionPredicateMatcher {
940 protected:
941   const CodeGenInstruction *I;
942 
943 public:
944   InstructionOpcodeMatcher(const CodeGenInstruction *I)
945       : InstructionPredicateMatcher(IPM_Opcode), I(I) {}
946 
947   static bool classof(const InstructionPredicateMatcher *P) {
948     return P->getKind() == IPM_Opcode;
949   }
950 
951   void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
952                             unsigned InsnVarID) const override {
953     Table << MatchTable::Opcode("GIM_CheckOpcode") << MatchTable::Comment("MI")
954           << MatchTable::IntValue(InsnVarID)
955           << MatchTable::NamedValue(I->Namespace, I->TheDef->getName())
956           << MatchTable::LineBreak;
957   }
958 
959   /// Compare the priority of this object and B.
960   ///
961   /// Returns true if this object is more important than B.
962   bool
963   isHigherPriorityThan(const InstructionPredicateMatcher &B) const override {
964     if (InstructionPredicateMatcher::isHigherPriorityThan(B))
965       return true;
966     if (B.InstructionPredicateMatcher::isHigherPriorityThan(*this))
967       return false;
968 
969     // Prioritize opcodes for cosmetic reasons in the generated source. Although
970     // this is cosmetic at the moment, we may want to drive a similar ordering
971     // using instruction frequency information to improve compile time.
972     if (const InstructionOpcodeMatcher *BO =
973             dyn_cast<InstructionOpcodeMatcher>(&B))
974       return I->TheDef->getName() < BO->I->TheDef->getName();
975 
976     return false;
977   };
978 };
979 
980 /// Generates code to check that a set of predicates and operands match for a
981 /// particular instruction.
982 ///
983 /// Typical predicates include:
984 /// * Has a specific opcode.
985 /// * Has an nsw/nuw flag or doesn't.
986 class InstructionMatcher
987     : public PredicateListMatcher<InstructionPredicateMatcher> {
988 protected:
989   typedef std::vector<std::unique_ptr<OperandMatcher>> OperandVec;
990 
991   /// The operands to match. All rendered operands must be present even if the
992   /// condition is always true.
993   OperandVec Operands;
994 
995 public:
996   /// Add an operand to the matcher.
997   OperandMatcher &addOperand(unsigned OpIdx, const std::string &SymbolicName,
998                              unsigned AllocatedTemporariesBaseID) {
999     Operands.emplace_back(new OperandMatcher(*this, OpIdx, SymbolicName,
1000                                              AllocatedTemporariesBaseID));
1001     return *Operands.back();
1002   }
1003 
1004   OperandMatcher &getOperand(unsigned OpIdx) {
1005     auto I = std::find_if(Operands.begin(), Operands.end(),
1006                           [&OpIdx](const std::unique_ptr<OperandMatcher> &X) {
1007                             return X->getOperandIndex() == OpIdx;
1008                           });
1009     if (I != Operands.end())
1010       return **I;
1011     llvm_unreachable("Failed to lookup operand");
1012   }
1013 
1014   Optional<const OperandMatcher *>
1015   getOptionalOperand(StringRef SymbolicName) const {
1016     assert(!SymbolicName.empty() && "Cannot lookup unnamed operand");
1017     for (const auto &Operand : Operands) {
1018       const auto &OM = Operand->getOptionalOperand(SymbolicName);
1019       if (OM.hasValue())
1020         return OM.getValue();
1021     }
1022     return None;
1023   }
1024 
1025   const OperandMatcher &getOperand(StringRef SymbolicName) const {
1026     Optional<const OperandMatcher *>OM = getOptionalOperand(SymbolicName);
1027     if (OM.hasValue())
1028       return *OM.getValue();
1029     llvm_unreachable("Failed to lookup operand");
1030   }
1031 
1032   unsigned getNumOperands() const { return Operands.size(); }
1033   OperandVec::iterator operands_begin() { return Operands.begin(); }
1034   OperandVec::iterator operands_end() { return Operands.end(); }
1035   iterator_range<OperandVec::iterator> operands() {
1036     return make_range(operands_begin(), operands_end());
1037   }
1038   OperandVec::const_iterator operands_begin() const { return Operands.begin(); }
1039   OperandVec::const_iterator operands_end() const { return Operands.end(); }
1040   iterator_range<OperandVec::const_iterator> operands() const {
1041     return make_range(operands_begin(), operands_end());
1042   }
1043 
1044   /// Emit MatchTable opcodes to check the shape of the match and capture
1045   /// instructions into the MIs table.
1046   void emitCaptureOpcodes(MatchTable &Table, RuleMatcher &Rule,
1047                           unsigned InsnID) {
1048     Table << MatchTable::Opcode("GIM_CheckNumOperands")
1049           << MatchTable::Comment("MI") << MatchTable::IntValue(InsnID)
1050           << MatchTable::Comment("Expected")
1051           << MatchTable::IntValue(getNumOperands()) << MatchTable::LineBreak;
1052     for (const auto &Operand : Operands)
1053       Operand->emitCaptureOpcodes(Table, Rule, InsnID);
1054   }
1055 
1056   /// Emit MatchTable opcodes that test whether the instruction named in
1057   /// InsnVarName matches all the predicates and all the operands.
1058   void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
1059                             unsigned InsnVarID) const {
1060     emitPredicateListOpcodes(Table, Rule, InsnVarID);
1061     for (const auto &Operand : Operands)
1062       Operand->emitPredicateOpcodes(Table, Rule, InsnVarID);
1063   }
1064 
1065   /// Compare the priority of this object and B.
1066   ///
1067   /// Returns true if this object is more important than B.
1068   bool isHigherPriorityThan(const InstructionMatcher &B) const {
1069     // Instruction matchers involving more operands have higher priority.
1070     if (Operands.size() > B.Operands.size())
1071       return true;
1072     if (Operands.size() < B.Operands.size())
1073       return false;
1074 
1075     for (const auto &Predicate : zip(predicates(), B.predicates())) {
1076       if (std::get<0>(Predicate)->isHigherPriorityThan(*std::get<1>(Predicate)))
1077         return true;
1078       if (std::get<1>(Predicate)->isHigherPriorityThan(*std::get<0>(Predicate)))
1079         return false;
1080     }
1081 
1082     for (const auto &Operand : zip(Operands, B.Operands)) {
1083       if (std::get<0>(Operand)->isHigherPriorityThan(*std::get<1>(Operand)))
1084         return true;
1085       if (std::get<1>(Operand)->isHigherPriorityThan(*std::get<0>(Operand)))
1086         return false;
1087     }
1088 
1089     return false;
1090   };
1091 
1092   /// Report the maximum number of temporary operands needed by the instruction
1093   /// matcher.
1094   unsigned countRendererFns() const {
1095     return std::accumulate(predicates().begin(), predicates().end(), 0,
1096                            [](unsigned A,
1097                               const std::unique_ptr<InstructionPredicateMatcher>
1098                                   &Predicate) {
1099                              return A + Predicate->countRendererFns();
1100                            }) +
1101            std::accumulate(
1102                Operands.begin(), Operands.end(), 0,
1103                [](unsigned A, const std::unique_ptr<OperandMatcher> &Operand) {
1104                  return A + Operand->countRendererFns();
1105                });
1106   }
1107 };
1108 
1109 /// Generates code to check that the operand is a register defined by an
1110 /// instruction that matches the given instruction matcher.
1111 ///
1112 /// For example, the pattern:
1113 ///   (set $dst, (G_MUL (G_ADD $src1, $src2), $src3))
1114 /// would use an InstructionOperandMatcher for operand 1 of the G_MUL to match
1115 /// the:
1116 ///   (G_ADD $src1, $src2)
1117 /// subpattern.
1118 class InstructionOperandMatcher : public OperandPredicateMatcher {
1119 protected:
1120   std::unique_ptr<InstructionMatcher> InsnMatcher;
1121 
1122 public:
1123   InstructionOperandMatcher()
1124       : OperandPredicateMatcher(OPM_Instruction),
1125         InsnMatcher(new InstructionMatcher()) {}
1126 
1127   static bool classof(const OperandPredicateMatcher *P) {
1128     return P->getKind() == OPM_Instruction;
1129   }
1130 
1131   InstructionMatcher &getInsnMatcher() const { return *InsnMatcher; }
1132 
1133   Optional<const OperandMatcher *>
1134   getOptionalOperand(StringRef SymbolicName) const override {
1135     assert(!SymbolicName.empty() && "Cannot lookup unnamed operand");
1136     return InsnMatcher->getOptionalOperand(SymbolicName);
1137   }
1138 
1139   void emitCaptureOpcodes(MatchTable &Table, RuleMatcher &Rule,
1140                           unsigned InsnID, unsigned OpIdx) const override {
1141     unsigned InsnVarID = Rule.defineInsnVar(Table, *InsnMatcher, InsnID, OpIdx);
1142     InsnMatcher->emitCaptureOpcodes(Table, Rule, InsnVarID);
1143   }
1144 
1145   void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
1146                             unsigned InsnVarID_,
1147                             unsigned OpIdx_) const override {
1148     unsigned InsnVarID = Rule.getInsnVarID(*InsnMatcher);
1149     InsnMatcher->emitPredicateOpcodes(Table, Rule, InsnVarID);
1150   }
1151 };
1152 
1153 //===- Actions ------------------------------------------------------------===//
1154 class OperandRenderer {
1155 public:
1156   enum RendererKind {
1157     OR_Copy,
1158     OR_CopySubReg,
1159     OR_Imm,
1160     OR_Register,
1161     OR_ComplexPattern
1162   };
1163 
1164 protected:
1165   RendererKind Kind;
1166 
1167 public:
1168   OperandRenderer(RendererKind Kind) : Kind(Kind) {}
1169   virtual ~OperandRenderer() {}
1170 
1171   RendererKind getKind() const { return Kind; }
1172 
1173   virtual void emitRenderOpcodes(MatchTable &Table,
1174                                  RuleMatcher &Rule) const = 0;
1175 };
1176 
1177 /// A CopyRenderer emits code to copy a single operand from an existing
1178 /// instruction to the one being built.
1179 class CopyRenderer : public OperandRenderer {
1180 protected:
1181   unsigned NewInsnID;
1182   /// The matcher for the instruction that this operand is copied from.
1183   /// This provides the facility for looking up an a operand by it's name so
1184   /// that it can be used as a source for the instruction being built.
1185   const InstructionMatcher &Matched;
1186   /// The name of the operand.
1187   const StringRef SymbolicName;
1188 
1189 public:
1190   CopyRenderer(unsigned NewInsnID, const InstructionMatcher &Matched,
1191                StringRef SymbolicName)
1192       : OperandRenderer(OR_Copy), NewInsnID(NewInsnID), Matched(Matched),
1193         SymbolicName(SymbolicName) {}
1194 
1195   static bool classof(const OperandRenderer *R) {
1196     return R->getKind() == OR_Copy;
1197   }
1198 
1199   const StringRef getSymbolicName() const { return SymbolicName; }
1200 
1201   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
1202     const OperandMatcher &Operand = Matched.getOperand(SymbolicName);
1203     unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
1204     Table << MatchTable::Opcode("GIR_Copy") << MatchTable::Comment("NewInsnID")
1205           << MatchTable::IntValue(NewInsnID) << MatchTable::Comment("OldInsnID")
1206           << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
1207           << MatchTable::IntValue(Operand.getOperandIndex())
1208           << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
1209   }
1210 };
1211 
1212 /// A CopySubRegRenderer emits code to copy a single register operand from an
1213 /// existing instruction to the one being built and indicate that only a
1214 /// subregister should be copied.
1215 class CopySubRegRenderer : public OperandRenderer {
1216 protected:
1217   unsigned NewInsnID;
1218   /// The matcher for the instruction that this operand is copied from.
1219   /// This provides the facility for looking up an a operand by it's name so
1220   /// that it can be used as a source for the instruction being built.
1221   const InstructionMatcher &Matched;
1222   /// The name of the operand.
1223   const StringRef SymbolicName;
1224   /// The subregister to extract.
1225   const CodeGenSubRegIndex *SubReg;
1226 
1227 public:
1228   CopySubRegRenderer(unsigned NewInsnID, const InstructionMatcher &Matched,
1229                      StringRef SymbolicName, const CodeGenSubRegIndex *SubReg)
1230       : OperandRenderer(OR_CopySubReg), NewInsnID(NewInsnID), Matched(Matched),
1231         SymbolicName(SymbolicName), SubReg(SubReg) {}
1232 
1233   static bool classof(const OperandRenderer *R) {
1234     return R->getKind() == OR_CopySubReg;
1235   }
1236 
1237   const StringRef getSymbolicName() const { return SymbolicName; }
1238 
1239   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
1240     const OperandMatcher &Operand = Matched.getOperand(SymbolicName);
1241     unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
1242     Table << MatchTable::Opcode("GIR_CopySubReg")
1243           << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
1244           << MatchTable::Comment("OldInsnID")
1245           << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
1246           << MatchTable::IntValue(Operand.getOperandIndex())
1247           << MatchTable::Comment("SubRegIdx")
1248           << MatchTable::IntValue(SubReg->EnumValue)
1249           << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
1250   }
1251 };
1252 
1253 /// Adds a specific physical register to the instruction being built.
1254 /// This is typically useful for WZR/XZR on AArch64.
1255 class AddRegisterRenderer : public OperandRenderer {
1256 protected:
1257   unsigned InsnID;
1258   const Record *RegisterDef;
1259 
1260 public:
1261   AddRegisterRenderer(unsigned InsnID, const Record *RegisterDef)
1262       : OperandRenderer(OR_Register), InsnID(InsnID), RegisterDef(RegisterDef) {
1263   }
1264 
1265   static bool classof(const OperandRenderer *R) {
1266     return R->getKind() == OR_Register;
1267   }
1268 
1269   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
1270     Table << MatchTable::Opcode("GIR_AddRegister")
1271           << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1272           << MatchTable::NamedValue(
1273                  (RegisterDef->getValue("Namespace")
1274                       ? RegisterDef->getValueAsString("Namespace")
1275                       : ""),
1276                  RegisterDef->getName())
1277           << MatchTable::LineBreak;
1278   }
1279 };
1280 
1281 /// Adds a specific immediate to the instruction being built.
1282 class ImmRenderer : public OperandRenderer {
1283 protected:
1284   unsigned InsnID;
1285   int64_t Imm;
1286 
1287 public:
1288   ImmRenderer(unsigned InsnID, int64_t Imm)
1289       : OperandRenderer(OR_Imm), InsnID(InsnID), Imm(Imm) {}
1290 
1291   static bool classof(const OperandRenderer *R) {
1292     return R->getKind() == OR_Imm;
1293   }
1294 
1295   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
1296     Table << MatchTable::Opcode("GIR_AddImm") << MatchTable::Comment("InsnID")
1297           << MatchTable::IntValue(InsnID) << MatchTable::Comment("Imm")
1298           << MatchTable::IntValue(Imm) << MatchTable::LineBreak;
1299   }
1300 };
1301 
1302 /// Adds operands by calling a renderer function supplied by the ComplexPattern
1303 /// matcher function.
1304 class RenderComplexPatternOperand : public OperandRenderer {
1305 private:
1306   unsigned InsnID;
1307   const Record &TheDef;
1308   /// The name of the operand.
1309   const StringRef SymbolicName;
1310   /// The renderer number. This must be unique within a rule since it's used to
1311   /// identify a temporary variable to hold the renderer function.
1312   unsigned RendererID;
1313 
1314   unsigned getNumOperands() const {
1315     return TheDef.getValueAsDag("Operands")->getNumArgs();
1316   }
1317 
1318 public:
1319   RenderComplexPatternOperand(unsigned InsnID, const Record &TheDef,
1320                               StringRef SymbolicName, unsigned RendererID)
1321       : OperandRenderer(OR_ComplexPattern), InsnID(InsnID), TheDef(TheDef),
1322         SymbolicName(SymbolicName), RendererID(RendererID) {}
1323 
1324   static bool classof(const OperandRenderer *R) {
1325     return R->getKind() == OR_ComplexPattern;
1326   }
1327 
1328   void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
1329     Table << MatchTable::Opcode("GIR_ComplexRenderer")
1330           << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1331           << MatchTable::Comment("RendererID")
1332           << MatchTable::IntValue(RendererID) << MatchTable::LineBreak;
1333   }
1334 };
1335 
1336 /// An action taken when all Matcher predicates succeeded for a parent rule.
1337 ///
1338 /// Typical actions include:
1339 /// * Changing the opcode of an instruction.
1340 /// * Adding an operand to an instruction.
1341 class MatchAction {
1342 public:
1343   virtual ~MatchAction() {}
1344 
1345   /// Emit the MatchTable opcodes to implement the action.
1346   ///
1347   /// \param RecycleInsnID If given, it's an instruction to recycle. The
1348   ///                      requirements on the instruction vary from action to
1349   ///                      action.
1350   virtual void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule,
1351                                  unsigned RecycleInsnID) const = 0;
1352 };
1353 
1354 /// Generates a comment describing the matched rule being acted upon.
1355 class DebugCommentAction : public MatchAction {
1356 private:
1357   const PatternToMatch &P;
1358 
1359 public:
1360   DebugCommentAction(const PatternToMatch &P) : P(P) {}
1361 
1362   void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule,
1363                          unsigned RecycleInsnID) const override {
1364     Table << MatchTable::Comment(llvm::to_string(*P.getSrcPattern()) + "  =>  " +
1365                                llvm::to_string(*P.getDstPattern()))
1366           << MatchTable::LineBreak;
1367   }
1368 };
1369 
1370 /// Generates code to build an instruction or mutate an existing instruction
1371 /// into the desired instruction when this is possible.
1372 class BuildMIAction : public MatchAction {
1373 private:
1374   unsigned InsnID;
1375   const CodeGenInstruction *I;
1376   const InstructionMatcher &Matched;
1377   std::vector<std::unique_ptr<OperandRenderer>> OperandRenderers;
1378 
1379   /// True if the instruction can be built solely by mutating the opcode.
1380   bool canMutate() const {
1381     if (OperandRenderers.size() != Matched.getNumOperands())
1382       return false;
1383 
1384     for (const auto &Renderer : enumerate(OperandRenderers)) {
1385       if (const auto *Copy = dyn_cast<CopyRenderer>(&*Renderer.value())) {
1386         const OperandMatcher &OM = Matched.getOperand(Copy->getSymbolicName());
1387         if (&Matched != &OM.getInstructionMatcher() ||
1388             OM.getOperandIndex() != Renderer.index())
1389           return false;
1390       } else
1391         return false;
1392     }
1393 
1394     return true;
1395   }
1396 
1397 public:
1398   BuildMIAction(unsigned InsnID, const CodeGenInstruction *I,
1399                 const InstructionMatcher &Matched)
1400       : InsnID(InsnID), I(I), Matched(Matched) {}
1401 
1402   template <class Kind, class... Args>
1403   Kind &addRenderer(Args&&... args) {
1404     OperandRenderers.emplace_back(
1405         llvm::make_unique<Kind>(std::forward<Args>(args)...));
1406     return *static_cast<Kind *>(OperandRenderers.back().get());
1407   }
1408 
1409   void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule,
1410                          unsigned RecycleInsnID) const override {
1411     if (canMutate()) {
1412       Table << MatchTable::Opcode("GIR_MutateOpcode")
1413             << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1414             << MatchTable::Comment("RecycleInsnID")
1415             << MatchTable::IntValue(RecycleInsnID)
1416             << MatchTable::Comment("Opcode")
1417             << MatchTable::NamedValue(I->Namespace, I->TheDef->getName())
1418             << MatchTable::LineBreak;
1419 
1420       if (!I->ImplicitDefs.empty() || !I->ImplicitUses.empty()) {
1421         for (auto Def : I->ImplicitDefs) {
1422           auto Namespace = Def->getValue("Namespace")
1423                                ? Def->getValueAsString("Namespace")
1424                                : "";
1425           Table << MatchTable::Opcode("GIR_AddImplicitDef")
1426                 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1427                 << MatchTable::NamedValue(Namespace, Def->getName())
1428                 << MatchTable::LineBreak;
1429         }
1430         for (auto Use : I->ImplicitUses) {
1431           auto Namespace = Use->getValue("Namespace")
1432                                ? Use->getValueAsString("Namespace")
1433                                : "";
1434           Table << MatchTable::Opcode("GIR_AddImplicitUse")
1435                 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1436                 << MatchTable::NamedValue(Namespace, Use->getName())
1437                 << MatchTable::LineBreak;
1438         }
1439       }
1440       return;
1441     }
1442 
1443     // TODO: Simple permutation looks like it could be almost as common as
1444     //       mutation due to commutative operations.
1445 
1446     Table << MatchTable::Opcode("GIR_BuildMI") << MatchTable::Comment("InsnID")
1447           << MatchTable::IntValue(InsnID) << MatchTable::Comment("Opcode")
1448           << MatchTable::NamedValue(I->Namespace, I->TheDef->getName())
1449           << MatchTable::LineBreak;
1450     for (const auto &Renderer : OperandRenderers)
1451       Renderer->emitRenderOpcodes(Table, Rule);
1452 
1453     Table << MatchTable::Opcode("GIR_MergeMemOperands")
1454           << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1455           << MatchTable::LineBreak << MatchTable::Opcode("GIR_EraseFromParent")
1456           << MatchTable::Comment("InsnID")
1457           << MatchTable::IntValue(RecycleInsnID) << MatchTable::LineBreak;
1458   }
1459 };
1460 
1461 /// Generates code to constrain the operands of an output instruction to the
1462 /// register classes specified by the definition of that instruction.
1463 class ConstrainOperandsToDefinitionAction : public MatchAction {
1464   unsigned InsnID;
1465 
1466 public:
1467   ConstrainOperandsToDefinitionAction(unsigned InsnID) : InsnID(InsnID) {}
1468 
1469   void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule,
1470                          unsigned RecycleInsnID) const override {
1471     Table << MatchTable::Opcode("GIR_ConstrainSelectedInstOperands")
1472           << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1473           << MatchTable::LineBreak;
1474   }
1475 };
1476 
1477 /// Generates code to constrain the specified operand of an output instruction
1478 /// to the specified register class.
1479 class ConstrainOperandToRegClassAction : public MatchAction {
1480   unsigned InsnID;
1481   unsigned OpIdx;
1482   const CodeGenRegisterClass &RC;
1483 
1484 public:
1485   ConstrainOperandToRegClassAction(unsigned InsnID, unsigned OpIdx,
1486                                    const CodeGenRegisterClass &RC)
1487       : InsnID(InsnID), OpIdx(OpIdx), RC(RC) {}
1488 
1489   void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule,
1490                          unsigned RecycleInsnID) const override {
1491     Table << MatchTable::Opcode("GIR_ConstrainOperandRC")
1492           << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1493           << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1494           << MatchTable::Comment("RC " + RC.getName())
1495           << MatchTable::IntValue(RC.EnumValue) << MatchTable::LineBreak;
1496   }
1497 };
1498 
1499 InstructionMatcher &RuleMatcher::addInstructionMatcher() {
1500   Matchers.emplace_back(new InstructionMatcher());
1501   return *Matchers.back();
1502 }
1503 
1504 void RuleMatcher::addRequiredFeature(Record *Feature) {
1505   RequiredFeatures.push_back(Feature);
1506 }
1507 
1508 const std::vector<Record *> &RuleMatcher::getRequiredFeatures() const {
1509   return RequiredFeatures;
1510 }
1511 
1512 template <class Kind, class... Args>
1513 Kind &RuleMatcher::addAction(Args &&... args) {
1514   Actions.emplace_back(llvm::make_unique<Kind>(std::forward<Args>(args)...));
1515   return *static_cast<Kind *>(Actions.back().get());
1516 }
1517 
1518 unsigned
1519 RuleMatcher::implicitlyDefineInsnVar(const InstructionMatcher &Matcher) {
1520   unsigned NewInsnVarID = NextInsnVarID++;
1521   InsnVariableIDs[&Matcher] = NewInsnVarID;
1522   return NewInsnVarID;
1523 }
1524 
1525 unsigned RuleMatcher::defineInsnVar(MatchTable &Table,
1526                                     const InstructionMatcher &Matcher,
1527                                     unsigned InsnID, unsigned OpIdx) {
1528   unsigned NewInsnVarID = implicitlyDefineInsnVar(Matcher);
1529   Table << MatchTable::Opcode("GIM_RecordInsn")
1530         << MatchTable::Comment("DefineMI") << MatchTable::IntValue(NewInsnVarID)
1531         << MatchTable::Comment("MI") << MatchTable::IntValue(InsnID)
1532         << MatchTable::Comment("OpIdx") << MatchTable::IntValue(OpIdx)
1533         << MatchTable::Comment("MIs[" + llvm::to_string(NewInsnVarID) + "]")
1534         << MatchTable::LineBreak;
1535   return NewInsnVarID;
1536 }
1537 
1538 unsigned RuleMatcher::getInsnVarID(const InstructionMatcher &InsnMatcher) const {
1539   const auto &I = InsnVariableIDs.find(&InsnMatcher);
1540   if (I != InsnVariableIDs.end())
1541     return I->second;
1542   llvm_unreachable("Matched Insn was not captured in a local variable");
1543 }
1544 
1545 /// Emit MatchTable opcodes to check the shape of the match and capture
1546 /// instructions into local variables.
1547 void RuleMatcher::emitCaptureOpcodes(MatchTable &Table) {
1548   assert(Matchers.size() == 1 && "Cannot handle multi-root matchers yet");
1549   unsigned InsnVarID = implicitlyDefineInsnVar(*Matchers.front());
1550   Matchers.front()->emitCaptureOpcodes(Table, *this, InsnVarID);
1551 }
1552 
1553 void RuleMatcher::emit(MatchTable &Table) {
1554   if (Matchers.empty())
1555     llvm_unreachable("Unexpected empty matcher!");
1556 
1557   // The representation supports rules that require multiple roots such as:
1558   //    %ptr(p0) = ...
1559   //    %elt0(s32) = G_LOAD %ptr
1560   //    %1(p0) = G_ADD %ptr, 4
1561   //    %elt1(s32) = G_LOAD p0 %1
1562   // which could be usefully folded into:
1563   //    %ptr(p0) = ...
1564   //    %elt0(s32), %elt1(s32) = TGT_LOAD_PAIR %ptr
1565   // on some targets but we don't need to make use of that yet.
1566   assert(Matchers.size() == 1 && "Cannot handle multi-root matchers yet");
1567 
1568   unsigned LabelID = Table.allocateLabelID();
1569   Table << MatchTable::Opcode("GIM_Try", +1)
1570         << MatchTable::Comment("On fail goto") << MatchTable::JumpTarget(LabelID)
1571         << MatchTable::LineBreak;
1572 
1573   if (!RequiredFeatures.empty()) {
1574     Table << MatchTable::Opcode("GIM_CheckFeatures")
1575           << MatchTable::NamedValue(getNameForFeatureBitset(RequiredFeatures))
1576           << MatchTable::LineBreak;
1577   }
1578 
1579   emitCaptureOpcodes(Table);
1580 
1581   Matchers.front()->emitPredicateOpcodes(Table, *this,
1582                                          getInsnVarID(*Matchers.front()));
1583 
1584   // We must also check if it's safe to fold the matched instructions.
1585   if (InsnVariableIDs.size() >= 2) {
1586     // Invert the map to create stable ordering (by var names)
1587     SmallVector<unsigned, 2> InsnIDs;
1588     for (const auto &Pair : InsnVariableIDs) {
1589       // Skip the root node since it isn't moving anywhere. Everything else is
1590       // sinking to meet it.
1591       if (Pair.first == Matchers.front().get())
1592         continue;
1593 
1594       InsnIDs.push_back(Pair.second);
1595     }
1596     std::sort(InsnIDs.begin(), InsnIDs.end());
1597 
1598     for (const auto &InsnID : InsnIDs) {
1599       // Reject the difficult cases until we have a more accurate check.
1600       Table << MatchTable::Opcode("GIM_CheckIsSafeToFold")
1601             << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1602             << MatchTable::LineBreak;
1603 
1604       // FIXME: Emit checks to determine it's _actually_ safe to fold and/or
1605       //        account for unsafe cases.
1606       //
1607       //        Example:
1608       //          MI1--> %0 = ...
1609       //                 %1 = ... %0
1610       //          MI0--> %2 = ... %0
1611       //          It's not safe to erase MI1. We currently handle this by not
1612       //          erasing %0 (even when it's dead).
1613       //
1614       //        Example:
1615       //          MI1--> %0 = load volatile @a
1616       //                 %1 = load volatile @a
1617       //          MI0--> %2 = ... %0
1618       //          It's not safe to sink %0's def past %1. We currently handle
1619       //          this by rejecting all loads.
1620       //
1621       //        Example:
1622       //          MI1--> %0 = load @a
1623       //                 %1 = store @a
1624       //          MI0--> %2 = ... %0
1625       //          It's not safe to sink %0's def past %1. We currently handle
1626       //          this by rejecting all loads.
1627       //
1628       //        Example:
1629       //                   G_CONDBR %cond, @BB1
1630       //                 BB0:
1631       //          MI1-->   %0 = load @a
1632       //                   G_BR @BB1
1633       //                 BB1:
1634       //          MI0-->   %2 = ... %0
1635       //          It's not always safe to sink %0 across control flow. In this
1636       //          case it may introduce a memory fault. We currentl handle this
1637       //          by rejecting all loads.
1638     }
1639   }
1640 
1641   for (const auto &MA : Actions)
1642     MA->emitActionOpcodes(Table, *this, 0);
1643   Table << MatchTable::Opcode("GIR_Done", -1) << MatchTable::LineBreak
1644         << MatchTable::Label(LabelID);
1645 }
1646 
1647 bool RuleMatcher::isHigherPriorityThan(const RuleMatcher &B) const {
1648   // Rules involving more match roots have higher priority.
1649   if (Matchers.size() > B.Matchers.size())
1650     return true;
1651   if (Matchers.size() < B.Matchers.size())
1652     return false;
1653 
1654   for (const auto &Matcher : zip(Matchers, B.Matchers)) {
1655     if (std::get<0>(Matcher)->isHigherPriorityThan(*std::get<1>(Matcher)))
1656       return true;
1657     if (std::get<1>(Matcher)->isHigherPriorityThan(*std::get<0>(Matcher)))
1658       return false;
1659   }
1660 
1661   return false;
1662 }
1663 
1664 unsigned RuleMatcher::countRendererFns() const {
1665   return std::accumulate(
1666       Matchers.begin(), Matchers.end(), 0,
1667       [](unsigned A, const std::unique_ptr<InstructionMatcher> &Matcher) {
1668         return A + Matcher->countRendererFns();
1669       });
1670 }
1671 
1672 //===- GlobalISelEmitter class --------------------------------------------===//
1673 
1674 class GlobalISelEmitter {
1675 public:
1676   explicit GlobalISelEmitter(RecordKeeper &RK);
1677   void run(raw_ostream &OS);
1678 
1679 private:
1680   const RecordKeeper &RK;
1681   const CodeGenDAGPatterns CGP;
1682   const CodeGenTarget &Target;
1683   CodeGenRegBank CGRegs;
1684 
1685   /// Keep track of the equivalence between SDNodes and Instruction.
1686   /// This is defined using 'GINodeEquiv' in the target description.
1687   DenseMap<Record *, const CodeGenInstruction *> NodeEquivs;
1688 
1689   /// Keep track of the equivalence between ComplexPattern's and
1690   /// GIComplexOperandMatcher. Map entries are specified by subclassing
1691   /// GIComplexPatternEquiv.
1692   DenseMap<const Record *, const Record *> ComplexPatternEquivs;
1693 
1694   // Map of predicates to their subtarget features.
1695   SubtargetFeatureInfoMap SubtargetFeatures;
1696 
1697   void gatherNodeEquivs();
1698   const CodeGenInstruction *findNodeEquiv(Record *N) const;
1699 
1700   Error importRulePredicates(RuleMatcher &M, ArrayRef<Init *> Predicates);
1701   Expected<InstructionMatcher &>
1702   createAndImportSelDAGMatcher(InstructionMatcher &InsnMatcher,
1703                                const TreePatternNode *Src,
1704                                unsigned &TempOpIdx) const;
1705   Error importChildMatcher(InstructionMatcher &InsnMatcher,
1706                            const TreePatternNode *SrcChild, unsigned OpIdx,
1707                            unsigned &TempOpIdx) const;
1708   Expected<BuildMIAction &>
1709   createAndImportInstructionRenderer(RuleMatcher &M, const TreePatternNode *Dst,
1710                                      const InstructionMatcher &InsnMatcher);
1711   Error importExplicitUseRenderer(BuildMIAction &DstMIBuilder,
1712                                   TreePatternNode *DstChild,
1713                                   const InstructionMatcher &InsnMatcher) const;
1714   Error importDefaultOperandRenderers(BuildMIAction &DstMIBuilder,
1715                                       DagInit *DefaultOps) const;
1716   Error
1717   importImplicitDefRenderers(BuildMIAction &DstMIBuilder,
1718                              const std::vector<Record *> &ImplicitDefs) const;
1719 
1720   /// Analyze pattern \p P, returning a matcher for it if possible.
1721   /// Otherwise, return an Error explaining why we don't support it.
1722   Expected<RuleMatcher> runOnPattern(const PatternToMatch &P);
1723 
1724   void declareSubtargetFeature(Record *Predicate);
1725 };
1726 
1727 void GlobalISelEmitter::gatherNodeEquivs() {
1728   assert(NodeEquivs.empty());
1729   for (Record *Equiv : RK.getAllDerivedDefinitions("GINodeEquiv"))
1730     NodeEquivs[Equiv->getValueAsDef("Node")] =
1731         &Target.getInstruction(Equiv->getValueAsDef("I"));
1732 
1733   assert(ComplexPatternEquivs.empty());
1734   for (Record *Equiv : RK.getAllDerivedDefinitions("GIComplexPatternEquiv")) {
1735     Record *SelDAGEquiv = Equiv->getValueAsDef("SelDAGEquivalent");
1736     if (!SelDAGEquiv)
1737       continue;
1738     ComplexPatternEquivs[SelDAGEquiv] = Equiv;
1739  }
1740 }
1741 
1742 const CodeGenInstruction *GlobalISelEmitter::findNodeEquiv(Record *N) const {
1743   return NodeEquivs.lookup(N);
1744 }
1745 
1746 GlobalISelEmitter::GlobalISelEmitter(RecordKeeper &RK)
1747     : RK(RK), CGP(RK), Target(CGP.getTargetInfo()), CGRegs(RK) {}
1748 
1749 //===- Emitter ------------------------------------------------------------===//
1750 
1751 Error
1752 GlobalISelEmitter::importRulePredicates(RuleMatcher &M,
1753                                         ArrayRef<Init *> Predicates) {
1754   for (const Init *Predicate : Predicates) {
1755     const DefInit *PredicateDef = static_cast<const DefInit *>(Predicate);
1756     declareSubtargetFeature(PredicateDef->getDef());
1757     M.addRequiredFeature(PredicateDef->getDef());
1758   }
1759 
1760   return Error::success();
1761 }
1762 
1763 Expected<InstructionMatcher &>
1764 GlobalISelEmitter::createAndImportSelDAGMatcher(InstructionMatcher &InsnMatcher,
1765                                                 const TreePatternNode *Src,
1766                                                 unsigned &TempOpIdx) const {
1767   const CodeGenInstruction *SrcGIOrNull = nullptr;
1768 
1769   // Start with the defined operands (i.e., the results of the root operator).
1770   if (Src->getExtTypes().size() > 1)
1771     return failedImport("Src pattern has multiple results");
1772 
1773   if (Src->isLeaf()) {
1774     Init *SrcInit = Src->getLeafValue();
1775     if (isa<IntInit>(SrcInit)) {
1776       InsnMatcher.addPredicate<InstructionOpcodeMatcher>(
1777           &Target.getInstruction(RK.getDef("G_CONSTANT")));
1778     } else
1779       return failedImport(
1780           "Unable to deduce gMIR opcode to handle Src (which is a leaf)");
1781   } else {
1782     SrcGIOrNull = findNodeEquiv(Src->getOperator());
1783     if (!SrcGIOrNull)
1784       return failedImport("Pattern operator lacks an equivalent Instruction" +
1785                           explainOperator(Src->getOperator()));
1786     auto &SrcGI = *SrcGIOrNull;
1787 
1788     // The operators look good: match the opcode
1789     InsnMatcher.addPredicate<InstructionOpcodeMatcher>(&SrcGI);
1790   }
1791 
1792   unsigned OpIdx = 0;
1793   for (const EEVT::TypeSet &Ty : Src->getExtTypes()) {
1794     auto OpTyOrNone = MVTToLLT(Ty.getConcrete());
1795 
1796     if (!OpTyOrNone)
1797       return failedImport(
1798           "Result of Src pattern operator has an unsupported type");
1799 
1800     // Results don't have a name unless they are the root node. The caller will
1801     // set the name if appropriate.
1802     OperandMatcher &OM = InsnMatcher.addOperand(OpIdx++, "", TempOpIdx);
1803     OM.addPredicate<LLTOperandMatcher>(*OpTyOrNone);
1804   }
1805 
1806   if (Src->isLeaf()) {
1807     Init *SrcInit = Src->getLeafValue();
1808     if (IntInit *SrcIntInit = dyn_cast<IntInit>(SrcInit)) {
1809       OperandMatcher &OM = InsnMatcher.addOperand(OpIdx++, "", TempOpIdx);
1810       OM.addPredicate<LiteralIntOperandMatcher>(SrcIntInit->getValue());
1811     } else
1812       return failedImport(
1813           "Unable to deduce gMIR opcode to handle Src (which is a leaf)");
1814   } else {
1815     assert(SrcGIOrNull &&
1816            "Expected to have already found an equivalent Instruction");
1817     // Match the used operands (i.e. the children of the operator).
1818     for (unsigned i = 0, e = Src->getNumChildren(); i != e; ++i) {
1819       TreePatternNode *SrcChild = Src->getChild(i);
1820 
1821       // For G_INTRINSIC, the operand immediately following the defs is an
1822       // intrinsic ID.
1823       if (SrcGIOrNull->TheDef->getName() == "G_INTRINSIC" && i == 0) {
1824         if (const CodeGenIntrinsic *II = Src->getIntrinsicInfo(CGP)) {
1825           OperandMatcher &OM =
1826               InsnMatcher.addOperand(OpIdx++, SrcChild->getName(), TempOpIdx);
1827           OM.addPredicate<IntrinsicIDOperandMatcher>(II);
1828           continue;
1829         }
1830 
1831         return failedImport("Expected IntInit containing instrinsic ID)");
1832       }
1833 
1834       if (auto Error =
1835               importChildMatcher(InsnMatcher, SrcChild, OpIdx++, TempOpIdx))
1836         return std::move(Error);
1837     }
1838   }
1839 
1840   return InsnMatcher;
1841 }
1842 
1843 Error GlobalISelEmitter::importChildMatcher(InstructionMatcher &InsnMatcher,
1844                                             const TreePatternNode *SrcChild,
1845                                             unsigned OpIdx,
1846                                             unsigned &TempOpIdx) const {
1847   OperandMatcher &OM =
1848       InsnMatcher.addOperand(OpIdx, SrcChild->getName(), TempOpIdx);
1849 
1850   if (SrcChild->hasAnyPredicate())
1851     return failedImport("Src pattern child has predicate (" +
1852                         explainPredicates(SrcChild) + ")");
1853 
1854   ArrayRef<EEVT::TypeSet> ChildTypes = SrcChild->getExtTypes();
1855   if (ChildTypes.size() != 1)
1856     return failedImport("Src pattern child has multiple results");
1857 
1858   // Check MBB's before the type check since they are not a known type.
1859   if (!SrcChild->isLeaf()) {
1860     if (SrcChild->getOperator()->isSubClassOf("SDNode")) {
1861       auto &ChildSDNI = CGP.getSDNodeInfo(SrcChild->getOperator());
1862       if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") {
1863         OM.addPredicate<MBBOperandMatcher>();
1864         return Error::success();
1865       }
1866     }
1867   }
1868 
1869   auto OpTyOrNone = MVTToLLT(ChildTypes.front().getConcrete());
1870   if (!OpTyOrNone)
1871     return failedImport("Src operand has an unsupported type (" + to_string(*SrcChild) + ")");
1872   OM.addPredicate<LLTOperandMatcher>(*OpTyOrNone);
1873 
1874   // Check for nested instructions.
1875   if (!SrcChild->isLeaf()) {
1876     // Map the node to a gMIR instruction.
1877     InstructionOperandMatcher &InsnOperand =
1878         OM.addPredicate<InstructionOperandMatcher>();
1879     auto InsnMatcherOrError = createAndImportSelDAGMatcher(
1880         InsnOperand.getInsnMatcher(), SrcChild, TempOpIdx);
1881     if (auto Error = InsnMatcherOrError.takeError())
1882       return Error;
1883 
1884     return Error::success();
1885   }
1886 
1887   // Check for constant immediates.
1888   if (auto *ChildInt = dyn_cast<IntInit>(SrcChild->getLeafValue())) {
1889     OM.addPredicate<ConstantIntOperandMatcher>(ChildInt->getValue());
1890     return Error::success();
1891   }
1892 
1893   // Check for def's like register classes or ComplexPattern's.
1894   if (auto *ChildDefInit = dyn_cast<DefInit>(SrcChild->getLeafValue())) {
1895     auto *ChildRec = ChildDefInit->getDef();
1896 
1897     // Check for register classes.
1898     if (ChildRec->isSubClassOf("RegisterClass") ||
1899         ChildRec->isSubClassOf("RegisterOperand")) {
1900       OM.addPredicate<RegisterBankOperandMatcher>(
1901           Target.getRegisterClass(getInitValueAsRegClass(ChildDefInit)));
1902       return Error::success();
1903     }
1904 
1905     // Check for ComplexPattern's.
1906     if (ChildRec->isSubClassOf("ComplexPattern")) {
1907       const auto &ComplexPattern = ComplexPatternEquivs.find(ChildRec);
1908       if (ComplexPattern == ComplexPatternEquivs.end())
1909         return failedImport("SelectionDAG ComplexPattern (" +
1910                             ChildRec->getName() + ") not mapped to GlobalISel");
1911 
1912       OM.addPredicate<ComplexPatternOperandMatcher>(OM,
1913                                                     *ComplexPattern->second);
1914       TempOpIdx++;
1915       return Error::success();
1916     }
1917 
1918     if (ChildRec->isSubClassOf("ImmLeaf")) {
1919       return failedImport(
1920           "Src pattern child def is an unsupported tablegen class (ImmLeaf)");
1921     }
1922 
1923     return failedImport(
1924         "Src pattern child def is an unsupported tablegen class");
1925   }
1926 
1927   return failedImport("Src pattern child is an unsupported kind");
1928 }
1929 
1930 Error GlobalISelEmitter::importExplicitUseRenderer(
1931     BuildMIAction &DstMIBuilder, TreePatternNode *DstChild,
1932     const InstructionMatcher &InsnMatcher) const {
1933   // The only non-leaf child we accept is 'bb': it's an operator because
1934   // BasicBlockSDNode isn't inline, but in MI it's just another operand.
1935   if (!DstChild->isLeaf()) {
1936     if (DstChild->getOperator()->isSubClassOf("SDNode")) {
1937       auto &ChildSDNI = CGP.getSDNodeInfo(DstChild->getOperator());
1938       if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") {
1939         DstMIBuilder.addRenderer<CopyRenderer>(0, InsnMatcher,
1940                                                DstChild->getName());
1941         return Error::success();
1942       }
1943     }
1944     return failedImport("Dst pattern child isn't a leaf node or an MBB");
1945   }
1946 
1947   // Otherwise, we're looking for a bog-standard RegisterClass operand.
1948   if (DstChild->hasAnyPredicate())
1949     return failedImport("Dst pattern child has predicate (" +
1950                         explainPredicates(DstChild) + ")");
1951 
1952   if (auto *ChildDefInit = dyn_cast<DefInit>(DstChild->getLeafValue())) {
1953     auto *ChildRec = ChildDefInit->getDef();
1954 
1955     ArrayRef<EEVT::TypeSet> ChildTypes = DstChild->getExtTypes();
1956     if (ChildTypes.size() != 1)
1957       return failedImport("Dst pattern child has multiple results");
1958 
1959     auto OpTyOrNone = MVTToLLT(ChildTypes.front().getConcrete());
1960     if (!OpTyOrNone)
1961       return failedImport("Dst operand has an unsupported type");
1962 
1963     if (ChildRec->isSubClassOf("Register")) {
1964       DstMIBuilder.addRenderer<AddRegisterRenderer>(0, ChildRec);
1965       return Error::success();
1966     }
1967 
1968     if (ChildRec->isSubClassOf("RegisterClass") ||
1969         ChildRec->isSubClassOf("RegisterOperand")) {
1970       DstMIBuilder.addRenderer<CopyRenderer>(0, InsnMatcher,
1971                                              DstChild->getName());
1972       return Error::success();
1973     }
1974 
1975     if (ChildRec->isSubClassOf("ComplexPattern")) {
1976       const auto &ComplexPattern = ComplexPatternEquivs.find(ChildRec);
1977       if (ComplexPattern == ComplexPatternEquivs.end())
1978         return failedImport(
1979             "SelectionDAG ComplexPattern not mapped to GlobalISel");
1980 
1981       const OperandMatcher &OM = InsnMatcher.getOperand(DstChild->getName());
1982       DstMIBuilder.addRenderer<RenderComplexPatternOperand>(
1983           0, *ComplexPattern->second, DstChild->getName(),
1984           OM.getAllocatedTemporariesBaseID());
1985       return Error::success();
1986     }
1987 
1988     if (ChildRec->isSubClassOf("SDNodeXForm"))
1989       return failedImport("Dst pattern child def is an unsupported tablegen "
1990                           "class (SDNodeXForm)");
1991 
1992     return failedImport(
1993         "Dst pattern child def is an unsupported tablegen class");
1994   }
1995 
1996   return failedImport("Dst pattern child is an unsupported kind");
1997 }
1998 
1999 Expected<BuildMIAction &> GlobalISelEmitter::createAndImportInstructionRenderer(
2000     RuleMatcher &M, const TreePatternNode *Dst,
2001     const InstructionMatcher &InsnMatcher) {
2002   Record *DstOp = Dst->getOperator();
2003   if (!DstOp->isSubClassOf("Instruction")) {
2004     if (DstOp->isSubClassOf("ValueType"))
2005       return failedImport(
2006           "Pattern operator isn't an instruction (it's a ValueType)");
2007     return failedImport("Pattern operator isn't an instruction");
2008   }
2009   CodeGenInstruction *DstI = &Target.getInstruction(DstOp);
2010 
2011   unsigned DstINumUses = DstI->Operands.size() - DstI->Operands.NumDefs;
2012   unsigned ExpectedDstINumUses = Dst->getNumChildren();
2013   bool IsExtractSubReg = false;
2014 
2015   // COPY_TO_REGCLASS is just a copy with a ConstrainOperandToRegClassAction
2016   // attached. Similarly for EXTRACT_SUBREG except that's a subregister copy.
2017   if (DstI->TheDef->getName() == "COPY_TO_REGCLASS") {
2018     DstI = &Target.getInstruction(RK.getDef("COPY"));
2019     DstINumUses--; // Ignore the class constraint.
2020     ExpectedDstINumUses--;
2021   } else if (DstI->TheDef->getName() == "EXTRACT_SUBREG") {
2022     DstI = &Target.getInstruction(RK.getDef("COPY"));
2023     IsExtractSubReg = true;
2024   }
2025 
2026   auto &DstMIBuilder = M.addAction<BuildMIAction>(0, DstI, InsnMatcher);
2027 
2028   // Render the explicit defs.
2029   for (unsigned I = 0; I < DstI->Operands.NumDefs; ++I) {
2030     const CGIOperandList::OperandInfo &DstIOperand = DstI->Operands[I];
2031     DstMIBuilder.addRenderer<CopyRenderer>(0, InsnMatcher, DstIOperand.Name);
2032   }
2033 
2034   // EXTRACT_SUBREG needs to use a subregister COPY.
2035   if (IsExtractSubReg) {
2036     if (!Dst->getChild(0)->isLeaf())
2037       return failedImport("EXTRACT_SUBREG child #1 is not a leaf");
2038 
2039     if (DefInit *SubRegInit =
2040             dyn_cast<DefInit>(Dst->getChild(1)->getLeafValue())) {
2041       CodeGenRegisterClass *RC = CGRegs.getRegClass(
2042           getInitValueAsRegClass(Dst->getChild(0)->getLeafValue()));
2043       CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef());
2044 
2045       const auto &SrcRCDstRCPair =
2046           RC->getMatchingSubClassWithSubRegs(CGRegs, SubIdx);
2047       if (SrcRCDstRCPair.hasValue()) {
2048         assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
2049         if (SrcRCDstRCPair->first != RC)
2050           return failedImport("EXTRACT_SUBREG requires an additional COPY");
2051       }
2052 
2053       DstMIBuilder.addRenderer<CopySubRegRenderer>(
2054           0, InsnMatcher, Dst->getChild(0)->getName(), SubIdx);
2055       return DstMIBuilder;
2056     }
2057 
2058     return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
2059   }
2060 
2061   // Render the explicit uses.
2062   unsigned Child = 0;
2063   unsigned NumDefaultOps = 0;
2064   for (unsigned I = 0; I != DstINumUses; ++I) {
2065     const CGIOperandList::OperandInfo &DstIOperand =
2066         DstI->Operands[DstI->Operands.NumDefs + I];
2067 
2068     // If the operand has default values, introduce them now.
2069     // FIXME: Until we have a decent test case that dictates we should do
2070     // otherwise, we're going to assume that operands with default values cannot
2071     // be specified in the patterns. Therefore, adding them will not cause us to
2072     // end up with too many rendered operands.
2073     if (DstIOperand.Rec->isSubClassOf("OperandWithDefaultOps")) {
2074       DagInit *DefaultOps = DstIOperand.Rec->getValueAsDag("DefaultOps");
2075       if (auto Error = importDefaultOperandRenderers(DstMIBuilder, DefaultOps))
2076         return std::move(Error);
2077       ++NumDefaultOps;
2078       continue;
2079     }
2080 
2081     if (auto Error = importExplicitUseRenderer(
2082             DstMIBuilder, Dst->getChild(Child), InsnMatcher))
2083       return std::move(Error);
2084     ++Child;
2085   }
2086 
2087   if (NumDefaultOps + ExpectedDstINumUses != DstINumUses)
2088     return failedImport("Expected " + llvm::to_string(DstINumUses) +
2089                         " used operands but found " +
2090                         llvm::to_string(ExpectedDstINumUses) +
2091                         " explicit ones and " + llvm::to_string(NumDefaultOps) +
2092                         " default ones");
2093 
2094   return DstMIBuilder;
2095 }
2096 
2097 Error GlobalISelEmitter::importDefaultOperandRenderers(
2098     BuildMIAction &DstMIBuilder, DagInit *DefaultOps) const {
2099   for (const auto *DefaultOp : DefaultOps->getArgs()) {
2100     // Look through ValueType operators.
2101     if (const DagInit *DefaultDagOp = dyn_cast<DagInit>(DefaultOp)) {
2102       if (const DefInit *DefaultDagOperator =
2103               dyn_cast<DefInit>(DefaultDagOp->getOperator())) {
2104         if (DefaultDagOperator->getDef()->isSubClassOf("ValueType"))
2105           DefaultOp = DefaultDagOp->getArg(0);
2106       }
2107     }
2108 
2109     if (const DefInit *DefaultDefOp = dyn_cast<DefInit>(DefaultOp)) {
2110       DstMIBuilder.addRenderer<AddRegisterRenderer>(0, DefaultDefOp->getDef());
2111       continue;
2112     }
2113 
2114     if (const IntInit *DefaultIntOp = dyn_cast<IntInit>(DefaultOp)) {
2115       DstMIBuilder.addRenderer<ImmRenderer>(0, DefaultIntOp->getValue());
2116       continue;
2117     }
2118 
2119     return failedImport("Could not add default op");
2120   }
2121 
2122   return Error::success();
2123 }
2124 
2125 Error GlobalISelEmitter::importImplicitDefRenderers(
2126     BuildMIAction &DstMIBuilder,
2127     const std::vector<Record *> &ImplicitDefs) const {
2128   if (!ImplicitDefs.empty())
2129     return failedImport("Pattern defines a physical register");
2130   return Error::success();
2131 }
2132 
2133 Expected<RuleMatcher> GlobalISelEmitter::runOnPattern(const PatternToMatch &P) {
2134   // Keep track of the matchers and actions to emit.
2135   RuleMatcher M;
2136   M.addAction<DebugCommentAction>(P);
2137 
2138   if (auto Error = importRulePredicates(M, P.getPredicates()->getValues()))
2139     return std::move(Error);
2140 
2141   // Next, analyze the pattern operators.
2142   TreePatternNode *Src = P.getSrcPattern();
2143   TreePatternNode *Dst = P.getDstPattern();
2144 
2145   // If the root of either pattern isn't a simple operator, ignore it.
2146   if (auto Err = isTrivialOperatorNode(Dst))
2147     return failedImport("Dst pattern root isn't a trivial operator (" +
2148                         toString(std::move(Err)) + ")");
2149   if (auto Err = isTrivialOperatorNode(Src))
2150     return failedImport("Src pattern root isn't a trivial operator (" +
2151                         toString(std::move(Err)) + ")");
2152 
2153   if (Dst->isLeaf())
2154     return failedImport("Dst pattern root isn't a known leaf");
2155 
2156   // Start with the defined operands (i.e., the results of the root operator).
2157   Record *DstOp = Dst->getOperator();
2158   if (!DstOp->isSubClassOf("Instruction"))
2159     return failedImport("Pattern operator isn't an instruction");
2160 
2161   auto &DstI = Target.getInstruction(DstOp);
2162   if (DstI.Operands.NumDefs != Src->getExtTypes().size())
2163     return failedImport("Src pattern results and dst MI defs are different (" +
2164                         to_string(Src->getExtTypes().size()) + " def(s) vs " +
2165                         to_string(DstI.Operands.NumDefs) + " def(s))");
2166 
2167   InstructionMatcher &InsnMatcherTemp = M.addInstructionMatcher();
2168   unsigned TempOpIdx = 0;
2169   auto InsnMatcherOrError =
2170       createAndImportSelDAGMatcher(InsnMatcherTemp, Src, TempOpIdx);
2171   if (auto Error = InsnMatcherOrError.takeError())
2172     return std::move(Error);
2173   InstructionMatcher &InsnMatcher = InsnMatcherOrError.get();
2174 
2175   // The root of the match also has constraints on the register bank so that it
2176   // matches the result instruction.
2177   unsigned OpIdx = 0;
2178   for (const EEVT::TypeSet &Ty : Src->getExtTypes()) {
2179     (void)Ty;
2180 
2181     const auto &DstIOperand = DstI.Operands[OpIdx];
2182     Record *DstIOpRec = DstIOperand.Rec;
2183     if (DstI.TheDef->getName() == "COPY_TO_REGCLASS") {
2184       DstIOpRec = getInitValueAsRegClass(Dst->getChild(1)->getLeafValue());
2185 
2186       if (DstIOpRec == nullptr)
2187         return failedImport(
2188             "COPY_TO_REGCLASS operand #1 isn't a register class");
2189     } else if (DstI.TheDef->getName() == "EXTRACT_SUBREG") {
2190       if (!Dst->getChild(0)->isLeaf())
2191         return failedImport("EXTRACT_SUBREG operand #0 isn't a leaf");
2192 
2193       // We can assume that a subregister is in the same bank as it's super
2194       // register.
2195       DstIOpRec = getInitValueAsRegClass(Dst->getChild(0)->getLeafValue());
2196 
2197       if (DstIOpRec == nullptr)
2198         return failedImport(
2199             "EXTRACT_SUBREG operand #0 isn't a register class");
2200     } else if (DstIOpRec->isSubClassOf("RegisterOperand"))
2201       DstIOpRec = DstIOpRec->getValueAsDef("RegClass");
2202     else if (!DstIOpRec->isSubClassOf("RegisterClass"))
2203       return failedImport("Dst MI def isn't a register class" +
2204                           to_string(*Dst));
2205 
2206     OperandMatcher &OM = InsnMatcher.getOperand(OpIdx);
2207     OM.setSymbolicName(DstIOperand.Name);
2208     OM.addPredicate<RegisterBankOperandMatcher>(
2209         Target.getRegisterClass(DstIOpRec));
2210     ++OpIdx;
2211   }
2212 
2213   auto DstMIBuilderOrError =
2214       createAndImportInstructionRenderer(M, Dst, InsnMatcher);
2215   if (auto Error = DstMIBuilderOrError.takeError())
2216     return std::move(Error);
2217   BuildMIAction &DstMIBuilder = DstMIBuilderOrError.get();
2218 
2219   // Render the implicit defs.
2220   // These are only added to the root of the result.
2221   if (auto Error = importImplicitDefRenderers(DstMIBuilder, P.getDstRegs()))
2222     return std::move(Error);
2223 
2224   // Constrain the registers to classes. This is normally derived from the
2225   // emitted instruction but a few instructions require special handling.
2226   if (DstI.TheDef->getName() == "COPY_TO_REGCLASS") {
2227     // COPY_TO_REGCLASS does not provide operand constraints itself but the
2228     // result is constrained to the class given by the second child.
2229     Record *DstIOpRec =
2230         getInitValueAsRegClass(Dst->getChild(1)->getLeafValue());
2231 
2232     if (DstIOpRec == nullptr)
2233       return failedImport("COPY_TO_REGCLASS operand #1 isn't a register class");
2234 
2235     M.addAction<ConstrainOperandToRegClassAction>(
2236         0, 0, Target.getRegisterClass(DstIOpRec));
2237 
2238     // We're done with this pattern!  It's eligible for GISel emission; return
2239     // it.
2240     ++NumPatternImported;
2241     return std::move(M);
2242   }
2243 
2244   if (DstI.TheDef->getName() == "EXTRACT_SUBREG") {
2245     // EXTRACT_SUBREG selects into a subregister COPY but unlike most
2246     // instructions, the result register class is controlled by the
2247     // subregisters of the operand. As a result, we must constrain the result
2248     // class rather than check that it's already the right one.
2249     if (!Dst->getChild(0)->isLeaf())
2250       return failedImport("EXTRACT_SUBREG child #1 is not a leaf");
2251 
2252     DefInit *SubRegInit = dyn_cast<DefInit>(Dst->getChild(1)->getLeafValue());
2253     if (!SubRegInit)
2254       return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
2255 
2256     // Constrain the result to the same register bank as the operand.
2257     Record *DstIOpRec =
2258         getInitValueAsRegClass(Dst->getChild(0)->getLeafValue());
2259 
2260     if (DstIOpRec == nullptr)
2261       return failedImport("EXTRACT_SUBREG operand #1 isn't a register class");
2262 
2263     CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef());
2264     CodeGenRegisterClass *SrcRC = CGRegs.getRegClass(DstIOpRec);
2265 
2266     // It would be nice to leave this constraint implicit but we're required
2267     // to pick a register class so constrain the result to a register class
2268     // that can hold the correct MVT.
2269     //
2270     // FIXME: This may introduce an extra copy if the chosen class doesn't
2271     //        actually contain the subregisters.
2272     assert(Src->getExtTypes().size() == 1 &&
2273              "Expected Src of EXTRACT_SUBREG to have one result type");
2274 
2275     const auto &SrcRCDstRCPair =
2276         SrcRC->getMatchingSubClassWithSubRegs(CGRegs, SubIdx);
2277     assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
2278     M.addAction<ConstrainOperandToRegClassAction>(0, 0, *SrcRCDstRCPair->second);
2279     M.addAction<ConstrainOperandToRegClassAction>(0, 1, *SrcRCDstRCPair->first);
2280 
2281     // We're done with this pattern!  It's eligible for GISel emission; return
2282     // it.
2283     ++NumPatternImported;
2284     return std::move(M);
2285   }
2286 
2287   M.addAction<ConstrainOperandsToDefinitionAction>(0);
2288 
2289   // We're done with this pattern!  It's eligible for GISel emission; return it.
2290   ++NumPatternImported;
2291   return std::move(M);
2292 }
2293 
2294 void GlobalISelEmitter::run(raw_ostream &OS) {
2295   // Track the GINodeEquiv definitions.
2296   gatherNodeEquivs();
2297 
2298   emitSourceFileHeader(("Global Instruction Selector for the " +
2299                        Target.getName() + " target").str(), OS);
2300   std::vector<RuleMatcher> Rules;
2301   // Look through the SelectionDAG patterns we found, possibly emitting some.
2302   for (const PatternToMatch &Pat : CGP.ptms()) {
2303     ++NumPatternTotal;
2304     auto MatcherOrErr = runOnPattern(Pat);
2305 
2306     // The pattern analysis can fail, indicating an unsupported pattern.
2307     // Report that if we've been asked to do so.
2308     if (auto Err = MatcherOrErr.takeError()) {
2309       if (WarnOnSkippedPatterns) {
2310         PrintWarning(Pat.getSrcRecord()->getLoc(),
2311                      "Skipped pattern: " + toString(std::move(Err)));
2312       } else {
2313         consumeError(std::move(Err));
2314       }
2315       ++NumPatternImportsSkipped;
2316       continue;
2317     }
2318 
2319     Rules.push_back(std::move(MatcherOrErr.get()));
2320   }
2321 
2322   std::stable_sort(Rules.begin(), Rules.end(),
2323             [&](const RuleMatcher &A, const RuleMatcher &B) {
2324               if (A.isHigherPriorityThan(B)) {
2325                 assert(!B.isHigherPriorityThan(A) && "Cannot be more important "
2326                                                      "and less important at "
2327                                                      "the same time");
2328                 return true;
2329               }
2330               return false;
2331             });
2332 
2333   std::vector<Record *> ComplexPredicates =
2334       RK.getAllDerivedDefinitions("GIComplexOperandMatcher");
2335   std::sort(ComplexPredicates.begin(), ComplexPredicates.end(),
2336             [](const Record *A, const Record *B) {
2337               if (A->getName() < B->getName())
2338                 return true;
2339               return false;
2340             });
2341   unsigned MaxTemporaries = 0;
2342   for (const auto &Rule : Rules)
2343     MaxTemporaries = std::max(MaxTemporaries, Rule.countRendererFns());
2344 
2345   OS << "#ifdef GET_GLOBALISEL_PREDICATE_BITSET\n"
2346      << "const unsigned MAX_SUBTARGET_PREDICATES = " << SubtargetFeatures.size()
2347      << ";\n"
2348      << "using PredicateBitset = "
2349         "llvm::PredicateBitsetImpl<MAX_SUBTARGET_PREDICATES>;\n"
2350      << "#endif // ifdef GET_GLOBALISEL_PREDICATE_BITSET\n\n";
2351 
2352   OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n"
2353      << "  mutable MatcherState State;\n"
2354      << "  typedef "
2355         "ComplexRendererFn("
2356      << Target.getName()
2357      << "InstructionSelector::*ComplexMatcherMemFn)(MachineOperand &) const;\n"
2358      << "const MatcherInfoTy<PredicateBitset, ComplexMatcherMemFn> "
2359         "MatcherInfo;\n"
2360      << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n\n";
2361 
2362   OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n"
2363      << ", State(" << MaxTemporaries << "),\n"
2364      << "MatcherInfo({TypeObjects, FeatureBitsets, {\n"
2365      << "  nullptr, // GICP_Invalid\n";
2366   for (const auto &Record : ComplexPredicates)
2367     OS << "  &" << Target.getName()
2368        << "InstructionSelector::" << Record->getValueAsString("MatcherFn")
2369        << ", // " << Record->getName() << "\n";
2370   OS << "}})\n"
2371      << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n\n";
2372 
2373   OS << "#ifdef GET_GLOBALISEL_IMPL\n";
2374   SubtargetFeatureInfo::emitSubtargetFeatureBitEnumeration(SubtargetFeatures,
2375                                                            OS);
2376 
2377   // Separate subtarget features by how often they must be recomputed.
2378   SubtargetFeatureInfoMap ModuleFeatures;
2379   std::copy_if(SubtargetFeatures.begin(), SubtargetFeatures.end(),
2380                std::inserter(ModuleFeatures, ModuleFeatures.end()),
2381                [](const SubtargetFeatureInfoMap::value_type &X) {
2382                  return !X.second.mustRecomputePerFunction();
2383                });
2384   SubtargetFeatureInfoMap FunctionFeatures;
2385   std::copy_if(SubtargetFeatures.begin(), SubtargetFeatures.end(),
2386                std::inserter(FunctionFeatures, FunctionFeatures.end()),
2387                [](const SubtargetFeatureInfoMap::value_type &X) {
2388                  return X.second.mustRecomputePerFunction();
2389                });
2390 
2391   SubtargetFeatureInfo::emitComputeAvailableFeatures(
2392       Target.getName(), "InstructionSelector", "computeAvailableModuleFeatures",
2393       ModuleFeatures, OS);
2394   SubtargetFeatureInfo::emitComputeAvailableFeatures(
2395       Target.getName(), "InstructionSelector",
2396       "computeAvailableFunctionFeatures", FunctionFeatures, OS,
2397       "const MachineFunction *MF");
2398 
2399   // Emit a table containing the LLT objects needed by the matcher and an enum
2400   // for the matcher to reference them with.
2401   std::vector<LLTCodeGen> TypeObjects = {
2402       LLT::scalar(8),      LLT::scalar(16),     LLT::scalar(32),
2403       LLT::scalar(64),     LLT::scalar(80),     LLT::vector(8, 1),
2404       LLT::vector(16, 1),  LLT::vector(32, 1),  LLT::vector(64, 1),
2405       LLT::vector(8, 8),   LLT::vector(16, 8),  LLT::vector(32, 8),
2406       LLT::vector(64, 8),  LLT::vector(4, 16),  LLT::vector(8, 16),
2407       LLT::vector(16, 16), LLT::vector(32, 16), LLT::vector(2, 32),
2408       LLT::vector(4, 32),  LLT::vector(8, 32),  LLT::vector(16, 32),
2409       LLT::vector(2, 64),  LLT::vector(4, 64),  LLT::vector(8, 64),
2410   };
2411   std::sort(TypeObjects.begin(), TypeObjects.end());
2412   OS << "enum {\n";
2413   for (const auto &TypeObject : TypeObjects) {
2414     OS << "  ";
2415     TypeObject.emitCxxEnumValue(OS);
2416     OS << ",\n";
2417   }
2418   OS << "};\n"
2419      << "const static LLT TypeObjects[] = {\n";
2420   for (const auto &TypeObject : TypeObjects) {
2421     OS << "  ";
2422     TypeObject.emitCxxConstructorCall(OS);
2423     OS << ",\n";
2424   }
2425   OS << "};\n\n";
2426 
2427   // Emit a table containing the PredicateBitsets objects needed by the matcher
2428   // and an enum for the matcher to reference them with.
2429   std::vector<std::vector<Record *>> FeatureBitsets;
2430   for (auto &Rule : Rules)
2431     FeatureBitsets.push_back(Rule.getRequiredFeatures());
2432   std::sort(
2433       FeatureBitsets.begin(), FeatureBitsets.end(),
2434       [&](const std::vector<Record *> &A, const std::vector<Record *> &B) {
2435         if (A.size() < B.size())
2436           return true;
2437         if (A.size() > B.size())
2438           return false;
2439         for (const auto &Pair : zip(A, B)) {
2440           if (std::get<0>(Pair)->getName() < std::get<1>(Pair)->getName())
2441             return true;
2442           if (std::get<0>(Pair)->getName() > std::get<1>(Pair)->getName())
2443             return false;
2444         }
2445         return false;
2446       });
2447   FeatureBitsets.erase(
2448       std::unique(FeatureBitsets.begin(), FeatureBitsets.end()),
2449       FeatureBitsets.end());
2450   OS << "enum {\n"
2451      << "  GIFBS_Invalid,\n";
2452   for (const auto &FeatureBitset : FeatureBitsets) {
2453     if (FeatureBitset.empty())
2454       continue;
2455     OS << "  " << getNameForFeatureBitset(FeatureBitset) << ",\n";
2456   }
2457   OS << "};\n"
2458      << "const static PredicateBitset FeatureBitsets[] {\n"
2459      << "  {}, // GIFBS_Invalid\n";
2460   for (const auto &FeatureBitset : FeatureBitsets) {
2461     if (FeatureBitset.empty())
2462       continue;
2463     OS << "  {";
2464     for (const auto &Feature : FeatureBitset) {
2465       const auto &I = SubtargetFeatures.find(Feature);
2466       assert(I != SubtargetFeatures.end() && "Didn't import predicate?");
2467       OS << I->second.getEnumBitName() << ", ";
2468     }
2469     OS << "},\n";
2470   }
2471   OS << "};\n\n";
2472 
2473   // Emit complex predicate table and an enum to reference them with.
2474   OS << "enum {\n"
2475      << "  GICP_Invalid,\n";
2476   for (const auto &Record : ComplexPredicates)
2477     OS << "  GICP_" << Record->getName() << ",\n";
2478   OS << "};\n"
2479      << "// See constructor for table contents\n\n";
2480 
2481   OS << "bool " << Target.getName()
2482      << "InstructionSelector::selectImpl(MachineInstr &I) const {\n"
2483      << "  MachineFunction &MF = *I.getParent()->getParent();\n"
2484      << "  MachineRegisterInfo &MRI = MF.getRegInfo();\n"
2485      << "  // FIXME: This should be computed on a per-function basis rather "
2486         "than per-insn.\n"
2487      << "  AvailableFunctionFeatures = computeAvailableFunctionFeatures(&STI, "
2488         "&MF);\n"
2489      << "  const PredicateBitset AvailableFeatures = getAvailableFeatures();\n"
2490      << "  NewMIVector OutMIs;\n"
2491      << "  State.MIs.clear();\n"
2492      << "  State.MIs.push_back(&I);\n\n";
2493 
2494   MatchTable Table(0);
2495   for (auto &Rule : Rules) {
2496     Rule.emit(Table);
2497     ++NumPatternEmitted;
2498   }
2499   Table << MatchTable::Opcode("GIM_Reject") << MatchTable::LineBreak;
2500   Table.emitDeclaration(OS);
2501   OS << "  if (executeMatchTable(*this, OutMIs, State, MatcherInfo, ";
2502   Table.emitUse(OS);
2503   OS << ", TII, MRI, TRI, RBI, AvailableFeatures)) {\n"
2504      << "    return true;\n"
2505      << "  }\n\n";
2506 
2507   OS << "  return false;\n"
2508      << "}\n"
2509      << "#endif // ifdef GET_GLOBALISEL_IMPL\n";
2510 
2511   OS << "#ifdef GET_GLOBALISEL_PREDICATES_DECL\n"
2512      << "PredicateBitset AvailableModuleFeatures;\n"
2513      << "mutable PredicateBitset AvailableFunctionFeatures;\n"
2514      << "PredicateBitset getAvailableFeatures() const {\n"
2515      << "  return AvailableModuleFeatures | AvailableFunctionFeatures;\n"
2516      << "}\n"
2517      << "PredicateBitset\n"
2518      << "computeAvailableModuleFeatures(const " << Target.getName()
2519      << "Subtarget *Subtarget) const;\n"
2520      << "PredicateBitset\n"
2521      << "computeAvailableFunctionFeatures(const " << Target.getName()
2522      << "Subtarget *Subtarget,\n"
2523      << "                                 const MachineFunction *MF) const;\n"
2524      << "#endif // ifdef GET_GLOBALISEL_PREDICATES_DECL\n";
2525 
2526   OS << "#ifdef GET_GLOBALISEL_PREDICATES_INIT\n"
2527      << "AvailableModuleFeatures(computeAvailableModuleFeatures(&STI)),\n"
2528      << "AvailableFunctionFeatures()\n"
2529      << "#endif // ifdef GET_GLOBALISEL_PREDICATES_INIT\n";
2530 }
2531 
2532 void GlobalISelEmitter::declareSubtargetFeature(Record *Predicate) {
2533   if (SubtargetFeatures.count(Predicate) == 0)
2534     SubtargetFeatures.emplace(
2535         Predicate, SubtargetFeatureInfo(Predicate, SubtargetFeatures.size()));
2536 }
2537 
2538 } // end anonymous namespace
2539 
2540 //===----------------------------------------------------------------------===//
2541 
2542 namespace llvm {
2543 void EmitGlobalISel(RecordKeeper &RK, raw_ostream &OS) {
2544   GlobalISelEmitter(RK).run(OS);
2545 }
2546 } // End llvm namespace
2547