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