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