1 //===- GlobalISelEmitter.cpp - Generate an instruction selector -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 /// \file
11 /// This tablegen backend emits code for use by the GlobalISel instruction
12 /// selector. See include/llvm/CodeGen/TargetGlobalISel.td.
13 ///
14 /// This file analyzes the patterns recognized by the SelectionDAGISel tablegen
15 /// backend, filters out the ones that are unsupported, maps
16 /// SelectionDAG-specific constructs to their GlobalISel counterpart
17 /// (when applicable: MVT to LLT;  SDNode to generic Instruction).
18 ///
19 /// Not all patterns are supported: pass the tablegen invocation
20 /// "-warn-on-skipped-patterns" to emit a warning when a pattern is skipped,
21 /// as well as why.
22 ///
23 /// The generated file defines a single method:
24 ///     bool <Target>InstructionSelector::selectImpl(MachineInstr &I) const;
25 /// intended to be used in InstructionSelector::select as the first-step
26 /// selector for the patterns that don't require complex C++.
27 ///
28 /// FIXME: We'll probably want to eventually define a base
29 /// "TargetGenInstructionSelector" class.
30 ///
31 //===----------------------------------------------------------------------===//
32 
33 #include "CodeGenDAGPatterns.h"
34 #include "SubtargetFeatureInfo.h"
35 #include "llvm/ADT/Optional.h"
36 #include "llvm/ADT/SmallSet.h"
37 #include "llvm/ADT/Statistic.h"
38 #include "llvm/CodeGen/MachineValueType.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/Error.h"
41 #include "llvm/Support/LowLevelTypeImpl.h"
42 #include "llvm/Support/ScopedPrinter.h"
43 #include "llvm/TableGen/Error.h"
44 #include "llvm/TableGen/Record.h"
45 #include "llvm/TableGen/TableGenBackend.h"
46 #include <string>
47 #include <numeric>
48 using namespace llvm;
49 
50 #define DEBUG_TYPE "gisel-emitter"
51 
52 STATISTIC(NumPatternTotal, "Total number of patterns");
53 STATISTIC(NumPatternImported, "Number of patterns imported from SelectionDAG");
54 STATISTIC(NumPatternImportsSkipped, "Number of SelectionDAG imports skipped");
55 STATISTIC(NumPatternEmitted, "Number of patterns emitted");
56 
57 cl::OptionCategory GlobalISelEmitterCat("Options for -gen-global-isel");
58 
59 static cl::opt<bool> WarnOnSkippedPatterns(
60     "warn-on-skipped-patterns",
61     cl::desc("Explain why a pattern was skipped for inclusion "
62              "in the GlobalISel selector"),
63     cl::init(false), cl::cat(GlobalISelEmitterCat));
64 
65 namespace {
66 //===- Helper functions ---------------------------------------------------===//
67 
68 /// This class stands in for LLT wherever we want to tablegen-erate an
69 /// equivalent at compiler run-time.
70 class LLTCodeGen {
71 private:
72   LLT Ty;
73 
74 public:
75   LLTCodeGen(const LLT &Ty) : Ty(Ty) {}
76 
77   void emitCxxConstructorCall(raw_ostream &OS) const {
78     if (Ty.isScalar()) {
79       OS << "LLT::scalar(" << Ty.getSizeInBits() << ")";
80       return;
81     }
82     if (Ty.isVector()) {
83       OS << "LLT::vector(" << Ty.getNumElements() << ", " << Ty.getScalarSizeInBits()
84          << ")";
85       return;
86     }
87     llvm_unreachable("Unhandled LLT");
88   }
89 
90   const LLT &get() const { return Ty; }
91 };
92 
93 class InstructionMatcher;
94 /// Convert an MVT to an equivalent LLT if possible, or the invalid LLT() for
95 /// MVTs that don't map cleanly to an LLT (e.g., iPTR, *any, ...).
96 static Optional<LLTCodeGen> MVTToLLT(MVT::SimpleValueType SVT) {
97   MVT VT(SVT);
98   if (VT.isVector() && VT.getVectorNumElements() != 1)
99     return LLTCodeGen(LLT::vector(VT.getVectorNumElements(), VT.getScalarSizeInBits()));
100   if (VT.isInteger() || VT.isFloatingPoint())
101     return LLTCodeGen(LLT::scalar(VT.getSizeInBits()));
102   return None;
103 }
104 
105 static std::string explainPredicates(const TreePatternNode *N) {
106   std::string Explanation = "";
107   StringRef Separator = "";
108   for (const auto &P : N->getPredicateFns()) {
109     Explanation +=
110         (Separator + P.getOrigPatFragRecord()->getRecord()->getName()).str();
111     if (P.isAlwaysTrue())
112       Explanation += " always-true";
113     if (P.isImmediatePattern())
114       Explanation += " immediate";
115   }
116   return Explanation;
117 }
118 
119 std::string explainOperator(Record *Operator) {
120   if (Operator->isSubClassOf("SDNode"))
121     return (" (" + Operator->getValueAsString("Opcode") + ")").str();
122 
123   if (Operator->isSubClassOf("Intrinsic"))
124     return (" (Operator is an Intrinsic, " + Operator->getName() + ")").str();
125 
126   return " (Operator not understood)";
127 }
128 
129 /// Helper function to let the emitter report skip reason error messages.
130 static Error failedImport(const Twine &Reason) {
131   return make_error<StringError>(Reason, inconvertibleErrorCode());
132 }
133 
134 static Error isTrivialOperatorNode(const TreePatternNode *N) {
135   std::string Explanation = "";
136   std::string Separator = "";
137   if (N->isLeaf()) {
138     if (isa<IntInit>(N->getLeafValue()))
139       return Error::success();
140 
141     Explanation = "Is a leaf";
142     Separator = ", ";
143   }
144 
145   if (N->hasAnyPredicate()) {
146     Explanation = Separator + "Has a predicate (" + explainPredicates(N) + ")";
147     Separator = ", ";
148   }
149 
150   if (N->getTransformFn()) {
151     Explanation += Separator + "Has a transform function";
152     Separator = ", ";
153   }
154 
155   if (!N->isLeaf() && !N->hasAnyPredicate() && !N->getTransformFn())
156     return Error::success();
157 
158   return failedImport(Explanation);
159 }
160 
161 static Record *getInitValueAsRegClass(Init *V) {
162   if (DefInit *VDefInit = dyn_cast<DefInit>(V)) {
163     if (VDefInit->getDef()->isSubClassOf("RegisterOperand"))
164       return VDefInit->getDef()->getValueAsDef("RegClass");
165     if (VDefInit->getDef()->isSubClassOf("RegisterClass"))
166       return VDefInit->getDef();
167   }
168   return nullptr;
169 }
170 
171 //===- Matchers -----------------------------------------------------------===//
172 
173 class OperandMatcher;
174 class MatchAction;
175 
176 /// Generates code to check that a match rule matches.
177 class RuleMatcher {
178   /// A list of matchers that all need to succeed for the current rule to match.
179   /// FIXME: This currently supports a single match position but could be
180   /// extended to support multiple positions to support div/rem fusion or
181   /// load-multiple instructions.
182   std::vector<std::unique_ptr<InstructionMatcher>> Matchers;
183 
184   /// A list of actions that need to be taken when all predicates in this rule
185   /// have succeeded.
186   std::vector<std::unique_ptr<MatchAction>> Actions;
187 
188   /// A map of instruction matchers to the local variables created by
189   /// emitCxxCaptureStmts().
190   std::map<const InstructionMatcher *, std::string> InsnVariableNames;
191 
192   /// ID for the next instruction variable defined with defineInsnVar()
193   unsigned NextInsnVarID;
194 
195   std::vector<Record *> RequiredFeatures;
196 
197 public:
198   RuleMatcher()
199       : Matchers(), Actions(), InsnVariableNames(), NextInsnVarID(0) {}
200   RuleMatcher(RuleMatcher &&Other) = default;
201   RuleMatcher &operator=(RuleMatcher &&Other) = default;
202 
203   InstructionMatcher &addInstructionMatcher();
204   void addRequiredFeature(Record *Feature);
205 
206   template <class Kind, class... Args> Kind &addAction(Args &&... args);
207 
208   std::string defineInsnVar(raw_ostream &OS, const InstructionMatcher &Matcher,
209                             StringRef Value);
210   StringRef getInsnVarName(const InstructionMatcher &InsnMatcher) const;
211 
212   void emitCxxCapturedInsnList(raw_ostream &OS);
213   void emitCxxCaptureStmts(raw_ostream &OS, StringRef Expr);
214 
215 void emit(raw_ostream &OS, SubtargetFeatureInfoMap SubtargetFeatures);
216 
217 /// Compare the priority of this object and B.
218 ///
219 /// Returns true if this object is more important than B.
220 bool isHigherPriorityThan(const RuleMatcher &B) const;
221 
222 /// Report the maximum number of temporary operands needed by the rule
223 /// matcher.
224 unsigned countRendererFns() const;
225 
226 // FIXME: Remove this as soon as possible
227 InstructionMatcher &insnmatcher_front() const { return *Matchers.front(); }
228 };
229 
230 template <class PredicateTy> class PredicateListMatcher {
231 private:
232   typedef std::vector<std::unique_ptr<PredicateTy>> PredicateVec;
233   PredicateVec Predicates;
234 
235 public:
236   /// Construct a new operand predicate and add it to the matcher.
237   template <class Kind, class... Args>
238   Kind &addPredicate(Args&&... args) {
239     Predicates.emplace_back(
240         llvm::make_unique<Kind>(std::forward<Args>(args)...));
241     return *static_cast<Kind *>(Predicates.back().get());
242   }
243 
244   typename PredicateVec::const_iterator predicates_begin() const { return Predicates.begin(); }
245   typename PredicateVec::const_iterator predicates_end() const { return Predicates.end(); }
246   iterator_range<typename PredicateVec::const_iterator> predicates() const {
247     return make_range(predicates_begin(), predicates_end());
248   }
249   typename PredicateVec::size_type predicates_size() const { return Predicates.size(); }
250 
251   /// Emit a C++ expression that tests whether all the predicates are met.
252   template <class... Args>
253   void emitCxxPredicateListExpr(raw_ostream &OS, Args &&... args) const {
254     if (Predicates.empty()) {
255       OS << "true";
256       return;
257     }
258 
259     StringRef Separator = "";
260     for (const auto &Predicate : predicates()) {
261       OS << Separator << "(";
262       Predicate->emitCxxPredicateExpr(OS, std::forward<Args>(args)...);
263       OS << ")";
264       Separator = " &&\n";
265     }
266   }
267 };
268 
269 /// Generates code to check a predicate of an operand.
270 ///
271 /// Typical predicates include:
272 /// * Operand is a particular register.
273 /// * Operand is assigned a particular register bank.
274 /// * Operand is an MBB.
275 class OperandPredicateMatcher {
276 public:
277   /// This enum is used for RTTI and also defines the priority that is given to
278   /// the predicate when generating the matcher code. Kinds with higher priority
279   /// must be tested first.
280   ///
281   /// The relative priority of OPM_LLT, OPM_RegBank, and OPM_MBB do not matter
282   /// but OPM_Int must have priority over OPM_RegBank since constant integers
283   /// are represented by a virtual register defined by a G_CONSTANT instruction.
284   enum PredicateKind {
285     OPM_ComplexPattern,
286     OPM_Instruction,
287     OPM_Int,
288     OPM_LiteralInt,
289     OPM_LLT,
290     OPM_RegBank,
291     OPM_MBB,
292   };
293 
294 protected:
295   PredicateKind Kind;
296 
297 public:
298   OperandPredicateMatcher(PredicateKind Kind) : Kind(Kind) {}
299   virtual ~OperandPredicateMatcher() {}
300 
301   PredicateKind getKind() const { return Kind; }
302 
303   /// Return the OperandMatcher for the specified operand or nullptr if there
304   /// isn't one by that name in this operand predicate matcher.
305   ///
306   /// InstructionOperandMatcher is the only subclass that can return non-null
307   /// for this.
308   virtual Optional<const OperandMatcher *>
309   getOptionalOperand(StringRef SymbolicName) const {
310     assert(!SymbolicName.empty() && "Cannot lookup unnamed operand");
311     return None;
312   }
313 
314   /// Emit C++ statements to capture instructions into local variables.
315   ///
316   /// Only InstructionOperandMatcher needs to do anything for this method.
317   virtual void emitCxxCaptureStmts(raw_ostream &OS, RuleMatcher &Rule,
318                                    StringRef Expr) const {}
319 
320   /// Emit a C++ expression that checks the predicate for the given operand.
321   virtual void emitCxxPredicateExpr(raw_ostream &OS, RuleMatcher &Rule,
322                                     StringRef OperandExpr) const = 0;
323 
324   /// Compare the priority of this object and B.
325   ///
326   /// Returns true if this object is more important than B.
327   virtual bool isHigherPriorityThan(const OperandPredicateMatcher &B) const {
328     return Kind < B.Kind;
329   };
330 
331   /// Report the maximum number of temporary operands needed by the predicate
332   /// matcher.
333   virtual unsigned countRendererFns() const { return 0; }
334 };
335 
336 /// Generates code to check that an operand is a particular LLT.
337 class LLTOperandMatcher : public OperandPredicateMatcher {
338 protected:
339   LLTCodeGen Ty;
340 
341 public:
342   LLTOperandMatcher(const LLTCodeGen &Ty)
343       : OperandPredicateMatcher(OPM_LLT), Ty(Ty) {}
344 
345   static bool classof(const OperandPredicateMatcher *P) {
346     return P->getKind() == OPM_LLT;
347   }
348 
349   void emitCxxPredicateExpr(raw_ostream &OS, RuleMatcher &Rule,
350                             StringRef OperandExpr) const override {
351     OS << "MRI.getType(" << OperandExpr << ".getReg()) == (";
352     Ty.emitCxxConstructorCall(OS);
353     OS << ")";
354   }
355 };
356 
357 /// Generates code to check that an operand is a particular target constant.
358 class ComplexPatternOperandMatcher : public OperandPredicateMatcher {
359 protected:
360   const OperandMatcher &Operand;
361   const Record &TheDef;
362 
363   unsigned getAllocatedTemporariesBaseID() const;
364 
365 public:
366   ComplexPatternOperandMatcher(const OperandMatcher &Operand,
367                                const Record &TheDef)
368       : OperandPredicateMatcher(OPM_ComplexPattern), Operand(Operand),
369         TheDef(TheDef) {}
370 
371   static bool classof(const OperandPredicateMatcher *P) {
372     return P->getKind() == OPM_ComplexPattern;
373   }
374 
375   void emitCxxPredicateExpr(raw_ostream &OS, RuleMatcher &Rule,
376                             StringRef OperandExpr) const override {
377     unsigned ID = getAllocatedTemporariesBaseID();
378     OS << "(Renderer" << ID << " = " << TheDef.getValueAsString("MatcherFn")
379        << "(" << OperandExpr << "))";
380   }
381 
382   unsigned countRendererFns() const override {
383     return 1;
384   }
385 };
386 
387 /// Generates code to check that an operand is in a particular register bank.
388 class RegisterBankOperandMatcher : public OperandPredicateMatcher {
389 protected:
390   const CodeGenRegisterClass &RC;
391 
392 public:
393   RegisterBankOperandMatcher(const CodeGenRegisterClass &RC)
394       : OperandPredicateMatcher(OPM_RegBank), RC(RC) {}
395 
396   static bool classof(const OperandPredicateMatcher *P) {
397     return P->getKind() == OPM_RegBank;
398   }
399 
400   void emitCxxPredicateExpr(raw_ostream &OS, RuleMatcher &Rule,
401                             StringRef OperandExpr) const override {
402     OS << "(&RBI.getRegBankFromRegClass(" << RC.getQualifiedName()
403        << "RegClass) == RBI.getRegBank(" << OperandExpr
404        << ".getReg(), MRI, TRI))";
405   }
406 };
407 
408 /// Generates code to check that an operand is a basic block.
409 class MBBOperandMatcher : public OperandPredicateMatcher {
410 public:
411   MBBOperandMatcher() : OperandPredicateMatcher(OPM_MBB) {}
412 
413   static bool classof(const OperandPredicateMatcher *P) {
414     return P->getKind() == OPM_MBB;
415   }
416 
417   void emitCxxPredicateExpr(raw_ostream &OS, RuleMatcher &Rule,
418                             StringRef OperandExpr) const override {
419     OS << OperandExpr << ".isMBB()";
420   }
421 };
422 
423 /// Generates code to check that an operand is a G_CONSTANT with a particular
424 /// int.
425 class ConstantIntOperandMatcher : public OperandPredicateMatcher {
426 protected:
427   int64_t Value;
428 
429 public:
430   ConstantIntOperandMatcher(int64_t Value)
431       : OperandPredicateMatcher(OPM_Int), Value(Value) {}
432 
433   static bool classof(const OperandPredicateMatcher *P) {
434     return P->getKind() == OPM_Int;
435   }
436 
437   void emitCxxPredicateExpr(raw_ostream &OS, RuleMatcher &Rule,
438                             StringRef OperandExpr) const override {
439     OS << "isOperandImmEqual(" << OperandExpr << ", " << Value << ", MRI)";
440   }
441 };
442 
443 /// Generates code to check that an operand is a raw int (where MO.isImm() or
444 /// MO.isCImm() is true).
445 class LiteralIntOperandMatcher : public OperandPredicateMatcher {
446 protected:
447   int64_t Value;
448 
449 public:
450   LiteralIntOperandMatcher(int64_t Value)
451       : OperandPredicateMatcher(OPM_LiteralInt), Value(Value) {}
452 
453   static bool classof(const OperandPredicateMatcher *P) {
454     return P->getKind() == OPM_LiteralInt;
455   }
456 
457   void emitCxxPredicateExpr(raw_ostream &OS, RuleMatcher &Rule,
458                             StringRef OperandExpr) const override {
459     OS << OperandExpr << ".isCImm() && " << OperandExpr
460        << ".getCImm()->equalsInt(" << Value << ")";
461   }
462 };
463 
464 /// Generates code to check that a set of predicates match for a particular
465 /// operand.
466 class OperandMatcher : public PredicateListMatcher<OperandPredicateMatcher> {
467 protected:
468   InstructionMatcher &Insn;
469   unsigned OpIdx;
470   std::string SymbolicName;
471 
472   /// The index of the first temporary variable allocated to this operand. The
473   /// number of allocated temporaries can be found with
474   /// countRendererFns().
475   unsigned AllocatedTemporariesBaseID;
476 
477 public:
478   OperandMatcher(InstructionMatcher &Insn, unsigned OpIdx,
479                  const std::string &SymbolicName,
480                  unsigned AllocatedTemporariesBaseID)
481       : Insn(Insn), OpIdx(OpIdx), SymbolicName(SymbolicName),
482         AllocatedTemporariesBaseID(AllocatedTemporariesBaseID) {}
483 
484   bool hasSymbolicName() const { return !SymbolicName.empty(); }
485   const StringRef getSymbolicName() const { return SymbolicName; }
486   void setSymbolicName(StringRef Name) {
487     assert(SymbolicName.empty() && "Operand already has a symbolic name");
488     SymbolicName = Name;
489   }
490   unsigned getOperandIndex() const { return OpIdx; }
491 
492   std::string getOperandExpr(StringRef InsnVarName) const {
493     return (InsnVarName + ".getOperand(" + llvm::to_string(OpIdx) + ")").str();
494   }
495 
496   Optional<const OperandMatcher *>
497   getOptionalOperand(StringRef DesiredSymbolicName) const {
498     assert(!DesiredSymbolicName.empty() && "Cannot lookup unnamed operand");
499     if (DesiredSymbolicName == SymbolicName)
500       return this;
501     for (const auto &OP : predicates()) {
502       const auto &MaybeOperand = OP->getOptionalOperand(DesiredSymbolicName);
503       if (MaybeOperand.hasValue())
504         return MaybeOperand.getValue();
505     }
506     return None;
507   }
508 
509   InstructionMatcher &getInstructionMatcher() const { return Insn; }
510 
511   /// Emit C++ statements to capture instructions into local variables.
512   void emitCxxCaptureStmts(raw_ostream &OS, RuleMatcher &Rule,
513                            StringRef OperandExpr) const {
514     for (const auto &Predicate : predicates())
515       Predicate->emitCxxCaptureStmts(OS, Rule, OperandExpr);
516   }
517 
518   /// Emit a C++ expression that tests whether the instruction named in
519   /// InsnVarName matches all the predicate and all the operands.
520   void emitCxxPredicateExpr(raw_ostream &OS, RuleMatcher &Rule,
521                             StringRef InsnVarName) const {
522     OS << "(/* ";
523     if (SymbolicName.empty())
524       OS << "Operand " << OpIdx;
525     else
526       OS << SymbolicName;
527     OS << " */ ";
528     emitCxxPredicateListExpr(OS, Rule, getOperandExpr(InsnVarName));
529     OS << ")";
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 OperandMatcher &B) const {
536     // Operand matchers involving more predicates have higher priority.
537     if (predicates_size() > B.predicates_size())
538       return true;
539     if (predicates_size() < B.predicates_size())
540       return false;
541 
542     // This assumes that predicates are added in a consistent order.
543     for (const auto &Predicate : zip(predicates(), B.predicates())) {
544       if (std::get<0>(Predicate)->isHigherPriorityThan(*std::get<1>(Predicate)))
545         return true;
546       if (std::get<1>(Predicate)->isHigherPriorityThan(*std::get<0>(Predicate)))
547         return false;
548     }
549 
550     return false;
551   };
552 
553   /// Report the maximum number of temporary operands needed by the operand
554   /// matcher.
555   unsigned countRendererFns() const {
556     return std::accumulate(
557         predicates().begin(), predicates().end(), 0,
558         [](unsigned A,
559            const std::unique_ptr<OperandPredicateMatcher> &Predicate) {
560           return A + Predicate->countRendererFns();
561         });
562   }
563 
564   unsigned getAllocatedTemporariesBaseID() const {
565     return AllocatedTemporariesBaseID;
566   }
567 };
568 
569 unsigned ComplexPatternOperandMatcher::getAllocatedTemporariesBaseID() const {
570   return Operand.getAllocatedTemporariesBaseID();
571 }
572 
573 /// Generates code to check a predicate on an instruction.
574 ///
575 /// Typical predicates include:
576 /// * The opcode of the instruction is a particular value.
577 /// * The nsw/nuw flag is/isn't set.
578 class InstructionPredicateMatcher {
579 protected:
580   /// This enum is used for RTTI and also defines the priority that is given to
581   /// the predicate when generating the matcher code. Kinds with higher priority
582   /// must be tested first.
583   enum PredicateKind {
584     IPM_Opcode,
585   };
586 
587   PredicateKind Kind;
588 
589 public:
590   InstructionPredicateMatcher(PredicateKind Kind) : Kind(Kind) {}
591   virtual ~InstructionPredicateMatcher() {}
592 
593   PredicateKind getKind() const { return Kind; }
594 
595   /// Emit a C++ expression that tests whether the instruction named in
596   /// InsnVarName matches the predicate.
597   virtual void emitCxxPredicateExpr(raw_ostream &OS, RuleMatcher &Rule,
598                                     StringRef InsnVarName) const = 0;
599 
600   /// Compare the priority of this object and B.
601   ///
602   /// Returns true if this object is more important than B.
603   virtual bool isHigherPriorityThan(const InstructionPredicateMatcher &B) const {
604     return Kind < B.Kind;
605   };
606 
607   /// Report the maximum number of temporary operands needed by the predicate
608   /// matcher.
609   virtual unsigned countRendererFns() const { return 0; }
610 };
611 
612 /// Generates code to check the opcode of an instruction.
613 class InstructionOpcodeMatcher : public InstructionPredicateMatcher {
614 protected:
615   const CodeGenInstruction *I;
616 
617 public:
618   InstructionOpcodeMatcher(const CodeGenInstruction *I)
619       : InstructionPredicateMatcher(IPM_Opcode), I(I) {}
620 
621   static bool classof(const InstructionPredicateMatcher *P) {
622     return P->getKind() == IPM_Opcode;
623   }
624 
625   void emitCxxPredicateExpr(raw_ostream &OS, RuleMatcher &Rule,
626                             StringRef InsnVarName) const override {
627     OS << InsnVarName << ".getOpcode() == " << I->Namespace
628        << "::" << I->TheDef->getName();
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 InstructionPredicateMatcher &B) const override {
635     if (InstructionPredicateMatcher::isHigherPriorityThan(B))
636       return true;
637     if (B.InstructionPredicateMatcher::isHigherPriorityThan(*this))
638       return false;
639 
640     // Prioritize opcodes for cosmetic reasons in the generated source. Although
641     // this is cosmetic at the moment, we may want to drive a similar ordering
642     // using instruction frequency information to improve compile time.
643     if (const InstructionOpcodeMatcher *BO =
644             dyn_cast<InstructionOpcodeMatcher>(&B))
645       return I->TheDef->getName() < BO->I->TheDef->getName();
646 
647     return false;
648   };
649 };
650 
651 /// Generates code to check that a set of predicates and operands match for a
652 /// particular instruction.
653 ///
654 /// Typical predicates include:
655 /// * Has a specific opcode.
656 /// * Has an nsw/nuw flag or doesn't.
657 class InstructionMatcher
658     : public PredicateListMatcher<InstructionPredicateMatcher> {
659 protected:
660   typedef std::vector<std::unique_ptr<OperandMatcher>> OperandVec;
661 
662   /// The operands to match. All rendered operands must be present even if the
663   /// condition is always true.
664   OperandVec Operands;
665 
666 public:
667   /// Add an operand to the matcher.
668   OperandMatcher &addOperand(unsigned OpIdx, const std::string &SymbolicName,
669                              unsigned AllocatedTemporariesBaseID) {
670     Operands.emplace_back(new OperandMatcher(*this, OpIdx, SymbolicName,
671                                              AllocatedTemporariesBaseID));
672     return *Operands.back();
673   }
674 
675   OperandMatcher &getOperand(unsigned OpIdx) {
676     auto I = std::find_if(Operands.begin(), Operands.end(),
677                           [&OpIdx](const std::unique_ptr<OperandMatcher> &X) {
678                             return X->getOperandIndex() == OpIdx;
679                           });
680     if (I != Operands.end())
681       return **I;
682     llvm_unreachable("Failed to lookup operand");
683   }
684 
685   Optional<const OperandMatcher *>
686   getOptionalOperand(StringRef SymbolicName) const {
687     assert(!SymbolicName.empty() && "Cannot lookup unnamed operand");
688     for (const auto &Operand : Operands) {
689       const auto &OM = Operand->getOptionalOperand(SymbolicName);
690       if (OM.hasValue())
691         return OM.getValue();
692     }
693     return None;
694   }
695 
696   const OperandMatcher &getOperand(StringRef SymbolicName) const {
697     Optional<const OperandMatcher *>OM = getOptionalOperand(SymbolicName);
698     if (OM.hasValue())
699       return *OM.getValue();
700     llvm_unreachable("Failed to lookup operand");
701   }
702 
703   unsigned getNumOperands() const { return Operands.size(); }
704   OperandVec::iterator operands_begin() { return Operands.begin(); }
705   OperandVec::iterator operands_end() { return Operands.end(); }
706   iterator_range<OperandVec::iterator> operands() {
707     return make_range(operands_begin(), operands_end());
708   }
709   OperandVec::const_iterator operands_begin() const { return Operands.begin(); }
710   OperandVec::const_iterator operands_end() const { return Operands.end(); }
711   iterator_range<OperandVec::const_iterator> operands() const {
712     return make_range(operands_begin(), operands_end());
713   }
714 
715   /// Emit C++ statements to check the shape of the match and capture
716   /// instructions into local variables.
717   void emitCxxCaptureStmts(raw_ostream &OS, RuleMatcher &Rule, StringRef Expr) {
718     OS << "if (" << Expr << ".getNumOperands() < " << getNumOperands() << ")\n"
719        << "  return false;\n";
720     for (const auto &Operand : Operands) {
721       Operand->emitCxxCaptureStmts(OS, Rule, Operand->getOperandExpr(Expr));
722     }
723   }
724 
725   /// Emit a C++ expression that tests whether the instruction named in
726   /// InsnVarName matches all the predicates and all the operands.
727   void emitCxxPredicateExpr(raw_ostream &OS, RuleMatcher &Rule,
728                             StringRef InsnVarName) const {
729     emitCxxPredicateListExpr(OS, Rule, InsnVarName);
730     for (const auto &Operand : Operands) {
731       OS << " &&\n(";
732       Operand->emitCxxPredicateExpr(OS, Rule, InsnVarName);
733       OS << ")";
734     }
735   }
736 
737   /// Compare the priority of this object and B.
738   ///
739   /// Returns true if this object is more important than B.
740   bool isHigherPriorityThan(const InstructionMatcher &B) const {
741     // Instruction matchers involving more operands have higher priority.
742     if (Operands.size() > B.Operands.size())
743       return true;
744     if (Operands.size() < B.Operands.size())
745       return false;
746 
747     for (const auto &Predicate : zip(predicates(), B.predicates())) {
748       if (std::get<0>(Predicate)->isHigherPriorityThan(*std::get<1>(Predicate)))
749         return true;
750       if (std::get<1>(Predicate)->isHigherPriorityThan(*std::get<0>(Predicate)))
751         return false;
752     }
753 
754     for (const auto &Operand : zip(Operands, B.Operands)) {
755       if (std::get<0>(Operand)->isHigherPriorityThan(*std::get<1>(Operand)))
756         return true;
757       if (std::get<1>(Operand)->isHigherPriorityThan(*std::get<0>(Operand)))
758         return false;
759     }
760 
761     return false;
762   };
763 
764   /// Report the maximum number of temporary operands needed by the instruction
765   /// matcher.
766   unsigned countRendererFns() const {
767     return std::accumulate(predicates().begin(), predicates().end(), 0,
768                            [](unsigned A,
769                               const std::unique_ptr<InstructionPredicateMatcher>
770                                   &Predicate) {
771                              return A + Predicate->countRendererFns();
772                            }) +
773            std::accumulate(
774                Operands.begin(), Operands.end(), 0,
775                [](unsigned A, const std::unique_ptr<OperandMatcher> &Operand) {
776                  return A + Operand->countRendererFns();
777                });
778   }
779 };
780 
781 /// Generates code to check that the operand is a register defined by an
782 /// instruction that matches the given instruction matcher.
783 ///
784 /// For example, the pattern:
785 ///   (set $dst, (G_MUL (G_ADD $src1, $src2), $src3))
786 /// would use an InstructionOperandMatcher for operand 1 of the G_MUL to match
787 /// the:
788 ///   (G_ADD $src1, $src2)
789 /// subpattern.
790 class InstructionOperandMatcher : public OperandPredicateMatcher {
791 protected:
792   std::unique_ptr<InstructionMatcher> InsnMatcher;
793 
794 public:
795   InstructionOperandMatcher()
796       : OperandPredicateMatcher(OPM_Instruction),
797         InsnMatcher(new InstructionMatcher()) {}
798 
799   static bool classof(const OperandPredicateMatcher *P) {
800     return P->getKind() == OPM_Instruction;
801   }
802 
803   InstructionMatcher &getInsnMatcher() const { return *InsnMatcher; }
804 
805   Optional<const OperandMatcher *>
806   getOptionalOperand(StringRef SymbolicName) const override {
807     assert(!SymbolicName.empty() && "Cannot lookup unnamed operand");
808     return InsnMatcher->getOptionalOperand(SymbolicName);
809   }
810 
811   void emitCxxCaptureStmts(raw_ostream &OS, RuleMatcher &Rule,
812                            StringRef OperandExpr) const override {
813     OS << "if (!" << OperandExpr + ".isReg())\n"
814        << "  return false;\n"
815        << "if (TRI.isPhysicalRegister(" << OperandExpr + ".getReg()))\n"
816        << "  return false;\n";
817     std::string InsnVarName = Rule.defineInsnVar(
818         OS, *InsnMatcher,
819         ("*MRI.getVRegDef(" + OperandExpr + ".getReg())").str());
820     InsnMatcher->emitCxxCaptureStmts(OS, Rule, InsnVarName);
821   }
822 
823   void emitCxxPredicateExpr(raw_ostream &OS, RuleMatcher &Rule,
824                             StringRef OperandExpr) const override {
825     OperandExpr = Rule.getInsnVarName(*InsnMatcher);
826     OS << "(";
827     InsnMatcher->emitCxxPredicateExpr(OS, Rule, OperandExpr);
828     OS << ")\n";
829   }
830 };
831 
832 //===- Actions ------------------------------------------------------------===//
833 class OperandRenderer {
834 public:
835   enum RendererKind {
836     OR_Copy,
837     OR_CopySubReg,
838     OR_Imm,
839     OR_Register,
840     OR_ComplexPattern
841   };
842 
843 protected:
844   RendererKind Kind;
845 
846 public:
847   OperandRenderer(RendererKind Kind) : Kind(Kind) {}
848   virtual ~OperandRenderer() {}
849 
850   RendererKind getKind() const { return Kind; }
851 
852   virtual void emitCxxRenderStmts(raw_ostream &OS, RuleMatcher &Rule) const = 0;
853 };
854 
855 /// A CopyRenderer emits code to copy a single operand from an existing
856 /// instruction to the one being built.
857 class CopyRenderer : public OperandRenderer {
858 protected:
859   /// The matcher for the instruction that this operand is copied from.
860   /// This provides the facility for looking up an a operand by it's name so
861   /// that it can be used as a source for the instruction being built.
862   const InstructionMatcher &Matched;
863   /// The name of the operand.
864   const StringRef SymbolicName;
865 
866 public:
867   CopyRenderer(const InstructionMatcher &Matched, StringRef SymbolicName)
868       : OperandRenderer(OR_Copy), Matched(Matched), SymbolicName(SymbolicName) {
869   }
870 
871   static bool classof(const OperandRenderer *R) {
872     return R->getKind() == OR_Copy;
873   }
874 
875   const StringRef getSymbolicName() const { return SymbolicName; }
876 
877   void emitCxxRenderStmts(raw_ostream &OS, RuleMatcher &Rule) const override {
878     const OperandMatcher &Operand = Matched.getOperand(SymbolicName);
879     StringRef InsnVarName =
880         Rule.getInsnVarName(Operand.getInstructionMatcher());
881     std::string OperandExpr = Operand.getOperandExpr(InsnVarName);
882     OS << "    MIB.add(" << OperandExpr << "/*" << SymbolicName << "*/);\n";
883   }
884 };
885 
886 /// A CopySubRegRenderer emits code to copy a single register operand from an
887 /// existing instruction to the one being built and indicate that only a
888 /// subregister should be copied.
889 class CopySubRegRenderer : public OperandRenderer {
890 protected:
891   /// The matcher for the instruction that this operand is copied from.
892   /// This provides the facility for looking up an a operand by it's name so
893   /// that it can be used as a source for the instruction being built.
894   const InstructionMatcher &Matched;
895   /// The name of the operand.
896   const StringRef SymbolicName;
897   /// The subregister to extract.
898   const CodeGenSubRegIndex *SubReg;
899 
900 public:
901   CopySubRegRenderer(const InstructionMatcher &Matched, StringRef SymbolicName,
902                      const CodeGenSubRegIndex *SubReg)
903       : OperandRenderer(OR_CopySubReg), Matched(Matched),
904         SymbolicName(SymbolicName), SubReg(SubReg) {}
905 
906   static bool classof(const OperandRenderer *R) {
907     return R->getKind() == OR_CopySubReg;
908   }
909 
910   const StringRef getSymbolicName() const { return SymbolicName; }
911 
912   void emitCxxRenderStmts(raw_ostream &OS, RuleMatcher &Rule) const override {
913     const OperandMatcher &Operand = Matched.getOperand(SymbolicName);
914     StringRef InsnVarName =
915         Rule.getInsnVarName(Operand.getInstructionMatcher());
916     std::string OperandExpr = Operand.getOperandExpr(InsnVarName);
917     OS << "    MIB.addReg(" << OperandExpr << ".getReg() /*" << SymbolicName
918        << "*/, 0, " << SubReg->EnumValue << ");\n";
919   }
920 };
921 
922 /// Adds a specific physical register to the instruction being built.
923 /// This is typically useful for WZR/XZR on AArch64.
924 class AddRegisterRenderer : public OperandRenderer {
925 protected:
926   const Record *RegisterDef;
927 
928 public:
929   AddRegisterRenderer(const Record *RegisterDef)
930       : OperandRenderer(OR_Register), RegisterDef(RegisterDef) {}
931 
932   static bool classof(const OperandRenderer *R) {
933     return R->getKind() == OR_Register;
934   }
935 
936   void emitCxxRenderStmts(raw_ostream &OS, RuleMatcher &Rule) const override {
937     OS << "    MIB.addReg(" << (RegisterDef->getValue("Namespace")
938                                     ? RegisterDef->getValueAsString("Namespace")
939                                     : "")
940        << "::" << RegisterDef->getName() << ");\n";
941   }
942 };
943 
944 /// Adds a specific immediate to the instruction being built.
945 class ImmRenderer : public OperandRenderer {
946 protected:
947   int64_t Imm;
948 
949 public:
950   ImmRenderer(int64_t Imm)
951       : OperandRenderer(OR_Imm), Imm(Imm) {}
952 
953   static bool classof(const OperandRenderer *R) {
954     return R->getKind() == OR_Imm;
955   }
956 
957   void emitCxxRenderStmts(raw_ostream &OS, RuleMatcher &Rule) const override {
958     OS << "    MIB.addImm(" << Imm << ");\n";
959   }
960 };
961 
962 /// Adds operands by calling a renderer function supplied by the ComplexPattern
963 /// matcher function.
964 class RenderComplexPatternOperand : public OperandRenderer {
965 private:
966   const Record &TheDef;
967   /// The name of the operand.
968   const StringRef SymbolicName;
969   /// The renderer number. This must be unique within a rule since it's used to
970   /// identify a temporary variable to hold the renderer function.
971   unsigned RendererID;
972 
973   unsigned getNumOperands() const {
974     return TheDef.getValueAsDag("Operands")->getNumArgs();
975   }
976 
977 public:
978   RenderComplexPatternOperand(const Record &TheDef, StringRef SymbolicName,
979                               unsigned RendererID)
980       : OperandRenderer(OR_ComplexPattern), TheDef(TheDef),
981         SymbolicName(SymbolicName), RendererID(RendererID) {}
982 
983   static bool classof(const OperandRenderer *R) {
984     return R->getKind() == OR_ComplexPattern;
985   }
986 
987   void emitCxxRenderStmts(raw_ostream &OS, RuleMatcher &Rule) const override {
988     OS << "Renderer" << RendererID << "(MIB);\n";
989   }
990 };
991 
992 /// An action taken when all Matcher predicates succeeded for a parent rule.
993 ///
994 /// Typical actions include:
995 /// * Changing the opcode of an instruction.
996 /// * Adding an operand to an instruction.
997 class MatchAction {
998 public:
999   virtual ~MatchAction() {}
1000 
1001   /// Emit the C++ statements to implement the action.
1002   ///
1003   /// \param RecycleVarName If given, it's an instruction to recycle. The
1004   ///                       requirements on the instruction vary from action to
1005   ///                       action.
1006   virtual void emitCxxActionStmts(raw_ostream &OS, RuleMatcher &Rule,
1007                                   StringRef RecycleVarName) const = 0;
1008 };
1009 
1010 /// Generates a comment describing the matched rule being acted upon.
1011 class DebugCommentAction : public MatchAction {
1012 private:
1013   const PatternToMatch &P;
1014 
1015 public:
1016   DebugCommentAction(const PatternToMatch &P) : P(P) {}
1017 
1018   void emitCxxActionStmts(raw_ostream &OS, RuleMatcher &Rule,
1019                           StringRef RecycleVarName) const override {
1020     OS << "// " << *P.getSrcPattern() << "  =>  " << *P.getDstPattern() << "\n";
1021   }
1022 };
1023 
1024 /// Generates code to build an instruction or mutate an existing instruction
1025 /// into the desired instruction when this is possible.
1026 class BuildMIAction : public MatchAction {
1027 private:
1028   std::string Name;
1029   const CodeGenInstruction *I;
1030   const InstructionMatcher &Matched;
1031   std::vector<std::unique_ptr<OperandRenderer>> OperandRenderers;
1032 
1033   /// True if the instruction can be built solely by mutating the opcode.
1034   bool canMutate() const {
1035     if (OperandRenderers.size() != Matched.getNumOperands())
1036       return false;
1037 
1038     for (const auto &Renderer : enumerate(OperandRenderers)) {
1039       if (const auto *Copy = dyn_cast<CopyRenderer>(&*Renderer.value())) {
1040         const OperandMatcher &OM = Matched.getOperand(Copy->getSymbolicName());
1041         if (&Matched != &OM.getInstructionMatcher() ||
1042             OM.getOperandIndex() != Renderer.index())
1043           return false;
1044       } else
1045         return false;
1046     }
1047 
1048     return true;
1049   }
1050 
1051 public:
1052   BuildMIAction(const StringRef Name, const CodeGenInstruction *I,
1053                 const InstructionMatcher &Matched)
1054       : Name(Name), I(I), Matched(Matched) {}
1055 
1056   template <class Kind, class... Args>
1057   Kind &addRenderer(Args&&... args) {
1058     OperandRenderers.emplace_back(
1059         llvm::make_unique<Kind>(std::forward<Args>(args)...));
1060     return *static_cast<Kind *>(OperandRenderers.back().get());
1061   }
1062 
1063   void emitCxxActionStmts(raw_ostream &OS, RuleMatcher &Rule,
1064                           StringRef RecycleVarName) const override {
1065     if (canMutate()) {
1066       OS << "    " << RecycleVarName << ".setDesc(TII.get(" << I->Namespace
1067          << "::" << I->TheDef->getName() << "));\n";
1068 
1069       if (!I->ImplicitDefs.empty() || !I->ImplicitUses.empty()) {
1070         OS << "    auto MIB = MachineInstrBuilder(MF, &" << RecycleVarName
1071            << ");\n";
1072 
1073         for (auto Def : I->ImplicitDefs) {
1074           auto Namespace = Def->getValue("Namespace")
1075                                ? Def->getValueAsString("Namespace")
1076                                : "";
1077           OS << "    MIB.addDef(" << Namespace << "::" << Def->getName()
1078              << ", RegState::Implicit);\n";
1079         }
1080         for (auto Use : I->ImplicitUses) {
1081           auto Namespace = Use->getValue("Namespace")
1082                                ? Use->getValueAsString("Namespace")
1083                                : "";
1084           OS << "    MIB.addUse(" << Namespace << "::" << Use->getName()
1085              << ", RegState::Implicit);\n";
1086         }
1087       }
1088 
1089       OS << "    MachineInstr &" << Name << " = " << RecycleVarName << ";\n";
1090       return;
1091     }
1092 
1093     // TODO: Simple permutation looks like it could be almost as common as
1094     //       mutation due to commutative operations.
1095 
1096     OS << "MachineInstrBuilder MIB = BuildMI(*I.getParent(), I, "
1097           "I.getDebugLoc(), TII.get("
1098        << I->Namespace << "::" << I->TheDef->getName() << "));\n";
1099     for (const auto &Renderer : OperandRenderers)
1100       Renderer->emitCxxRenderStmts(OS, Rule);
1101     OS << "    for (const auto *FromMI : ";
1102     Rule.emitCxxCapturedInsnList(OS);
1103     OS << ")\n";
1104     OS << "      for (const auto &MMO : FromMI->memoperands())\n";
1105     OS << "        MIB.addMemOperand(MMO);\n";
1106     OS << "    " << RecycleVarName << ".eraseFromParent();\n";
1107     OS << "    MachineInstr &" << Name << " = *MIB;\n";
1108   }
1109 };
1110 
1111 /// Generates code to constrain the operands of an output instruction to the
1112 /// register classes specified by the definition of that instruction.
1113 class ConstrainOperandsToDefinitionAction : public MatchAction {
1114   std::string Name;
1115 
1116 public:
1117   ConstrainOperandsToDefinitionAction(const StringRef Name) : Name(Name) {}
1118 
1119   void emitCxxActionStmts(raw_ostream &OS, RuleMatcher &Rule,
1120                           StringRef RecycleVarName) const override {
1121     OS << "      constrainSelectedInstRegOperands(" << Name << ", TII, TRI, RBI);\n";
1122   }
1123 };
1124 
1125 /// Generates code to constrain the specified operand of an output instruction
1126 /// to the specified register class.
1127 class ConstrainOperandToRegClassAction : public MatchAction {
1128   std::string Name;
1129   unsigned OpIdx;
1130   const CodeGenRegisterClass &RC;
1131 
1132 public:
1133   ConstrainOperandToRegClassAction(const StringRef Name, unsigned OpIdx,
1134                                    const CodeGenRegisterClass &RC)
1135       : Name(Name), OpIdx(OpIdx), RC(RC) {}
1136 
1137   void emitCxxActionStmts(raw_ostream &OS, RuleMatcher &Rule,
1138                           StringRef RecycleVarName) const override {
1139     OS << "      constrainOperandRegToRegClass(" << Name << ", " << OpIdx
1140        << ", " << RC.getQualifiedName() << "RegClass, TII, TRI, RBI);\n";
1141   }
1142 };
1143 
1144 InstructionMatcher &RuleMatcher::addInstructionMatcher() {
1145   Matchers.emplace_back(new InstructionMatcher());
1146   return *Matchers.back();
1147 }
1148 
1149 void RuleMatcher::addRequiredFeature(Record *Feature) {
1150   RequiredFeatures.push_back(Feature);
1151 }
1152 
1153 template <class Kind, class... Args>
1154 Kind &RuleMatcher::addAction(Args &&... args) {
1155   Actions.emplace_back(llvm::make_unique<Kind>(std::forward<Args>(args)...));
1156   return *static_cast<Kind *>(Actions.back().get());
1157 }
1158 
1159 std::string RuleMatcher::defineInsnVar(raw_ostream &OS,
1160                                        const InstructionMatcher &Matcher,
1161                                        StringRef Value) {
1162   std::string InsnVarName = "MI" + llvm::to_string(NextInsnVarID++);
1163   OS << "MachineInstr &" << InsnVarName << " = " << Value << ";\n";
1164   InsnVariableNames[&Matcher] = InsnVarName;
1165   return InsnVarName;
1166 }
1167 
1168 StringRef RuleMatcher::getInsnVarName(const InstructionMatcher &InsnMatcher) const {
1169   const auto &I = InsnVariableNames.find(&InsnMatcher);
1170   if (I != InsnVariableNames.end())
1171     return I->second;
1172   llvm_unreachable("Matched Insn was not captured in a local variable");
1173 }
1174 
1175 /// Emit a C++ initializer_list containing references to every matched instruction.
1176 void RuleMatcher::emitCxxCapturedInsnList(raw_ostream &OS) {
1177   SmallVector<StringRef, 2> Names;
1178   for (const auto &Pair : InsnVariableNames)
1179     Names.push_back(Pair.second);
1180   std::sort(Names.begin(), Names.end());
1181 
1182   OS << "{";
1183   for (const auto &Name : Names)
1184     OS << "&" << Name << ", ";
1185   OS << "}";
1186 }
1187 
1188 /// Emit C++ statements to check the shape of the match and capture
1189 /// instructions into local variables.
1190 void RuleMatcher::emitCxxCaptureStmts(raw_ostream &OS, StringRef Expr) {
1191   assert(Matchers.size() == 1 && "Cannot handle multi-root matchers yet");
1192   std::string InsnVarName = defineInsnVar(OS, *Matchers.front(), Expr);
1193   Matchers.front()->emitCxxCaptureStmts(OS, *this, InsnVarName);
1194 }
1195 
1196 void RuleMatcher::emit(raw_ostream &OS,
1197                        SubtargetFeatureInfoMap SubtargetFeatures) {
1198   if (Matchers.empty())
1199     llvm_unreachable("Unexpected empty matcher!");
1200 
1201   // The representation supports rules that require multiple roots such as:
1202   //    %ptr(p0) = ...
1203   //    %elt0(s32) = G_LOAD %ptr
1204   //    %1(p0) = G_ADD %ptr, 4
1205   //    %elt1(s32) = G_LOAD p0 %1
1206   // which could be usefully folded into:
1207   //    %ptr(p0) = ...
1208   //    %elt0(s32), %elt1(s32) = TGT_LOAD_PAIR %ptr
1209   // on some targets but we don't need to make use of that yet.
1210   assert(Matchers.size() == 1 && "Cannot handle multi-root matchers yet");
1211 
1212   OS << "if (";
1213   OS << "[&]() {\n";
1214   if (!RequiredFeatures.empty()) {
1215     OS << "  PredicateBitset ExpectedFeatures = {";
1216     StringRef Separator = "";
1217     for (const auto &Predicate : RequiredFeatures) {
1218       const auto &I = SubtargetFeatures.find(Predicate);
1219       assert(I != SubtargetFeatures.end() && "Didn't import predicate?");
1220       OS << Separator << I->second.getEnumBitName();
1221       Separator = ", ";
1222     }
1223     OS << "};\n";
1224     OS << "if ((AvailableFeatures & ExpectedFeatures) != ExpectedFeatures)\n"
1225        << "  return false;\n";
1226   }
1227 
1228   emitCxxCaptureStmts(OS, "I");
1229 
1230   OS << "    if (";
1231   Matchers.front()->emitCxxPredicateExpr(OS, *this,
1232                                          getInsnVarName(*Matchers.front()));
1233   OS << ") {\n";
1234 
1235   // We must also check if it's safe to fold the matched instructions.
1236   if (InsnVariableNames.size() >= 2) {
1237     // Invert the map to create stable ordering (by var names)
1238     SmallVector<StringRef, 2> Names;
1239     for (const auto &Pair : InsnVariableNames) {
1240       // Skip the root node since it isn't moving anywhere. Everything else is
1241       // sinking to meet it.
1242       if (Pair.first == Matchers.front().get())
1243         continue;
1244 
1245       Names.push_back(Pair.second);
1246     }
1247     std::sort(Names.begin(), Names.end());
1248 
1249     for (const auto &Name : Names) {
1250       // Reject the difficult cases until we have a more accurate check.
1251       OS << "      if (!isObviouslySafeToFold(" << Name
1252          << ")) return false;\n";
1253 
1254       // FIXME: Emit checks to determine it's _actually_ safe to fold and/or
1255       //        account for unsafe cases.
1256       //
1257       //        Example:
1258       //          MI1--> %0 = ...
1259       //                 %1 = ... %0
1260       //          MI0--> %2 = ... %0
1261       //          It's not safe to erase MI1. We currently handle this by not
1262       //          erasing %0 (even when it's dead).
1263       //
1264       //        Example:
1265       //          MI1--> %0 = load volatile @a
1266       //                 %1 = load volatile @a
1267       //          MI0--> %2 = ... %0
1268       //          It's not safe to sink %0's def past %1. We currently handle
1269       //          this by rejecting all loads.
1270       //
1271       //        Example:
1272       //          MI1--> %0 = load @a
1273       //                 %1 = store @a
1274       //          MI0--> %2 = ... %0
1275       //          It's not safe to sink %0's def past %1. We currently handle
1276       //          this by rejecting all loads.
1277       //
1278       //        Example:
1279       //                   G_CONDBR %cond, @BB1
1280       //                 BB0:
1281       //          MI1-->   %0 = load @a
1282       //                   G_BR @BB1
1283       //                 BB1:
1284       //          MI0-->   %2 = ... %0
1285       //          It's not always safe to sink %0 across control flow. In this
1286       //          case it may introduce a memory fault. We currentl handle this
1287       //          by rejecting all loads.
1288     }
1289   }
1290 
1291   for (const auto &MA : Actions) {
1292     MA->emitCxxActionStmts(OS, *this, "I");
1293   }
1294 
1295   OS << "      return true;\n";
1296   OS << "    }\n";
1297   OS << "    return false;\n";
1298   OS << "  }()) { return true; }\n\n";
1299 }
1300 
1301 bool RuleMatcher::isHigherPriorityThan(const RuleMatcher &B) const {
1302   // Rules involving more match roots have higher priority.
1303   if (Matchers.size() > B.Matchers.size())
1304     return true;
1305   if (Matchers.size() < B.Matchers.size())
1306     return false;
1307 
1308   for (const auto &Matcher : zip(Matchers, B.Matchers)) {
1309     if (std::get<0>(Matcher)->isHigherPriorityThan(*std::get<1>(Matcher)))
1310       return true;
1311     if (std::get<1>(Matcher)->isHigherPriorityThan(*std::get<0>(Matcher)))
1312       return false;
1313   }
1314 
1315   return false;
1316 }
1317 
1318 unsigned RuleMatcher::countRendererFns() const {
1319   return std::accumulate(
1320       Matchers.begin(), Matchers.end(), 0,
1321       [](unsigned A, const std::unique_ptr<InstructionMatcher> &Matcher) {
1322         return A + Matcher->countRendererFns();
1323       });
1324 }
1325 
1326 //===- GlobalISelEmitter class --------------------------------------------===//
1327 
1328 class GlobalISelEmitter {
1329 public:
1330   explicit GlobalISelEmitter(RecordKeeper &RK);
1331   void run(raw_ostream &OS);
1332 
1333 private:
1334   const RecordKeeper &RK;
1335   const CodeGenDAGPatterns CGP;
1336   const CodeGenTarget &Target;
1337   CodeGenRegBank CGRegs;
1338 
1339   /// Keep track of the equivalence between SDNodes and Instruction.
1340   /// This is defined using 'GINodeEquiv' in the target description.
1341   DenseMap<Record *, const CodeGenInstruction *> NodeEquivs;
1342 
1343   /// Keep track of the equivalence between ComplexPattern's and
1344   /// GIComplexOperandMatcher. Map entries are specified by subclassing
1345   /// GIComplexPatternEquiv.
1346   DenseMap<const Record *, const Record *> ComplexPatternEquivs;
1347 
1348   // Map of predicates to their subtarget features.
1349   SubtargetFeatureInfoMap SubtargetFeatures;
1350 
1351   void gatherNodeEquivs();
1352   const CodeGenInstruction *findNodeEquiv(Record *N) const;
1353 
1354   Error importRulePredicates(RuleMatcher &M, ArrayRef<Init *> Predicates);
1355   Expected<InstructionMatcher &>
1356   createAndImportSelDAGMatcher(InstructionMatcher &InsnMatcher,
1357                                const TreePatternNode *Src) const;
1358   Error importChildMatcher(InstructionMatcher &InsnMatcher,
1359                            const TreePatternNode *SrcChild, unsigned OpIdx,
1360                            unsigned &TempOpIdx) const;
1361   Expected<BuildMIAction &>
1362   createAndImportInstructionRenderer(RuleMatcher &M, const TreePatternNode *Dst,
1363                                      const InstructionMatcher &InsnMatcher);
1364   Error importExplicitUseRenderer(BuildMIAction &DstMIBuilder,
1365                                   TreePatternNode *DstChild,
1366                                   const InstructionMatcher &InsnMatcher) const;
1367   Error importDefaultOperandRenderers(BuildMIAction &DstMIBuilder,
1368                                       DagInit *DefaultOps) const;
1369   Error
1370   importImplicitDefRenderers(BuildMIAction &DstMIBuilder,
1371                              const std::vector<Record *> &ImplicitDefs) const;
1372 
1373   /// Analyze pattern \p P, returning a matcher for it if possible.
1374   /// Otherwise, return an Error explaining why we don't support it.
1375   Expected<RuleMatcher> runOnPattern(const PatternToMatch &P);
1376 
1377   void declareSubtargetFeature(Record *Predicate);
1378 };
1379 
1380 void GlobalISelEmitter::gatherNodeEquivs() {
1381   assert(NodeEquivs.empty());
1382   for (Record *Equiv : RK.getAllDerivedDefinitions("GINodeEquiv"))
1383     NodeEquivs[Equiv->getValueAsDef("Node")] =
1384         &Target.getInstruction(Equiv->getValueAsDef("I"));
1385 
1386   assert(ComplexPatternEquivs.empty());
1387   for (Record *Equiv : RK.getAllDerivedDefinitions("GIComplexPatternEquiv")) {
1388     Record *SelDAGEquiv = Equiv->getValueAsDef("SelDAGEquivalent");
1389     if (!SelDAGEquiv)
1390       continue;
1391     ComplexPatternEquivs[SelDAGEquiv] = Equiv;
1392  }
1393 }
1394 
1395 const CodeGenInstruction *GlobalISelEmitter::findNodeEquiv(Record *N) const {
1396   return NodeEquivs.lookup(N);
1397 }
1398 
1399 GlobalISelEmitter::GlobalISelEmitter(RecordKeeper &RK)
1400     : RK(RK), CGP(RK), Target(CGP.getTargetInfo()), CGRegs(RK) {}
1401 
1402 //===- Emitter ------------------------------------------------------------===//
1403 
1404 Error
1405 GlobalISelEmitter::importRulePredicates(RuleMatcher &M,
1406                                         ArrayRef<Init *> Predicates) {
1407   for (const Init *Predicate : Predicates) {
1408     const DefInit *PredicateDef = static_cast<const DefInit *>(Predicate);
1409     declareSubtargetFeature(PredicateDef->getDef());
1410     M.addRequiredFeature(PredicateDef->getDef());
1411   }
1412 
1413   return Error::success();
1414 }
1415 
1416 Expected<InstructionMatcher &> GlobalISelEmitter::createAndImportSelDAGMatcher(
1417     InstructionMatcher &InsnMatcher, const TreePatternNode *Src) const {
1418   // Start with the defined operands (i.e., the results of the root operator).
1419   if (Src->getExtTypes().size() > 1)
1420     return failedImport("Src pattern has multiple results");
1421 
1422   if (Src->isLeaf()) {
1423     Init *SrcInit = Src->getLeafValue();
1424     if (isa<IntInit>(SrcInit)) {
1425       InsnMatcher.addPredicate<InstructionOpcodeMatcher>(
1426           &Target.getInstruction(RK.getDef("G_CONSTANT")));
1427     } else
1428       return failedImport("Unable to deduce gMIR opcode to handle Src (which is a leaf)");
1429   } else {
1430     auto SrcGIOrNull = findNodeEquiv(Src->getOperator());
1431     if (!SrcGIOrNull)
1432       return failedImport("Pattern operator lacks an equivalent Instruction" +
1433                           explainOperator(Src->getOperator()));
1434     auto &SrcGI = *SrcGIOrNull;
1435 
1436     // The operators look good: match the opcode
1437     InsnMatcher.addPredicate<InstructionOpcodeMatcher>(&SrcGI);
1438   }
1439 
1440   unsigned OpIdx = 0;
1441   unsigned TempOpIdx = 0;
1442   for (const EEVT::TypeSet &Ty : Src->getExtTypes()) {
1443     auto OpTyOrNone = MVTToLLT(Ty.getConcrete());
1444 
1445     if (!OpTyOrNone)
1446       return failedImport(
1447           "Result of Src pattern operator has an unsupported type");
1448 
1449     // Results don't have a name unless they are the root node. The caller will
1450     // set the name if appropriate.
1451     OperandMatcher &OM = InsnMatcher.addOperand(OpIdx++, "", TempOpIdx);
1452     OM.addPredicate<LLTOperandMatcher>(*OpTyOrNone);
1453   }
1454 
1455   if (Src->isLeaf()) {
1456     Init *SrcInit = Src->getLeafValue();
1457     if (IntInit *SrcIntInit = dyn_cast<IntInit>(SrcInit)) {
1458       OperandMatcher &OM = InsnMatcher.addOperand(OpIdx++, "", TempOpIdx);
1459       OM.addPredicate<LiteralIntOperandMatcher>(SrcIntInit->getValue());
1460     } else
1461       return failedImport("Unable to deduce gMIR opcode to handle Src (which is a leaf)");
1462   } else {
1463     // Match the used operands (i.e. the children of the operator).
1464     for (unsigned i = 0, e = Src->getNumChildren(); i != e; ++i) {
1465       if (auto Error = importChildMatcher(InsnMatcher, Src->getChild(i),
1466                                           OpIdx++, TempOpIdx))
1467         return std::move(Error);
1468     }
1469   }
1470 
1471   return InsnMatcher;
1472 }
1473 
1474 Error GlobalISelEmitter::importChildMatcher(InstructionMatcher &InsnMatcher,
1475                                             const TreePatternNode *SrcChild,
1476                                             unsigned OpIdx,
1477                                             unsigned &TempOpIdx) const {
1478   OperandMatcher &OM =
1479       InsnMatcher.addOperand(OpIdx, SrcChild->getName(), TempOpIdx);
1480 
1481   if (SrcChild->hasAnyPredicate())
1482     return failedImport("Src pattern child has predicate (" +
1483                         explainPredicates(SrcChild) + ")");
1484 
1485   ArrayRef<EEVT::TypeSet> ChildTypes = SrcChild->getExtTypes();
1486   if (ChildTypes.size() != 1)
1487     return failedImport("Src pattern child has multiple results");
1488 
1489   // Check MBB's before the type check since they are not a known type.
1490   if (!SrcChild->isLeaf()) {
1491     if (SrcChild->getOperator()->isSubClassOf("SDNode")) {
1492       auto &ChildSDNI = CGP.getSDNodeInfo(SrcChild->getOperator());
1493       if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") {
1494         OM.addPredicate<MBBOperandMatcher>();
1495         return Error::success();
1496       }
1497     }
1498   }
1499 
1500   auto OpTyOrNone = MVTToLLT(ChildTypes.front().getConcrete());
1501   if (!OpTyOrNone)
1502     return failedImport("Src operand has an unsupported type");
1503   OM.addPredicate<LLTOperandMatcher>(*OpTyOrNone);
1504 
1505   // Check for nested instructions.
1506   if (!SrcChild->isLeaf()) {
1507     // Map the node to a gMIR instruction.
1508     InstructionOperandMatcher &InsnOperand =
1509         OM.addPredicate<InstructionOperandMatcher>();
1510     auto InsnMatcherOrError =
1511         createAndImportSelDAGMatcher(InsnOperand.getInsnMatcher(), SrcChild);
1512     if (auto Error = InsnMatcherOrError.takeError())
1513       return Error;
1514 
1515     return Error::success();
1516   }
1517 
1518   // Check for constant immediates.
1519   if (auto *ChildInt = dyn_cast<IntInit>(SrcChild->getLeafValue())) {
1520     OM.addPredicate<ConstantIntOperandMatcher>(ChildInt->getValue());
1521     return Error::success();
1522   }
1523 
1524   // Check for def's like register classes or ComplexPattern's.
1525   if (auto *ChildDefInit = dyn_cast<DefInit>(SrcChild->getLeafValue())) {
1526     auto *ChildRec = ChildDefInit->getDef();
1527 
1528     // Check for register classes.
1529     if (ChildRec->isSubClassOf("RegisterClass") ||
1530         ChildRec->isSubClassOf("RegisterOperand")) {
1531       OM.addPredicate<RegisterBankOperandMatcher>(
1532           Target.getRegisterClass(getInitValueAsRegClass(ChildDefInit)));
1533       return Error::success();
1534     }
1535 
1536     // Check for ComplexPattern's.
1537     if (ChildRec->isSubClassOf("ComplexPattern")) {
1538       const auto &ComplexPattern = ComplexPatternEquivs.find(ChildRec);
1539       if (ComplexPattern == ComplexPatternEquivs.end())
1540         return failedImport("SelectionDAG ComplexPattern (" +
1541                             ChildRec->getName() + ") not mapped to GlobalISel");
1542 
1543       OM.addPredicate<ComplexPatternOperandMatcher>(OM,
1544                                                     *ComplexPattern->second);
1545       TempOpIdx++;
1546       return Error::success();
1547     }
1548 
1549     if (ChildRec->isSubClassOf("ImmLeaf")) {
1550       return failedImport(
1551           "Src pattern child def is an unsupported tablegen class (ImmLeaf)");
1552     }
1553 
1554     return failedImport(
1555         "Src pattern child def is an unsupported tablegen class");
1556   }
1557 
1558   return failedImport("Src pattern child is an unsupported kind");
1559 }
1560 
1561 Error GlobalISelEmitter::importExplicitUseRenderer(
1562     BuildMIAction &DstMIBuilder, TreePatternNode *DstChild,
1563     const InstructionMatcher &InsnMatcher) const {
1564   // The only non-leaf child we accept is 'bb': it's an operator because
1565   // BasicBlockSDNode isn't inline, but in MI it's just another operand.
1566   if (!DstChild->isLeaf()) {
1567     if (DstChild->getOperator()->isSubClassOf("SDNode")) {
1568       auto &ChildSDNI = CGP.getSDNodeInfo(DstChild->getOperator());
1569       if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") {
1570         DstMIBuilder.addRenderer<CopyRenderer>(InsnMatcher,
1571                                                DstChild->getName());
1572         return Error::success();
1573       }
1574     }
1575     return failedImport("Dst pattern child isn't a leaf node or an MBB");
1576   }
1577 
1578   // Otherwise, we're looking for a bog-standard RegisterClass operand.
1579   if (DstChild->hasAnyPredicate())
1580     return failedImport("Dst pattern child has predicate (" +
1581                         explainPredicates(DstChild) + ")");
1582 
1583   if (auto *ChildDefInit = dyn_cast<DefInit>(DstChild->getLeafValue())) {
1584     auto *ChildRec = ChildDefInit->getDef();
1585 
1586     ArrayRef<EEVT::TypeSet> ChildTypes = DstChild->getExtTypes();
1587     if (ChildTypes.size() != 1)
1588       return failedImport("Dst pattern child has multiple results");
1589 
1590     auto OpTyOrNone = MVTToLLT(ChildTypes.front().getConcrete());
1591     if (!OpTyOrNone)
1592       return failedImport("Dst operand has an unsupported type");
1593 
1594     if (ChildRec->isSubClassOf("Register")) {
1595       DstMIBuilder.addRenderer<AddRegisterRenderer>(ChildRec);
1596       return Error::success();
1597     }
1598 
1599     if (ChildRec->isSubClassOf("RegisterClass") ||
1600         ChildRec->isSubClassOf("RegisterOperand")) {
1601       DstMIBuilder.addRenderer<CopyRenderer>(InsnMatcher, DstChild->getName());
1602       return Error::success();
1603     }
1604 
1605     if (ChildRec->isSubClassOf("ComplexPattern")) {
1606       const auto &ComplexPattern = ComplexPatternEquivs.find(ChildRec);
1607       if (ComplexPattern == ComplexPatternEquivs.end())
1608         return failedImport(
1609             "SelectionDAG ComplexPattern not mapped to GlobalISel");
1610 
1611       const OperandMatcher &OM = InsnMatcher.getOperand(DstChild->getName());
1612       DstMIBuilder.addRenderer<RenderComplexPatternOperand>(
1613           *ComplexPattern->second, DstChild->getName(),
1614           OM.getAllocatedTemporariesBaseID());
1615       return Error::success();
1616     }
1617 
1618     if (ChildRec->isSubClassOf("SDNodeXForm"))
1619       return failedImport("Dst pattern child def is an unsupported tablegen "
1620                           "class (SDNodeXForm)");
1621 
1622     return failedImport(
1623         "Dst pattern child def is an unsupported tablegen class");
1624   }
1625 
1626   return failedImport("Dst pattern child is an unsupported kind");
1627 }
1628 
1629 Expected<BuildMIAction &> GlobalISelEmitter::createAndImportInstructionRenderer(
1630     RuleMatcher &M, const TreePatternNode *Dst,
1631     const InstructionMatcher &InsnMatcher) {
1632   Record *DstOp = Dst->getOperator();
1633   if (!DstOp->isSubClassOf("Instruction")) {
1634     if (DstOp->isSubClassOf("ValueType"))
1635       return failedImport(
1636           "Pattern operator isn't an instruction (it's a ValueType)");
1637     return failedImport("Pattern operator isn't an instruction");
1638   }
1639   CodeGenInstruction *DstI = &Target.getInstruction(DstOp);
1640 
1641   unsigned DstINumUses = DstI->Operands.size() - DstI->Operands.NumDefs;
1642   unsigned ExpectedDstINumUses = Dst->getNumChildren();
1643   bool IsExtractSubReg = false;
1644 
1645   // COPY_TO_REGCLASS is just a copy with a ConstrainOperandToRegClassAction
1646   // attached. Similarly for EXTRACT_SUBREG except that's a subregister copy.
1647   if (DstI->TheDef->getName() == "COPY_TO_REGCLASS") {
1648     DstI = &Target.getInstruction(RK.getDef("COPY"));
1649     DstINumUses--; // Ignore the class constraint.
1650     ExpectedDstINumUses--;
1651   } else if (DstI->TheDef->getName() == "EXTRACT_SUBREG") {
1652     DstI = &Target.getInstruction(RK.getDef("COPY"));
1653     IsExtractSubReg = true;
1654   }
1655 
1656   auto &DstMIBuilder = M.addAction<BuildMIAction>("NewI", DstI, InsnMatcher);
1657 
1658   // Render the explicit defs.
1659   for (unsigned I = 0; I < DstI->Operands.NumDefs; ++I) {
1660     const CGIOperandList::OperandInfo &DstIOperand = DstI->Operands[I];
1661     DstMIBuilder.addRenderer<CopyRenderer>(InsnMatcher, DstIOperand.Name);
1662   }
1663 
1664   // EXTRACT_SUBREG needs to use a subregister COPY.
1665   if (IsExtractSubReg) {
1666     if (!Dst->getChild(0)->isLeaf())
1667       return failedImport("EXTRACT_SUBREG child #1 is not a leaf");
1668 
1669     if (DefInit *SubRegInit = dyn_cast<DefInit>(Dst->getChild(1)->getLeafValue())) {
1670       CodeGenRegisterClass *RC = CGRegs.getRegClass(
1671           getInitValueAsRegClass(Dst->getChild(0)->getLeafValue()));
1672       CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef());
1673 
1674       const auto &SrcRCDstRCPair =
1675           RC->getMatchingSubClassWithSubRegs(CGRegs, SubIdx);
1676       if (SrcRCDstRCPair.hasValue()) {
1677         assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
1678         if (SrcRCDstRCPair->first != RC)
1679           return failedImport("EXTRACT_SUBREG requires an additional COPY");
1680       }
1681 
1682       DstMIBuilder.addRenderer<CopySubRegRenderer>(
1683           InsnMatcher, Dst->getChild(0)->getName(), SubIdx);
1684       return DstMIBuilder;
1685     }
1686 
1687     return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
1688   }
1689 
1690   // Render the explicit uses.
1691   unsigned Child = 0;
1692   unsigned NumDefaultOps = 0;
1693   for (unsigned I = 0; I != DstINumUses; ++I) {
1694     const CGIOperandList::OperandInfo &DstIOperand =
1695         DstI->Operands[DstI->Operands.NumDefs + I];
1696 
1697     // If the operand has default values, introduce them now.
1698     // FIXME: Until we have a decent test case that dictates we should do
1699     // otherwise, we're going to assume that operands with default values cannot
1700     // be specified in the patterns. Therefore, adding them will not cause us to
1701     // end up with too many rendered operands.
1702     if (DstIOperand.Rec->isSubClassOf("OperandWithDefaultOps")) {
1703       DagInit *DefaultOps = DstIOperand.Rec->getValueAsDag("DefaultOps");
1704       if (auto Error = importDefaultOperandRenderers(DstMIBuilder, DefaultOps))
1705         return std::move(Error);
1706       ++NumDefaultOps;
1707       continue;
1708     }
1709 
1710     if (auto Error = importExplicitUseRenderer(
1711             DstMIBuilder, Dst->getChild(Child), InsnMatcher))
1712       return std::move(Error);
1713     ++Child;
1714   }
1715 
1716   if (NumDefaultOps + ExpectedDstINumUses != DstINumUses)
1717     return failedImport("Expected " + llvm::to_string(DstINumUses) +
1718                         " used operands but found " +
1719                         llvm::to_string(ExpectedDstINumUses) +
1720                         " explicit ones and " + llvm::to_string(NumDefaultOps) +
1721                         " default ones");
1722 
1723   return DstMIBuilder;
1724 }
1725 
1726 Error GlobalISelEmitter::importDefaultOperandRenderers(
1727     BuildMIAction &DstMIBuilder, DagInit *DefaultOps) const {
1728   for (const auto *DefaultOp : DefaultOps->getArgs()) {
1729     // Look through ValueType operators.
1730     if (const DagInit *DefaultDagOp = dyn_cast<DagInit>(DefaultOp)) {
1731       if (const DefInit *DefaultDagOperator =
1732               dyn_cast<DefInit>(DefaultDagOp->getOperator())) {
1733         if (DefaultDagOperator->getDef()->isSubClassOf("ValueType"))
1734           DefaultOp = DefaultDagOp->getArg(0);
1735       }
1736     }
1737 
1738     if (const DefInit *DefaultDefOp = dyn_cast<DefInit>(DefaultOp)) {
1739       DstMIBuilder.addRenderer<AddRegisterRenderer>(DefaultDefOp->getDef());
1740       continue;
1741     }
1742 
1743     if (const IntInit *DefaultIntOp = dyn_cast<IntInit>(DefaultOp)) {
1744       DstMIBuilder.addRenderer<ImmRenderer>(DefaultIntOp->getValue());
1745       continue;
1746     }
1747 
1748     return failedImport("Could not add default op");
1749   }
1750 
1751   return Error::success();
1752 }
1753 
1754 Error GlobalISelEmitter::importImplicitDefRenderers(
1755     BuildMIAction &DstMIBuilder,
1756     const std::vector<Record *> &ImplicitDefs) const {
1757   if (!ImplicitDefs.empty())
1758     return failedImport("Pattern defines a physical register");
1759   return Error::success();
1760 }
1761 
1762 Expected<RuleMatcher> GlobalISelEmitter::runOnPattern(const PatternToMatch &P) {
1763   // Keep track of the matchers and actions to emit.
1764   RuleMatcher M;
1765   M.addAction<DebugCommentAction>(P);
1766 
1767   if (auto Error = importRulePredicates(M, P.getPredicates()->getValues()))
1768     return std::move(Error);
1769 
1770   // Next, analyze the pattern operators.
1771   TreePatternNode *Src = P.getSrcPattern();
1772   TreePatternNode *Dst = P.getDstPattern();
1773 
1774   // If the root of either pattern isn't a simple operator, ignore it.
1775   if (auto Err = isTrivialOperatorNode(Dst))
1776     return failedImport("Dst pattern root isn't a trivial operator (" +
1777                         toString(std::move(Err)) + ")");
1778   if (auto Err = isTrivialOperatorNode(Src))
1779     return failedImport("Src pattern root isn't a trivial operator (" +
1780                         toString(std::move(Err)) + ")");
1781 
1782   if (Dst->isLeaf())
1783     return failedImport("Dst pattern root isn't a known leaf");
1784 
1785   // Start with the defined operands (i.e., the results of the root operator).
1786   Record *DstOp = Dst->getOperator();
1787   if (!DstOp->isSubClassOf("Instruction"))
1788     return failedImport("Pattern operator isn't an instruction");
1789 
1790   auto &DstI = Target.getInstruction(DstOp);
1791   if (DstI.Operands.NumDefs != Src->getExtTypes().size())
1792     return failedImport("Src pattern results and dst MI defs are different (" +
1793                         to_string(Src->getExtTypes().size()) + " def(s) vs " +
1794                         to_string(DstI.Operands.NumDefs) + " def(s))");
1795 
1796   InstructionMatcher &InsnMatcherTemp = M.addInstructionMatcher();
1797   auto InsnMatcherOrError = createAndImportSelDAGMatcher(InsnMatcherTemp, Src);
1798   if (auto Error = InsnMatcherOrError.takeError())
1799     return std::move(Error);
1800   InstructionMatcher &InsnMatcher = InsnMatcherOrError.get();
1801 
1802   // The root of the match also has constraints on the register bank so that it
1803   // matches the result instruction.
1804   unsigned OpIdx = 0;
1805   for (const EEVT::TypeSet &Ty : Src->getExtTypes()) {
1806     (void)Ty;
1807 
1808     const auto &DstIOperand = DstI.Operands[OpIdx];
1809     Record *DstIOpRec = DstIOperand.Rec;
1810     if (DstI.TheDef->getName() == "COPY_TO_REGCLASS") {
1811       DstIOpRec = getInitValueAsRegClass(Dst->getChild(1)->getLeafValue());
1812 
1813       if (DstIOpRec == nullptr)
1814         return failedImport(
1815             "COPY_TO_REGCLASS operand #1 isn't a register class");
1816     } else if (DstI.TheDef->getName() == "EXTRACT_SUBREG") {
1817       if (!Dst->getChild(0)->isLeaf())
1818         return failedImport("EXTRACT_SUBREG operand #0 isn't a leaf");
1819 
1820       // We can assume that a subregister is in the same bank as it's super register.
1821       DstIOpRec = getInitValueAsRegClass(Dst->getChild(0)->getLeafValue());
1822 
1823       if (DstIOpRec == nullptr)
1824         return failedImport(
1825             "EXTRACT_SUBREG operand #0 isn't a register class");
1826     } else if (DstIOpRec->isSubClassOf("RegisterOperand"))
1827       DstIOpRec = DstIOpRec->getValueAsDef("RegClass");
1828     else if (!DstIOpRec->isSubClassOf("RegisterClass"))
1829       return failedImport("Dst MI def isn't a register class" + to_string(*Dst));
1830 
1831     OperandMatcher &OM = InsnMatcher.getOperand(OpIdx);
1832     OM.setSymbolicName(DstIOperand.Name);
1833     OM.addPredicate<RegisterBankOperandMatcher>(
1834         Target.getRegisterClass(DstIOpRec));
1835     ++OpIdx;
1836   }
1837 
1838   auto DstMIBuilderOrError =
1839       createAndImportInstructionRenderer(M, Dst, InsnMatcher);
1840   if (auto Error = DstMIBuilderOrError.takeError())
1841     return std::move(Error);
1842   BuildMIAction &DstMIBuilder = DstMIBuilderOrError.get();
1843 
1844   // Render the implicit defs.
1845   // These are only added to the root of the result.
1846   if (auto Error = importImplicitDefRenderers(DstMIBuilder, P.getDstRegs()))
1847     return std::move(Error);
1848 
1849   // Constrain the registers to classes. This is normally derived from the
1850   // emitted instruction but a few instructions require special handling.
1851   if (DstI.TheDef->getName() == "COPY_TO_REGCLASS") {
1852     // COPY_TO_REGCLASS does not provide operand constraints itself but the
1853     // result is constrained to the class given by the second child.
1854     Record *DstIOpRec =
1855         getInitValueAsRegClass(Dst->getChild(1)->getLeafValue());
1856 
1857     if (DstIOpRec == nullptr)
1858       return failedImport("COPY_TO_REGCLASS operand #1 isn't a register class");
1859 
1860     M.addAction<ConstrainOperandToRegClassAction>(
1861         "NewI", 0, Target.getRegisterClass(DstIOpRec));
1862 
1863     // We're done with this pattern!  It's eligible for GISel emission; return
1864     // it.
1865     ++NumPatternImported;
1866     return std::move(M);
1867   }
1868 
1869   if (DstI.TheDef->getName() == "EXTRACT_SUBREG") {
1870     // EXTRACT_SUBREG selects into a subregister COPY but unlike most
1871     // instructions, the result register class is controlled by the
1872     // subregisters of the operand. As a result, we must constrain the result
1873     // class rather than check that it's already the right one.
1874     if (!Dst->getChild(0)->isLeaf())
1875       return failedImport("EXTRACT_SUBREG child #1 is not a leaf");
1876 
1877     if (DefInit *SubRegInit =
1878             dyn_cast<DefInit>(Dst->getChild(1)->getLeafValue())) {
1879       // Constrain the result to the same register bank as the operand.
1880       Record *DstIOpRec =
1881           getInitValueAsRegClass(Dst->getChild(0)->getLeafValue());
1882 
1883       if (DstIOpRec == nullptr)
1884         return failedImport("EXTRACT_SUBREG operand #1 isn't a register class");
1885 
1886       CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef());
1887       CodeGenRegisterClass *SrcRC = CGRegs.getRegClass(
1888           getInitValueAsRegClass(Dst->getChild(0)->getLeafValue()));
1889 
1890       // It would be nice to leave this constraint implicit but we're required
1891       // to pick a register class so constrain the result to a register class
1892       // that can hold the correct MVT.
1893       //
1894       // FIXME: This may introduce an extra copy if the chosen class doesn't
1895       //        actually contain the subregisters.
1896       assert(Src->getExtTypes().size() == 1);
1897 
1898       const auto &SrcRCDstRCPair =
1899           SrcRC->getMatchingSubClassWithSubRegs(CGRegs, SubIdx);
1900       assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
1901       M.addAction<ConstrainOperandToRegClassAction>("NewI", 0, *SrcRCDstRCPair->second);
1902       M.addAction<ConstrainOperandToRegClassAction>("NewI", 1, *SrcRCDstRCPair->first);
1903 
1904       // We're done with this pattern!  It's eligible for GISel emission; return
1905       // it.
1906       ++NumPatternImported;
1907       return std::move(M);
1908     }
1909 
1910     return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
1911   }
1912 
1913   M.addAction<ConstrainOperandsToDefinitionAction>("NewI");
1914 
1915   // We're done with this pattern!  It's eligible for GISel emission; return it.
1916   ++NumPatternImported;
1917   return std::move(M);
1918 }
1919 
1920 void GlobalISelEmitter::run(raw_ostream &OS) {
1921   // Track the GINodeEquiv definitions.
1922   gatherNodeEquivs();
1923 
1924   emitSourceFileHeader(("Global Instruction Selector for the " +
1925                        Target.getName() + " target").str(), OS);
1926   std::vector<RuleMatcher> Rules;
1927   // Look through the SelectionDAG patterns we found, possibly emitting some.
1928   for (const PatternToMatch &Pat : CGP.ptms()) {
1929     ++NumPatternTotal;
1930     auto MatcherOrErr = runOnPattern(Pat);
1931 
1932     // The pattern analysis can fail, indicating an unsupported pattern.
1933     // Report that if we've been asked to do so.
1934     if (auto Err = MatcherOrErr.takeError()) {
1935       if (WarnOnSkippedPatterns) {
1936         PrintWarning(Pat.getSrcRecord()->getLoc(),
1937                      "Skipped pattern: " + toString(std::move(Err)));
1938       } else {
1939         consumeError(std::move(Err));
1940       }
1941       ++NumPatternImportsSkipped;
1942       continue;
1943     }
1944 
1945     Rules.push_back(std::move(MatcherOrErr.get()));
1946   }
1947 
1948   std::stable_sort(Rules.begin(), Rules.end(),
1949             [&](const RuleMatcher &A, const RuleMatcher &B) {
1950               if (A.isHigherPriorityThan(B)) {
1951                 assert(!B.isHigherPriorityThan(A) && "Cannot be more important "
1952                                                      "and less important at "
1953                                                      "the same time");
1954                 return true;
1955               }
1956               return false;
1957             });
1958 
1959   unsigned MaxTemporaries = 0;
1960   for (const auto &Rule : Rules)
1961     MaxTemporaries = std::max(MaxTemporaries, Rule.countRendererFns());
1962 
1963   OS << "#ifdef GET_GLOBALISEL_PREDICATE_BITSET\n"
1964      << "const unsigned MAX_SUBTARGET_PREDICATES = " << SubtargetFeatures.size()
1965      << ";\n"
1966      << "using PredicateBitset = "
1967         "llvm::PredicateBitsetImpl<MAX_SUBTARGET_PREDICATES>;\n"
1968      << "#endif // ifdef GET_GLOBALISEL_PREDICATE_BITSET\n\n";
1969 
1970   OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n";
1971   for (unsigned I = 0; I < MaxTemporaries; ++I)
1972     OS << "  mutable ComplexRendererFn Renderer" << I << ";\n";
1973   OS << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n\n";
1974 
1975   OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n";
1976   for (unsigned I = 0; I < MaxTemporaries; ++I)
1977     OS << ", Renderer" << I << "(nullptr)\n";
1978   OS << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n\n";
1979 
1980   OS << "#ifdef GET_GLOBALISEL_IMPL\n";
1981   SubtargetFeatureInfo::emitSubtargetFeatureBitEnumeration(SubtargetFeatures,
1982                                                            OS);
1983 
1984   // Separate subtarget features by how often they must be recomputed.
1985   SubtargetFeatureInfoMap ModuleFeatures;
1986   std::copy_if(SubtargetFeatures.begin(), SubtargetFeatures.end(),
1987                std::inserter(ModuleFeatures, ModuleFeatures.end()),
1988                [](const SubtargetFeatureInfoMap::value_type &X) {
1989                  return !X.second.mustRecomputePerFunction();
1990                });
1991   SubtargetFeatureInfoMap FunctionFeatures;
1992   std::copy_if(SubtargetFeatures.begin(), SubtargetFeatures.end(),
1993                std::inserter(FunctionFeatures, FunctionFeatures.end()),
1994                [](const SubtargetFeatureInfoMap::value_type &X) {
1995                  return X.second.mustRecomputePerFunction();
1996                });
1997 
1998   SubtargetFeatureInfo::emitComputeAvailableFeatures(
1999       Target.getName(), "InstructionSelector", "computeAvailableModuleFeatures",
2000       ModuleFeatures, OS);
2001   SubtargetFeatureInfo::emitComputeAvailableFeatures(
2002       Target.getName(), "InstructionSelector",
2003       "computeAvailableFunctionFeatures", FunctionFeatures, OS,
2004       "const MachineFunction *MF");
2005 
2006   OS << "bool " << Target.getName()
2007      << "InstructionSelector::selectImpl(MachineInstr &I) const {\n"
2008      << "  MachineFunction &MF = *I.getParent()->getParent();\n"
2009      << "  const MachineRegisterInfo &MRI = MF.getRegInfo();\n"
2010      << "  // FIXME: This should be computed on a per-function basis rather than per-insn.\n"
2011      << "  AvailableFunctionFeatures = computeAvailableFunctionFeatures(&STI, &MF);\n"
2012      << "  const PredicateBitset AvailableFeatures = getAvailableFeatures();\n";
2013 
2014   for (auto &Rule : Rules) {
2015     Rule.emit(OS, SubtargetFeatures);
2016     ++NumPatternEmitted;
2017   }
2018 
2019   OS << "  return false;\n"
2020      << "}\n"
2021      << "#endif // ifdef GET_GLOBALISEL_IMPL\n";
2022 
2023   OS << "#ifdef GET_GLOBALISEL_PREDICATES_DECL\n"
2024      << "PredicateBitset AvailableModuleFeatures;\n"
2025      << "mutable PredicateBitset AvailableFunctionFeatures;\n"
2026      << "PredicateBitset getAvailableFeatures() const {\n"
2027      << "  return AvailableModuleFeatures | AvailableFunctionFeatures;\n"
2028      << "}\n"
2029      << "PredicateBitset\n"
2030      << "computeAvailableModuleFeatures(const " << Target.getName()
2031      << "Subtarget *Subtarget) const;\n"
2032      << "PredicateBitset\n"
2033      << "computeAvailableFunctionFeatures(const " << Target.getName()
2034      << "Subtarget *Subtarget,\n"
2035      << "                                 const MachineFunction *MF) const;\n"
2036      << "#endif // ifdef GET_GLOBALISEL_PREDICATES_DECL\n";
2037 
2038   OS << "#ifdef GET_GLOBALISEL_PREDICATES_INIT\n"
2039      << "AvailableModuleFeatures(computeAvailableModuleFeatures(&STI)),\n"
2040      << "AvailableFunctionFeatures()\n"
2041      << "#endif // ifdef GET_GLOBALISEL_PREDICATES_INIT\n";
2042 }
2043 
2044 void GlobalISelEmitter::declareSubtargetFeature(Record *Predicate) {
2045   if (SubtargetFeatures.count(Predicate) == 0)
2046     SubtargetFeatures.emplace(
2047         Predicate, SubtargetFeatureInfo(Predicate, SubtargetFeatures.size()));
2048 }
2049 
2050 } // end anonymous namespace
2051 
2052 //===----------------------------------------------------------------------===//
2053 
2054 namespace llvm {
2055 void EmitGlobalISel(RecordKeeper &RK, raw_ostream &OS) {
2056   GlobalISelEmitter(RK).run(OS);
2057 }
2058 } // End llvm namespace
2059