1 //===- GlobalISelEmitter.cpp - Generate an instruction selector -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 /// \file
11 /// This tablegen backend emits code for use by the GlobalISel instruction
12 /// selector. See include/llvm/CodeGen/TargetGlobalISel.td.
13 ///
14 /// This file analyzes the patterns recognized by the SelectionDAGISel tablegen
15 /// backend, filters out the ones that are unsupported, maps
16 /// SelectionDAG-specific constructs to their GlobalISel counterpart
17 /// (when applicable: MVT to LLT;  SDNode to generic Instruction).
18 ///
19 /// Not all patterns are supported: pass the tablegen invocation
20 /// "-warn-on-skipped-patterns" to emit a warning when a pattern is skipped,
21 /// as well as why.
22 ///
23 /// The generated file defines a single method:
24 ///     bool <Target>InstructionSelector::selectImpl(MachineInstr &I) const;
25 /// intended to be used in InstructionSelector::select as the first-step
26 /// selector for the patterns that don't require complex C++.
27 ///
28 /// FIXME: We'll probably want to eventually define a base
29 /// "TargetGenInstructionSelector" class.
30 ///
31 //===----------------------------------------------------------------------===//
32 
33 #include "CodeGenDAGPatterns.h"
34 #include "llvm/ADT/Optional.h"
35 #include "llvm/ADT/Statistic.h"
36 #include "llvm/CodeGen/MachineValueType.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/Error.h"
39 #include "llvm/TableGen/Error.h"
40 #include "llvm/TableGen/Record.h"
41 #include "llvm/TableGen/TableGenBackend.h"
42 #include <string>
43 using namespace llvm;
44 
45 #define DEBUG_TYPE "gisel-emitter"
46 
47 STATISTIC(NumPatternTotal, "Total number of patterns");
48 STATISTIC(NumPatternSkipped, "Number of patterns skipped");
49 STATISTIC(NumPatternEmitted, "Number of patterns emitted");
50 
51 static cl::opt<bool> WarnOnSkippedPatterns(
52     "warn-on-skipped-patterns",
53     cl::desc("Explain why a pattern was skipped for inclusion "
54              "in the GlobalISel selector"),
55     cl::init(false));
56 
57 namespace {
58 class RuleMatcher;
59 
60 //===- Helper functions ---------------------------------------------------===//
61 
62 /// Convert an MVT to an equivalent LLT if possible, or the invalid LLT() for
63 /// MVTs that don't map cleanly to an LLT (e.g., iPTR, *any, ...).
64 static Optional<std::string> MVTToLLT(MVT::SimpleValueType SVT) {
65   std::string TyStr;
66   raw_string_ostream OS(TyStr);
67   MVT VT(SVT);
68   if (VT.isVector() && VT.getVectorNumElements() != 1) {
69     OS << "LLT::vector(" << VT.getVectorNumElements() << ", "
70        << VT.getScalarSizeInBits() << ")";
71   } else if (VT.isInteger() || VT.isFloatingPoint()) {
72     OS << "LLT::scalar(" << VT.getSizeInBits() << ")";
73   } else {
74     return None;
75   }
76   OS.flush();
77   return TyStr;
78 }
79 
80 static bool isTrivialOperatorNode(const TreePatternNode *N) {
81   return !N->isLeaf() && !N->hasAnyPredicate() && !N->getTransformFn();
82 }
83 
84 //===- Matchers -----------------------------------------------------------===//
85 
86 template <class PredicateTy> class PredicateListMatcher {
87 private:
88   typedef std::vector<std::unique_ptr<PredicateTy>> PredicateVec;
89   PredicateVec Predicates;
90 
91 public:
92   /// Construct a new operand predicate and add it to the matcher.
93   template <class Kind, class... Args>
94   Kind &addPredicate(Args&&... args) {
95     Predicates.emplace_back(
96         llvm::make_unique<Kind>(std::forward<Args>(args)...));
97     return *static_cast<Kind *>(Predicates.back().get());
98   }
99 
100   typename PredicateVec::const_iterator predicates_begin() const { return Predicates.begin(); }
101   typename PredicateVec::const_iterator predicates_end() const { return Predicates.end(); }
102   iterator_range<typename PredicateVec::const_iterator> predicates() const {
103     return make_range(predicates_begin(), predicates_end());
104   }
105 
106   /// Emit a C++ expression that tests whether all the predicates are met.
107   template <class... Args>
108   void emitCxxPredicateListExpr(raw_ostream &OS, Args &&... args) const {
109     if (Predicates.empty()) {
110       OS << "true";
111       return;
112     }
113 
114     StringRef Separator = "";
115     for (const auto &Predicate : predicates()) {
116       OS << Separator << "(";
117       Predicate->emitCxxPredicateExpr(OS, std::forward<Args>(args)...);
118       OS << ")";
119       Separator = " &&\n";
120     }
121   }
122 };
123 
124 /// Generates code to check a predicate of an operand.
125 ///
126 /// Typical predicates include:
127 /// * Operand is a particular register.
128 /// * Operand is assigned a particular register bank.
129 /// * Operand is an MBB.
130 class OperandPredicateMatcher {
131 public:
132   virtual ~OperandPredicateMatcher() {}
133 
134   /// Emit a C++ expression that checks the predicate for the OpIdx operand of
135   /// the instruction given in InsnVarName.
136   virtual void emitCxxPredicateExpr(raw_ostream &OS, StringRef InsnVarName,
137                                     unsigned OpIdx) const = 0;
138 };
139 
140 /// Generates code to check that an operand is a particular LLT.
141 class LLTOperandMatcher : public OperandPredicateMatcher {
142 protected:
143   std::string Ty;
144 
145 public:
146   LLTOperandMatcher(std::string Ty) : Ty(Ty) {}
147 
148   void emitCxxPredicateExpr(raw_ostream &OS, StringRef InsnVarName,
149                             unsigned OpIdx) const override {
150     OS << "MRI.getType(" << InsnVarName << ".getOperand(" << OpIdx
151        << ").getReg()) == (" << Ty << ")";
152   }
153 };
154 
155 /// Generates code to check that an operand is in a particular register bank.
156 class RegisterBankOperandMatcher : public OperandPredicateMatcher {
157 protected:
158   const CodeGenRegisterClass &RC;
159 
160 public:
161   RegisterBankOperandMatcher(const CodeGenRegisterClass &RC) : RC(RC) {}
162 
163   void emitCxxPredicateExpr(raw_ostream &OS, StringRef InsnVarName,
164                             unsigned OpIdx) const override {
165     OS << "(&RBI.getRegBankFromRegClass(" << RC.getQualifiedName()
166        << "RegClass) == RBI.getRegBank(" << InsnVarName << ".getOperand("
167        << OpIdx << ").getReg(), MRI, TRI))";
168   }
169 };
170 
171 /// Generates code to check that an operand is a basic block.
172 class MBBOperandMatcher : public OperandPredicateMatcher {
173 public:
174   void emitCxxPredicateExpr(raw_ostream &OS, StringRef InsnVarName,
175                             unsigned OpIdx) const override {
176     OS << InsnVarName << ".getOperand(" << OpIdx << ").isMBB()";
177   }
178 };
179 
180 /// Generates code to check that a set of predicates match for a particular
181 /// operand.
182 class OperandMatcher : public PredicateListMatcher<OperandPredicateMatcher> {
183 protected:
184   unsigned OpIdx;
185 
186 public:
187   OperandMatcher(unsigned OpIdx) : OpIdx(OpIdx) {}
188 
189   /// Emit a C++ expression that tests whether the instruction named in
190   /// InsnVarName matches all the predicate and all the operands.
191   void emitCxxPredicateExpr(raw_ostream &OS, StringRef InsnVarName) const {
192     OS << "(";
193     emitCxxPredicateListExpr(OS, InsnVarName, OpIdx);
194     OS << ")";
195   }
196 };
197 
198 /// Generates code to check a predicate on an instruction.
199 ///
200 /// Typical predicates include:
201 /// * The opcode of the instruction is a particular value.
202 /// * The nsw/nuw flag is/isn't set.
203 class InstructionPredicateMatcher {
204 public:
205   virtual ~InstructionPredicateMatcher() {}
206 
207   /// Emit a C++ expression that tests whether the instruction named in
208   /// InsnVarName matches the predicate.
209   virtual void emitCxxPredicateExpr(raw_ostream &OS,
210                                     StringRef InsnVarName) const = 0;
211 };
212 
213 /// Generates code to check the opcode of an instruction.
214 class InstructionOpcodeMatcher : public InstructionPredicateMatcher {
215 protected:
216   const CodeGenInstruction *I;
217 
218 public:
219   InstructionOpcodeMatcher(const CodeGenInstruction *I) : I(I) {}
220 
221   void emitCxxPredicateExpr(raw_ostream &OS,
222                             StringRef InsnVarName) const override {
223     OS << InsnVarName << ".getOpcode() == " << I->Namespace
224        << "::" << I->TheDef->getName();
225   }
226 };
227 
228 /// Generates code to check that a set of predicates and operands match for a
229 /// particular instruction.
230 ///
231 /// Typical predicates include:
232 /// * Has a specific opcode.
233 /// * Has an nsw/nuw flag or doesn't.
234 class InstructionMatcher
235     : public PredicateListMatcher<InstructionPredicateMatcher> {
236 protected:
237   std::vector<OperandMatcher> Operands;
238 
239 public:
240   /// Add an operand to the matcher.
241   OperandMatcher &addOperand(unsigned OpIdx) {
242     Operands.emplace_back(OpIdx);
243     return Operands.back();
244   }
245 
246   /// Emit a C++ expression that tests whether the instruction named in
247   /// InsnVarName matches all the predicates and all the operands.
248   void emitCxxPredicateExpr(raw_ostream &OS, StringRef InsnVarName) const {
249     emitCxxPredicateListExpr(OS, InsnVarName);
250     for (const auto &Operand : Operands) {
251       OS << " &&\n(";
252       Operand.emitCxxPredicateExpr(OS, InsnVarName);
253       OS << ")";
254     }
255   }
256 };
257 
258 //===- Actions ------------------------------------------------------------===//
259 
260 /// An action taken when all Matcher predicates succeeded for a parent rule.
261 ///
262 /// Typical actions include:
263 /// * Changing the opcode of an instruction.
264 /// * Adding an operand to an instruction.
265 class MatchAction {
266 public:
267   virtual ~MatchAction() {}
268   virtual void emitCxxActionStmts(raw_ostream &OS) const = 0;
269 };
270 
271 /// Generates a comment describing the matched rule being acted upon.
272 class DebugCommentAction : public MatchAction {
273 private:
274   const PatternToMatch &P;
275 
276 public:
277   DebugCommentAction(const PatternToMatch &P) : P(P) {}
278 
279   virtual void emitCxxActionStmts(raw_ostream &OS) const {
280     OS << "// " << *P.getSrcPattern() << "  =>  " << *P.getDstPattern();
281   }
282 };
283 
284 /// Generates code to set the opcode (really, the MCInstrDesc) of a matched
285 /// instruction to a given Instruction.
286 class MutateOpcodeAction : public MatchAction {
287 private:
288   const CodeGenInstruction *I;
289 
290 public:
291   MutateOpcodeAction(const CodeGenInstruction *I) : I(I) {}
292 
293   virtual void emitCxxActionStmts(raw_ostream &OS) const {
294     OS << "I.setDesc(TII.get(" << I->Namespace << "::" << I->TheDef->getName()
295        << "));";
296   }
297 };
298 
299 /// Generates code to check that a match rule matches.
300 class RuleMatcher {
301   /// A list of matchers that all need to succeed for the current rule to match.
302   /// FIXME: This currently supports a single match position but could be
303   /// extended to support multiple positions to support div/rem fusion or
304   /// load-multiple instructions.
305   std::vector<std::unique_ptr<InstructionMatcher>> Matchers;
306 
307   /// A list of actions that need to be taken when all predicates in this rule
308   /// have succeeded.
309   std::vector<std::unique_ptr<MatchAction>> Actions;
310 
311 public:
312   RuleMatcher() {}
313 
314   InstructionMatcher &addInstructionMatcher() {
315     Matchers.emplace_back(new InstructionMatcher());
316     return *Matchers.back();
317   }
318 
319   template <class Kind, class... Args>
320   Kind &addAction(Args&&... args) {
321     Actions.emplace_back(llvm::make_unique<Kind>(std::forward<Args>(args)...));
322     return *static_cast<Kind *>(Actions.back().get());
323   }
324 
325   void emit(raw_ostream &OS) {
326     if (Matchers.empty())
327       llvm_unreachable("Unexpected empty matcher!");
328 
329     // The representation supports rules that require multiple roots such as:
330     //    %ptr(p0) = ...
331     //    %elt0(s32) = G_LOAD %ptr
332     //    %1(p0) = G_ADD %ptr, 4
333     //    %elt1(s32) = G_LOAD p0 %1
334     // which could be usefully folded into:
335     //    %ptr(p0) = ...
336     //    %elt0(s32), %elt1(s32) = TGT_LOAD_PAIR %ptr
337     // on some targets but we don't need to make use of that yet.
338     assert(Matchers.size() == 1 && "Cannot handle multi-root matchers yet");
339     OS << "  if (";
340     Matchers.front()->emitCxxPredicateExpr(OS, "I");
341     OS << ") {\n";
342 
343     for (const auto &MA : Actions) {
344       OS << "    ";
345       MA->emitCxxActionStmts(OS);
346       OS << "\n";
347     }
348 
349     OS << "    constrainSelectedInstRegOperands(I, TII, TRI, RBI);\n";
350     OS << "    return true;\n";
351     OS << "  }\n\n";
352   }
353 };
354 
355 //===- GlobalISelEmitter class --------------------------------------------===//
356 
357 class GlobalISelEmitter {
358 public:
359   explicit GlobalISelEmitter(RecordKeeper &RK);
360   void run(raw_ostream &OS);
361 
362 private:
363   const RecordKeeper &RK;
364   const CodeGenDAGPatterns CGP;
365   const CodeGenTarget &Target;
366 
367   /// Keep track of the equivalence between SDNodes and Instruction.
368   /// This is defined using 'GINodeEquiv' in the target description.
369   DenseMap<Record *, const CodeGenInstruction *> NodeEquivs;
370 
371   void gatherNodeEquivs();
372   const CodeGenInstruction *findNodeEquiv(Record *N);
373 
374   /// Analyze pattern \p P, returning a matcher for it if possible.
375   /// Otherwise, return an Error explaining why we don't support it.
376   Expected<RuleMatcher> runOnPattern(const PatternToMatch &P);
377 };
378 
379 void GlobalISelEmitter::gatherNodeEquivs() {
380   assert(NodeEquivs.empty());
381   for (Record *Equiv : RK.getAllDerivedDefinitions("GINodeEquiv"))
382     NodeEquivs[Equiv->getValueAsDef("Node")] =
383         &Target.getInstruction(Equiv->getValueAsDef("I"));
384 }
385 
386 const CodeGenInstruction *GlobalISelEmitter::findNodeEquiv(Record *N) {
387   return NodeEquivs.lookup(N);
388 }
389 
390 GlobalISelEmitter::GlobalISelEmitter(RecordKeeper &RK)
391     : RK(RK), CGP(RK), Target(CGP.getTargetInfo()) {}
392 
393 //===- Emitter ------------------------------------------------------------===//
394 
395 /// Helper function to let the emitter report skip reason error messages.
396 static Error failedImport(const Twine &Reason) {
397   return make_error<StringError>(Reason, inconvertibleErrorCode());
398 }
399 
400 Expected<RuleMatcher> GlobalISelEmitter::runOnPattern(const PatternToMatch &P) {
401   // Keep track of the matchers and actions to emit.
402   RuleMatcher M;
403   M.addAction<DebugCommentAction>(P);
404 
405   // First, analyze the whole pattern.
406   // If the entire pattern has a predicate (e.g., target features), ignore it.
407   if (!P.getPredicates()->getValues().empty())
408     return failedImport("Pattern has a predicate");
409 
410   // Physreg imp-defs require additional logic.  Ignore the pattern.
411   if (!P.getDstRegs().empty())
412     return failedImport("Pattern defines a physical register");
413 
414   // Next, analyze the pattern operators.
415   TreePatternNode *Src = P.getSrcPattern();
416   TreePatternNode *Dst = P.getDstPattern();
417 
418   // If the root of either pattern isn't a simple operator, ignore it.
419   if (!isTrivialOperatorNode(Dst))
420     return failedImport("Dst pattern root isn't a trivial operator");
421   if (!isTrivialOperatorNode(Src))
422     return failedImport("Src pattern root isn't a trivial operator");
423 
424   Record *DstOp = Dst->getOperator();
425   if (!DstOp->isSubClassOf("Instruction"))
426     return failedImport("Pattern operator isn't an instruction");
427 
428   auto &DstI = Target.getInstruction(DstOp);
429 
430   auto SrcGIOrNull = findNodeEquiv(Src->getOperator());
431   if (!SrcGIOrNull)
432     return failedImport("Pattern operator lacks an equivalent Instruction");
433   auto &SrcGI = *SrcGIOrNull;
434 
435   // The operators look good: match the opcode and mutate it to the new one.
436   InstructionMatcher &InsnMatcher = M.addInstructionMatcher();
437   InsnMatcher.addPredicate<InstructionOpcodeMatcher>(&SrcGI);
438   M.addAction<MutateOpcodeAction>(&DstI);
439 
440   // Next, analyze the children, only accepting patterns that don't require
441   // any change to operands.
442   if (Src->getNumChildren() != Dst->getNumChildren())
443     return failedImport("Src/dst patterns have a different # of children");
444 
445   unsigned OpIdx = 0;
446 
447   // Start with the defined operands (i.e., the results of the root operator).
448   if (DstI.Operands.NumDefs != Src->getExtTypes().size())
449     return failedImport("Src pattern results and dst MI defs are different");
450 
451   for (const EEVT::TypeSet &Ty : Src->getExtTypes()) {
452     Record *DstIOpRec = DstI.Operands[OpIdx].Rec;
453     if (!DstIOpRec->isSubClassOf("RegisterClass"))
454       return failedImport("Dst MI def isn't a register class");
455 
456     auto OpTyOrNone = MVTToLLT(Ty.getConcrete());
457     if (!OpTyOrNone)
458       return failedImport("Dst operand has an unsupported type");
459 
460     OperandMatcher &OM = InsnMatcher.addOperand(OpIdx);
461     OM.addPredicate<LLTOperandMatcher>(*OpTyOrNone);
462     OM.addPredicate<RegisterBankOperandMatcher>(
463         Target.getRegisterClass(DstIOpRec));
464     ++OpIdx;
465   }
466 
467   // Finally match the used operands (i.e., the children of the root operator).
468   for (unsigned i = 0, e = Src->getNumChildren(); i != e; ++i) {
469     auto *SrcChild = Src->getChild(i);
470     auto *DstChild = Dst->getChild(i);
471 
472     // Patterns can reorder operands.  Ignore those for now.
473     if (SrcChild->getName() != DstChild->getName())
474       return failedImport("Src/dst pattern children not in same order");
475 
476     // The only non-leaf child we accept is 'bb': it's an operator because
477     // BasicBlockSDNode isn't inline, but in MI it's just another operand.
478     if (!SrcChild->isLeaf()) {
479       if (DstChild->isLeaf() ||
480           SrcChild->getOperator() != DstChild->getOperator())
481         return failedImport("Src/dst pattern child operator mismatch");
482 
483       if (SrcChild->getOperator()->isSubClassOf("SDNode")) {
484         auto &ChildSDNI = CGP.getSDNodeInfo(SrcChild->getOperator());
485         if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") {
486           InsnMatcher.addOperand(OpIdx++).addPredicate<MBBOperandMatcher>();
487           continue;
488         }
489       }
490       return failedImport("Src pattern child isn't a leaf node");
491     }
492 
493     if (SrcChild->getLeafValue() != DstChild->getLeafValue())
494       return failedImport("Src/dst pattern child leaf mismatch");
495 
496     // Otherwise, we're looking for a bog-standard RegisterClass operand.
497     if (SrcChild->hasAnyPredicate())
498       return failedImport("Src pattern child has predicate");
499     auto *ChildRec = cast<DefInit>(SrcChild->getLeafValue())->getDef();
500     if (!ChildRec->isSubClassOf("RegisterClass"))
501       return failedImport("Src pattern child isn't a RegisterClass");
502 
503     ArrayRef<EEVT::TypeSet> ChildTypes = SrcChild->getExtTypes();
504     if (ChildTypes.size() != 1)
505       return failedImport("Src pattern child has multiple results");
506 
507     auto OpTyOrNone = MVTToLLT(ChildTypes.front().getConcrete());
508     if (!OpTyOrNone)
509       return failedImport("Src operand has an unsupported type");
510 
511     OperandMatcher &OM = InsnMatcher.addOperand(OpIdx);
512     OM.addPredicate<LLTOperandMatcher>(*OpTyOrNone);
513     OM.addPredicate<RegisterBankOperandMatcher>(
514         Target.getRegisterClass(ChildRec));
515     ++OpIdx;
516   }
517 
518   // We're done with this pattern!  It's eligible for GISel emission; return it.
519   return std::move(M);
520 }
521 
522 void GlobalISelEmitter::run(raw_ostream &OS) {
523   // Track the GINodeEquiv definitions.
524   gatherNodeEquivs();
525 
526   emitSourceFileHeader(("Global Instruction Selector for the " +
527                        Target.getName() + " target").str(), OS);
528   OS << "bool " << Target.getName()
529      << "InstructionSelector::selectImpl"
530         "(MachineInstr &I) const {\n  const MachineRegisterInfo &MRI = "
531         "I.getParent()->getParent()->getRegInfo();\n\n";
532 
533   // Look through the SelectionDAG patterns we found, possibly emitting some.
534   for (const PatternToMatch &Pat : CGP.ptms()) {
535     ++NumPatternTotal;
536     auto MatcherOrErr = runOnPattern(Pat);
537 
538     // The pattern analysis can fail, indicating an unsupported pattern.
539     // Report that if we've been asked to do so.
540     if (auto Err = MatcherOrErr.takeError()) {
541       if (WarnOnSkippedPatterns) {
542         PrintWarning(Pat.getSrcRecord()->getLoc(),
543                      "Skipped pattern: " + toString(std::move(Err)));
544       } else {
545         consumeError(std::move(Err));
546       }
547       ++NumPatternSkipped;
548       continue;
549     }
550 
551     MatcherOrErr->emit(OS);
552     ++NumPatternEmitted;
553   }
554 
555   OS << "  return false;\n}\n";
556 }
557 
558 } // end anonymous namespace
559 
560 //===----------------------------------------------------------------------===//
561 
562 namespace llvm {
563 void EmitGlobalISel(RecordKeeper &RK, raw_ostream &OS) {
564   GlobalISelEmitter(RK).run(OS);
565 }
566 } // End llvm namespace
567