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