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