1 //===- DAGISelEmitter.cpp - Generate an instruction selector --------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This tablegen backend emits a DAG instruction selector.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "CodeGenDAGPatterns.h"
14 #include "DAGISelMatcher.h"
15 #include "llvm/Support/Debug.h"
16 #include "llvm/TableGen/Record.h"
17 #include "llvm/TableGen/TableGenBackend.h"
18 using namespace llvm;
19 
20 #define DEBUG_TYPE "dag-isel-emitter"
21 
22 namespace {
23 /// DAGISelEmitter - The top-level class which coordinates construction
24 /// and emission of the instruction selector.
25 class DAGISelEmitter {
26   RecordKeeper &Records; // Just so we can get at the timing functions.
27   CodeGenDAGPatterns CGP;
28 public:
DAGISelEmitter(RecordKeeper & R)29   explicit DAGISelEmitter(RecordKeeper &R) : Records(R), CGP(R) {}
30   void run(raw_ostream &OS);
31 };
32 } // End anonymous namespace
33 
34 //===----------------------------------------------------------------------===//
35 // DAGISelEmitter Helper methods
36 //
37 
38 /// getResultPatternCost - Compute the number of instructions for this pattern.
39 /// This is a temporary hack.  We should really include the instruction
40 /// latencies in this calculation.
getResultPatternCost(TreePatternNode * P,CodeGenDAGPatterns & CGP)41 static unsigned getResultPatternCost(TreePatternNode *P,
42                                      CodeGenDAGPatterns &CGP) {
43   if (P->isLeaf()) return 0;
44 
45   unsigned Cost = 0;
46   Record *Op = P->getOperator();
47   if (Op->isSubClassOf("Instruction")) {
48     Cost++;
49     CodeGenInstruction &II = CGP.getTargetInfo().getInstruction(Op);
50     if (II.usesCustomInserter)
51       Cost += 10;
52   }
53   for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
54     Cost += getResultPatternCost(P->getChild(i), CGP);
55   return Cost;
56 }
57 
58 /// getResultPatternCodeSize - Compute the code size of instructions for this
59 /// pattern.
getResultPatternSize(TreePatternNode * P,CodeGenDAGPatterns & CGP)60 static unsigned getResultPatternSize(TreePatternNode *P,
61                                      CodeGenDAGPatterns &CGP) {
62   if (P->isLeaf()) return 0;
63 
64   unsigned Cost = 0;
65   Record *Op = P->getOperator();
66   if (Op->isSubClassOf("Instruction")) {
67     Cost += Op->getValueAsInt("CodeSize");
68   }
69   for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
70     Cost += getResultPatternSize(P->getChild(i), CGP);
71   return Cost;
72 }
73 
74 namespace {
75 // PatternSortingPredicate - return true if we prefer to match LHS before RHS.
76 // In particular, we want to match maximal patterns first and lowest cost within
77 // a particular complexity first.
78 struct PatternSortingPredicate {
PatternSortingPredicate__anonb72c32e80211::PatternSortingPredicate79   PatternSortingPredicate(CodeGenDAGPatterns &cgp) : CGP(cgp) {}
80   CodeGenDAGPatterns &CGP;
81 
operator ()__anonb72c32e80211::PatternSortingPredicate82   bool operator()(const PatternToMatch *LHS, const PatternToMatch *RHS) {
83     const TreePatternNode *LT = LHS->getSrcPattern();
84     const TreePatternNode *RT = RHS->getSrcPattern();
85 
86     MVT LHSVT = LT->getNumTypes() != 0 ? LT->getSimpleType(0) : MVT::Other;
87     MVT RHSVT = RT->getNumTypes() != 0 ? RT->getSimpleType(0) : MVT::Other;
88     if (LHSVT.isVector() != RHSVT.isVector())
89       return RHSVT.isVector();
90 
91     if (LHSVT.isFloatingPoint() != RHSVT.isFloatingPoint())
92       return RHSVT.isFloatingPoint();
93 
94     // Otherwise, if the patterns might both match, sort based on complexity,
95     // which means that we prefer to match patterns that cover more nodes in the
96     // input over nodes that cover fewer.
97     int LHSSize = LHS->getPatternComplexity(CGP);
98     int RHSSize = RHS->getPatternComplexity(CGP);
99     if (LHSSize > RHSSize) return true;   // LHS -> bigger -> less cost
100     if (LHSSize < RHSSize) return false;
101 
102     // If the patterns have equal complexity, compare generated instruction cost
103     unsigned LHSCost = getResultPatternCost(LHS->getDstPattern(), CGP);
104     unsigned RHSCost = getResultPatternCost(RHS->getDstPattern(), CGP);
105     if (LHSCost < RHSCost) return true;
106     if (LHSCost > RHSCost) return false;
107 
108     unsigned LHSPatSize = getResultPatternSize(LHS->getDstPattern(), CGP);
109     unsigned RHSPatSize = getResultPatternSize(RHS->getDstPattern(), CGP);
110     if (LHSPatSize < RHSPatSize) return true;
111     if (LHSPatSize > RHSPatSize) return false;
112 
113     // Sort based on the UID of the pattern, to reflect source order.
114     // Note that this is not guaranteed to be unique, since a single source
115     // pattern may have been resolved into multiple match patterns due to
116     // alternative fragments.  To ensure deterministic output, always use
117     // std::stable_sort with this predicate.
118     return LHS->getID() < RHS->getID();
119   }
120 };
121 } // End anonymous namespace
122 
123 
run(raw_ostream & OS)124 void DAGISelEmitter::run(raw_ostream &OS) {
125   emitSourceFileHeader("DAG Instruction Selector for the " +
126                        CGP.getTargetInfo().getName().str() + " target", OS);
127 
128   OS << "// *** NOTE: This file is #included into the middle of the target\n"
129      << "// *** instruction selector class.  These functions are really "
130      << "methods.\n\n";
131 
132   OS << "// If GET_DAGISEL_DECL is #defined with any value, only function\n"
133         "// declarations will be included when this file is included.\n"
134         "// If GET_DAGISEL_BODY is #defined, its value should be the name of\n"
135         "// the instruction selector class. Function bodies will be emitted\n"
136         "// and each function's name will be qualified with the name of the\n"
137         "// class.\n"
138         "//\n"
139         "// When neither of the GET_DAGISEL* macros is defined, the functions\n"
140         "// are emitted inline.\n\n";
141 
142   LLVM_DEBUG(errs() << "\n\nALL PATTERNS TO MATCH:\n\n";
143              for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(),
144                   E = CGP.ptm_end();
145                   I != E; ++I) {
146                errs() << "PATTERN: ";
147                I->getSrcPattern()->dump();
148                errs() << "\nRESULT:  ";
149                I->getDstPattern()->dump();
150                errs() << "\n";
151              });
152 
153   // Add all the patterns to a temporary list so we can sort them.
154   Records.startTimer("Sort patterns");
155   std::vector<const PatternToMatch*> Patterns;
156   for (const PatternToMatch &PTM : CGP.ptms())
157     Patterns.push_back(&PTM);
158 
159   // We want to process the matches in order of minimal cost.  Sort the patterns
160   // so the least cost one is at the start.
161   llvm::stable_sort(Patterns, PatternSortingPredicate(CGP));
162 
163   // Convert each variant of each pattern into a Matcher.
164   Records.startTimer("Convert to matchers");
165   std::vector<Matcher*> PatternMatchers;
166   for (const PatternToMatch *PTM : Patterns) {
167     for (unsigned Variant = 0; ; ++Variant) {
168       if (Matcher *M = ConvertPatternToMatcher(*PTM, Variant, CGP))
169         PatternMatchers.push_back(M);
170       else
171         break;
172     }
173   }
174 
175   std::unique_ptr<Matcher> TheMatcher =
176     std::make_unique<ScopeMatcher>(PatternMatchers);
177 
178   Records.startTimer("Optimize matchers");
179   OptimizeMatcher(TheMatcher, CGP);
180 
181   //Matcher->dump();
182 
183   Records.startTimer("Emit matcher table");
184   EmitMatcherTable(TheMatcher.get(), CGP, OS);
185 }
186 
187 namespace llvm {
188 
EmitDAGISel(RecordKeeper & RK,raw_ostream & OS)189 void EmitDAGISel(RecordKeeper &RK, raw_ostream &OS) {
190   RK.startTimer("Parse patterns");
191   DAGISelEmitter(RK).run(OS);
192 }
193 
194 } // End llvm namespace
195