blob: 3df189bcf6e5dcf938e891055403c5fdc564d592 [file] [log] [blame]
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001//===- 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"
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +000038#include "llvm/Support/Error.h"
Daniel Sanders52b4ce72017-03-07 23:20:35 +000039#include "llvm/Support/LowLevelTypeImpl.h"
Pavel Labath52a82e22017-02-21 09:19:41 +000040#include "llvm/Support/ScopedPrinter.h"
Ahmed Bougacha36f70352016-12-21 23:26:20 +000041#include "llvm/TableGen/Error.h"
42#include "llvm/TableGen/Record.h"
43#include "llvm/TableGen/TableGenBackend.h"
44#include <string>
45using namespace llvm;
46
47#define DEBUG_TYPE "gisel-emitter"
48
49STATISTIC(NumPatternTotal, "Total number of patterns");
Daniel Sandersb41ce2b2017-02-20 14:31:27 +000050STATISTIC(NumPatternImported, "Number of patterns imported from SelectionDAG");
51STATISTIC(NumPatternImportsSkipped, "Number of SelectionDAG imports skipped");
Ahmed Bougacha36f70352016-12-21 23:26:20 +000052STATISTIC(NumPatternEmitted, "Number of patterns emitted");
53
54static cl::opt<bool> WarnOnSkippedPatterns(
55 "warn-on-skipped-patterns",
56 cl::desc("Explain why a pattern was skipped for inclusion "
57 "in the GlobalISel selector"),
58 cl::init(false));
59
Ahmed Bougacha36f70352016-12-21 23:26:20 +000060//===- Helper functions ---------------------------------------------------===//
61
Daniel Sanders52b4ce72017-03-07 23:20:35 +000062/// This class stands in for LLT wherever we want to tablegen-erate an
63/// equivalent at compiler run-time.
64class LLTCodeGen {
65private:
66 LLT Ty;
67
68public:
69 LLTCodeGen(const LLT &Ty) : Ty(Ty) {}
70
71 void emitCxxConstructorCall(raw_ostream &OS) const {
72 if (Ty.isScalar()) {
73 OS << "LLT::scalar(" << Ty.getSizeInBits() << ")";
74 return;
75 }
76 if (Ty.isVector()) {
77 OS << "LLT::vector(" << Ty.getNumElements() << ", " << Ty.getSizeInBits()
78 << ")";
79 return;
80 }
81 llvm_unreachable("Unhandled LLT");
82 }
83};
84
Ahmed Bougacha36f70352016-12-21 23:26:20 +000085/// Convert an MVT to an equivalent LLT if possible, or the invalid LLT() for
86/// MVTs that don't map cleanly to an LLT (e.g., iPTR, *any, ...).
Daniel Sanders52b4ce72017-03-07 23:20:35 +000087static Optional<LLTCodeGen> MVTToLLT(MVT::SimpleValueType SVT) {
Ahmed Bougacha36f70352016-12-21 23:26:20 +000088 MVT VT(SVT);
Daniel Sanders52b4ce72017-03-07 23:20:35 +000089 if (VT.isVector() && VT.getVectorNumElements() != 1)
90 return LLTCodeGen(LLT::vector(VT.getVectorNumElements(), VT.getScalarSizeInBits()));
91 if (VT.isInteger() || VT.isFloatingPoint())
92 return LLTCodeGen(LLT::scalar(VT.getSizeInBits()));
93 return None;
Ahmed Bougacha36f70352016-12-21 23:26:20 +000094}
95
96static bool isTrivialOperatorNode(const TreePatternNode *N) {
97 return !N->isLeaf() && !N->hasAnyPredicate() && !N->getTransformFn();
98}
99
100//===- Matchers -----------------------------------------------------------===//
101
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000102template <class PredicateTy> class PredicateListMatcher {
103private:
104 typedef std::vector<std::unique_ptr<PredicateTy>> PredicateVec;
105 PredicateVec Predicates;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000106
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000107public:
108 /// Construct a new operand predicate and add it to the matcher.
109 template <class Kind, class... Args>
110 Kind &addPredicate(Args&&... args) {
Ahmed Bougachab67a3ce2017-01-26 22:07:37 +0000111 Predicates.emplace_back(
112 llvm::make_unique<Kind>(std::forward<Args>(args)...));
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000113 return *static_cast<Kind *>(Predicates.back().get());
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000114 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000115
116 typename PredicateVec::const_iterator predicates_begin() const { return Predicates.begin(); }
117 typename PredicateVec::const_iterator predicates_end() const { return Predicates.end(); }
118 iterator_range<typename PredicateVec::const_iterator> predicates() const {
119 return make_range(predicates_begin(), predicates_end());
120 }
Daniel Sanders759ff412017-02-24 13:58:11 +0000121 typename PredicateVec::size_type predicates_size() const { return Predicates.size(); }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000122
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000123 /// Emit a C++ expression that tests whether all the predicates are met.
Ahmed Bougachab67a3ce2017-01-26 22:07:37 +0000124 template <class... Args>
Daniel Sandersf8c804f2017-01-28 11:10:42 +0000125 void emitCxxPredicateListExpr(raw_ostream &OS, Args &&... args) const {
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000126 if (Predicates.empty()) {
127 OS << "true";
128 return;
129 }
130
131 StringRef Separator = "";
132 for (const auto &Predicate : predicates()) {
133 OS << Separator << "(";
Ahmed Bougachab67a3ce2017-01-26 22:07:37 +0000134 Predicate->emitCxxPredicateExpr(OS, std::forward<Args>(args)...);
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000135 OS << ")";
Ahmed Bougacha905af9f2017-02-04 00:47:02 +0000136 Separator = " &&\n";
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000137 }
138 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000139};
140
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000141/// Generates code to check a predicate of an operand.
142///
143/// Typical predicates include:
144/// * Operand is a particular register.
145/// * Operand is assigned a particular register bank.
146/// * Operand is an MBB.
147class OperandPredicateMatcher {
148public:
Daniel Sanders759ff412017-02-24 13:58:11 +0000149 /// This enum is used for RTTI and also defines the priority that is given to
150 /// the predicate when generating the matcher code. Kinds with higher priority
151 /// must be tested first.
152 ///
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000153 /// The relative priority of OPM_LLT, OPM_RegBank, and OPM_MBB do not matter
154 /// but OPM_Int must have priority over OPM_RegBank since constant integers
155 /// are represented by a virtual register defined by a G_CONSTANT instruction.
Daniel Sanders759ff412017-02-24 13:58:11 +0000156 enum PredicateKind {
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000157 OPM_Int,
Daniel Sanders759ff412017-02-24 13:58:11 +0000158 OPM_LLT,
159 OPM_RegBank,
160 OPM_MBB,
161 };
162
163protected:
164 PredicateKind Kind;
165
166public:
167 OperandPredicateMatcher(PredicateKind Kind) : Kind(Kind) {}
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000168 virtual ~OperandPredicateMatcher() {}
169
Daniel Sanders759ff412017-02-24 13:58:11 +0000170 PredicateKind getKind() const { return Kind; }
171
Daniel Sanderse604ef52017-02-20 15:30:43 +0000172 /// Emit a C++ expression that checks the predicate for the given operand.
173 virtual void emitCxxPredicateExpr(raw_ostream &OS,
174 StringRef OperandExpr) const = 0;
Daniel Sanders759ff412017-02-24 13:58:11 +0000175
176 /// Compare the priority of this object and B.
177 ///
178 /// Returns true if this object is more important than B.
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000179 virtual bool isHigherPriorityThan(const OperandPredicateMatcher &B) const {
180 return Kind < B.Kind;
Daniel Sanders759ff412017-02-24 13:58:11 +0000181 };
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000182};
183
184/// Generates code to check that an operand is a particular LLT.
185class LLTOperandMatcher : public OperandPredicateMatcher {
186protected:
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000187 LLTCodeGen Ty;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000188
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000189public:
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000190 LLTOperandMatcher(const LLTCodeGen &Ty)
Daniel Sanders759ff412017-02-24 13:58:11 +0000191 : OperandPredicateMatcher(OPM_LLT), Ty(Ty) {}
192
193 static bool classof(const OperandPredicateMatcher *P) {
194 return P->getKind() == OPM_LLT;
195 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000196
Daniel Sanderse604ef52017-02-20 15:30:43 +0000197 void emitCxxPredicateExpr(raw_ostream &OS,
198 StringRef OperandExpr) const override {
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000199 OS << "MRI.getType(" << OperandExpr << ".getReg()) == (";
200 Ty.emitCxxConstructorCall(OS);
201 OS << ")";
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000202 }
203};
204
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000205/// Generates code to check that an operand is in a particular register bank.
206class RegisterBankOperandMatcher : public OperandPredicateMatcher {
207protected:
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000208 const CodeGenRegisterClass &RC;
209
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000210public:
Daniel Sanders759ff412017-02-24 13:58:11 +0000211 RegisterBankOperandMatcher(const CodeGenRegisterClass &RC)
212 : OperandPredicateMatcher(OPM_RegBank), RC(RC) {}
213
214 static bool classof(const OperandPredicateMatcher *P) {
215 return P->getKind() == OPM_RegBank;
216 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000217
Daniel Sanderse604ef52017-02-20 15:30:43 +0000218 void emitCxxPredicateExpr(raw_ostream &OS,
219 StringRef OperandExpr) const override {
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000220 OS << "(&RBI.getRegBankFromRegClass(" << RC.getQualifiedName()
Daniel Sanderse604ef52017-02-20 15:30:43 +0000221 << "RegClass) == RBI.getRegBank(" << OperandExpr
222 << ".getReg(), MRI, TRI))";
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000223 }
224};
225
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000226/// Generates code to check that an operand is a basic block.
227class MBBOperandMatcher : public OperandPredicateMatcher {
228public:
Daniel Sanders759ff412017-02-24 13:58:11 +0000229 MBBOperandMatcher() : OperandPredicateMatcher(OPM_MBB) {}
230
231 static bool classof(const OperandPredicateMatcher *P) {
232 return P->getKind() == OPM_MBB;
233 }
234
Daniel Sanderse604ef52017-02-20 15:30:43 +0000235 void emitCxxPredicateExpr(raw_ostream &OS,
236 StringRef OperandExpr) const override {
237 OS << OperandExpr << ".isMBB()";
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000238 }
239};
240
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000241/// Generates code to check that an operand is a particular int.
242class IntOperandMatcher : public OperandPredicateMatcher {
243protected:
244 int64_t Value;
245
246public:
247 IntOperandMatcher(int64_t Value)
248 : OperandPredicateMatcher(OPM_Int), Value(Value) {}
249
250 static bool classof(const OperandPredicateMatcher *P) {
251 return P->getKind() == OPM_Int;
252 }
253
254 void emitCxxPredicateExpr(raw_ostream &OS,
Simon Pilgrimd0302912017-02-24 17:20:27 +0000255 StringRef OperandExpr) const override {
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000256 OS << "isOperandImmEqual(" << OperandExpr << ", " << Value << ", MRI)";
257 }
258};
259
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000260/// Generates code to check that a set of predicates match for a particular
261/// operand.
262class OperandMatcher : public PredicateListMatcher<OperandPredicateMatcher> {
263protected:
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000264 unsigned OpIdx;
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000265 std::string SymbolicName;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000266
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000267public:
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000268 OperandMatcher(unsigned OpIdx, const std::string &SymbolicName)
269 : OpIdx(OpIdx), SymbolicName(SymbolicName) {}
270
271 bool hasSymbolicName() const { return !SymbolicName.empty(); }
272 const StringRef getSymbolicName() const { return SymbolicName; }
273 unsigned getOperandIndex() const { return OpIdx; }
274
275 std::string getOperandExpr(const StringRef InsnVarName) const {
Pavel Labath52a82e22017-02-21 09:19:41 +0000276 return (InsnVarName + ".getOperand(" + llvm::to_string(OpIdx) + ")").str();
Daniel Sanderse604ef52017-02-20 15:30:43 +0000277 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000278
279 /// Emit a C++ expression that tests whether the instruction named in
280 /// InsnVarName matches all the predicate and all the operands.
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000281 void emitCxxPredicateExpr(raw_ostream &OS, const StringRef InsnVarName) const {
282 OS << "(/* ";
283 if (SymbolicName.empty())
284 OS << "Operand " << OpIdx;
285 else
286 OS << SymbolicName;
287 OS << " */ ";
Daniel Sanderse604ef52017-02-20 15:30:43 +0000288 emitCxxPredicateListExpr(OS, getOperandExpr(InsnVarName));
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000289 OS << ")";
290 }
Daniel Sanders759ff412017-02-24 13:58:11 +0000291
292 /// Compare the priority of this object and B.
293 ///
294 /// Returns true if this object is more important than B.
295 bool isHigherPriorityThan(const OperandMatcher &B) const {
296 // Operand matchers involving more predicates have higher priority.
297 if (predicates_size() > B.predicates_size())
298 return true;
299 if (predicates_size() < B.predicates_size())
300 return false;
301
302 // This assumes that predicates are added in a consistent order.
303 for (const auto &Predicate : zip(predicates(), B.predicates())) {
304 if (std::get<0>(Predicate)->isHigherPriorityThan(*std::get<1>(Predicate)))
305 return true;
306 if (std::get<1>(Predicate)->isHigherPriorityThan(*std::get<0>(Predicate)))
307 return false;
308 }
309
310 return false;
311 };
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000312};
313
314/// Generates code to check a predicate on an instruction.
315///
316/// Typical predicates include:
317/// * The opcode of the instruction is a particular value.
318/// * The nsw/nuw flag is/isn't set.
319class InstructionPredicateMatcher {
Daniel Sanders759ff412017-02-24 13:58:11 +0000320protected:
321 /// This enum is used for RTTI and also defines the priority that is given to
322 /// the predicate when generating the matcher code. Kinds with higher priority
323 /// must be tested first.
324 enum PredicateKind {
325 IPM_Opcode,
326 };
327
328 PredicateKind Kind;
329
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000330public:
Daniel Sanders8d4d72f2017-02-24 14:53:35 +0000331 InstructionPredicateMatcher(PredicateKind Kind) : Kind(Kind) {}
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000332 virtual ~InstructionPredicateMatcher() {}
333
Daniel Sanders759ff412017-02-24 13:58:11 +0000334 PredicateKind getKind() const { return Kind; }
335
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000336 /// Emit a C++ expression that tests whether the instruction named in
337 /// InsnVarName matches the predicate.
338 virtual void emitCxxPredicateExpr(raw_ostream &OS,
Ahmed Bougacha6a1ac5a2017-02-09 02:50:01 +0000339 StringRef InsnVarName) const = 0;
Daniel Sanders759ff412017-02-24 13:58:11 +0000340
341 /// Compare the priority of this object and B.
342 ///
343 /// Returns true if this object is more important than B.
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000344 virtual bool isHigherPriorityThan(const InstructionPredicateMatcher &B) const {
Daniel Sanders759ff412017-02-24 13:58:11 +0000345 return Kind < B.Kind;
346 };
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000347};
348
349/// Generates code to check the opcode of an instruction.
350class InstructionOpcodeMatcher : public InstructionPredicateMatcher {
351protected:
352 const CodeGenInstruction *I;
353
354public:
Daniel Sanders8d4d72f2017-02-24 14:53:35 +0000355 InstructionOpcodeMatcher(const CodeGenInstruction *I)
356 : InstructionPredicateMatcher(IPM_Opcode), I(I) {}
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000357
Daniel Sanders759ff412017-02-24 13:58:11 +0000358 static bool classof(const InstructionPredicateMatcher *P) {
359 return P->getKind() == IPM_Opcode;
360 }
361
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000362 void emitCxxPredicateExpr(raw_ostream &OS,
Ahmed Bougacha6a1ac5a2017-02-09 02:50:01 +0000363 StringRef InsnVarName) const override {
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000364 OS << InsnVarName << ".getOpcode() == " << I->Namespace
365 << "::" << I->TheDef->getName();
366 }
Daniel Sanders759ff412017-02-24 13:58:11 +0000367
368 /// Compare the priority of this object and B.
369 ///
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000370 /// Returns true if this object is more important than B.
371 bool isHigherPriorityThan(const InstructionPredicateMatcher &B) const override {
Daniel Sanders759ff412017-02-24 13:58:11 +0000372 if (InstructionPredicateMatcher::isHigherPriorityThan(B))
373 return true;
374 if (B.InstructionPredicateMatcher::isHigherPriorityThan(*this))
375 return false;
376
377 // Prioritize opcodes for cosmetic reasons in the generated source. Although
378 // this is cosmetic at the moment, we may want to drive a similar ordering
379 // using instruction frequency information to improve compile time.
380 if (const InstructionOpcodeMatcher *BO =
381 dyn_cast<InstructionOpcodeMatcher>(&B))
382 return I->TheDef->getName() < BO->I->TheDef->getName();
383
384 return false;
385 };
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000386};
387
388/// Generates code to check that a set of predicates and operands match for a
389/// particular instruction.
390///
391/// Typical predicates include:
392/// * Has a specific opcode.
393/// * Has an nsw/nuw flag or doesn't.
394class InstructionMatcher
395 : public PredicateListMatcher<InstructionPredicateMatcher> {
396protected:
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000397 typedef std::vector<OperandMatcher> OperandVec;
398
399 /// The operands to match. All rendered operands must be present even if the
400 /// condition is always true.
401 OperandVec Operands;
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000402
403public:
404 /// Add an operand to the matcher.
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000405 OperandMatcher &addOperand(unsigned OpIdx, const std::string &SymbolicName) {
406 Operands.emplace_back(OpIdx, SymbolicName);
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000407 return Operands.back();
408 }
409
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000410 const OperandMatcher &getOperand(const StringRef SymbolicName) const {
411 assert(!SymbolicName.empty() && "Cannot lookup unnamed operand");
412 const auto &I = std::find_if(Operands.begin(), Operands.end(),
413 [&SymbolicName](const OperandMatcher &X) {
414 return X.getSymbolicName() == SymbolicName;
415 });
416 if (I != Operands.end())
417 return *I;
418 llvm_unreachable("Failed to lookup operand");
419 }
420
421 unsigned getNumOperands() const { return Operands.size(); }
422 OperandVec::const_iterator operands_begin() const {
423 return Operands.begin();
424 }
425 OperandVec::const_iterator operands_end() const {
426 return Operands.end();
427 }
428 iterator_range<OperandVec::const_iterator> operands() const {
429 return make_range(operands_begin(), operands_end());
430 }
431
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000432 /// Emit a C++ expression that tests whether the instruction named in
433 /// InsnVarName matches all the predicates and all the operands.
Ahmed Bougacha6a1ac5a2017-02-09 02:50:01 +0000434 void emitCxxPredicateExpr(raw_ostream &OS, StringRef InsnVarName) const {
Daniel Sandersf8c804f2017-01-28 11:10:42 +0000435 emitCxxPredicateListExpr(OS, InsnVarName);
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000436 for (const auto &Operand : Operands) {
Ahmed Bougacha905af9f2017-02-04 00:47:02 +0000437 OS << " &&\n(";
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000438 Operand.emitCxxPredicateExpr(OS, InsnVarName);
439 OS << ")";
440 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000441 }
Daniel Sanders759ff412017-02-24 13:58:11 +0000442
443 /// Compare the priority of this object and B.
444 ///
445 /// Returns true if this object is more important than B.
446 bool isHigherPriorityThan(const InstructionMatcher &B) const {
447 // Instruction matchers involving more operands have higher priority.
448 if (Operands.size() > B.Operands.size())
449 return true;
450 if (Operands.size() < B.Operands.size())
451 return false;
452
453 for (const auto &Predicate : zip(predicates(), B.predicates())) {
454 if (std::get<0>(Predicate)->isHigherPriorityThan(*std::get<1>(Predicate)))
455 return true;
456 if (std::get<1>(Predicate)->isHigherPriorityThan(*std::get<0>(Predicate)))
457 return false;
458 }
459
460 for (const auto &Operand : zip(Operands, B.Operands)) {
461 if (std::get<0>(Operand).isHigherPriorityThan(std::get<1>(Operand)))
462 return true;
463 if (std::get<1>(Operand).isHigherPriorityThan(std::get<0>(Operand)))
464 return false;
465 }
466
467 return false;
468 };
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000469};
470
Daniel Sanders43c882c2017-02-01 10:53:10 +0000471//===- Actions ------------------------------------------------------------===//
472
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000473namespace {
474class OperandRenderer {
475public:
476 enum RendererKind { OR_Copy, OR_Register };
477
478protected:
479 RendererKind Kind;
480
481public:
482 OperandRenderer(RendererKind Kind) : Kind(Kind) {}
483 virtual ~OperandRenderer() {}
484
485 RendererKind getKind() const { return Kind; }
486
487 virtual void emitCxxRenderStmts(raw_ostream &OS) const = 0;
488};
489
490/// A CopyRenderer emits code to copy a single operand from an existing
491/// instruction to the one being built.
492class CopyRenderer : public OperandRenderer {
493protected:
494 /// The matcher for the instruction that this operand is copied from.
495 /// This provides the facility for looking up an a operand by it's name so
496 /// that it can be used as a source for the instruction being built.
497 const InstructionMatcher &Matched;
498 /// The name of the instruction to copy from.
499 const StringRef InsnVarName;
500 /// The name of the operand.
501 const StringRef SymbolicName;
502
503public:
504 CopyRenderer(const InstructionMatcher &Matched, const StringRef InsnVarName,
505 const StringRef SymbolicName)
506 : OperandRenderer(OR_Copy), Matched(Matched), InsnVarName(InsnVarName),
507 SymbolicName(SymbolicName) {}
508
509 static bool classof(const OperandRenderer *R) {
510 return R->getKind() == OR_Copy;
511 }
512
513 const StringRef getSymbolicName() const { return SymbolicName; }
514
515 void emitCxxRenderStmts(raw_ostream &OS) const override {
516 std::string OperandExpr =
517 Matched.getOperand(SymbolicName).getOperandExpr(InsnVarName);
518 OS << " MIB.add(" << OperandExpr << "/*" << SymbolicName << "*/);\n";
519 }
520};
521
522/// Adds a specific physical register to the instruction being built.
523/// This is typically useful for WZR/XZR on AArch64.
524class AddRegisterRenderer : public OperandRenderer {
525protected:
526 const Record *RegisterDef;
527
528public:
529 AddRegisterRenderer(const Record *RegisterDef)
530 : OperandRenderer(OR_Register), RegisterDef(RegisterDef) {}
531
532 static bool classof(const OperandRenderer *R) {
533 return R->getKind() == OR_Register;
534 }
535
536 void emitCxxRenderStmts(raw_ostream &OS) const override {
537 OS << " MIB.addReg(" << RegisterDef->getValueAsString("Namespace")
538 << "::" << RegisterDef->getName() << ");\n";
539 }
540};
541
Ahmed Bougacha56ca3a92017-02-04 00:47:10 +0000542/// An action taken when all Matcher predicates succeeded for a parent rule.
543///
544/// Typical actions include:
545/// * Changing the opcode of an instruction.
546/// * Adding an operand to an instruction.
Daniel Sanders43c882c2017-02-01 10:53:10 +0000547class MatchAction {
548public:
549 virtual ~MatchAction() {}
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000550
551 /// Emit the C++ statements to implement the action.
552 ///
553 /// \param InsnVarName If given, it's an instruction to recycle. The
554 /// requirements on the instruction vary from action to
555 /// action.
556 virtual void emitCxxActionStmts(raw_ostream &OS,
557 const StringRef InsnVarName) const = 0;
Daniel Sanders43c882c2017-02-01 10:53:10 +0000558};
559
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +0000560/// Generates a comment describing the matched rule being acted upon.
561class DebugCommentAction : public MatchAction {
562private:
563 const PatternToMatch &P;
564
565public:
566 DebugCommentAction(const PatternToMatch &P) : P(P) {}
567
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000568 void emitCxxActionStmts(raw_ostream &OS,
569 const StringRef InsnVarName) const override {
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +0000570 OS << "// " << *P.getSrcPattern() << " => " << *P.getDstPattern();
571 }
572};
573
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000574/// Generates code to build an instruction or mutate an existing instruction
575/// into the desired instruction when this is possible.
576class BuildMIAction : public MatchAction {
Daniel Sanders43c882c2017-02-01 10:53:10 +0000577private:
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000578 const CodeGenInstruction *I;
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000579 const InstructionMatcher &Matched;
580 std::vector<std::unique_ptr<OperandRenderer>> OperandRenderers;
581
582 /// True if the instruction can be built solely by mutating the opcode.
583 bool canMutate() const {
584 for (const auto &Renderer : enumerate(OperandRenderers)) {
585 if (const auto *Copy = dyn_cast<CopyRenderer>(&*Renderer.Value)) {
586 if (Matched.getOperand(Copy->getSymbolicName()).getOperandIndex() !=
587 Renderer.Index)
588 return false;
589 } else
590 return false;
591 }
592
593 return true;
594 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000595
Daniel Sanders43c882c2017-02-01 10:53:10 +0000596public:
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000597 BuildMIAction(const CodeGenInstruction *I, const InstructionMatcher &Matched)
598 : I(I), Matched(Matched) {}
Daniel Sanders43c882c2017-02-01 10:53:10 +0000599
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000600 template <class Kind, class... Args>
601 Kind &addRenderer(Args&&... args) {
602 OperandRenderers.emplace_back(
603 llvm::make_unique<Kind>(std::forward<Args>(args)...));
604 return *static_cast<Kind *>(OperandRenderers.back().get());
605 }
606
607 virtual void emitCxxActionStmts(raw_ostream &OS,
608 const StringRef InsnVarName) const {
609 if (canMutate()) {
610 OS << "I.setDesc(TII.get(" << I->Namespace << "::" << I->TheDef->getName()
611 << "));\n";
612 OS << " MachineInstr &NewI = I;\n";
613 return;
614 }
615
616 // TODO: Simple permutation looks like it could be almost as common as
617 // mutation due to commutative operations.
618
619 OS << "MachineInstrBuilder MIB = BuildMI(*I.getParent(), I, "
620 "I.getDebugLoc(), TII.get("
621 << I->Namespace << "::" << I->TheDef->getName() << "));\n";
622 for (const auto &Renderer : OperandRenderers)
623 Renderer->emitCxxRenderStmts(OS);
624 OS << " MIB.setMemRefs(I.memoperands_begin(), I.memoperands_end());\n";
625 OS << " " << InsnVarName << ".eraseFromParent();\n";
626 OS << " MachineInstr &NewI = *MIB;\n";
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000627 }
628};
629
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000630/// Generates code to check that a match rule matches.
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000631class RuleMatcher {
Ahmed Bougacha56ca3a92017-02-04 00:47:10 +0000632 /// A list of matchers that all need to succeed for the current rule to match.
633 /// FIXME: This currently supports a single match position but could be
634 /// extended to support multiple positions to support div/rem fusion or
635 /// load-multiple instructions.
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000636 std::vector<std::unique_ptr<InstructionMatcher>> Matchers;
Ahmed Bougacha56ca3a92017-02-04 00:47:10 +0000637
638 /// A list of actions that need to be taken when all predicates in this rule
639 /// have succeeded.
Daniel Sanders43c882c2017-02-01 10:53:10 +0000640 std::vector<std::unique_ptr<MatchAction>> Actions;
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000641
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000642public:
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +0000643 RuleMatcher() {}
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000644
645 InstructionMatcher &addInstructionMatcher() {
646 Matchers.emplace_back(new InstructionMatcher());
647 return *Matchers.back();
648 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000649
Daniel Sanders43c882c2017-02-01 10:53:10 +0000650 template <class Kind, class... Args>
651 Kind &addAction(Args&&... args) {
652 Actions.emplace_back(llvm::make_unique<Kind>(std::forward<Args>(args)...));
653 return *static_cast<Kind *>(Actions.back().get());
654 }
655
Daniel Sandersb41ce2b2017-02-20 14:31:27 +0000656 void emit(raw_ostream &OS) const {
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000657 if (Matchers.empty())
658 llvm_unreachable("Unexpected empty matcher!");
659
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000660 // The representation supports rules that require multiple roots such as:
661 // %ptr(p0) = ...
662 // %elt0(s32) = G_LOAD %ptr
663 // %1(p0) = G_ADD %ptr, 4
664 // %elt1(s32) = G_LOAD p0 %1
665 // which could be usefully folded into:
666 // %ptr(p0) = ...
667 // %elt0(s32), %elt1(s32) = TGT_LOAD_PAIR %ptr
668 // on some targets but we don't need to make use of that yet.
669 assert(Matchers.size() == 1 && "Cannot handle multi-root matchers yet");
670 OS << " if (";
671 Matchers.front()->emitCxxPredicateExpr(OS, "I");
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000672 OS << ") {\n";
673
Daniel Sanders43c882c2017-02-01 10:53:10 +0000674 for (const auto &MA : Actions) {
675 OS << " ";
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000676 MA->emitCxxActionStmts(OS, "I");
Daniel Sanders43c882c2017-02-01 10:53:10 +0000677 OS << "\n";
678 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000679
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000680 OS << " constrainSelectedInstRegOperands(NewI, TII, TRI, RBI);\n";
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000681 OS << " return true;\n";
Ahmed Bougacha905af9f2017-02-04 00:47:02 +0000682 OS << " }\n\n";
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000683 }
Daniel Sanders759ff412017-02-24 13:58:11 +0000684
685 /// Compare the priority of this object and B.
686 ///
687 /// Returns true if this object is more important than B.
688 bool isHigherPriorityThan(const RuleMatcher &B) const {
689 // Rules involving more match roots have higher priority.
690 if (Matchers.size() > B.Matchers.size())
691 return true;
692 if (Matchers.size() < B.Matchers.size())
693 return false;
694
695 for (const auto &Matcher : zip(Matchers, B.Matchers)) {
696 if (std::get<0>(Matcher)->isHigherPriorityThan(*std::get<1>(Matcher)))
697 return true;
698 if (std::get<1>(Matcher)->isHigherPriorityThan(*std::get<0>(Matcher)))
699 return false;
700 }
701
702 return false;
703 };
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000704};
705
706//===- GlobalISelEmitter class --------------------------------------------===//
707
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +0000708class GlobalISelEmitter {
709public:
710 explicit GlobalISelEmitter(RecordKeeper &RK);
711 void run(raw_ostream &OS);
712
713private:
714 const RecordKeeper &RK;
715 const CodeGenDAGPatterns CGP;
716 const CodeGenTarget &Target;
717
718 /// Keep track of the equivalence between SDNodes and Instruction.
719 /// This is defined using 'GINodeEquiv' in the target description.
720 DenseMap<Record *, const CodeGenInstruction *> NodeEquivs;
721
722 void gatherNodeEquivs();
723 const CodeGenInstruction *findNodeEquiv(Record *N);
724
725 /// Analyze pattern \p P, returning a matcher for it if possible.
726 /// Otherwise, return an Error explaining why we don't support it.
727 Expected<RuleMatcher> runOnPattern(const PatternToMatch &P);
728};
729
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000730void GlobalISelEmitter::gatherNodeEquivs() {
731 assert(NodeEquivs.empty());
732 for (Record *Equiv : RK.getAllDerivedDefinitions("GINodeEquiv"))
733 NodeEquivs[Equiv->getValueAsDef("Node")] =
734 &Target.getInstruction(Equiv->getValueAsDef("I"));
735}
736
737const CodeGenInstruction *GlobalISelEmitter::findNodeEquiv(Record *N) {
738 return NodeEquivs.lookup(N);
739}
740
741GlobalISelEmitter::GlobalISelEmitter(RecordKeeper &RK)
742 : RK(RK), CGP(RK), Target(CGP.getTargetInfo()) {}
743
744//===- Emitter ------------------------------------------------------------===//
745
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +0000746/// Helper function to let the emitter report skip reason error messages.
747static Error failedImport(const Twine &Reason) {
748 return make_error<StringError>(Reason, inconvertibleErrorCode());
749}
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000750
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +0000751Expected<RuleMatcher> GlobalISelEmitter::runOnPattern(const PatternToMatch &P) {
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000752 // Keep track of the matchers and actions to emit.
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +0000753 RuleMatcher M;
754 M.addAction<DebugCommentAction>(P);
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000755
756 // First, analyze the whole pattern.
757 // If the entire pattern has a predicate (e.g., target features), ignore it.
758 if (!P.getPredicates()->getValues().empty())
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +0000759 return failedImport("Pattern has a predicate");
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000760
761 // Physreg imp-defs require additional logic. Ignore the pattern.
762 if (!P.getDstRegs().empty())
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +0000763 return failedImport("Pattern defines a physical register");
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000764
765 // Next, analyze the pattern operators.
766 TreePatternNode *Src = P.getSrcPattern();
767 TreePatternNode *Dst = P.getDstPattern();
768
769 // If the root of either pattern isn't a simple operator, ignore it.
770 if (!isTrivialOperatorNode(Dst))
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +0000771 return failedImport("Dst pattern root isn't a trivial operator");
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000772 if (!isTrivialOperatorNode(Src))
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +0000773 return failedImport("Src pattern root isn't a trivial operator");
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000774
775 Record *DstOp = Dst->getOperator();
776 if (!DstOp->isSubClassOf("Instruction"))
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +0000777 return failedImport("Pattern operator isn't an instruction");
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000778
779 auto &DstI = Target.getInstruction(DstOp);
780
781 auto SrcGIOrNull = findNodeEquiv(Src->getOperator());
782 if (!SrcGIOrNull)
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +0000783 return failedImport("Pattern operator lacks an equivalent Instruction");
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000784 auto &SrcGI = *SrcGIOrNull;
785
786 // The operators look good: match the opcode and mutate it to the new one.
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000787 InstructionMatcher &InsnMatcher = M.addInstructionMatcher();
788 InsnMatcher.addPredicate<InstructionOpcodeMatcher>(&SrcGI);
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000789 auto &DstMIBuilder = M.addAction<BuildMIAction>(&DstI, InsnMatcher);
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000790
791 // Next, analyze the children, only accepting patterns that don't require
792 // any change to operands.
793 if (Src->getNumChildren() != Dst->getNumChildren())
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +0000794 return failedImport("Src/dst patterns have a different # of children");
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000795
796 unsigned OpIdx = 0;
797
798 // Start with the defined operands (i.e., the results of the root operator).
799 if (DstI.Operands.NumDefs != Src->getExtTypes().size())
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +0000800 return failedImport("Src pattern results and dst MI defs are different");
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000801
802 for (const EEVT::TypeSet &Ty : Src->getExtTypes()) {
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000803 const auto &DstIOperand = DstI.Operands[OpIdx];
804 Record *DstIOpRec = DstIOperand.Rec;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000805 if (!DstIOpRec->isSubClassOf("RegisterClass"))
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +0000806 return failedImport("Dst MI def isn't a register class");
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000807
808 auto OpTyOrNone = MVTToLLT(Ty.getConcrete());
809 if (!OpTyOrNone)
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +0000810 return failedImport("Dst operand has an unsupported type");
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000811
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000812 OperandMatcher &OM = InsnMatcher.addOperand(OpIdx, DstIOperand.Name);
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000813 OM.addPredicate<LLTOperandMatcher>(*OpTyOrNone);
814 OM.addPredicate<RegisterBankOperandMatcher>(
815 Target.getRegisterClass(DstIOpRec));
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000816 DstMIBuilder.addRenderer<CopyRenderer>(InsnMatcher, "I", DstIOperand.Name);
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000817 ++OpIdx;
818 }
819
820 // Finally match the used operands (i.e., the children of the root operator).
821 for (unsigned i = 0, e = Src->getNumChildren(); i != e; ++i) {
822 auto *SrcChild = Src->getChild(i);
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000823
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000824 OperandMatcher &OM = InsnMatcher.addOperand(OpIdx++, SrcChild->getName());
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000825
826 // The only non-leaf child we accept is 'bb': it's an operator because
827 // BasicBlockSDNode isn't inline, but in MI it's just another operand.
828 if (!SrcChild->isLeaf()) {
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000829 if (SrcChild->getOperator()->isSubClassOf("SDNode")) {
830 auto &ChildSDNI = CGP.getSDNodeInfo(SrcChild->getOperator());
831 if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") {
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000832 OM.addPredicate<MBBOperandMatcher>();
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000833 continue;
834 }
835 }
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000836 return failedImport("Src pattern child isn't a leaf node or an MBB");
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000837 }
838
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000839 if (SrcChild->hasAnyPredicate())
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +0000840 return failedImport("Src pattern child has predicate");
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000841
842 ArrayRef<EEVT::TypeSet> ChildTypes = SrcChild->getExtTypes();
843 if (ChildTypes.size() != 1)
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +0000844 return failedImport("Src pattern child has multiple results");
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000845
846 auto OpTyOrNone = MVTToLLT(ChildTypes.front().getConcrete());
847 if (!OpTyOrNone)
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +0000848 return failedImport("Src operand has an unsupported type");
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000849 OM.addPredicate<LLTOperandMatcher>(*OpTyOrNone);
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000850
851 if (auto *ChildInt = dyn_cast<IntInit>(SrcChild->getLeafValue())) {
852 OM.addPredicate<IntOperandMatcher>(ChildInt->getValue());
853 continue;
854 }
855
856 if (auto *ChildDefInit = dyn_cast<DefInit>(SrcChild->getLeafValue())) {
857 auto *ChildRec = ChildDefInit->getDef();
858
859 // Otherwise, we're looking for a bog-standard RegisterClass operand.
860 if (!ChildRec->isSubClassOf("RegisterClass"))
861 return failedImport("Src pattern child isn't a RegisterClass");
862
863 OM.addPredicate<RegisterBankOperandMatcher>(
864 Target.getRegisterClass(ChildRec));
865 continue;
866 }
867
868 return failedImport("Src pattern child is an unsupported kind");
869 }
870
871 // Finally render the used operands (i.e., the children of the root operator).
872 for (unsigned i = 0, e = Dst->getNumChildren(); i != e; ++i) {
873 auto *DstChild = Dst->getChild(i);
874
875 // The only non-leaf child we accept is 'bb': it's an operator because
876 // BasicBlockSDNode isn't inline, but in MI it's just another operand.
877 if (!DstChild->isLeaf()) {
878 if (DstChild->getOperator()->isSubClassOf("SDNode")) {
879 auto &ChildSDNI = CGP.getSDNodeInfo(DstChild->getOperator());
880 if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") {
881 DstMIBuilder.addRenderer<CopyRenderer>(InsnMatcher, "I",
882 DstChild->getName());
883 continue;
884 }
885 }
886 return failedImport("Dst pattern child isn't a leaf node or an MBB");
887 }
888
889 // Otherwise, we're looking for a bog-standard RegisterClass operand.
890 if (DstChild->hasAnyPredicate())
891 return failedImport("Dst pattern child has predicate");
892
893 if (auto *ChildDefInit = dyn_cast<DefInit>(DstChild->getLeafValue())) {
894 auto *ChildRec = ChildDefInit->getDef();
895
896 ArrayRef<EEVT::TypeSet> ChildTypes = DstChild->getExtTypes();
897 if (ChildTypes.size() != 1)
898 return failedImport("Dst pattern child has multiple results");
899
900 auto OpTyOrNone = MVTToLLT(ChildTypes.front().getConcrete());
901 if (!OpTyOrNone)
902 return failedImport("Dst operand has an unsupported type");
903
904 if (ChildRec->isSubClassOf("Register")) {
905 DstMIBuilder.addRenderer<AddRegisterRenderer>(ChildRec);
906 continue;
907 }
908
909 if (ChildRec->isSubClassOf("RegisterClass")) {
910 DstMIBuilder.addRenderer<CopyRenderer>(InsnMatcher, "I",
911 DstChild->getName());
912 continue;
913 }
914
915 return failedImport(
916 "Dst pattern child def is an unsupported tablegen class");
917 }
918
919 return failedImport("Src pattern child is an unsupported kind");
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000920 }
921
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +0000922 // We're done with this pattern! It's eligible for GISel emission; return it.
Daniel Sandersb41ce2b2017-02-20 14:31:27 +0000923 ++NumPatternImported;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +0000924 return std::move(M);
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000925}
926
927void GlobalISelEmitter::run(raw_ostream &OS) {
928 // Track the GINodeEquiv definitions.
929 gatherNodeEquivs();
930
931 emitSourceFileHeader(("Global Instruction Selector for the " +
932 Target.getName() + " target").str(), OS);
933 OS << "bool " << Target.getName()
934 << "InstructionSelector::selectImpl"
935 "(MachineInstr &I) const {\n const MachineRegisterInfo &MRI = "
Ahmed Bougacha905af9f2017-02-04 00:47:02 +0000936 "I.getParent()->getParent()->getRegInfo();\n\n";
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000937
Daniel Sandersb41ce2b2017-02-20 14:31:27 +0000938 std::vector<RuleMatcher> Rules;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000939 // Look through the SelectionDAG patterns we found, possibly emitting some.
940 for (const PatternToMatch &Pat : CGP.ptms()) {
941 ++NumPatternTotal;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +0000942 auto MatcherOrErr = runOnPattern(Pat);
943
944 // The pattern analysis can fail, indicating an unsupported pattern.
945 // Report that if we've been asked to do so.
946 if (auto Err = MatcherOrErr.takeError()) {
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000947 if (WarnOnSkippedPatterns) {
948 PrintWarning(Pat.getSrcRecord()->getLoc(),
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +0000949 "Skipped pattern: " + toString(std::move(Err)));
950 } else {
951 consumeError(std::move(Err));
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000952 }
Daniel Sandersb41ce2b2017-02-20 14:31:27 +0000953 ++NumPatternImportsSkipped;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +0000954 continue;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000955 }
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +0000956
Daniel Sandersb41ce2b2017-02-20 14:31:27 +0000957 Rules.push_back(std::move(MatcherOrErr.get()));
958 }
959
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000960 std::stable_sort(Rules.begin(), Rules.end(),
961 [&](const RuleMatcher &A, const RuleMatcher &B) {
Daniel Sanders759ff412017-02-24 13:58:11 +0000962 if (A.isHigherPriorityThan(B)) {
963 assert(!B.isHigherPriorityThan(A) && "Cannot be more important "
964 "and less important at "
965 "the same time");
966 return true;
967 }
968 return false;
969 });
970
Daniel Sandersb41ce2b2017-02-20 14:31:27 +0000971 for (const auto &Rule : Rules) {
972 Rule.emit(OS);
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +0000973 ++NumPatternEmitted;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000974 }
975
976 OS << " return false;\n}\n";
977}
978
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +0000979} // end anonymous namespace
980
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000981//===----------------------------------------------------------------------===//
982
983namespace llvm {
984void EmitGlobalISel(RecordKeeper &RK, raw_ostream &OS) {
985 GlobalISelEmitter(RK).run(OS);
986}
987} // End llvm namespace