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 "llvm/ADT/Optional.h"
35 #include "llvm/ADT/Statistic.h"
36 #include "llvm/CodeGen/MachineValueType.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/Error.h"
39 #include "llvm/Support/LowLevelTypeImpl.h"
40 #include "llvm/Support/ScopedPrinter.h"
41 #include "llvm/TableGen/Error.h"
42 #include "llvm/TableGen/Record.h"
43 #include "llvm/TableGen/TableGenBackend.h"
44 #include <string>
45 #include <numeric>
46 using namespace llvm;
47 
48 #define DEBUG_TYPE "gisel-emitter"
49 
50 STATISTIC(NumPatternTotal, "Total number of patterns");
51 STATISTIC(NumPatternImported, "Number of patterns imported from SelectionDAG");
52 STATISTIC(NumPatternImportsSkipped, "Number of SelectionDAG imports skipped");
53 STATISTIC(NumPatternEmitted, "Number of patterns emitted");
54 
55 cl::OptionCategory GlobalISelEmitterCat("Options for -gen-global-isel");
56 
57 static cl::opt<bool> WarnOnSkippedPatterns(
58     "warn-on-skipped-patterns",
59     cl::desc("Explain why a pattern was skipped for inclusion "
60              "in the GlobalISel selector"),
61     cl::init(false), cl::cat(GlobalISelEmitterCat));
62 
63 namespace {
64 //===- Helper functions ---------------------------------------------------===//
65 
66 /// This class stands in for LLT wherever we want to tablegen-erate an
67 /// equivalent at compiler run-time.
68 class LLTCodeGen {
69 private:
70   LLT Ty;
71 
72 public:
73   LLTCodeGen(const LLT &Ty) : Ty(Ty) {}
74 
75   void emitCxxConstructorCall(raw_ostream &OS) const {
76     if (Ty.isScalar()) {
77       OS << "LLT::scalar(" << Ty.getSizeInBits() << ")";
78       return;
79     }
80     if (Ty.isVector()) {
81       OS << "LLT::vector(" << Ty.getNumElements() << ", " << Ty.getSizeInBits()
82          << ")";
83       return;
84     }
85     llvm_unreachable("Unhandled LLT");
86   }
87 
88   const LLT &get() const { return Ty; }
89 };
90 
91 class InstructionMatcher;
92 class OperandPlaceholder {
93 private:
94   enum PlaceholderKind {
95     OP_MatchReference,
96     OP_Temporary,
97   } Kind;
98 
99   struct MatchReferenceData {
100     InstructionMatcher *InsnMatcher;
101     StringRef InsnVarName;
102     StringRef SymbolicName;
103   };
104 
105   struct TemporaryData {
106     unsigned OpIdx;
107   };
108 
109   union {
110     struct MatchReferenceData MatchReference;
111     struct TemporaryData Temporary;
112   };
113 
114   OperandPlaceholder(PlaceholderKind Kind) : Kind(Kind) {}
115 
116 public:
117   ~OperandPlaceholder() {}
118 
119   static OperandPlaceholder
120   CreateMatchReference(InstructionMatcher *InsnMatcher,
121                        const StringRef InsnVarName, const StringRef SymbolicName) {
122     OperandPlaceholder Result(OP_MatchReference);
123     Result.MatchReference.InsnMatcher = InsnMatcher;
124     Result.MatchReference.InsnVarName = InsnVarName;
125     Result.MatchReference.SymbolicName = SymbolicName;
126     return Result;
127   }
128 
129   static OperandPlaceholder CreateTemporary(unsigned OpIdx) {
130     OperandPlaceholder Result(OP_Temporary);
131     Result.Temporary.OpIdx = OpIdx;
132     return Result;
133   }
134 
135   void emitCxxValueExpr(raw_ostream &OS) const;
136 };
137 
138 /// Convert an MVT to an equivalent LLT if possible, or the invalid LLT() for
139 /// MVTs that don't map cleanly to an LLT (e.g., iPTR, *any, ...).
140 static Optional<LLTCodeGen> MVTToLLT(MVT::SimpleValueType SVT) {
141   MVT VT(SVT);
142   if (VT.isVector() && VT.getVectorNumElements() != 1)
143     return LLTCodeGen(LLT::vector(VT.getVectorNumElements(), VT.getScalarSizeInBits()));
144   if (VT.isInteger() || VT.isFloatingPoint())
145     return LLTCodeGen(LLT::scalar(VT.getSizeInBits()));
146   return None;
147 }
148 
149 static bool isTrivialOperatorNode(const TreePatternNode *N) {
150   return !N->isLeaf() && !N->hasAnyPredicate() && !N->getTransformFn();
151 }
152 
153 //===- Matchers -----------------------------------------------------------===//
154 
155 class MatchAction;
156 
157 /// Generates code to check that a match rule matches.
158 class RuleMatcher {
159   /// A list of matchers that all need to succeed for the current rule to match.
160   /// FIXME: This currently supports a single match position but could be
161   /// extended to support multiple positions to support div/rem fusion or
162   /// load-multiple instructions.
163   std::vector<std::unique_ptr<InstructionMatcher>> Matchers;
164 
165   /// A list of actions that need to be taken when all predicates in this rule
166   /// have succeeded.
167   std::vector<std::unique_ptr<MatchAction>> Actions;
168 
169   /// A map of instruction matchers to the local variables created by
170   /// emitCxxCaptureStmts().
171   std::map<const InstructionMatcher *, std::string> InsnVariableNames;
172 
173   /// ID for the next instruction variable defined with defineInsnVar()
174   unsigned NextInsnVarID;
175 
176 public:
177   RuleMatcher()
178       : Matchers(), Actions(), InsnVariableNames(), NextInsnVarID(0) {}
179   RuleMatcher(RuleMatcher &&Other) = default;
180   RuleMatcher &operator=(RuleMatcher &&Other) = default;
181 
182   InstructionMatcher &addInstructionMatcher();
183 
184   template <class Kind, class... Args> Kind &addAction(Args &&... args);
185 
186   std::string defineInsnVar(raw_ostream &OS, const InstructionMatcher &Matcher,
187                             StringRef Value);
188   StringRef getInsnVarName(const InstructionMatcher &InsnMatcher) const;
189 
190   void emitCxxCaptureStmts(raw_ostream &OS, StringRef Expr);
191 
192   void emit(raw_ostream &OS);
193 
194   /// Compare the priority of this object and B.
195   ///
196   /// Returns true if this object is more important than B.
197   bool isHigherPriorityThan(const RuleMatcher &B) const;
198 
199   /// Report the maximum number of temporary operands needed by the rule
200   /// matcher.
201   unsigned countTemporaryOperands() const;
202 };
203 
204 template <class PredicateTy> class PredicateListMatcher {
205 private:
206   typedef std::vector<std::unique_ptr<PredicateTy>> PredicateVec;
207   PredicateVec Predicates;
208 
209 public:
210   /// Construct a new operand predicate and add it to the matcher.
211   template <class Kind, class... Args>
212   Kind &addPredicate(Args&&... args) {
213     Predicates.emplace_back(
214         llvm::make_unique<Kind>(std::forward<Args>(args)...));
215     return *static_cast<Kind *>(Predicates.back().get());
216   }
217 
218   typename PredicateVec::const_iterator predicates_begin() const { return Predicates.begin(); }
219   typename PredicateVec::const_iterator predicates_end() const { return Predicates.end(); }
220   iterator_range<typename PredicateVec::const_iterator> predicates() const {
221     return make_range(predicates_begin(), predicates_end());
222   }
223   typename PredicateVec::size_type predicates_size() const { return Predicates.size(); }
224 
225   /// Emit a C++ expression that tests whether all the predicates are met.
226   template <class... Args>
227   void emitCxxPredicateListExpr(raw_ostream &OS, Args &&... args) const {
228     if (Predicates.empty()) {
229       OS << "true";
230       return;
231     }
232 
233     StringRef Separator = "";
234     for (const auto &Predicate : predicates()) {
235       OS << Separator << "(";
236       Predicate->emitCxxPredicateExpr(OS, std::forward<Args>(args)...);
237       OS << ")";
238       Separator = " &&\n";
239     }
240   }
241 };
242 
243 /// Generates code to check a predicate of an operand.
244 ///
245 /// Typical predicates include:
246 /// * Operand is a particular register.
247 /// * Operand is assigned a particular register bank.
248 /// * Operand is an MBB.
249 class OperandPredicateMatcher {
250 public:
251   /// This enum is used for RTTI and also defines the priority that is given to
252   /// the predicate when generating the matcher code. Kinds with higher priority
253   /// must be tested first.
254   ///
255   /// The relative priority of OPM_LLT, OPM_RegBank, and OPM_MBB do not matter
256   /// but OPM_Int must have priority over OPM_RegBank since constant integers
257   /// are represented by a virtual register defined by a G_CONSTANT instruction.
258   enum PredicateKind {
259     OPM_ComplexPattern,
260     OPM_Int,
261     OPM_LLT,
262     OPM_RegBank,
263     OPM_MBB,
264   };
265 
266 protected:
267   PredicateKind Kind;
268 
269 public:
270   OperandPredicateMatcher(PredicateKind Kind) : Kind(Kind) {}
271   virtual ~OperandPredicateMatcher() {}
272 
273   PredicateKind getKind() const { return Kind; }
274 
275   /// Emit a C++ expression that checks the predicate for the given operand.
276   virtual void emitCxxPredicateExpr(raw_ostream &OS, RuleMatcher &Rule,
277                                     StringRef OperandExpr) const = 0;
278 
279   /// Compare the priority of this object and B.
280   ///
281   /// Returns true if this object is more important than B.
282   virtual bool isHigherPriorityThan(const OperandPredicateMatcher &B) const {
283     return Kind < B.Kind;
284   };
285 
286   /// Report the maximum number of temporary operands needed by the predicate
287   /// matcher.
288   virtual unsigned countTemporaryOperands() const { return 0; }
289 };
290 
291 /// Generates code to check that an operand is a particular LLT.
292 class LLTOperandMatcher : public OperandPredicateMatcher {
293 protected:
294   LLTCodeGen Ty;
295 
296 public:
297   LLTOperandMatcher(const LLTCodeGen &Ty)
298       : OperandPredicateMatcher(OPM_LLT), Ty(Ty) {}
299 
300   static bool classof(const OperandPredicateMatcher *P) {
301     return P->getKind() == OPM_LLT;
302   }
303 
304   void emitCxxPredicateExpr(raw_ostream &OS, RuleMatcher &Rule,
305                             StringRef OperandExpr) const override {
306     OS << "MRI.getType(" << OperandExpr << ".getReg()) == (";
307     Ty.emitCxxConstructorCall(OS);
308     OS << ")";
309   }
310 };
311 
312 /// Generates code to check that an operand is a particular target constant.
313 class ComplexPatternOperandMatcher : public OperandPredicateMatcher {
314 protected:
315   const Record &TheDef;
316   /// The index of the first temporary operand to allocate to this
317   /// ComplexPattern.
318   unsigned BaseTemporaryID;
319 
320   unsigned getNumOperands() const {
321     return TheDef.getValueAsDag("Operands")->getNumArgs();
322   }
323 
324 public:
325   ComplexPatternOperandMatcher(const Record &TheDef, unsigned BaseTemporaryID)
326       : OperandPredicateMatcher(OPM_ComplexPattern), TheDef(TheDef),
327         BaseTemporaryID(BaseTemporaryID) {}
328 
329   void emitCxxPredicateExpr(raw_ostream &OS, RuleMatcher &Rule,
330                             StringRef OperandExpr) const override {
331     OS << TheDef.getValueAsString("MatcherFn") << "(" << OperandExpr;
332     for (unsigned I = 0; I < getNumOperands(); ++I) {
333       OS << ", ";
334       OperandPlaceholder::CreateTemporary(BaseTemporaryID + I)
335           .emitCxxValueExpr(OS);
336     }
337     OS << ")";
338   }
339 
340   unsigned countTemporaryOperands() const override {
341     return getNumOperands();
342   }
343 };
344 
345 /// Generates code to check that an operand is in a particular register bank.
346 class RegisterBankOperandMatcher : public OperandPredicateMatcher {
347 protected:
348   const CodeGenRegisterClass &RC;
349 
350 public:
351   RegisterBankOperandMatcher(const CodeGenRegisterClass &RC)
352       : OperandPredicateMatcher(OPM_RegBank), RC(RC) {}
353 
354   static bool classof(const OperandPredicateMatcher *P) {
355     return P->getKind() == OPM_RegBank;
356   }
357 
358   void emitCxxPredicateExpr(raw_ostream &OS, RuleMatcher &Rule,
359                             StringRef OperandExpr) const override {
360     OS << "(&RBI.getRegBankFromRegClass(" << RC.getQualifiedName()
361        << "RegClass) == RBI.getRegBank(" << OperandExpr
362        << ".getReg(), MRI, TRI))";
363   }
364 };
365 
366 /// Generates code to check that an operand is a basic block.
367 class MBBOperandMatcher : public OperandPredicateMatcher {
368 public:
369   MBBOperandMatcher() : OperandPredicateMatcher(OPM_MBB) {}
370 
371   static bool classof(const OperandPredicateMatcher *P) {
372     return P->getKind() == OPM_MBB;
373   }
374 
375   void emitCxxPredicateExpr(raw_ostream &OS, RuleMatcher &Rule,
376                             StringRef OperandExpr) const override {
377     OS << OperandExpr << ".isMBB()";
378   }
379 };
380 
381 /// Generates code to check that an operand is a particular int.
382 class IntOperandMatcher : public OperandPredicateMatcher {
383 protected:
384   int64_t Value;
385 
386 public:
387   IntOperandMatcher(int64_t Value)
388       : OperandPredicateMatcher(OPM_Int), Value(Value) {}
389 
390   static bool classof(const OperandPredicateMatcher *P) {
391     return P->getKind() == OPM_Int;
392   }
393 
394   void emitCxxPredicateExpr(raw_ostream &OS, RuleMatcher &Rule,
395                             StringRef OperandExpr) const override {
396     OS << "isOperandImmEqual(" << OperandExpr << ", " << Value << ", MRI)";
397   }
398 };
399 
400 /// Generates code to check that a set of predicates match for a particular
401 /// operand.
402 class OperandMatcher : public PredicateListMatcher<OperandPredicateMatcher> {
403 protected:
404   InstructionMatcher &Insn;
405   unsigned OpIdx;
406   std::string SymbolicName;
407 
408 public:
409   OperandMatcher(InstructionMatcher &Insn, unsigned OpIdx,
410                  const std::string &SymbolicName)
411       : Insn(Insn), OpIdx(OpIdx), SymbolicName(SymbolicName) {}
412 
413   bool hasSymbolicName() const { return !SymbolicName.empty(); }
414   const StringRef getSymbolicName() const { return SymbolicName; }
415   void setSymbolicName(StringRef Name) {
416     assert(SymbolicName.empty() && "Operand already has a symbolic name");
417     SymbolicName = Name;
418   }
419   unsigned getOperandIndex() const { return OpIdx; }
420 
421   std::string getOperandExpr(const StringRef InsnVarName) const {
422     return (InsnVarName + ".getOperand(" + llvm::to_string(OpIdx) + ")").str();
423   }
424 
425   InstructionMatcher &getInstructionMatcher() const { return Insn; }
426 
427   /// Emit a C++ expression that tests whether the instruction named in
428   /// InsnVarName matches all the predicate and all the operands.
429   void emitCxxPredicateExpr(raw_ostream &OS, RuleMatcher &Rule,
430                             const StringRef InsnVarName) const {
431     OS << "(/* ";
432     if (SymbolicName.empty())
433       OS << "Operand " << OpIdx;
434     else
435       OS << SymbolicName;
436     OS << " */ ";
437     emitCxxPredicateListExpr(OS, Rule, getOperandExpr(InsnVarName));
438     OS << ")";
439   }
440 
441   /// Compare the priority of this object and B.
442   ///
443   /// Returns true if this object is more important than B.
444   bool isHigherPriorityThan(const OperandMatcher &B) const {
445     // Operand matchers involving more predicates have higher priority.
446     if (predicates_size() > B.predicates_size())
447       return true;
448     if (predicates_size() < B.predicates_size())
449       return false;
450 
451     // This assumes that predicates are added in a consistent order.
452     for (const auto &Predicate : zip(predicates(), B.predicates())) {
453       if (std::get<0>(Predicate)->isHigherPriorityThan(*std::get<1>(Predicate)))
454         return true;
455       if (std::get<1>(Predicate)->isHigherPriorityThan(*std::get<0>(Predicate)))
456         return false;
457     }
458 
459     return false;
460   };
461 
462   /// Report the maximum number of temporary operands needed by the operand
463   /// matcher.
464   unsigned countTemporaryOperands() const {
465     return std::accumulate(
466         predicates().begin(), predicates().end(), 0,
467         [](unsigned A,
468            const std::unique_ptr<OperandPredicateMatcher> &Predicate) {
469           return A + Predicate->countTemporaryOperands();
470         });
471   }
472 };
473 
474 /// Generates code to check a predicate on an instruction.
475 ///
476 /// Typical predicates include:
477 /// * The opcode of the instruction is a particular value.
478 /// * The nsw/nuw flag is/isn't set.
479 class InstructionPredicateMatcher {
480 protected:
481   /// This enum is used for RTTI and also defines the priority that is given to
482   /// the predicate when generating the matcher code. Kinds with higher priority
483   /// must be tested first.
484   enum PredicateKind {
485     IPM_Opcode,
486   };
487 
488   PredicateKind Kind;
489 
490 public:
491   InstructionPredicateMatcher(PredicateKind Kind) : Kind(Kind) {}
492   virtual ~InstructionPredicateMatcher() {}
493 
494   PredicateKind getKind() const { return Kind; }
495 
496   /// Emit a C++ expression that tests whether the instruction named in
497   /// InsnVarName matches the predicate.
498   virtual void emitCxxPredicateExpr(raw_ostream &OS, RuleMatcher &Rule,
499                                     StringRef InsnVarName) const = 0;
500 
501   /// Compare the priority of this object and B.
502   ///
503   /// Returns true if this object is more important than B.
504   virtual bool isHigherPriorityThan(const InstructionPredicateMatcher &B) const {
505     return Kind < B.Kind;
506   };
507 
508   /// Report the maximum number of temporary operands needed by the predicate
509   /// matcher.
510   virtual unsigned countTemporaryOperands() const { return 0; }
511 };
512 
513 /// Generates code to check the opcode of an instruction.
514 class InstructionOpcodeMatcher : public InstructionPredicateMatcher {
515 protected:
516   const CodeGenInstruction *I;
517 
518 public:
519   InstructionOpcodeMatcher(const CodeGenInstruction *I)
520       : InstructionPredicateMatcher(IPM_Opcode), I(I) {}
521 
522   static bool classof(const InstructionPredicateMatcher *P) {
523     return P->getKind() == IPM_Opcode;
524   }
525 
526   void emitCxxPredicateExpr(raw_ostream &OS, RuleMatcher &Rule,
527                             StringRef InsnVarName) const override {
528     OS << InsnVarName << ".getOpcode() == " << I->Namespace
529        << "::" << I->TheDef->getName();
530   }
531 
532   /// Compare the priority of this object and B.
533   ///
534   /// Returns true if this object is more important than B.
535   bool isHigherPriorityThan(const InstructionPredicateMatcher &B) const override {
536     if (InstructionPredicateMatcher::isHigherPriorityThan(B))
537       return true;
538     if (B.InstructionPredicateMatcher::isHigherPriorityThan(*this))
539       return false;
540 
541     // Prioritize opcodes for cosmetic reasons in the generated source. Although
542     // this is cosmetic at the moment, we may want to drive a similar ordering
543     // using instruction frequency information to improve compile time.
544     if (const InstructionOpcodeMatcher *BO =
545             dyn_cast<InstructionOpcodeMatcher>(&B))
546       return I->TheDef->getName() < BO->I->TheDef->getName();
547 
548     return false;
549   };
550 };
551 
552 /// Generates code to check that a set of predicates and operands match for a
553 /// particular instruction.
554 ///
555 /// Typical predicates include:
556 /// * Has a specific opcode.
557 /// * Has an nsw/nuw flag or doesn't.
558 class InstructionMatcher
559     : public PredicateListMatcher<InstructionPredicateMatcher> {
560 protected:
561   typedef std::vector<OperandMatcher> OperandVec;
562 
563   /// The operands to match. All rendered operands must be present even if the
564   /// condition is always true.
565   OperandVec Operands;
566 
567 public:
568   /// Add an operand to the matcher.
569   OperandMatcher &addOperand(unsigned OpIdx, const std::string &SymbolicName) {
570     Operands.emplace_back(*this, OpIdx, SymbolicName);
571     return Operands.back();
572   }
573 
574   OperandMatcher &getOperand(unsigned OpIdx) {
575     auto I = std::find_if(Operands.begin(), Operands.end(),
576                           [&OpIdx](const OperandMatcher &X) {
577                             return X.getOperandIndex() == OpIdx;
578                           });
579     if (I != Operands.end())
580       return *I;
581     llvm_unreachable("Failed to lookup operand");
582   }
583 
584   Optional<const OperandMatcher *> getOptionalOperand(StringRef SymbolicName) const {
585     assert(!SymbolicName.empty() && "Cannot lookup unnamed operand");
586     const auto &I = std::find_if(Operands.begin(), Operands.end(),
587                                  [&SymbolicName](const OperandMatcher &X) {
588                                    return X.getSymbolicName() == SymbolicName;
589                                  });
590     if (I != Operands.end())
591       return &*I;
592     return None;
593   }
594 
595   const OperandMatcher &getOperand(const StringRef SymbolicName) const {
596     Optional<const OperandMatcher *>OM = getOptionalOperand(SymbolicName);
597     if (OM.hasValue())
598       return *OM.getValue();
599     llvm_unreachable("Failed to lookup operand");
600   }
601 
602   unsigned getNumOperands() const { return Operands.size(); }
603   OperandVec::const_iterator operands_begin() const { return Operands.begin(); }
604   OperandVec::const_iterator operands_end() const { return Operands.end(); }
605   iterator_range<OperandVec::const_iterator> operands() const {
606     return make_range(operands_begin(), operands_end());
607   }
608 
609   /// Emit C++ statements to check the shape of the match and capture
610   /// instructions into local variables.
611   ///
612   /// TODO: When nested instruction matching is implemented, this function will
613   ///       descend into the operands and capture variables.
614   void emitCxxCaptureStmts(raw_ostream &OS, RuleMatcher &Rule, StringRef Expr) {
615     OS << "if (" << Expr << ".getNumOperands() < " << getNumOperands() << ")\n"
616        << "  return false;\n";
617   }
618 
619   /// Emit a C++ expression that tests whether the instruction named in
620   /// InsnVarName matches all the predicates and all the operands.
621   void emitCxxPredicateExpr(raw_ostream &OS, RuleMatcher &Rule,
622                             StringRef InsnVarName) const {
623     emitCxxPredicateListExpr(OS, Rule, InsnVarName);
624     for (const auto &Operand : Operands) {
625       OS << " &&\n(";
626       Operand.emitCxxPredicateExpr(OS, Rule, InsnVarName);
627       OS << ")";
628     }
629   }
630 
631   /// Compare the priority of this object and B.
632   ///
633   /// Returns true if this object is more important than B.
634   bool isHigherPriorityThan(const InstructionMatcher &B) const {
635     // Instruction matchers involving more operands have higher priority.
636     if (Operands.size() > B.Operands.size())
637       return true;
638     if (Operands.size() < B.Operands.size())
639       return false;
640 
641     for (const auto &Predicate : zip(predicates(), B.predicates())) {
642       if (std::get<0>(Predicate)->isHigherPriorityThan(*std::get<1>(Predicate)))
643         return true;
644       if (std::get<1>(Predicate)->isHigherPriorityThan(*std::get<0>(Predicate)))
645         return false;
646     }
647 
648     for (const auto &Operand : zip(Operands, B.Operands)) {
649       if (std::get<0>(Operand).isHigherPriorityThan(std::get<1>(Operand)))
650         return true;
651       if (std::get<1>(Operand).isHigherPriorityThan(std::get<0>(Operand)))
652         return false;
653     }
654 
655     return false;
656   };
657 
658   /// Report the maximum number of temporary operands needed by the instruction
659   /// matcher.
660   unsigned countTemporaryOperands() const {
661     return std::accumulate(predicates().begin(), predicates().end(), 0,
662                            [](unsigned A,
663                               const std::unique_ptr<InstructionPredicateMatcher>
664                                   &Predicate) {
665                              return A + Predicate->countTemporaryOperands();
666                            }) +
667            std::accumulate(Operands.begin(), Operands.end(), 0,
668                            [](unsigned A, const OperandMatcher &Operand) {
669                              return A + Operand.countTemporaryOperands();
670                            });
671   }
672 };
673 
674 //===- Actions ------------------------------------------------------------===//
675 void OperandPlaceholder::emitCxxValueExpr(raw_ostream &OS) const {
676   switch (Kind) {
677   case OP_MatchReference:
678     OS << MatchReference.InsnMatcher->getOperand(MatchReference.SymbolicName)
679               .getOperandExpr(MatchReference.InsnVarName);
680     break;
681   case OP_Temporary:
682     OS << "TempOp" << Temporary.OpIdx;
683     break;
684   }
685 }
686 
687 class OperandRenderer {
688 public:
689   enum RendererKind { OR_Copy, OR_Register, OR_ComplexPattern };
690 
691 protected:
692   RendererKind Kind;
693 
694 public:
695   OperandRenderer(RendererKind Kind) : Kind(Kind) {}
696   virtual ~OperandRenderer() {}
697 
698   RendererKind getKind() const { return Kind; }
699 
700   virtual void emitCxxRenderStmts(raw_ostream &OS, RuleMatcher &Rule) const = 0;
701 };
702 
703 /// A CopyRenderer emits code to copy a single operand from an existing
704 /// instruction to the one being built.
705 class CopyRenderer : public OperandRenderer {
706 protected:
707   /// The matcher for the instruction that this operand is copied from.
708   /// This provides the facility for looking up an a operand by it's name so
709   /// that it can be used as a source for the instruction being built.
710   const InstructionMatcher &Matched;
711   /// The name of the operand.
712   const StringRef SymbolicName;
713 
714 public:
715   CopyRenderer(const InstructionMatcher &Matched, StringRef SymbolicName)
716       : OperandRenderer(OR_Copy), Matched(Matched), SymbolicName(SymbolicName) {
717   }
718 
719   static bool classof(const OperandRenderer *R) {
720     return R->getKind() == OR_Copy;
721   }
722 
723   const StringRef getSymbolicName() const { return SymbolicName; }
724 
725   void emitCxxRenderStmts(raw_ostream &OS, RuleMatcher &Rule) const override {
726     const OperandMatcher &Operand = Matched.getOperand(SymbolicName);
727     StringRef InsnVarName =
728         Rule.getInsnVarName(Operand.getInstructionMatcher());
729     std::string OperandExpr = Operand.getOperandExpr(InsnVarName);
730     OS << "    MIB.add(" << OperandExpr << "/*" << SymbolicName << "*/);\n";
731   }
732 };
733 
734 /// Adds a specific physical register to the instruction being built.
735 /// This is typically useful for WZR/XZR on AArch64.
736 class AddRegisterRenderer : public OperandRenderer {
737 protected:
738   const Record *RegisterDef;
739 
740 public:
741   AddRegisterRenderer(const Record *RegisterDef)
742       : OperandRenderer(OR_Register), RegisterDef(RegisterDef) {}
743 
744   static bool classof(const OperandRenderer *R) {
745     return R->getKind() == OR_Register;
746   }
747 
748   void emitCxxRenderStmts(raw_ostream &OS, RuleMatcher &Rule) const override {
749     OS << "    MIB.addReg(" << RegisterDef->getValueAsString("Namespace")
750        << "::" << RegisterDef->getName() << ");\n";
751   }
752 };
753 
754 class RenderComplexPatternOperand : public OperandRenderer {
755 private:
756   const Record &TheDef;
757   std::vector<OperandPlaceholder> Sources;
758 
759   unsigned getNumOperands() const {
760     return TheDef.getValueAsDag("Operands")->getNumArgs();
761   }
762 
763 public:
764   RenderComplexPatternOperand(const Record &TheDef,
765                               const ArrayRef<OperandPlaceholder> Sources)
766       : OperandRenderer(OR_ComplexPattern), TheDef(TheDef), Sources(Sources) {}
767 
768   static bool classof(const OperandRenderer *R) {
769     return R->getKind() == OR_ComplexPattern;
770   }
771 
772   void emitCxxRenderStmts(raw_ostream &OS, RuleMatcher &Rule) const override {
773     assert(Sources.size() == getNumOperands() && "Inconsistent number of operands");
774     for (const auto &Source : Sources) {
775       OS << "MIB.add(";
776       Source.emitCxxValueExpr(OS);
777       OS << ");\n";
778     }
779   }
780 };
781 
782 /// An action taken when all Matcher predicates succeeded for a parent rule.
783 ///
784 /// Typical actions include:
785 /// * Changing the opcode of an instruction.
786 /// * Adding an operand to an instruction.
787 class MatchAction {
788 public:
789   virtual ~MatchAction() {}
790 
791   /// Emit the C++ statements to implement the action.
792   ///
793   /// \param RecycleVarName If given, it's an instruction to recycle. The
794   ///                       requirements on the instruction vary from action to
795   ///                       action.
796   virtual void emitCxxActionStmts(raw_ostream &OS, RuleMatcher &Rule,
797                                   StringRef RecycleVarName) const = 0;
798 };
799 
800 /// Generates a comment describing the matched rule being acted upon.
801 class DebugCommentAction : public MatchAction {
802 private:
803   const PatternToMatch &P;
804 
805 public:
806   DebugCommentAction(const PatternToMatch &P) : P(P) {}
807 
808   void emitCxxActionStmts(raw_ostream &OS, RuleMatcher &Rule,
809                           StringRef RecycleVarName) const override {
810     OS << "// " << *P.getSrcPattern() << "  =>  " << *P.getDstPattern() << "\n";
811   }
812 };
813 
814 /// Generates code to build an instruction or mutate an existing instruction
815 /// into the desired instruction when this is possible.
816 class BuildMIAction : public MatchAction {
817 private:
818   const CodeGenInstruction *I;
819   const InstructionMatcher &Matched;
820   std::vector<std::unique_ptr<OperandRenderer>> OperandRenderers;
821 
822   /// True if the instruction can be built solely by mutating the opcode.
823   bool canMutate() const {
824     for (const auto &Renderer : enumerate(OperandRenderers)) {
825       if (const auto *Copy = dyn_cast<CopyRenderer>(&*Renderer.value())) {
826         if (Matched.getOperand(Copy->getSymbolicName()).getOperandIndex() !=
827             Renderer.index())
828           return false;
829       } else
830         return false;
831     }
832 
833     return true;
834   }
835 
836 public:
837   BuildMIAction(const CodeGenInstruction *I, const InstructionMatcher &Matched)
838       : I(I), Matched(Matched) {}
839 
840   template <class Kind, class... Args>
841   Kind &addRenderer(Args&&... args) {
842     OperandRenderers.emplace_back(
843         llvm::make_unique<Kind>(std::forward<Args>(args)...));
844     return *static_cast<Kind *>(OperandRenderers.back().get());
845   }
846 
847   void emitCxxActionStmts(raw_ostream &OS, RuleMatcher &Rule,
848                           StringRef RecycleVarName) const override {
849     if (canMutate()) {
850       OS << "    " << RecycleVarName << ".setDesc(TII.get(" << I->Namespace
851          << "::" << I->TheDef->getName() << "));\n";
852 
853       if (!I->ImplicitDefs.empty() || !I->ImplicitUses.empty()) {
854         OS << "    auto MIB = MachineInstrBuilder(MF, &" << RecycleVarName
855            << ");\n";
856 
857         for (auto Def : I->ImplicitDefs) {
858           auto Namespace = Def->getValueAsString("Namespace");
859           OS << "    MIB.addDef(" << Namespace << "::" << Def->getName()
860              << ", RegState::Implicit);\n";
861         }
862         for (auto Use : I->ImplicitUses) {
863           auto Namespace = Use->getValueAsString("Namespace");
864           OS << "    MIB.addUse(" << Namespace << "::" << Use->getName()
865              << ", RegState::Implicit);\n";
866         }
867       }
868 
869       OS << "    MachineInstr &NewI = " << RecycleVarName << ";\n";
870       return;
871     }
872 
873     // TODO: Simple permutation looks like it could be almost as common as
874     //       mutation due to commutative operations.
875 
876     OS << "MachineInstrBuilder MIB = BuildMI(*I.getParent(), I, "
877           "I.getDebugLoc(), TII.get("
878        << I->Namespace << "::" << I->TheDef->getName() << "));\n";
879     for (const auto &Renderer : OperandRenderers)
880       Renderer->emitCxxRenderStmts(OS, Rule);
881     OS << "    MIB.setMemRefs(I.memoperands_begin(), I.memoperands_end());\n";
882     OS << "    " << RecycleVarName << ".eraseFromParent();\n";
883     OS << "    MachineInstr &NewI = *MIB;\n";
884   }
885 };
886 
887 InstructionMatcher &RuleMatcher::addInstructionMatcher() {
888   Matchers.emplace_back(new InstructionMatcher());
889   return *Matchers.back();
890 }
891 
892 template <class Kind, class... Args>
893 Kind &RuleMatcher::addAction(Args &&... args) {
894   Actions.emplace_back(llvm::make_unique<Kind>(std::forward<Args>(args)...));
895   return *static_cast<Kind *>(Actions.back().get());
896 }
897 
898 std::string RuleMatcher::defineInsnVar(raw_ostream &OS,
899                                        const InstructionMatcher &Matcher,
900                                        StringRef Value) {
901   std::string InsnVarName = "MI" + llvm::to_string(NextInsnVarID++);
902   OS << "MachineInstr &" << InsnVarName << " = " << Value << ";\n";
903   InsnVariableNames[&Matcher] = InsnVarName;
904   return InsnVarName;
905 }
906 
907 StringRef RuleMatcher::getInsnVarName(const InstructionMatcher &InsnMatcher) const {
908   const auto &I = InsnVariableNames.find(&InsnMatcher);
909   if (I != InsnVariableNames.end())
910     return I->second;
911   llvm_unreachable("Matched Insn was not captured in a local variable");
912 }
913 
914 /// Emit C++ statements to check the shape of the match and capture
915 /// instructions into local variables.
916 void RuleMatcher::emitCxxCaptureStmts(raw_ostream &OS, StringRef Expr) {
917   assert(Matchers.size() == 1 && "Cannot handle multi-root matchers yet");
918   std::string InsnVarName = defineInsnVar(OS, *Matchers.front(), Expr);
919   Matchers.front()->emitCxxCaptureStmts(OS, *this, InsnVarName);
920 }
921 
922 void RuleMatcher::emit(raw_ostream &OS) {
923   if (Matchers.empty())
924     llvm_unreachable("Unexpected empty matcher!");
925 
926   // The representation supports rules that require multiple roots such as:
927   //    %ptr(p0) = ...
928   //    %elt0(s32) = G_LOAD %ptr
929   //    %1(p0) = G_ADD %ptr, 4
930   //    %elt1(s32) = G_LOAD p0 %1
931   // which could be usefully folded into:
932   //    %ptr(p0) = ...
933   //    %elt0(s32), %elt1(s32) = TGT_LOAD_PAIR %ptr
934   // on some targets but we don't need to make use of that yet.
935   assert(Matchers.size() == 1 && "Cannot handle multi-root matchers yet");
936   OS << "if ([&]() {\n";
937 
938   emitCxxCaptureStmts(OS, "I");
939 
940   OS << "    if (";
941   Matchers.front()->emitCxxPredicateExpr(OS, *this,
942                                          getInsnVarName(*Matchers.front()));
943   OS << ") {\n";
944 
945   for (const auto &MA : Actions) {
946     MA->emitCxxActionStmts(OS, *this, "I");
947   }
948 
949   OS << "      constrainSelectedInstRegOperands(NewI, TII, TRI, RBI);\n";
950   OS << "      return true;\n";
951   OS << "    }\n";
952   OS << "    return false;\n";
953   OS << "  }()) { return true; }\n\n";
954 }
955 
956 bool RuleMatcher::isHigherPriorityThan(const RuleMatcher &B) const {
957   // Rules involving more match roots have higher priority.
958   if (Matchers.size() > B.Matchers.size())
959     return true;
960   if (Matchers.size() < B.Matchers.size())
961     return false;
962 
963   for (const auto &Matcher : zip(Matchers, B.Matchers)) {
964     if (std::get<0>(Matcher)->isHigherPriorityThan(*std::get<1>(Matcher)))
965       return true;
966     if (std::get<1>(Matcher)->isHigherPriorityThan(*std::get<0>(Matcher)))
967       return false;
968   }
969 
970   return false;
971 }
972 
973 unsigned RuleMatcher::countTemporaryOperands() const {
974   return std::accumulate(
975       Matchers.begin(), Matchers.end(), 0,
976       [](unsigned A, const std::unique_ptr<InstructionMatcher> &Matcher) {
977         return A + Matcher->countTemporaryOperands();
978       });
979 }
980 
981 //===- GlobalISelEmitter class --------------------------------------------===//
982 
983 class GlobalISelEmitter {
984 public:
985   explicit GlobalISelEmitter(RecordKeeper &RK);
986   void run(raw_ostream &OS);
987 
988 private:
989   const RecordKeeper &RK;
990   const CodeGenDAGPatterns CGP;
991   const CodeGenTarget &Target;
992 
993   /// Keep track of the equivalence between SDNodes and Instruction.
994   /// This is defined using 'GINodeEquiv' in the target description.
995   DenseMap<Record *, const CodeGenInstruction *> NodeEquivs;
996 
997   /// Keep track of the equivalence between ComplexPattern's and
998   /// GIComplexOperandMatcher. Map entries are specified by subclassing
999   /// GIComplexPatternEquiv.
1000   DenseMap<const Record *, const Record *> ComplexPatternEquivs;
1001 
1002   void gatherNodeEquivs();
1003   const CodeGenInstruction *findNodeEquiv(Record *N) const;
1004 
1005   Error importRulePredicates(RuleMatcher &M, ArrayRef<Init *> Predicates) const;
1006   Expected<InstructionMatcher &>
1007   createAndImportSelDAGMatcher(InstructionMatcher &InsnMatcher,
1008                                const TreePatternNode *Src) const;
1009   Error importChildMatcher(InstructionMatcher &InsnMatcher,
1010                            TreePatternNode *SrcChild, unsigned OpIdx,
1011                            unsigned &TempOpIdx) const;
1012   Expected<BuildMIAction &> createAndImportInstructionRenderer(
1013       RuleMatcher &M, const TreePatternNode *Dst,
1014       const InstructionMatcher &InsnMatcher) const;
1015   Error importExplicitUseRenderer(BuildMIAction &DstMIBuilder,
1016                                   TreePatternNode *DstChild,
1017                                   const InstructionMatcher &InsnMatcher,
1018                                   unsigned &TempOpIdx) const;
1019   Error
1020   importImplicitDefRenderers(BuildMIAction &DstMIBuilder,
1021                              const std::vector<Record *> &ImplicitDefs) const;
1022 
1023   /// Analyze pattern \p P, returning a matcher for it if possible.
1024   /// Otherwise, return an Error explaining why we don't support it.
1025   Expected<RuleMatcher> runOnPattern(const PatternToMatch &P);
1026 };
1027 
1028 void GlobalISelEmitter::gatherNodeEquivs() {
1029   assert(NodeEquivs.empty());
1030   for (Record *Equiv : RK.getAllDerivedDefinitions("GINodeEquiv"))
1031     NodeEquivs[Equiv->getValueAsDef("Node")] =
1032         &Target.getInstruction(Equiv->getValueAsDef("I"));
1033 
1034   assert(ComplexPatternEquivs.empty());
1035   for (Record *Equiv : RK.getAllDerivedDefinitions("GIComplexPatternEquiv")) {
1036     Record *SelDAGEquiv = Equiv->getValueAsDef("SelDAGEquivalent");
1037     if (!SelDAGEquiv)
1038       continue;
1039     ComplexPatternEquivs[SelDAGEquiv] = Equiv;
1040  }
1041 }
1042 
1043 const CodeGenInstruction *GlobalISelEmitter::findNodeEquiv(Record *N) const {
1044   return NodeEquivs.lookup(N);
1045 }
1046 
1047 GlobalISelEmitter::GlobalISelEmitter(RecordKeeper &RK)
1048     : RK(RK), CGP(RK), Target(CGP.getTargetInfo()) {}
1049 
1050 //===- Emitter ------------------------------------------------------------===//
1051 
1052 /// Helper function to let the emitter report skip reason error messages.
1053 static Error failedImport(const Twine &Reason) {
1054   return make_error<StringError>(Reason, inconvertibleErrorCode());
1055 }
1056 
1057 Error
1058 GlobalISelEmitter::importRulePredicates(RuleMatcher &M,
1059                                         ArrayRef<Init *> Predicates) const {
1060   if (!Predicates.empty())
1061     return failedImport("Pattern has a predicate");
1062   return Error::success();
1063 }
1064 
1065 Expected<InstructionMatcher &> GlobalISelEmitter::createAndImportSelDAGMatcher(
1066     InstructionMatcher &InsnMatcher, const TreePatternNode *Src) const {
1067   // Start with the defined operands (i.e., the results of the root operator).
1068   if (Src->getExtTypes().size() > 1)
1069     return failedImport("Src pattern has multiple results");
1070 
1071   auto SrcGIOrNull = findNodeEquiv(Src->getOperator());
1072   if (!SrcGIOrNull)
1073     return failedImport("Pattern operator lacks an equivalent Instruction");
1074   auto &SrcGI = *SrcGIOrNull;
1075 
1076   // The operators look good: match the opcode and mutate it to the new one.
1077   InsnMatcher.addPredicate<InstructionOpcodeMatcher>(&SrcGI);
1078 
1079   unsigned OpIdx = 0;
1080   for (const EEVT::TypeSet &Ty : Src->getExtTypes()) {
1081     auto OpTyOrNone = MVTToLLT(Ty.getConcrete());
1082 
1083     if (!OpTyOrNone)
1084       return failedImport(
1085           "Result of Src pattern operator has an unsupported type");
1086 
1087     // Results don't have a name unless they are the root node. The caller will
1088     // set the name if appropriate.
1089     OperandMatcher &OM = InsnMatcher.addOperand(OpIdx++, "");
1090     OM.addPredicate<LLTOperandMatcher>(*OpTyOrNone);
1091   }
1092 
1093   unsigned TempOpIdx = 0;
1094   // Match the used operands (i.e. the children of the operator).
1095   for (unsigned i = 0, e = Src->getNumChildren(); i != e; ++i) {
1096     if (auto Error = importChildMatcher(InsnMatcher, Src->getChild(i), OpIdx++,
1097                                         TempOpIdx))
1098       return std::move(Error);
1099   }
1100 
1101   return InsnMatcher;
1102 }
1103 
1104 Error GlobalISelEmitter::importChildMatcher(InstructionMatcher &InsnMatcher,
1105                                             TreePatternNode *SrcChild,
1106                                             unsigned OpIdx,
1107                                             unsigned &TempOpIdx) const {
1108   OperandMatcher &OM = InsnMatcher.addOperand(OpIdx, SrcChild->getName());
1109 
1110   if (SrcChild->hasAnyPredicate())
1111     return failedImport("Src pattern child has predicate");
1112 
1113   ArrayRef<EEVT::TypeSet> ChildTypes = SrcChild->getExtTypes();
1114   if (ChildTypes.size() != 1)
1115     return failedImport("Src pattern child has multiple results");
1116 
1117   // Check MBB's before the type check since they are not a known type.
1118   if (!SrcChild->isLeaf()) {
1119     if (SrcChild->getOperator()->isSubClassOf("SDNode")) {
1120       auto &ChildSDNI = CGP.getSDNodeInfo(SrcChild->getOperator());
1121       if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") {
1122         OM.addPredicate<MBBOperandMatcher>();
1123         return Error::success();
1124       }
1125     }
1126 
1127     return failedImport("Src child operand is an unsupported type");
1128   }
1129 
1130   auto OpTyOrNone = MVTToLLT(ChildTypes.front().getConcrete());
1131   if (!OpTyOrNone)
1132     return failedImport("Src operand has an unsupported type");
1133   OM.addPredicate<LLTOperandMatcher>(*OpTyOrNone);
1134 
1135   // Check for constant immediates.
1136   if (auto *ChildInt = dyn_cast<IntInit>(SrcChild->getLeafValue())) {
1137     OM.addPredicate<IntOperandMatcher>(ChildInt->getValue());
1138     return Error::success();
1139   }
1140 
1141   // Check for def's like register classes or ComplexPattern's.
1142   if (auto *ChildDefInit = dyn_cast<DefInit>(SrcChild->getLeafValue())) {
1143     auto *ChildRec = ChildDefInit->getDef();
1144 
1145     // Check for register classes.
1146     if (ChildRec->isSubClassOf("RegisterClass")) {
1147       OM.addPredicate<RegisterBankOperandMatcher>(
1148           Target.getRegisterClass(ChildRec));
1149       return Error::success();
1150     }
1151 
1152     // Check for ComplexPattern's.
1153     if (ChildRec->isSubClassOf("ComplexPattern")) {
1154       const auto &ComplexPattern = ComplexPatternEquivs.find(ChildRec);
1155       if (ComplexPattern == ComplexPatternEquivs.end())
1156         return failedImport(
1157             "SelectionDAG ComplexPattern not mapped to GlobalISel");
1158 
1159       const auto &Predicate = OM.addPredicate<ComplexPatternOperandMatcher>(
1160           *ComplexPattern->second, TempOpIdx);
1161       TempOpIdx += Predicate.countTemporaryOperands();
1162       return Error::success();
1163     }
1164 
1165     return failedImport(
1166         "Src pattern child def is an unsupported tablegen class");
1167   }
1168 
1169   return failedImport("Src pattern child is an unsupported kind");
1170 }
1171 
1172 Error GlobalISelEmitter::importExplicitUseRenderer(
1173     BuildMIAction &DstMIBuilder, TreePatternNode *DstChild,
1174     const InstructionMatcher &InsnMatcher, unsigned &TempOpIdx) const {
1175   // The only non-leaf child we accept is 'bb': it's an operator because
1176   // BasicBlockSDNode isn't inline, but in MI it's just another operand.
1177   if (!DstChild->isLeaf()) {
1178     if (DstChild->getOperator()->isSubClassOf("SDNode")) {
1179       auto &ChildSDNI = CGP.getSDNodeInfo(DstChild->getOperator());
1180       if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") {
1181         DstMIBuilder.addRenderer<CopyRenderer>(InsnMatcher,
1182                                                DstChild->getName());
1183         return Error::success();
1184       }
1185     }
1186     return failedImport("Dst pattern child isn't a leaf node or an MBB");
1187   }
1188 
1189   // Otherwise, we're looking for a bog-standard RegisterClass operand.
1190   if (DstChild->hasAnyPredicate())
1191     return failedImport("Dst pattern child has predicate");
1192 
1193   if (auto *ChildDefInit = dyn_cast<DefInit>(DstChild->getLeafValue())) {
1194     auto *ChildRec = ChildDefInit->getDef();
1195 
1196     ArrayRef<EEVT::TypeSet> ChildTypes = DstChild->getExtTypes();
1197     if (ChildTypes.size() != 1)
1198       return failedImport("Dst pattern child has multiple results");
1199 
1200     auto OpTyOrNone = MVTToLLT(ChildTypes.front().getConcrete());
1201     if (!OpTyOrNone)
1202       return failedImport("Dst operand has an unsupported type");
1203 
1204     if (ChildRec->isSubClassOf("Register")) {
1205       DstMIBuilder.addRenderer<AddRegisterRenderer>(ChildRec);
1206       return Error::success();
1207     }
1208 
1209     if (ChildRec->isSubClassOf("RegisterClass")) {
1210       DstMIBuilder.addRenderer<CopyRenderer>(InsnMatcher, DstChild->getName());
1211       return Error::success();
1212     }
1213 
1214     if (ChildRec->isSubClassOf("ComplexPattern")) {
1215       const auto &ComplexPattern = ComplexPatternEquivs.find(ChildRec);
1216       if (ComplexPattern == ComplexPatternEquivs.end())
1217         return failedImport(
1218             "SelectionDAG ComplexPattern not mapped to GlobalISel");
1219 
1220       SmallVector<OperandPlaceholder, 2> RenderedOperands;
1221       for (unsigned I = 0;
1222            I <
1223            InsnMatcher.getOperand(DstChild->getName()).countTemporaryOperands();
1224            ++I) {
1225         RenderedOperands.push_back(OperandPlaceholder::CreateTemporary(I));
1226         TempOpIdx++;
1227       }
1228       DstMIBuilder.addRenderer<RenderComplexPatternOperand>(
1229           *ComplexPattern->second, RenderedOperands);
1230       return Error::success();
1231     }
1232 
1233     return failedImport(
1234         "Dst pattern child def is an unsupported tablegen class");
1235   }
1236 
1237   return failedImport("Dst pattern child is an unsupported kind");
1238 }
1239 
1240 Expected<BuildMIAction &> GlobalISelEmitter::createAndImportInstructionRenderer(
1241     RuleMatcher &M, const TreePatternNode *Dst,
1242     const InstructionMatcher &InsnMatcher) const {
1243   Record *DstOp = Dst->getOperator();
1244   if (!DstOp->isSubClassOf("Instruction"))
1245     return failedImport("Pattern operator isn't an instruction");
1246   auto &DstI = Target.getInstruction(DstOp);
1247 
1248   auto &DstMIBuilder = M.addAction<BuildMIAction>(&DstI, InsnMatcher);
1249 
1250   // Render the explicit defs.
1251   for (unsigned I = 0; I < DstI.Operands.NumDefs; ++I) {
1252     const auto &DstIOperand = DstI.Operands[I];
1253     DstMIBuilder.addRenderer<CopyRenderer>(InsnMatcher, DstIOperand.Name);
1254   }
1255 
1256   // Render the explicit uses.
1257   unsigned TempOpIdx = 0;
1258   for (unsigned i = 0, e = Dst->getNumChildren(); i != e; ++i) {
1259     if (auto Error = importExplicitUseRenderer(DstMIBuilder, Dst->getChild(i),
1260                                                InsnMatcher, TempOpIdx))
1261       return std::move(Error);
1262   }
1263 
1264   return DstMIBuilder;
1265 }
1266 
1267 Error GlobalISelEmitter::importImplicitDefRenderers(
1268     BuildMIAction &DstMIBuilder,
1269     const std::vector<Record *> &ImplicitDefs) const {
1270   if (!ImplicitDefs.empty())
1271     return failedImport("Pattern defines a physical register");
1272   return Error::success();
1273 }
1274 
1275 Expected<RuleMatcher> GlobalISelEmitter::runOnPattern(const PatternToMatch &P) {
1276   // Keep track of the matchers and actions to emit.
1277   RuleMatcher M;
1278   M.addAction<DebugCommentAction>(P);
1279 
1280   if (auto Error = importRulePredicates(M, P.getPredicates()->getValues()))
1281     return std::move(Error);
1282 
1283   // Next, analyze the pattern operators.
1284   TreePatternNode *Src = P.getSrcPattern();
1285   TreePatternNode *Dst = P.getDstPattern();
1286 
1287   // If the root of either pattern isn't a simple operator, ignore it.
1288   if (!isTrivialOperatorNode(Dst))
1289     return failedImport("Dst pattern root isn't a trivial operator");
1290   if (!isTrivialOperatorNode(Src))
1291     return failedImport("Src pattern root isn't a trivial operator");
1292 
1293   Record *DstOp = Dst->getOperator();
1294   if (!DstOp->isSubClassOf("Instruction"))
1295     return failedImport("Pattern operator isn't an instruction");
1296 
1297   auto &DstI = Target.getInstruction(DstOp);
1298   if (DstI.Operands.NumDefs != Src->getExtTypes().size())
1299     return failedImport("Src pattern results and dst MI defs are different");
1300 
1301   InstructionMatcher &InsnMatcherTemp = M.addInstructionMatcher();
1302   auto InsnMatcherOrError = createAndImportSelDAGMatcher(InsnMatcherTemp, Src);
1303   if (auto Error = InsnMatcherOrError.takeError())
1304     return std::move(Error);
1305   InstructionMatcher &InsnMatcher = InsnMatcherOrError.get();
1306 
1307   // The root of the match also has constraints on the register bank so that it
1308   // matches the result instruction.
1309   unsigned OpIdx = 0;
1310   for (const EEVT::TypeSet &Ty : Src->getExtTypes()) {
1311     (void)Ty;
1312 
1313     const auto &DstIOperand = DstI.Operands[OpIdx];
1314     Record *DstIOpRec = DstIOperand.Rec;
1315     if (!DstIOpRec->isSubClassOf("RegisterClass"))
1316       return failedImport("Dst MI def isn't a register class");
1317 
1318     OperandMatcher &OM = InsnMatcher.getOperand(OpIdx);
1319     OM.setSymbolicName(DstIOperand.Name);
1320     OM.addPredicate<RegisterBankOperandMatcher>(
1321         Target.getRegisterClass(DstIOpRec));
1322     ++OpIdx;
1323   }
1324 
1325   auto DstMIBuilderOrError =
1326       createAndImportInstructionRenderer(M, Dst, InsnMatcher);
1327   if (auto Error = DstMIBuilderOrError.takeError())
1328     return std::move(Error);
1329   BuildMIAction &DstMIBuilder = DstMIBuilderOrError.get();
1330 
1331   // Render the implicit defs.
1332   // These are only added to the root of the result.
1333   if (auto Error = importImplicitDefRenderers(DstMIBuilder, P.getDstRegs()))
1334     return std::move(Error);
1335 
1336   // We're done with this pattern!  It's eligible for GISel emission; return it.
1337   ++NumPatternImported;
1338   return std::move(M);
1339 }
1340 
1341 void GlobalISelEmitter::run(raw_ostream &OS) {
1342   // Track the GINodeEquiv definitions.
1343   gatherNodeEquivs();
1344 
1345   emitSourceFileHeader(("Global Instruction Selector for the " +
1346                        Target.getName() + " target").str(), OS);
1347   std::vector<RuleMatcher> Rules;
1348   // Look through the SelectionDAG patterns we found, possibly emitting some.
1349   for (const PatternToMatch &Pat : CGP.ptms()) {
1350     ++NumPatternTotal;
1351     auto MatcherOrErr = runOnPattern(Pat);
1352 
1353     // The pattern analysis can fail, indicating an unsupported pattern.
1354     // Report that if we've been asked to do so.
1355     if (auto Err = MatcherOrErr.takeError()) {
1356       if (WarnOnSkippedPatterns) {
1357         PrintWarning(Pat.getSrcRecord()->getLoc(),
1358                      "Skipped pattern: " + toString(std::move(Err)));
1359       } else {
1360         consumeError(std::move(Err));
1361       }
1362       ++NumPatternImportsSkipped;
1363       continue;
1364     }
1365 
1366     Rules.push_back(std::move(MatcherOrErr.get()));
1367   }
1368 
1369   std::stable_sort(Rules.begin(), Rules.end(),
1370             [&](const RuleMatcher &A, const RuleMatcher &B) {
1371               if (A.isHigherPriorityThan(B)) {
1372                 assert(!B.isHigherPriorityThan(A) && "Cannot be more important "
1373                                                      "and less important at "
1374                                                      "the same time");
1375                 return true;
1376               }
1377               return false;
1378             });
1379 
1380   unsigned MaxTemporaries = 0;
1381   for (const auto &Rule : Rules)
1382     MaxTemporaries = std::max(MaxTemporaries, Rule.countTemporaryOperands());
1383 
1384   OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n";
1385   for (unsigned I = 0; I < MaxTemporaries; ++I)
1386     OS << "  mutable MachineOperand TempOp" << I << ";\n";
1387   OS << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n\n";
1388 
1389   OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n";
1390   for (unsigned I = 0; I < MaxTemporaries; ++I)
1391     OS << ", TempOp" << I << "(MachineOperand::CreatePlaceholder())\n";
1392   OS << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n\n";
1393 
1394   OS << "#ifdef GET_GLOBALISEL_IMPL\n"
1395      << "bool " << Target.getName()
1396      << "InstructionSelector::selectImpl(MachineInstr &I) const {\n"
1397      << "  MachineFunction &MF = *I.getParent()->getParent();\n"
1398      << "  const MachineRegisterInfo &MRI = MF.getRegInfo();\n";
1399 
1400   for (auto &Rule : Rules) {
1401     Rule.emit(OS);
1402     ++NumPatternEmitted;
1403   }
1404 
1405   OS << "  return false;\n"
1406      << "}\n"
1407      << "#endif // ifdef GET_GLOBALISEL_IMPL\n";
1408 }
1409 
1410 } // end anonymous namespace
1411 
1412 //===----------------------------------------------------------------------===//
1413 
1414 namespace llvm {
1415 void EmitGlobalISel(RecordKeeper &RK, raw_ostream &OS) {
1416   GlobalISelEmitter(RK).run(OS);
1417 }
1418 } // End llvm namespace
1419