blob: 238a50a94c6c0f1d8fed3f9b9b941c7176bbf976 [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"
Pavel Labath52a82e22017-02-21 09:19:41 +000039#include "llvm/Support/ScopedPrinter.h"
Ahmed Bougacha36f70352016-12-21 23:26:20 +000040#include "llvm/TableGen/Error.h"
41#include "llvm/TableGen/Record.h"
42#include "llvm/TableGen/TableGenBackend.h"
43#include <string>
44using namespace llvm;
45
46#define DEBUG_TYPE "gisel-emitter"
47
48STATISTIC(NumPatternTotal, "Total number of patterns");
Daniel Sandersb41ce2b2017-02-20 14:31:27 +000049STATISTIC(NumPatternImported, "Number of patterns imported from SelectionDAG");
50STATISTIC(NumPatternImportsSkipped, "Number of SelectionDAG imports skipped");
Ahmed Bougacha36f70352016-12-21 23:26:20 +000051STATISTIC(NumPatternEmitted, "Number of patterns emitted");
52
53static 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
Ahmed Bougacha36f70352016-12-21 23:26:20 +000059//===- Helper functions ---------------------------------------------------===//
60
61/// Convert an MVT to an equivalent LLT if possible, or the invalid LLT() for
62/// MVTs that don't map cleanly to an LLT (e.g., iPTR, *any, ...).
63static Optional<std::string> MVTToLLT(MVT::SimpleValueType SVT) {
64 std::string TyStr;
65 raw_string_ostream OS(TyStr);
66 MVT VT(SVT);
67 if (VT.isVector() && VT.getVectorNumElements() != 1) {
68 OS << "LLT::vector(" << VT.getVectorNumElements() << ", "
69 << VT.getScalarSizeInBits() << ")";
70 } else if (VT.isInteger() || VT.isFloatingPoint()) {
71 OS << "LLT::scalar(" << VT.getSizeInBits() << ")";
72 } else {
73 return None;
74 }
75 OS.flush();
76 return TyStr;
77}
78
79static bool isTrivialOperatorNode(const TreePatternNode *N) {
80 return !N->isLeaf() && !N->hasAnyPredicate() && !N->getTransformFn();
81}
82
83//===- Matchers -----------------------------------------------------------===//
84
Daniel Sandersdc662ff2017-01-26 11:10:14 +000085template <class PredicateTy> class PredicateListMatcher {
86private:
87 typedef std::vector<std::unique_ptr<PredicateTy>> PredicateVec;
88 PredicateVec Predicates;
Ahmed Bougacha36f70352016-12-21 23:26:20 +000089
Daniel Sandersdc662ff2017-01-26 11:10:14 +000090public:
91 /// Construct a new operand predicate and add it to the matcher.
92 template <class Kind, class... Args>
93 Kind &addPredicate(Args&&... args) {
Ahmed Bougachab67a3ce2017-01-26 22:07:37 +000094 Predicates.emplace_back(
95 llvm::make_unique<Kind>(std::forward<Args>(args)...));
Daniel Sandersdc662ff2017-01-26 11:10:14 +000096 return *static_cast<Kind *>(Predicates.back().get());
Ahmed Bougacha36f70352016-12-21 23:26:20 +000097 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +000098
99 typename PredicateVec::const_iterator predicates_begin() const { return Predicates.begin(); }
100 typename PredicateVec::const_iterator predicates_end() const { return Predicates.end(); }
101 iterator_range<typename PredicateVec::const_iterator> predicates() const {
102 return make_range(predicates_begin(), predicates_end());
103 }
Daniel Sanders759ff412017-02-24 13:58:11 +0000104 typename PredicateVec::size_type predicates_size() const { return Predicates.size(); }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000105
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000106 /// Emit a C++ expression that tests whether all the predicates are met.
Ahmed Bougachab67a3ce2017-01-26 22:07:37 +0000107 template <class... Args>
Daniel Sandersf8c804f2017-01-28 11:10:42 +0000108 void emitCxxPredicateListExpr(raw_ostream &OS, Args &&... args) const {
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000109 if (Predicates.empty()) {
110 OS << "true";
111 return;
112 }
113
114 StringRef Separator = "";
115 for (const auto &Predicate : predicates()) {
116 OS << Separator << "(";
Ahmed Bougachab67a3ce2017-01-26 22:07:37 +0000117 Predicate->emitCxxPredicateExpr(OS, std::forward<Args>(args)...);
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000118 OS << ")";
Ahmed Bougacha905af9f2017-02-04 00:47:02 +0000119 Separator = " &&\n";
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000120 }
121 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000122};
123
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000124/// 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.
130class OperandPredicateMatcher {
131public:
Daniel Sanders759ff412017-02-24 13:58:11 +0000132 /// This enum is used for RTTI and also defines the priority that is given to
133 /// the predicate when generating the matcher code. Kinds with higher priority
134 /// must be tested first.
135 ///
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000136 /// The relative priority of OPM_LLT, OPM_RegBank, and OPM_MBB do not matter
137 /// but OPM_Int must have priority over OPM_RegBank since constant integers
138 /// are represented by a virtual register defined by a G_CONSTANT instruction.
Daniel Sanders759ff412017-02-24 13:58:11 +0000139 enum PredicateKind {
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000140 OPM_Int,
Daniel Sanders759ff412017-02-24 13:58:11 +0000141 OPM_LLT,
142 OPM_RegBank,
143 OPM_MBB,
144 };
145
146protected:
147 PredicateKind Kind;
148
149public:
150 OperandPredicateMatcher(PredicateKind Kind) : Kind(Kind) {}
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000151 virtual ~OperandPredicateMatcher() {}
152
Daniel Sanders759ff412017-02-24 13:58:11 +0000153 PredicateKind getKind() const { return Kind; }
154
Daniel Sanderse604ef52017-02-20 15:30:43 +0000155 /// Emit a C++ expression that checks the predicate for the given operand.
156 virtual void emitCxxPredicateExpr(raw_ostream &OS,
157 StringRef OperandExpr) const = 0;
Daniel Sanders759ff412017-02-24 13:58:11 +0000158
159 /// Compare the priority of this object and B.
160 ///
161 /// Returns true if this object is more important than B.
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000162 virtual bool isHigherPriorityThan(const OperandPredicateMatcher &B) const {
163 return Kind < B.Kind;
Daniel Sanders759ff412017-02-24 13:58:11 +0000164 };
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000165};
166
167/// Generates code to check that an operand is a particular LLT.
168class LLTOperandMatcher : public OperandPredicateMatcher {
169protected:
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000170 std::string Ty;
171
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000172public:
Daniel Sanders759ff412017-02-24 13:58:11 +0000173 LLTOperandMatcher(std::string Ty)
174 : OperandPredicateMatcher(OPM_LLT), Ty(Ty) {}
175
176 static bool classof(const OperandPredicateMatcher *P) {
177 return P->getKind() == OPM_LLT;
178 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000179
Daniel Sanderse604ef52017-02-20 15:30:43 +0000180 void emitCxxPredicateExpr(raw_ostream &OS,
181 StringRef OperandExpr) const override {
182 OS << "MRI.getType(" << OperandExpr << ".getReg()) == (" << Ty << ")";
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000183 }
184};
185
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000186/// Generates code to check that an operand is in a particular register bank.
187class RegisterBankOperandMatcher : public OperandPredicateMatcher {
188protected:
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000189 const CodeGenRegisterClass &RC;
190
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000191public:
Daniel Sanders759ff412017-02-24 13:58:11 +0000192 RegisterBankOperandMatcher(const CodeGenRegisterClass &RC)
193 : OperandPredicateMatcher(OPM_RegBank), RC(RC) {}
194
195 static bool classof(const OperandPredicateMatcher *P) {
196 return P->getKind() == OPM_RegBank;
197 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000198
Daniel Sanderse604ef52017-02-20 15:30:43 +0000199 void emitCxxPredicateExpr(raw_ostream &OS,
200 StringRef OperandExpr) const override {
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000201 OS << "(&RBI.getRegBankFromRegClass(" << RC.getQualifiedName()
Daniel Sanderse604ef52017-02-20 15:30:43 +0000202 << "RegClass) == RBI.getRegBank(" << OperandExpr
203 << ".getReg(), MRI, TRI))";
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000204 }
205};
206
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000207/// Generates code to check that an operand is a basic block.
208class MBBOperandMatcher : public OperandPredicateMatcher {
209public:
Daniel Sanders759ff412017-02-24 13:58:11 +0000210 MBBOperandMatcher() : OperandPredicateMatcher(OPM_MBB) {}
211
212 static bool classof(const OperandPredicateMatcher *P) {
213 return P->getKind() == OPM_MBB;
214 }
215
Daniel Sanderse604ef52017-02-20 15:30:43 +0000216 void emitCxxPredicateExpr(raw_ostream &OS,
217 StringRef OperandExpr) const override {
218 OS << OperandExpr << ".isMBB()";
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000219 }
220};
221
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000222/// Generates code to check that an operand is a particular int.
223class IntOperandMatcher : public OperandPredicateMatcher {
224protected:
225 int64_t Value;
226
227public:
228 IntOperandMatcher(int64_t Value)
229 : OperandPredicateMatcher(OPM_Int), Value(Value) {}
230
231 static bool classof(const OperandPredicateMatcher *P) {
232 return P->getKind() == OPM_Int;
233 }
234
235 void emitCxxPredicateExpr(raw_ostream &OS,
Simon Pilgrimd0302912017-02-24 17:20:27 +0000236 StringRef OperandExpr) const override {
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000237 OS << "isOperandImmEqual(" << OperandExpr << ", " << Value << ", MRI)";
238 }
239};
240
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000241/// Generates code to check that a set of predicates match for a particular
242/// operand.
243class OperandMatcher : public PredicateListMatcher<OperandPredicateMatcher> {
244protected:
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000245 unsigned OpIdx;
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000246 std::string SymbolicName;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000247
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000248public:
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000249 OperandMatcher(unsigned OpIdx, const std::string &SymbolicName)
250 : OpIdx(OpIdx), SymbolicName(SymbolicName) {}
251
252 bool hasSymbolicName() const { return !SymbolicName.empty(); }
253 const StringRef getSymbolicName() const { return SymbolicName; }
254 unsigned getOperandIndex() const { return OpIdx; }
255
256 std::string getOperandExpr(const StringRef InsnVarName) const {
Pavel Labath52a82e22017-02-21 09:19:41 +0000257 return (InsnVarName + ".getOperand(" + llvm::to_string(OpIdx) + ")").str();
Daniel Sanderse604ef52017-02-20 15:30:43 +0000258 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000259
260 /// Emit a C++ expression that tests whether the instruction named in
261 /// InsnVarName matches all the predicate and all the operands.
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000262 void emitCxxPredicateExpr(raw_ostream &OS, const StringRef InsnVarName) const {
263 OS << "(/* ";
264 if (SymbolicName.empty())
265 OS << "Operand " << OpIdx;
266 else
267 OS << SymbolicName;
268 OS << " */ ";
Daniel Sanderse604ef52017-02-20 15:30:43 +0000269 emitCxxPredicateListExpr(OS, getOperandExpr(InsnVarName));
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000270 OS << ")";
271 }
Daniel Sanders759ff412017-02-24 13:58:11 +0000272
273 /// Compare the priority of this object and B.
274 ///
275 /// Returns true if this object is more important than B.
276 bool isHigherPriorityThan(const OperandMatcher &B) const {
277 // Operand matchers involving more predicates have higher priority.
278 if (predicates_size() > B.predicates_size())
279 return true;
280 if (predicates_size() < B.predicates_size())
281 return false;
282
283 // This assumes that predicates are added in a consistent order.
284 for (const auto &Predicate : zip(predicates(), B.predicates())) {
285 if (std::get<0>(Predicate)->isHigherPriorityThan(*std::get<1>(Predicate)))
286 return true;
287 if (std::get<1>(Predicate)->isHigherPriorityThan(*std::get<0>(Predicate)))
288 return false;
289 }
290
291 return false;
292 };
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000293};
294
295/// Generates code to check a predicate on an instruction.
296///
297/// Typical predicates include:
298/// * The opcode of the instruction is a particular value.
299/// * The nsw/nuw flag is/isn't set.
300class InstructionPredicateMatcher {
Daniel Sanders759ff412017-02-24 13:58:11 +0000301protected:
302 /// This enum is used for RTTI and also defines the priority that is given to
303 /// the predicate when generating the matcher code. Kinds with higher priority
304 /// must be tested first.
305 enum PredicateKind {
306 IPM_Opcode,
307 };
308
309 PredicateKind Kind;
310
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000311public:
Daniel Sanders8d4d72f2017-02-24 14:53:35 +0000312 InstructionPredicateMatcher(PredicateKind Kind) : Kind(Kind) {}
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000313 virtual ~InstructionPredicateMatcher() {}
314
Daniel Sanders759ff412017-02-24 13:58:11 +0000315 PredicateKind getKind() const { return Kind; }
316
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000317 /// Emit a C++ expression that tests whether the instruction named in
318 /// InsnVarName matches the predicate.
319 virtual void emitCxxPredicateExpr(raw_ostream &OS,
Ahmed Bougacha6a1ac5a2017-02-09 02:50:01 +0000320 StringRef InsnVarName) const = 0;
Daniel Sanders759ff412017-02-24 13:58:11 +0000321
322 /// Compare the priority of this object and B.
323 ///
324 /// Returns true if this object is more important than B.
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000325 virtual bool isHigherPriorityThan(const InstructionPredicateMatcher &B) const {
Daniel Sanders759ff412017-02-24 13:58:11 +0000326 return Kind < B.Kind;
327 };
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000328};
329
330/// Generates code to check the opcode of an instruction.
331class InstructionOpcodeMatcher : public InstructionPredicateMatcher {
332protected:
333 const CodeGenInstruction *I;
334
335public:
Daniel Sanders8d4d72f2017-02-24 14:53:35 +0000336 InstructionOpcodeMatcher(const CodeGenInstruction *I)
337 : InstructionPredicateMatcher(IPM_Opcode), I(I) {}
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000338
Daniel Sanders759ff412017-02-24 13:58:11 +0000339 static bool classof(const InstructionPredicateMatcher *P) {
340 return P->getKind() == IPM_Opcode;
341 }
342
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000343 void emitCxxPredicateExpr(raw_ostream &OS,
Ahmed Bougacha6a1ac5a2017-02-09 02:50:01 +0000344 StringRef InsnVarName) const override {
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000345 OS << InsnVarName << ".getOpcode() == " << I->Namespace
346 << "::" << I->TheDef->getName();
347 }
Daniel Sanders759ff412017-02-24 13:58:11 +0000348
349 /// Compare the priority of this object and B.
350 ///
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000351 /// Returns true if this object is more important than B.
352 bool isHigherPriorityThan(const InstructionPredicateMatcher &B) const override {
Daniel Sanders759ff412017-02-24 13:58:11 +0000353 if (InstructionPredicateMatcher::isHigherPriorityThan(B))
354 return true;
355 if (B.InstructionPredicateMatcher::isHigherPriorityThan(*this))
356 return false;
357
358 // Prioritize opcodes for cosmetic reasons in the generated source. Although
359 // this is cosmetic at the moment, we may want to drive a similar ordering
360 // using instruction frequency information to improve compile time.
361 if (const InstructionOpcodeMatcher *BO =
362 dyn_cast<InstructionOpcodeMatcher>(&B))
363 return I->TheDef->getName() < BO->I->TheDef->getName();
364
365 return false;
366 };
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000367};
368
369/// Generates code to check that a set of predicates and operands match for a
370/// particular instruction.
371///
372/// Typical predicates include:
373/// * Has a specific opcode.
374/// * Has an nsw/nuw flag or doesn't.
375class InstructionMatcher
376 : public PredicateListMatcher<InstructionPredicateMatcher> {
377protected:
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000378 typedef std::vector<OperandMatcher> OperandVec;
379
380 /// The operands to match. All rendered operands must be present even if the
381 /// condition is always true.
382 OperandVec Operands;
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000383
384public:
385 /// Add an operand to the matcher.
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000386 OperandMatcher &addOperand(unsigned OpIdx, const std::string &SymbolicName) {
387 Operands.emplace_back(OpIdx, SymbolicName);
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000388 return Operands.back();
389 }
390
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000391 const OperandMatcher &getOperand(const StringRef SymbolicName) const {
392 assert(!SymbolicName.empty() && "Cannot lookup unnamed operand");
393 const auto &I = std::find_if(Operands.begin(), Operands.end(),
394 [&SymbolicName](const OperandMatcher &X) {
395 return X.getSymbolicName() == SymbolicName;
396 });
397 if (I != Operands.end())
398 return *I;
399 llvm_unreachable("Failed to lookup operand");
400 }
401
402 unsigned getNumOperands() const { return Operands.size(); }
403 OperandVec::const_iterator operands_begin() const {
404 return Operands.begin();
405 }
406 OperandVec::const_iterator operands_end() const {
407 return Operands.end();
408 }
409 iterator_range<OperandVec::const_iterator> operands() const {
410 return make_range(operands_begin(), operands_end());
411 }
412
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000413 /// Emit a C++ expression that tests whether the instruction named in
414 /// InsnVarName matches all the predicates and all the operands.
Ahmed Bougacha6a1ac5a2017-02-09 02:50:01 +0000415 void emitCxxPredicateExpr(raw_ostream &OS, StringRef InsnVarName) const {
Daniel Sandersf8c804f2017-01-28 11:10:42 +0000416 emitCxxPredicateListExpr(OS, InsnVarName);
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000417 for (const auto &Operand : Operands) {
Ahmed Bougacha905af9f2017-02-04 00:47:02 +0000418 OS << " &&\n(";
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000419 Operand.emitCxxPredicateExpr(OS, InsnVarName);
420 OS << ")";
421 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000422 }
Daniel Sanders759ff412017-02-24 13:58:11 +0000423
424 /// Compare the priority of this object and B.
425 ///
426 /// Returns true if this object is more important than B.
427 bool isHigherPriorityThan(const InstructionMatcher &B) const {
428 // Instruction matchers involving more operands have higher priority.
429 if (Operands.size() > B.Operands.size())
430 return true;
431 if (Operands.size() < B.Operands.size())
432 return false;
433
434 for (const auto &Predicate : zip(predicates(), B.predicates())) {
435 if (std::get<0>(Predicate)->isHigherPriorityThan(*std::get<1>(Predicate)))
436 return true;
437 if (std::get<1>(Predicate)->isHigherPriorityThan(*std::get<0>(Predicate)))
438 return false;
439 }
440
441 for (const auto &Operand : zip(Operands, B.Operands)) {
442 if (std::get<0>(Operand).isHigherPriorityThan(std::get<1>(Operand)))
443 return true;
444 if (std::get<1>(Operand).isHigherPriorityThan(std::get<0>(Operand)))
445 return false;
446 }
447
448 return false;
449 };
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000450};
451
Daniel Sanders43c882c2017-02-01 10:53:10 +0000452//===- Actions ------------------------------------------------------------===//
453
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000454namespace {
455class OperandRenderer {
456public:
457 enum RendererKind { OR_Copy, OR_Register };
458
459protected:
460 RendererKind Kind;
461
462public:
463 OperandRenderer(RendererKind Kind) : Kind(Kind) {}
464 virtual ~OperandRenderer() {}
465
466 RendererKind getKind() const { return Kind; }
467
468 virtual void emitCxxRenderStmts(raw_ostream &OS) const = 0;
469};
470
471/// A CopyRenderer emits code to copy a single operand from an existing
472/// instruction to the one being built.
473class CopyRenderer : public OperandRenderer {
474protected:
475 /// The matcher for the instruction that this operand is copied from.
476 /// This provides the facility for looking up an a operand by it's name so
477 /// that it can be used as a source for the instruction being built.
478 const InstructionMatcher &Matched;
479 /// The name of the instruction to copy from.
480 const StringRef InsnVarName;
481 /// The name of the operand.
482 const StringRef SymbolicName;
483
484public:
485 CopyRenderer(const InstructionMatcher &Matched, const StringRef InsnVarName,
486 const StringRef SymbolicName)
487 : OperandRenderer(OR_Copy), Matched(Matched), InsnVarName(InsnVarName),
488 SymbolicName(SymbolicName) {}
489
490 static bool classof(const OperandRenderer *R) {
491 return R->getKind() == OR_Copy;
492 }
493
494 const StringRef getSymbolicName() const { return SymbolicName; }
495
496 void emitCxxRenderStmts(raw_ostream &OS) const override {
497 std::string OperandExpr =
498 Matched.getOperand(SymbolicName).getOperandExpr(InsnVarName);
499 OS << " MIB.add(" << OperandExpr << "/*" << SymbolicName << "*/);\n";
500 }
501};
502
503/// Adds a specific physical register to the instruction being built.
504/// This is typically useful for WZR/XZR on AArch64.
505class AddRegisterRenderer : public OperandRenderer {
506protected:
507 const Record *RegisterDef;
508
509public:
510 AddRegisterRenderer(const Record *RegisterDef)
511 : OperandRenderer(OR_Register), RegisterDef(RegisterDef) {}
512
513 static bool classof(const OperandRenderer *R) {
514 return R->getKind() == OR_Register;
515 }
516
517 void emitCxxRenderStmts(raw_ostream &OS) const override {
518 OS << " MIB.addReg(" << RegisterDef->getValueAsString("Namespace")
519 << "::" << RegisterDef->getName() << ");\n";
520 }
521};
522
Ahmed Bougacha56ca3a92017-02-04 00:47:10 +0000523/// An action taken when all Matcher predicates succeeded for a parent rule.
524///
525/// Typical actions include:
526/// * Changing the opcode of an instruction.
527/// * Adding an operand to an instruction.
Daniel Sanders43c882c2017-02-01 10:53:10 +0000528class MatchAction {
529public:
530 virtual ~MatchAction() {}
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000531
532 /// Emit the C++ statements to implement the action.
533 ///
534 /// \param InsnVarName If given, it's an instruction to recycle. The
535 /// requirements on the instruction vary from action to
536 /// action.
537 virtual void emitCxxActionStmts(raw_ostream &OS,
538 const StringRef InsnVarName) const = 0;
Daniel Sanders43c882c2017-02-01 10:53:10 +0000539};
540
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +0000541/// Generates a comment describing the matched rule being acted upon.
542class DebugCommentAction : public MatchAction {
543private:
544 const PatternToMatch &P;
545
546public:
547 DebugCommentAction(const PatternToMatch &P) : P(P) {}
548
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000549 void emitCxxActionStmts(raw_ostream &OS,
550 const StringRef InsnVarName) const override {
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +0000551 OS << "// " << *P.getSrcPattern() << " => " << *P.getDstPattern();
552 }
553};
554
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000555/// Generates code to build an instruction or mutate an existing instruction
556/// into the desired instruction when this is possible.
557class BuildMIAction : public MatchAction {
Daniel Sanders43c882c2017-02-01 10:53:10 +0000558private:
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000559 const CodeGenInstruction *I;
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000560 const InstructionMatcher &Matched;
561 std::vector<std::unique_ptr<OperandRenderer>> OperandRenderers;
562
563 /// True if the instruction can be built solely by mutating the opcode.
564 bool canMutate() const {
565 for (const auto &Renderer : enumerate(OperandRenderers)) {
566 if (const auto *Copy = dyn_cast<CopyRenderer>(&*Renderer.Value)) {
567 if (Matched.getOperand(Copy->getSymbolicName()).getOperandIndex() !=
568 Renderer.Index)
569 return false;
570 } else
571 return false;
572 }
573
574 return true;
575 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000576
Daniel Sanders43c882c2017-02-01 10:53:10 +0000577public:
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000578 BuildMIAction(const CodeGenInstruction *I, const InstructionMatcher &Matched)
579 : I(I), Matched(Matched) {}
Daniel Sanders43c882c2017-02-01 10:53:10 +0000580
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000581 template <class Kind, class... Args>
582 Kind &addRenderer(Args&&... args) {
583 OperandRenderers.emplace_back(
584 llvm::make_unique<Kind>(std::forward<Args>(args)...));
585 return *static_cast<Kind *>(OperandRenderers.back().get());
586 }
587
588 virtual void emitCxxActionStmts(raw_ostream &OS,
589 const StringRef InsnVarName) const {
590 if (canMutate()) {
591 OS << "I.setDesc(TII.get(" << I->Namespace << "::" << I->TheDef->getName()
592 << "));\n";
593 OS << " MachineInstr &NewI = I;\n";
594 return;
595 }
596
597 // TODO: Simple permutation looks like it could be almost as common as
598 // mutation due to commutative operations.
599
600 OS << "MachineInstrBuilder MIB = BuildMI(*I.getParent(), I, "
601 "I.getDebugLoc(), TII.get("
602 << I->Namespace << "::" << I->TheDef->getName() << "));\n";
603 for (const auto &Renderer : OperandRenderers)
604 Renderer->emitCxxRenderStmts(OS);
605 OS << " MIB.setMemRefs(I.memoperands_begin(), I.memoperands_end());\n";
606 OS << " " << InsnVarName << ".eraseFromParent();\n";
607 OS << " MachineInstr &NewI = *MIB;\n";
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000608 }
609};
610
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000611/// Generates code to check that a match rule matches.
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000612class RuleMatcher {
Ahmed Bougacha56ca3a92017-02-04 00:47:10 +0000613 /// A list of matchers that all need to succeed for the current rule to match.
614 /// FIXME: This currently supports a single match position but could be
615 /// extended to support multiple positions to support div/rem fusion or
616 /// load-multiple instructions.
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000617 std::vector<std::unique_ptr<InstructionMatcher>> Matchers;
Ahmed Bougacha56ca3a92017-02-04 00:47:10 +0000618
619 /// A list of actions that need to be taken when all predicates in this rule
620 /// have succeeded.
Daniel Sanders43c882c2017-02-01 10:53:10 +0000621 std::vector<std::unique_ptr<MatchAction>> Actions;
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000622
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000623public:
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +0000624 RuleMatcher() {}
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000625
626 InstructionMatcher &addInstructionMatcher() {
627 Matchers.emplace_back(new InstructionMatcher());
628 return *Matchers.back();
629 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000630
Daniel Sanders43c882c2017-02-01 10:53:10 +0000631 template <class Kind, class... Args>
632 Kind &addAction(Args&&... args) {
633 Actions.emplace_back(llvm::make_unique<Kind>(std::forward<Args>(args)...));
634 return *static_cast<Kind *>(Actions.back().get());
635 }
636
Daniel Sandersb41ce2b2017-02-20 14:31:27 +0000637 void emit(raw_ostream &OS) const {
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000638 if (Matchers.empty())
639 llvm_unreachable("Unexpected empty matcher!");
640
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000641 // The representation supports rules that require multiple roots such as:
642 // %ptr(p0) = ...
643 // %elt0(s32) = G_LOAD %ptr
644 // %1(p0) = G_ADD %ptr, 4
645 // %elt1(s32) = G_LOAD p0 %1
646 // which could be usefully folded into:
647 // %ptr(p0) = ...
648 // %elt0(s32), %elt1(s32) = TGT_LOAD_PAIR %ptr
649 // on some targets but we don't need to make use of that yet.
650 assert(Matchers.size() == 1 && "Cannot handle multi-root matchers yet");
651 OS << " if (";
652 Matchers.front()->emitCxxPredicateExpr(OS, "I");
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000653 OS << ") {\n";
654
Daniel Sanders43c882c2017-02-01 10:53:10 +0000655 for (const auto &MA : Actions) {
656 OS << " ";
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000657 MA->emitCxxActionStmts(OS, "I");
Daniel Sanders43c882c2017-02-01 10:53:10 +0000658 OS << "\n";
659 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000660
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000661 OS << " constrainSelectedInstRegOperands(NewI, TII, TRI, RBI);\n";
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000662 OS << " return true;\n";
Ahmed Bougacha905af9f2017-02-04 00:47:02 +0000663 OS << " }\n\n";
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000664 }
Daniel Sanders759ff412017-02-24 13:58:11 +0000665
666 /// Compare the priority of this object and B.
667 ///
668 /// Returns true if this object is more important than B.
669 bool isHigherPriorityThan(const RuleMatcher &B) const {
670 // Rules involving more match roots have higher priority.
671 if (Matchers.size() > B.Matchers.size())
672 return true;
673 if (Matchers.size() < B.Matchers.size())
674 return false;
675
676 for (const auto &Matcher : zip(Matchers, B.Matchers)) {
677 if (std::get<0>(Matcher)->isHigherPriorityThan(*std::get<1>(Matcher)))
678 return true;
679 if (std::get<1>(Matcher)->isHigherPriorityThan(*std::get<0>(Matcher)))
680 return false;
681 }
682
683 return false;
684 };
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000685};
686
687//===- GlobalISelEmitter class --------------------------------------------===//
688
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +0000689class GlobalISelEmitter {
690public:
691 explicit GlobalISelEmitter(RecordKeeper &RK);
692 void run(raw_ostream &OS);
693
694private:
695 const RecordKeeper &RK;
696 const CodeGenDAGPatterns CGP;
697 const CodeGenTarget &Target;
698
699 /// Keep track of the equivalence between SDNodes and Instruction.
700 /// This is defined using 'GINodeEquiv' in the target description.
701 DenseMap<Record *, const CodeGenInstruction *> NodeEquivs;
702
703 void gatherNodeEquivs();
704 const CodeGenInstruction *findNodeEquiv(Record *N);
705
706 /// Analyze pattern \p P, returning a matcher for it if possible.
707 /// Otherwise, return an Error explaining why we don't support it.
708 Expected<RuleMatcher> runOnPattern(const PatternToMatch &P);
709};
710
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000711void GlobalISelEmitter::gatherNodeEquivs() {
712 assert(NodeEquivs.empty());
713 for (Record *Equiv : RK.getAllDerivedDefinitions("GINodeEquiv"))
714 NodeEquivs[Equiv->getValueAsDef("Node")] =
715 &Target.getInstruction(Equiv->getValueAsDef("I"));
716}
717
718const CodeGenInstruction *GlobalISelEmitter::findNodeEquiv(Record *N) {
719 return NodeEquivs.lookup(N);
720}
721
722GlobalISelEmitter::GlobalISelEmitter(RecordKeeper &RK)
723 : RK(RK), CGP(RK), Target(CGP.getTargetInfo()) {}
724
725//===- Emitter ------------------------------------------------------------===//
726
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +0000727/// Helper function to let the emitter report skip reason error messages.
728static Error failedImport(const Twine &Reason) {
729 return make_error<StringError>(Reason, inconvertibleErrorCode());
730}
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000731
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +0000732Expected<RuleMatcher> GlobalISelEmitter::runOnPattern(const PatternToMatch &P) {
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000733 // Keep track of the matchers and actions to emit.
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +0000734 RuleMatcher M;
735 M.addAction<DebugCommentAction>(P);
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000736
737 // First, analyze the whole pattern.
738 // If the entire pattern has a predicate (e.g., target features), ignore it.
739 if (!P.getPredicates()->getValues().empty())
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +0000740 return failedImport("Pattern has a predicate");
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000741
742 // Physreg imp-defs require additional logic. Ignore the pattern.
743 if (!P.getDstRegs().empty())
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +0000744 return failedImport("Pattern defines a physical register");
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000745
746 // Next, analyze the pattern operators.
747 TreePatternNode *Src = P.getSrcPattern();
748 TreePatternNode *Dst = P.getDstPattern();
749
750 // If the root of either pattern isn't a simple operator, ignore it.
751 if (!isTrivialOperatorNode(Dst))
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +0000752 return failedImport("Dst pattern root isn't a trivial operator");
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000753 if (!isTrivialOperatorNode(Src))
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +0000754 return failedImport("Src pattern root isn't a trivial operator");
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000755
756 Record *DstOp = Dst->getOperator();
757 if (!DstOp->isSubClassOf("Instruction"))
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +0000758 return failedImport("Pattern operator isn't an instruction");
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000759
760 auto &DstI = Target.getInstruction(DstOp);
761
762 auto SrcGIOrNull = findNodeEquiv(Src->getOperator());
763 if (!SrcGIOrNull)
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +0000764 return failedImport("Pattern operator lacks an equivalent Instruction");
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000765 auto &SrcGI = *SrcGIOrNull;
766
767 // The operators look good: match the opcode and mutate it to the new one.
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000768 InstructionMatcher &InsnMatcher = M.addInstructionMatcher();
769 InsnMatcher.addPredicate<InstructionOpcodeMatcher>(&SrcGI);
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000770 auto &DstMIBuilder = M.addAction<BuildMIAction>(&DstI, InsnMatcher);
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000771
772 // Next, analyze the children, only accepting patterns that don't require
773 // any change to operands.
774 if (Src->getNumChildren() != Dst->getNumChildren())
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +0000775 return failedImport("Src/dst patterns have a different # of children");
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000776
777 unsigned OpIdx = 0;
778
779 // Start with the defined operands (i.e., the results of the root operator).
780 if (DstI.Operands.NumDefs != Src->getExtTypes().size())
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +0000781 return failedImport("Src pattern results and dst MI defs are different");
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000782
783 for (const EEVT::TypeSet &Ty : Src->getExtTypes()) {
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000784 const auto &DstIOperand = DstI.Operands[OpIdx];
785 Record *DstIOpRec = DstIOperand.Rec;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000786 if (!DstIOpRec->isSubClassOf("RegisterClass"))
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +0000787 return failedImport("Dst MI def isn't a register class");
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000788
789 auto OpTyOrNone = MVTToLLT(Ty.getConcrete());
790 if (!OpTyOrNone)
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +0000791 return failedImport("Dst operand has an unsupported type");
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000792
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000793 OperandMatcher &OM = InsnMatcher.addOperand(OpIdx, DstIOperand.Name);
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000794 OM.addPredicate<LLTOperandMatcher>(*OpTyOrNone);
795 OM.addPredicate<RegisterBankOperandMatcher>(
796 Target.getRegisterClass(DstIOpRec));
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000797 DstMIBuilder.addRenderer<CopyRenderer>(InsnMatcher, "I", DstIOperand.Name);
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000798 ++OpIdx;
799 }
800
801 // Finally match the used operands (i.e., the children of the root operator).
802 for (unsigned i = 0, e = Src->getNumChildren(); i != e; ++i) {
803 auto *SrcChild = Src->getChild(i);
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000804
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000805 OperandMatcher &OM = InsnMatcher.addOperand(OpIdx++, SrcChild->getName());
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000806
807 // The only non-leaf child we accept is 'bb': it's an operator because
808 // BasicBlockSDNode isn't inline, but in MI it's just another operand.
809 if (!SrcChild->isLeaf()) {
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000810 if (SrcChild->getOperator()->isSubClassOf("SDNode")) {
811 auto &ChildSDNI = CGP.getSDNodeInfo(SrcChild->getOperator());
812 if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") {
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000813 OM.addPredicate<MBBOperandMatcher>();
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000814 continue;
815 }
816 }
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000817 return failedImport("Src pattern child isn't a leaf node or an MBB");
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000818 }
819
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000820 if (SrcChild->hasAnyPredicate())
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +0000821 return failedImport("Src pattern child has predicate");
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000822
823 ArrayRef<EEVT::TypeSet> ChildTypes = SrcChild->getExtTypes();
824 if (ChildTypes.size() != 1)
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +0000825 return failedImport("Src pattern child has multiple results");
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000826
827 auto OpTyOrNone = MVTToLLT(ChildTypes.front().getConcrete());
828 if (!OpTyOrNone)
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +0000829 return failedImport("Src operand has an unsupported type");
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000830 OM.addPredicate<LLTOperandMatcher>(*OpTyOrNone);
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000831
832 if (auto *ChildInt = dyn_cast<IntInit>(SrcChild->getLeafValue())) {
833 OM.addPredicate<IntOperandMatcher>(ChildInt->getValue());
834 continue;
835 }
836
837 if (auto *ChildDefInit = dyn_cast<DefInit>(SrcChild->getLeafValue())) {
838 auto *ChildRec = ChildDefInit->getDef();
839
840 // Otherwise, we're looking for a bog-standard RegisterClass operand.
841 if (!ChildRec->isSubClassOf("RegisterClass"))
842 return failedImport("Src pattern child isn't a RegisterClass");
843
844 OM.addPredicate<RegisterBankOperandMatcher>(
845 Target.getRegisterClass(ChildRec));
846 continue;
847 }
848
849 return failedImport("Src pattern child is an unsupported kind");
850 }
851
852 // Finally render the used operands (i.e., the children of the root operator).
853 for (unsigned i = 0, e = Dst->getNumChildren(); i != e; ++i) {
854 auto *DstChild = Dst->getChild(i);
855
856 // The only non-leaf child we accept is 'bb': it's an operator because
857 // BasicBlockSDNode isn't inline, but in MI it's just another operand.
858 if (!DstChild->isLeaf()) {
859 if (DstChild->getOperator()->isSubClassOf("SDNode")) {
860 auto &ChildSDNI = CGP.getSDNodeInfo(DstChild->getOperator());
861 if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") {
862 DstMIBuilder.addRenderer<CopyRenderer>(InsnMatcher, "I",
863 DstChild->getName());
864 continue;
865 }
866 }
867 return failedImport("Dst pattern child isn't a leaf node or an MBB");
868 }
869
870 // Otherwise, we're looking for a bog-standard RegisterClass operand.
871 if (DstChild->hasAnyPredicate())
872 return failedImport("Dst pattern child has predicate");
873
874 if (auto *ChildDefInit = dyn_cast<DefInit>(DstChild->getLeafValue())) {
875 auto *ChildRec = ChildDefInit->getDef();
876
877 ArrayRef<EEVT::TypeSet> ChildTypes = DstChild->getExtTypes();
878 if (ChildTypes.size() != 1)
879 return failedImport("Dst pattern child has multiple results");
880
881 auto OpTyOrNone = MVTToLLT(ChildTypes.front().getConcrete());
882 if (!OpTyOrNone)
883 return failedImport("Dst operand has an unsupported type");
884
885 if (ChildRec->isSubClassOf("Register")) {
886 DstMIBuilder.addRenderer<AddRegisterRenderer>(ChildRec);
887 continue;
888 }
889
890 if (ChildRec->isSubClassOf("RegisterClass")) {
891 DstMIBuilder.addRenderer<CopyRenderer>(InsnMatcher, "I",
892 DstChild->getName());
893 continue;
894 }
895
896 return failedImport(
897 "Dst pattern child def is an unsupported tablegen class");
898 }
899
900 return failedImport("Src pattern child is an unsupported kind");
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000901 }
902
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +0000903 // We're done with this pattern! It's eligible for GISel emission; return it.
Daniel Sandersb41ce2b2017-02-20 14:31:27 +0000904 ++NumPatternImported;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +0000905 return std::move(M);
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000906}
907
908void GlobalISelEmitter::run(raw_ostream &OS) {
909 // Track the GINodeEquiv definitions.
910 gatherNodeEquivs();
911
912 emitSourceFileHeader(("Global Instruction Selector for the " +
913 Target.getName() + " target").str(), OS);
914 OS << "bool " << Target.getName()
915 << "InstructionSelector::selectImpl"
916 "(MachineInstr &I) const {\n const MachineRegisterInfo &MRI = "
Ahmed Bougacha905af9f2017-02-04 00:47:02 +0000917 "I.getParent()->getParent()->getRegInfo();\n\n";
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000918
Daniel Sandersb41ce2b2017-02-20 14:31:27 +0000919 std::vector<RuleMatcher> Rules;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000920 // Look through the SelectionDAG patterns we found, possibly emitting some.
921 for (const PatternToMatch &Pat : CGP.ptms()) {
922 ++NumPatternTotal;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +0000923 auto MatcherOrErr = runOnPattern(Pat);
924
925 // The pattern analysis can fail, indicating an unsupported pattern.
926 // Report that if we've been asked to do so.
927 if (auto Err = MatcherOrErr.takeError()) {
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000928 if (WarnOnSkippedPatterns) {
929 PrintWarning(Pat.getSrcRecord()->getLoc(),
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +0000930 "Skipped pattern: " + toString(std::move(Err)));
931 } else {
932 consumeError(std::move(Err));
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000933 }
Daniel Sandersb41ce2b2017-02-20 14:31:27 +0000934 ++NumPatternImportsSkipped;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +0000935 continue;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000936 }
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +0000937
Daniel Sandersb41ce2b2017-02-20 14:31:27 +0000938 Rules.push_back(std::move(MatcherOrErr.get()));
939 }
940
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000941 std::stable_sort(Rules.begin(), Rules.end(),
942 [&](const RuleMatcher &A, const RuleMatcher &B) {
Daniel Sanders759ff412017-02-24 13:58:11 +0000943 if (A.isHigherPriorityThan(B)) {
944 assert(!B.isHigherPriorityThan(A) && "Cannot be more important "
945 "and less important at "
946 "the same time");
947 return true;
948 }
949 return false;
950 });
951
Daniel Sandersb41ce2b2017-02-20 14:31:27 +0000952 for (const auto &Rule : Rules) {
953 Rule.emit(OS);
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +0000954 ++NumPatternEmitted;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000955 }
956
957 OS << " return false;\n}\n";
958}
959
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +0000960} // end anonymous namespace
961
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000962//===----------------------------------------------------------------------===//
963
964namespace llvm {
965void EmitGlobalISel(RecordKeeper &RK, raw_ostream &OS) {
966 GlobalISelEmitter(RK).run(OS);
967}
968} // End llvm namespace