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