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