blob: 387b797c84d94fc2d4d8a761b3f45c5d2ef2678c [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"
Daniel Sanderse7b0d662017-04-21 15:59:56 +000034#include "SubtargetFeatureInfo.h"
Ahmed Bougacha36f70352016-12-21 23:26:20 +000035#include "llvm/ADT/Optional.h"
Daniel Sanders0ed28822017-04-12 08:23:08 +000036#include "llvm/ADT/SmallSet.h"
Ahmed Bougacha36f70352016-12-21 23:26:20 +000037#include "llvm/ADT/Statistic.h"
38#include "llvm/CodeGen/MachineValueType.h"
39#include "llvm/Support/CommandLine.h"
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +000040#include "llvm/Support/Error.h"
Daniel Sanders52b4ce72017-03-07 23:20:35 +000041#include "llvm/Support/LowLevelTypeImpl.h"
Pavel Labath52a82e22017-02-21 09:19:41 +000042#include "llvm/Support/ScopedPrinter.h"
Ahmed Bougacha36f70352016-12-21 23:26:20 +000043#include "llvm/TableGen/Error.h"
44#include "llvm/TableGen/Record.h"
45#include "llvm/TableGen/TableGenBackend.h"
46#include <string>
Daniel Sanders8a4bae92017-03-14 21:32:08 +000047#include <numeric>
Ahmed Bougacha36f70352016-12-21 23:26:20 +000048using namespace llvm;
49
50#define DEBUG_TYPE "gisel-emitter"
51
52STATISTIC(NumPatternTotal, "Total number of patterns");
Daniel Sandersb41ce2b2017-02-20 14:31:27 +000053STATISTIC(NumPatternImported, "Number of patterns imported from SelectionDAG");
54STATISTIC(NumPatternImportsSkipped, "Number of SelectionDAG imports skipped");
Ahmed Bougacha36f70352016-12-21 23:26:20 +000055STATISTIC(NumPatternEmitted, "Number of patterns emitted");
Daniel Sandersc60abe32017-07-04 15:31:50 +000056/// A unique identifier for a MatchTable.
57static unsigned CurrentMatchTableID = 0;
Ahmed Bougacha36f70352016-12-21 23:26:20 +000058
Daniel Sanders0848b232017-03-27 13:15:13 +000059cl::OptionCategory GlobalISelEmitterCat("Options for -gen-global-isel");
60
Ahmed Bougacha36f70352016-12-21 23:26:20 +000061static cl::opt<bool> WarnOnSkippedPatterns(
62 "warn-on-skipped-patterns",
63 cl::desc("Explain why a pattern was skipped for inclusion "
64 "in the GlobalISel selector"),
Daniel Sanders0848b232017-03-27 13:15:13 +000065 cl::init(false), cl::cat(GlobalISelEmitterCat));
Ahmed Bougacha36f70352016-12-21 23:26:20 +000066
Daniel Sandersbdfebb82017-03-15 20:18:38 +000067namespace {
Ahmed Bougacha36f70352016-12-21 23:26:20 +000068//===- Helper functions ---------------------------------------------------===//
69
Daniel Sanders52b4ce72017-03-07 23:20:35 +000070/// This class stands in for LLT wherever we want to tablegen-erate an
71/// equivalent at compiler run-time.
72class LLTCodeGen {
73private:
74 LLT Ty;
75
76public:
77 LLTCodeGen(const LLT &Ty) : Ty(Ty) {}
78
Daniel Sanders6ab0daa2017-07-04 14:35:06 +000079 void emitCxxEnumValue(raw_ostream &OS) const {
80 if (Ty.isScalar()) {
81 OS << "GILLT_s" << Ty.getSizeInBits();
82 return;
83 }
84 if (Ty.isVector()) {
85 OS << "GILLT_v" << Ty.getNumElements() << "s" << Ty.getScalarSizeInBits();
86 return;
87 }
88 llvm_unreachable("Unhandled LLT");
89 }
90
Daniel Sanders52b4ce72017-03-07 23:20:35 +000091 void emitCxxConstructorCall(raw_ostream &OS) const {
92 if (Ty.isScalar()) {
93 OS << "LLT::scalar(" << Ty.getSizeInBits() << ")";
94 return;
95 }
96 if (Ty.isVector()) {
Daniel Sanders32291982017-06-28 13:50:04 +000097 OS << "LLT::vector(" << Ty.getNumElements() << ", "
98 << Ty.getScalarSizeInBits() << ")";
Daniel Sanders52b4ce72017-03-07 23:20:35 +000099 return;
100 }
101 llvm_unreachable("Unhandled LLT");
102 }
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000103
104 const LLT &get() const { return Ty; }
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000105
106 /// This ordering is used for std::unique() and std::sort(). There's no
107 /// particular logic behind the order.
108 bool operator<(const LLTCodeGen &Other) const {
109 if (!Ty.isValid())
110 return Other.Ty.isValid();
111 if (Ty.isScalar()) {
112 if (!Other.Ty.isValid())
113 return false;
114 if (Other.Ty.isScalar())
115 return Ty.getSizeInBits() < Other.Ty.getSizeInBits();
116 return false;
117 }
118 if (Ty.isVector()) {
119 if (!Other.Ty.isValid() || Other.Ty.isScalar())
120 return false;
121 if (Other.Ty.isVector()) {
122 if (Ty.getNumElements() < Other.Ty.getNumElements())
123 return true;
124 if (Ty.getNumElements() > Other.Ty.getNumElements())
125 return false;
126 return Ty.getSizeInBits() < Other.Ty.getSizeInBits();
127 }
128 return false;
129 }
130 llvm_unreachable("Unhandled LLT");
131 }
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000132};
133
134class InstructionMatcher;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000135/// Convert an MVT to an equivalent LLT if possible, or the invalid LLT() for
136/// MVTs that don't map cleanly to an LLT (e.g., iPTR, *any, ...).
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000137static Optional<LLTCodeGen> MVTToLLT(MVT::SimpleValueType SVT) {
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000138 MVT VT(SVT);
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000139 if (VT.isVector() && VT.getVectorNumElements() != 1)
Daniel Sanders32291982017-06-28 13:50:04 +0000140 return LLTCodeGen(
141 LLT::vector(VT.getVectorNumElements(), VT.getScalarSizeInBits()));
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000142 if (VT.isInteger() || VT.isFloatingPoint())
143 return LLTCodeGen(LLT::scalar(VT.getSizeInBits()));
144 return None;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000145}
146
Daniel Sandersd0656a32017-04-13 09:45:37 +0000147static std::string explainPredicates(const TreePatternNode *N) {
148 std::string Explanation = "";
149 StringRef Separator = "";
150 for (const auto &P : N->getPredicateFns()) {
151 Explanation +=
152 (Separator + P.getOrigPatFragRecord()->getRecord()->getName()).str();
153 if (P.isAlwaysTrue())
154 Explanation += " always-true";
155 if (P.isImmediatePattern())
156 Explanation += " immediate";
157 }
158 return Explanation;
159}
160
Daniel Sandersd0656a32017-04-13 09:45:37 +0000161std::string explainOperator(Record *Operator) {
162 if (Operator->isSubClassOf("SDNode"))
Craig Topper2b8419a2017-05-31 19:01:11 +0000163 return (" (" + Operator->getValueAsString("Opcode") + ")").str();
Daniel Sandersd0656a32017-04-13 09:45:37 +0000164
165 if (Operator->isSubClassOf("Intrinsic"))
166 return (" (Operator is an Intrinsic, " + Operator->getName() + ")").str();
167
168 return " (Operator not understood)";
169}
170
171/// Helper function to let the emitter report skip reason error messages.
172static Error failedImport(const Twine &Reason) {
173 return make_error<StringError>(Reason, inconvertibleErrorCode());
174}
175
176static Error isTrivialOperatorNode(const TreePatternNode *N) {
177 std::string Explanation = "";
178 std::string Separator = "";
179 if (N->isLeaf()) {
Daniel Sanders3334cc02017-05-23 20:02:48 +0000180 if (isa<IntInit>(N->getLeafValue()))
Daniel Sanders452c8ae2017-05-23 19:33:16 +0000181 return Error::success();
182
Daniel Sandersd0656a32017-04-13 09:45:37 +0000183 Explanation = "Is a leaf";
184 Separator = ", ";
185 }
186
187 if (N->hasAnyPredicate()) {
188 Explanation = Separator + "Has a predicate (" + explainPredicates(N) + ")";
189 Separator = ", ";
190 }
191
192 if (N->getTransformFn()) {
193 Explanation += Separator + "Has a transform function";
194 Separator = ", ";
195 }
196
197 if (!N->isLeaf() && !N->hasAnyPredicate() && !N->getTransformFn())
198 return Error::success();
199
200 return failedImport(Explanation);
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000201}
202
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +0000203static Record *getInitValueAsRegClass(Init *V) {
204 if (DefInit *VDefInit = dyn_cast<DefInit>(V)) {
205 if (VDefInit->getDef()->isSubClassOf("RegisterOperand"))
206 return VDefInit->getDef()->getValueAsDef("RegClass");
207 if (VDefInit->getDef()->isSubClassOf("RegisterClass"))
208 return VDefInit->getDef();
209 }
210 return nullptr;
211}
212
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000213std::string
214getNameForFeatureBitset(const std::vector<Record *> &FeatureBitset) {
215 std::string Name = "GIFBS";
216 for (const auto &Feature : FeatureBitset)
217 Name += ("_" + Feature->getName()).str();
218 return Name;
219}
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000220//===- Matchers -----------------------------------------------------------===//
221
Daniel Sandersbee57392017-04-04 13:25:23 +0000222class OperandMatcher;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000223class MatchAction;
224
225/// Generates code to check that a match rule matches.
226class RuleMatcher {
227 /// A list of matchers that all need to succeed for the current rule to match.
228 /// FIXME: This currently supports a single match position but could be
229 /// extended to support multiple positions to support div/rem fusion or
230 /// load-multiple instructions.
231 std::vector<std::unique_ptr<InstructionMatcher>> Matchers;
232
233 /// A list of actions that need to be taken when all predicates in this rule
234 /// have succeeded.
235 std::vector<std::unique_ptr<MatchAction>> Actions;
236
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000237 /// A map of instruction matchers to the local variables created by
238 /// emitCxxCaptureStmts().
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000239 std::map<const InstructionMatcher *, unsigned> InsnVariableIDs;
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000240
241 /// ID for the next instruction variable defined with defineInsnVar()
242 unsigned NextInsnVarID;
243
Daniel Sanderse7b0d662017-04-21 15:59:56 +0000244 std::vector<Record *> RequiredFeatures;
245
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000246public:
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000247 RuleMatcher()
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000248 : Matchers(), Actions(), InsnVariableIDs(), NextInsnVarID(0) {}
Zachary Turnerb7dbd872017-03-20 19:56:52 +0000249 RuleMatcher(RuleMatcher &&Other) = default;
250 RuleMatcher &operator=(RuleMatcher &&Other) = default;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000251
252 InstructionMatcher &addInstructionMatcher();
Daniel Sanderse7b0d662017-04-21 15:59:56 +0000253 void addRequiredFeature(Record *Feature);
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000254 const std::vector<Record *> &getRequiredFeatures() const;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000255
256 template <class Kind, class... Args> Kind &addAction(Args &&... args);
257
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000258 /// Define an instruction without emitting any code to do so.
259 /// This is used for the root of the match.
260 unsigned implicitlyDefineInsnVar(const InstructionMatcher &Matcher);
261 /// Define an instruction and emit corresponding state-machine opcodes.
262 unsigned defineInsnVar(raw_ostream &OS, const InstructionMatcher &Matcher,
263 unsigned InsnVarID, unsigned OpIdx);
264 unsigned getInsnVarID(const InstructionMatcher &InsnMatcher) const;
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000265
Daniel Sandersbee57392017-04-04 13:25:23 +0000266 void emitCxxCapturedInsnList(raw_ostream &OS);
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000267 void emitCxxCaptureStmts(raw_ostream &OS);
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000268
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000269 void emit(raw_ostream &OS);
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000270
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000271 /// Compare the priority of this object and B.
272 ///
273 /// Returns true if this object is more important than B.
274 bool isHigherPriorityThan(const RuleMatcher &B) const;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000275
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000276 /// Report the maximum number of temporary operands needed by the rule
277 /// matcher.
278 unsigned countRendererFns() const;
Daniel Sanders2deea182017-04-22 15:11:04 +0000279
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000280 // FIXME: Remove this as soon as possible
281 InstructionMatcher &insnmatcher_front() const { return *Matchers.front(); }
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000282};
283
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000284template <class PredicateTy> class PredicateListMatcher {
285private:
286 typedef std::vector<std::unique_ptr<PredicateTy>> PredicateVec;
287 PredicateVec Predicates;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000288
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000289public:
290 /// Construct a new operand predicate and add it to the matcher.
291 template <class Kind, class... Args>
292 Kind &addPredicate(Args&&... args) {
Ahmed Bougachab67a3ce2017-01-26 22:07:37 +0000293 Predicates.emplace_back(
294 llvm::make_unique<Kind>(std::forward<Args>(args)...));
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000295 return *static_cast<Kind *>(Predicates.back().get());
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000296 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000297
Daniel Sanders32291982017-06-28 13:50:04 +0000298 typename PredicateVec::const_iterator predicates_begin() const {
299 return Predicates.begin();
300 }
301 typename PredicateVec::const_iterator predicates_end() const {
302 return Predicates.end();
303 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000304 iterator_range<typename PredicateVec::const_iterator> predicates() const {
305 return make_range(predicates_begin(), predicates_end());
306 }
Daniel Sanders32291982017-06-28 13:50:04 +0000307 typename PredicateVec::size_type predicates_size() const {
308 return Predicates.size();
309 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000310
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000311 /// Emit a C++ expression that tests whether all the predicates are met.
Ahmed Bougachab67a3ce2017-01-26 22:07:37 +0000312 template <class... Args>
Daniel Sandersf8c804f2017-01-28 11:10:42 +0000313 void emitCxxPredicateListExpr(raw_ostream &OS, Args &&... args) const {
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000314 if (Predicates.empty()) {
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000315 OS << "// No predicates\n";
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000316 return;
317 }
318
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000319 for (const auto &Predicate : predicates())
Ahmed Bougachab67a3ce2017-01-26 22:07:37 +0000320 Predicate->emitCxxPredicateExpr(OS, std::forward<Args>(args)...);
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000321 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000322};
323
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000324/// Generates code to check a predicate of an operand.
325///
326/// Typical predicates include:
327/// * Operand is a particular register.
328/// * Operand is assigned a particular register bank.
329/// * Operand is an MBB.
330class OperandPredicateMatcher {
331public:
Daniel Sanders759ff412017-02-24 13:58:11 +0000332 /// This enum is used for RTTI and also defines the priority that is given to
333 /// the predicate when generating the matcher code. Kinds with higher priority
334 /// must be tested first.
335 ///
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000336 /// The relative priority of OPM_LLT, OPM_RegBank, and OPM_MBB do not matter
337 /// but OPM_Int must have priority over OPM_RegBank since constant integers
338 /// are represented by a virtual register defined by a G_CONSTANT instruction.
Daniel Sanders759ff412017-02-24 13:58:11 +0000339 enum PredicateKind {
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000340 OPM_ComplexPattern,
Daniel Sandersbee57392017-04-04 13:25:23 +0000341 OPM_Instruction,
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000342 OPM_Int,
Daniel Sanders452c8ae2017-05-23 19:33:16 +0000343 OPM_LiteralInt,
Daniel Sanders759ff412017-02-24 13:58:11 +0000344 OPM_LLT,
345 OPM_RegBank,
346 OPM_MBB,
347 };
348
349protected:
350 PredicateKind Kind;
351
352public:
353 OperandPredicateMatcher(PredicateKind Kind) : Kind(Kind) {}
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000354 virtual ~OperandPredicateMatcher() {}
355
Daniel Sanders759ff412017-02-24 13:58:11 +0000356 PredicateKind getKind() const { return Kind; }
357
Daniel Sandersbee57392017-04-04 13:25:23 +0000358 /// Return the OperandMatcher for the specified operand or nullptr if there
359 /// isn't one by that name in this operand predicate matcher.
360 ///
361 /// InstructionOperandMatcher is the only subclass that can return non-null
362 /// for this.
363 virtual Optional<const OperandMatcher *>
Daniel Sandersdb7ed372017-04-04 13:52:00 +0000364 getOptionalOperand(StringRef SymbolicName) const {
Daniel Sandersbee57392017-04-04 13:25:23 +0000365 assert(!SymbolicName.empty() && "Cannot lookup unnamed operand");
366 return None;
367 }
368
369 /// Emit C++ statements to capture instructions into local variables.
370 ///
371 /// Only InstructionOperandMatcher needs to do anything for this method.
372 virtual void emitCxxCaptureStmts(raw_ostream &OS, RuleMatcher &Rule,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000373 unsigned InsnVarID, unsigned OpIdx) const {}
Daniel Sandersbee57392017-04-04 13:25:23 +0000374
Daniel Sanderse604ef52017-02-20 15:30:43 +0000375 /// Emit a C++ expression that checks the predicate for the given operand.
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000376 virtual void emitCxxPredicateExpr(raw_ostream &OS, RuleMatcher &Rule,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000377 unsigned InsnVarID,
378 unsigned OpIdx) const = 0;
Daniel Sanders759ff412017-02-24 13:58:11 +0000379
380 /// Compare the priority of this object and B.
381 ///
382 /// Returns true if this object is more important than B.
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000383 virtual bool isHigherPriorityThan(const OperandPredicateMatcher &B) const {
384 return Kind < B.Kind;
Daniel Sanders759ff412017-02-24 13:58:11 +0000385 };
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000386
387 /// Report the maximum number of temporary operands needed by the predicate
388 /// matcher.
Daniel Sanders2deea182017-04-22 15:11:04 +0000389 virtual unsigned countRendererFns() const { return 0; }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000390};
391
392/// Generates code to check that an operand is a particular LLT.
393class LLTOperandMatcher : public OperandPredicateMatcher {
394protected:
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000395 LLTCodeGen Ty;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000396
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000397public:
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000398 LLTOperandMatcher(const LLTCodeGen &Ty)
Daniel Sanders759ff412017-02-24 13:58:11 +0000399 : OperandPredicateMatcher(OPM_LLT), Ty(Ty) {}
400
401 static bool classof(const OperandPredicateMatcher *P) {
402 return P->getKind() == OPM_LLT;
403 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000404
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000405 void emitCxxPredicateExpr(raw_ostream &OS, RuleMatcher &Rule,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000406 unsigned InsnVarID, unsigned OpIdx) const override {
407 OS << " GIM_CheckType, /*MI*/" << InsnVarID << ", /*Op*/" << OpIdx
408 << ", /*Type*/";
409 Ty.emitCxxEnumValue(OS);
410 OS << ", \n";
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000411 }
412};
413
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000414/// Generates code to check that an operand is a particular target constant.
415class ComplexPatternOperandMatcher : public OperandPredicateMatcher {
416protected:
Daniel Sanders4f3eb242017-04-05 13:14:03 +0000417 const OperandMatcher &Operand;
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000418 const Record &TheDef;
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000419
Daniel Sanders4f3eb242017-04-05 13:14:03 +0000420 unsigned getAllocatedTemporariesBaseID() const;
421
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000422public:
Daniel Sanders4f3eb242017-04-05 13:14:03 +0000423 ComplexPatternOperandMatcher(const OperandMatcher &Operand,
424 const Record &TheDef)
425 : OperandPredicateMatcher(OPM_ComplexPattern), Operand(Operand),
426 TheDef(TheDef) {}
427
428 static bool classof(const OperandPredicateMatcher *P) {
429 return P->getKind() == OPM_ComplexPattern;
430 }
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000431
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000432 void emitCxxPredicateExpr(raw_ostream &OS, RuleMatcher &Rule,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000433 unsigned InsnVarID, unsigned OpIdx) const override {
Daniel Sanders2deea182017-04-22 15:11:04 +0000434 unsigned ID = getAllocatedTemporariesBaseID();
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000435 OS << " GIM_CheckComplexPattern, /*MI*/" << InsnVarID << ", /*Op*/"
436 << OpIdx << ", /*Renderer*/" << ID << ", GICP_"
437 << TheDef.getName() << ",\n";
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000438 }
439
Daniel Sanders2deea182017-04-22 15:11:04 +0000440 unsigned countRendererFns() const override {
441 return 1;
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000442 }
443};
444
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000445/// Generates code to check that an operand is in a particular register bank.
446class RegisterBankOperandMatcher : public OperandPredicateMatcher {
447protected:
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000448 const CodeGenRegisterClass &RC;
449
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000450public:
Daniel Sanders759ff412017-02-24 13:58:11 +0000451 RegisterBankOperandMatcher(const CodeGenRegisterClass &RC)
452 : OperandPredicateMatcher(OPM_RegBank), RC(RC) {}
453
454 static bool classof(const OperandPredicateMatcher *P) {
455 return P->getKind() == OPM_RegBank;
456 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000457
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000458 void emitCxxPredicateExpr(raw_ostream &OS, RuleMatcher &Rule,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000459 unsigned InsnVarID, unsigned OpIdx) const override {
460 OS << " GIM_CheckRegBankForClass, /*MI*/" << InsnVarID << ", /*Op*/"
461 << OpIdx << ", /*RC*/" << RC.getQualifiedName() << "RegClassID,\n";
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000462 }
463};
464
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000465/// Generates code to check that an operand is a basic block.
466class MBBOperandMatcher : public OperandPredicateMatcher {
467public:
Daniel Sanders759ff412017-02-24 13:58:11 +0000468 MBBOperandMatcher() : OperandPredicateMatcher(OPM_MBB) {}
469
470 static bool classof(const OperandPredicateMatcher *P) {
471 return P->getKind() == OPM_MBB;
472 }
473
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000474 void emitCxxPredicateExpr(raw_ostream &OS, RuleMatcher &Rule,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000475 unsigned InsnVarID, unsigned OpIdx) const override {
476 OS << " GIM_CheckIsMBB, /*MI*/" << InsnVarID << ", /*Op*/" << OpIdx << ",\n";
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000477 }
478};
479
Daniel Sanders452c8ae2017-05-23 19:33:16 +0000480/// Generates code to check that an operand is a G_CONSTANT with a particular
481/// int.
482class ConstantIntOperandMatcher : public OperandPredicateMatcher {
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000483protected:
484 int64_t Value;
485
486public:
Daniel Sanders452c8ae2017-05-23 19:33:16 +0000487 ConstantIntOperandMatcher(int64_t Value)
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000488 : OperandPredicateMatcher(OPM_Int), Value(Value) {}
489
490 static bool classof(const OperandPredicateMatcher *P) {
491 return P->getKind() == OPM_Int;
492 }
493
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000494 void emitCxxPredicateExpr(raw_ostream &OS, RuleMatcher &Rule,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000495 unsigned InsnVarID, unsigned OpIdx) const override {
496 OS << " GIM_CheckConstantInt, /*MI*/" << InsnVarID << ", /*Op*/"
497 << OpIdx << ", " << Value << ",\n";
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000498 }
499};
500
Daniel Sanders452c8ae2017-05-23 19:33:16 +0000501/// Generates code to check that an operand is a raw int (where MO.isImm() or
502/// MO.isCImm() is true).
503class LiteralIntOperandMatcher : public OperandPredicateMatcher {
504protected:
505 int64_t Value;
506
507public:
508 LiteralIntOperandMatcher(int64_t Value)
509 : OperandPredicateMatcher(OPM_LiteralInt), Value(Value) {}
510
511 static bool classof(const OperandPredicateMatcher *P) {
512 return P->getKind() == OPM_LiteralInt;
513 }
514
515 void emitCxxPredicateExpr(raw_ostream &OS, RuleMatcher &Rule,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000516 unsigned InsnVarID, unsigned OpIdx) const override {
517 OS << " GIM_CheckLiteralInt, /*MI*/" << InsnVarID << ", /*Op*/"
518 << OpIdx << ", " << Value << ",\n";
Daniel Sanders452c8ae2017-05-23 19:33:16 +0000519 }
520};
521
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000522/// Generates code to check that a set of predicates match for a particular
523/// operand.
524class OperandMatcher : public PredicateListMatcher<OperandPredicateMatcher> {
525protected:
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000526 InstructionMatcher &Insn;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000527 unsigned OpIdx;
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000528 std::string SymbolicName;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000529
Daniel Sanders4f3eb242017-04-05 13:14:03 +0000530 /// The index of the first temporary variable allocated to this operand. The
531 /// number of allocated temporaries can be found with
Daniel Sanders2deea182017-04-22 15:11:04 +0000532 /// countRendererFns().
Daniel Sanders4f3eb242017-04-05 13:14:03 +0000533 unsigned AllocatedTemporariesBaseID;
534
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000535public:
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000536 OperandMatcher(InstructionMatcher &Insn, unsigned OpIdx,
Daniel Sanders4f3eb242017-04-05 13:14:03 +0000537 const std::string &SymbolicName,
538 unsigned AllocatedTemporariesBaseID)
539 : Insn(Insn), OpIdx(OpIdx), SymbolicName(SymbolicName),
540 AllocatedTemporariesBaseID(AllocatedTemporariesBaseID) {}
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000541
542 bool hasSymbolicName() const { return !SymbolicName.empty(); }
543 const StringRef getSymbolicName() const { return SymbolicName; }
Daniel Sandersffc7d582017-03-29 15:37:18 +0000544 void setSymbolicName(StringRef Name) {
545 assert(SymbolicName.empty() && "Operand already has a symbolic name");
546 SymbolicName = Name;
547 }
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000548 unsigned getOperandIndex() const { return OpIdx; }
549
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000550 std::string getOperandExpr(unsigned InsnVarID) const {
551 return "State.MIs[" + llvm::to_string(InsnVarID) + "]->getOperand(" +
552 llvm::to_string(OpIdx) + ")";
Daniel Sanderse604ef52017-02-20 15:30:43 +0000553 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000554
Daniel Sandersbee57392017-04-04 13:25:23 +0000555 Optional<const OperandMatcher *>
556 getOptionalOperand(StringRef DesiredSymbolicName) const {
557 assert(!DesiredSymbolicName.empty() && "Cannot lookup unnamed operand");
558 if (DesiredSymbolicName == SymbolicName)
559 return this;
560 for (const auto &OP : predicates()) {
561 const auto &MaybeOperand = OP->getOptionalOperand(DesiredSymbolicName);
562 if (MaybeOperand.hasValue())
563 return MaybeOperand.getValue();
564 }
565 return None;
566 }
567
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000568 InstructionMatcher &getInstructionMatcher() const { return Insn; }
569
Daniel Sandersbee57392017-04-04 13:25:23 +0000570 /// Emit C++ statements to capture instructions into local variables.
571 void emitCxxCaptureStmts(raw_ostream &OS, RuleMatcher &Rule,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000572 unsigned InsnVarID) const {
Daniel Sandersbee57392017-04-04 13:25:23 +0000573 for (const auto &Predicate : predicates())
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000574 Predicate->emitCxxCaptureStmts(OS, Rule, InsnVarID, OpIdx);
Daniel Sandersbee57392017-04-04 13:25:23 +0000575 }
576
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000577 /// Emit a C++ expression that tests whether the instruction named in
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000578 /// InsnVarID matches all the predicates and all the operands.
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000579 void emitCxxPredicateExpr(raw_ostream &OS, RuleMatcher &Rule,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000580 unsigned InsnVarID) const {
581 OS << " // MIs[" << InsnVarID << "] ";
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000582 if (SymbolicName.empty())
583 OS << "Operand " << OpIdx;
584 else
585 OS << SymbolicName;
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000586 OS << "\n";
587 emitCxxPredicateListExpr(OS, Rule, InsnVarID, OpIdx);
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000588 }
Daniel Sanders759ff412017-02-24 13:58:11 +0000589
590 /// Compare the priority of this object and B.
591 ///
592 /// Returns true if this object is more important than B.
593 bool isHigherPriorityThan(const OperandMatcher &B) const {
594 // Operand matchers involving more predicates have higher priority.
595 if (predicates_size() > B.predicates_size())
596 return true;
597 if (predicates_size() < B.predicates_size())
598 return false;
599
600 // This assumes that predicates are added in a consistent order.
601 for (const auto &Predicate : zip(predicates(), B.predicates())) {
602 if (std::get<0>(Predicate)->isHigherPriorityThan(*std::get<1>(Predicate)))
603 return true;
604 if (std::get<1>(Predicate)->isHigherPriorityThan(*std::get<0>(Predicate)))
605 return false;
606 }
607
608 return false;
609 };
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000610
611 /// Report the maximum number of temporary operands needed by the operand
612 /// matcher.
Daniel Sanders2deea182017-04-22 15:11:04 +0000613 unsigned countRendererFns() const {
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000614 return std::accumulate(
615 predicates().begin(), predicates().end(), 0,
616 [](unsigned A,
617 const std::unique_ptr<OperandPredicateMatcher> &Predicate) {
Daniel Sanders2deea182017-04-22 15:11:04 +0000618 return A + Predicate->countRendererFns();
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000619 });
620 }
Daniel Sanders4f3eb242017-04-05 13:14:03 +0000621
622 unsigned getAllocatedTemporariesBaseID() const {
623 return AllocatedTemporariesBaseID;
624 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000625};
626
Daniel Sanders4f3eb242017-04-05 13:14:03 +0000627unsigned ComplexPatternOperandMatcher::getAllocatedTemporariesBaseID() const {
628 return Operand.getAllocatedTemporariesBaseID();
629}
630
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000631/// Generates code to check a predicate on an instruction.
632///
633/// Typical predicates include:
634/// * The opcode of the instruction is a particular value.
635/// * The nsw/nuw flag is/isn't set.
636class InstructionPredicateMatcher {
Daniel Sanders759ff412017-02-24 13:58:11 +0000637protected:
638 /// This enum is used for RTTI and also defines the priority that is given to
639 /// the predicate when generating the matcher code. Kinds with higher priority
640 /// must be tested first.
641 enum PredicateKind {
642 IPM_Opcode,
643 };
644
645 PredicateKind Kind;
646
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000647public:
Daniel Sanders8d4d72f2017-02-24 14:53:35 +0000648 InstructionPredicateMatcher(PredicateKind Kind) : Kind(Kind) {}
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000649 virtual ~InstructionPredicateMatcher() {}
650
Daniel Sanders759ff412017-02-24 13:58:11 +0000651 PredicateKind getKind() const { return Kind; }
652
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000653 /// Emit a C++ expression that tests whether the instruction named in
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000654 /// InsnVarID matches the predicate.
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000655 virtual void emitCxxPredicateExpr(raw_ostream &OS, RuleMatcher &Rule,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000656 unsigned InsnVarID) const = 0;
Daniel Sanders759ff412017-02-24 13:58:11 +0000657
658 /// Compare the priority of this object and B.
659 ///
660 /// Returns true if this object is more important than B.
Daniel Sanders32291982017-06-28 13:50:04 +0000661 virtual bool
662 isHigherPriorityThan(const InstructionPredicateMatcher &B) const {
Daniel Sanders759ff412017-02-24 13:58:11 +0000663 return Kind < B.Kind;
664 };
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000665
666 /// Report the maximum number of temporary operands needed by the predicate
667 /// matcher.
Daniel Sanders2deea182017-04-22 15:11:04 +0000668 virtual unsigned countRendererFns() const { return 0; }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000669};
670
671/// Generates code to check the opcode of an instruction.
672class InstructionOpcodeMatcher : public InstructionPredicateMatcher {
673protected:
674 const CodeGenInstruction *I;
675
676public:
Daniel Sanders8d4d72f2017-02-24 14:53:35 +0000677 InstructionOpcodeMatcher(const CodeGenInstruction *I)
678 : InstructionPredicateMatcher(IPM_Opcode), I(I) {}
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000679
Daniel Sanders759ff412017-02-24 13:58:11 +0000680 static bool classof(const InstructionPredicateMatcher *P) {
681 return P->getKind() == IPM_Opcode;
682 }
683
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000684 void emitCxxPredicateExpr(raw_ostream &OS, RuleMatcher &Rule,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000685 unsigned InsnVarID) const override {
686 OS << " GIM_CheckOpcode, /*MI*/" << InsnVarID << ", " << I->Namespace
687 << "::" << I->TheDef->getName() << ",\n";
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000688 }
Daniel Sanders759ff412017-02-24 13:58:11 +0000689
690 /// Compare the priority of this object and B.
691 ///
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000692 /// Returns true if this object is more important than B.
Daniel Sanders32291982017-06-28 13:50:04 +0000693 bool
694 isHigherPriorityThan(const InstructionPredicateMatcher &B) const override {
Daniel Sanders759ff412017-02-24 13:58:11 +0000695 if (InstructionPredicateMatcher::isHigherPriorityThan(B))
696 return true;
697 if (B.InstructionPredicateMatcher::isHigherPriorityThan(*this))
698 return false;
699
700 // Prioritize opcodes for cosmetic reasons in the generated source. Although
701 // this is cosmetic at the moment, we may want to drive a similar ordering
702 // using instruction frequency information to improve compile time.
703 if (const InstructionOpcodeMatcher *BO =
704 dyn_cast<InstructionOpcodeMatcher>(&B))
705 return I->TheDef->getName() < BO->I->TheDef->getName();
706
707 return false;
708 };
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000709};
710
711/// Generates code to check that a set of predicates and operands match for a
712/// particular instruction.
713///
714/// Typical predicates include:
715/// * Has a specific opcode.
716/// * Has an nsw/nuw flag or doesn't.
717class InstructionMatcher
718 : public PredicateListMatcher<InstructionPredicateMatcher> {
719protected:
Daniel Sanders4f3eb242017-04-05 13:14:03 +0000720 typedef std::vector<std::unique_ptr<OperandMatcher>> OperandVec;
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000721
722 /// The operands to match. All rendered operands must be present even if the
723 /// condition is always true.
724 OperandVec Operands;
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000725
726public:
727 /// Add an operand to the matcher.
Daniel Sanders4f3eb242017-04-05 13:14:03 +0000728 OperandMatcher &addOperand(unsigned OpIdx, const std::string &SymbolicName,
729 unsigned AllocatedTemporariesBaseID) {
730 Operands.emplace_back(new OperandMatcher(*this, OpIdx, SymbolicName,
731 AllocatedTemporariesBaseID));
732 return *Operands.back();
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000733 }
734
Daniel Sandersffc7d582017-03-29 15:37:18 +0000735 OperandMatcher &getOperand(unsigned OpIdx) {
736 auto I = std::find_if(Operands.begin(), Operands.end(),
Daniel Sanders4f3eb242017-04-05 13:14:03 +0000737 [&OpIdx](const std::unique_ptr<OperandMatcher> &X) {
738 return X->getOperandIndex() == OpIdx;
Daniel Sandersffc7d582017-03-29 15:37:18 +0000739 });
740 if (I != Operands.end())
Daniel Sanders4f3eb242017-04-05 13:14:03 +0000741 return **I;
Daniel Sandersffc7d582017-03-29 15:37:18 +0000742 llvm_unreachable("Failed to lookup operand");
743 }
744
Daniel Sandersbee57392017-04-04 13:25:23 +0000745 Optional<const OperandMatcher *>
746 getOptionalOperand(StringRef SymbolicName) const {
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000747 assert(!SymbolicName.empty() && "Cannot lookup unnamed operand");
Daniel Sandersbee57392017-04-04 13:25:23 +0000748 for (const auto &Operand : Operands) {
Daniel Sanders4f3eb242017-04-05 13:14:03 +0000749 const auto &OM = Operand->getOptionalOperand(SymbolicName);
Daniel Sandersbee57392017-04-04 13:25:23 +0000750 if (OM.hasValue())
751 return OM.getValue();
752 }
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000753 return None;
754 }
755
Daniel Sandersdb7ed372017-04-04 13:52:00 +0000756 const OperandMatcher &getOperand(StringRef SymbolicName) const {
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000757 Optional<const OperandMatcher *>OM = getOptionalOperand(SymbolicName);
758 if (OM.hasValue())
759 return *OM.getValue();
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000760 llvm_unreachable("Failed to lookup operand");
761 }
762
763 unsigned getNumOperands() const { return Operands.size(); }
Daniel Sandersbee57392017-04-04 13:25:23 +0000764 OperandVec::iterator operands_begin() { return Operands.begin(); }
765 OperandVec::iterator operands_end() { return Operands.end(); }
766 iterator_range<OperandVec::iterator> operands() {
767 return make_range(operands_begin(), operands_end());
768 }
Daniel Sandersffc7d582017-03-29 15:37:18 +0000769 OperandVec::const_iterator operands_begin() const { return Operands.begin(); }
770 OperandVec::const_iterator operands_end() const { return Operands.end(); }
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000771 iterator_range<OperandVec::const_iterator> operands() const {
772 return make_range(operands_begin(), operands_end());
773 }
774
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000775 /// Emit C++ statements to check the shape of the match and capture
776 /// instructions into local variables.
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000777 void emitCxxCaptureStmts(raw_ostream &OS, RuleMatcher &Rule,
778 unsigned InsnID) {
779 OS << " GIM_CheckNumOperands, /*MI*/" << InsnID << ", /*Expected*/"
780 << getNumOperands() << ",\n";
781 for (const auto &Operand : Operands)
782 Operand->emitCxxCaptureStmts(OS, Rule, InsnID);
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000783 }
784
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000785 /// Emit a C++ expression that tests whether the instruction named in
786 /// InsnVarName matches all the predicates and all the operands.
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000787 void emitCxxPredicateExpr(raw_ostream &OS, RuleMatcher &Rule,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000788 unsigned InsnVarID) const {
789 emitCxxPredicateListExpr(OS, Rule, InsnVarID);
790 for (const auto &Operand : Operands)
791 Operand->emitCxxPredicateExpr(OS, Rule, InsnVarID);
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000792 }
Daniel Sanders759ff412017-02-24 13:58:11 +0000793
794 /// Compare the priority of this object and B.
795 ///
796 /// Returns true if this object is more important than B.
797 bool isHigherPriorityThan(const InstructionMatcher &B) const {
798 // Instruction matchers involving more operands have higher priority.
799 if (Operands.size() > B.Operands.size())
800 return true;
801 if (Operands.size() < B.Operands.size())
802 return false;
803
804 for (const auto &Predicate : zip(predicates(), B.predicates())) {
805 if (std::get<0>(Predicate)->isHigherPriorityThan(*std::get<1>(Predicate)))
806 return true;
807 if (std::get<1>(Predicate)->isHigherPriorityThan(*std::get<0>(Predicate)))
808 return false;
809 }
810
811 for (const auto &Operand : zip(Operands, B.Operands)) {
Daniel Sanders4f3eb242017-04-05 13:14:03 +0000812 if (std::get<0>(Operand)->isHigherPriorityThan(*std::get<1>(Operand)))
Daniel Sanders759ff412017-02-24 13:58:11 +0000813 return true;
Daniel Sanders4f3eb242017-04-05 13:14:03 +0000814 if (std::get<1>(Operand)->isHigherPriorityThan(*std::get<0>(Operand)))
Daniel Sanders759ff412017-02-24 13:58:11 +0000815 return false;
816 }
817
818 return false;
819 };
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000820
821 /// Report the maximum number of temporary operands needed by the instruction
822 /// matcher.
Daniel Sanders2deea182017-04-22 15:11:04 +0000823 unsigned countRendererFns() const {
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000824 return std::accumulate(predicates().begin(), predicates().end(), 0,
825 [](unsigned A,
826 const std::unique_ptr<InstructionPredicateMatcher>
827 &Predicate) {
Daniel Sanders2deea182017-04-22 15:11:04 +0000828 return A + Predicate->countRendererFns();
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000829 }) +
Daniel Sanders4f3eb242017-04-05 13:14:03 +0000830 std::accumulate(
831 Operands.begin(), Operands.end(), 0,
832 [](unsigned A, const std::unique_ptr<OperandMatcher> &Operand) {
Daniel Sanders2deea182017-04-22 15:11:04 +0000833 return A + Operand->countRendererFns();
Daniel Sanders4f3eb242017-04-05 13:14:03 +0000834 });
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000835 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000836};
837
Daniel Sandersbee57392017-04-04 13:25:23 +0000838/// Generates code to check that the operand is a register defined by an
839/// instruction that matches the given instruction matcher.
840///
841/// For example, the pattern:
842/// (set $dst, (G_MUL (G_ADD $src1, $src2), $src3))
843/// would use an InstructionOperandMatcher for operand 1 of the G_MUL to match
844/// the:
845/// (G_ADD $src1, $src2)
846/// subpattern.
847class InstructionOperandMatcher : public OperandPredicateMatcher {
848protected:
849 std::unique_ptr<InstructionMatcher> InsnMatcher;
850
851public:
852 InstructionOperandMatcher()
853 : OperandPredicateMatcher(OPM_Instruction),
854 InsnMatcher(new InstructionMatcher()) {}
855
856 static bool classof(const OperandPredicateMatcher *P) {
857 return P->getKind() == OPM_Instruction;
858 }
859
860 InstructionMatcher &getInsnMatcher() const { return *InsnMatcher; }
861
862 Optional<const OperandMatcher *>
863 getOptionalOperand(StringRef SymbolicName) const override {
864 assert(!SymbolicName.empty() && "Cannot lookup unnamed operand");
865 return InsnMatcher->getOptionalOperand(SymbolicName);
866 }
867
868 void emitCxxCaptureStmts(raw_ostream &OS, RuleMatcher &Rule,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000869 unsigned InsnID, unsigned OpIdx) const override {
870 unsigned InsnVarID = Rule.defineInsnVar(OS, *InsnMatcher, InsnID, OpIdx);
871 InsnMatcher->emitCxxCaptureStmts(OS, Rule, InsnVarID);
Daniel Sandersbee57392017-04-04 13:25:23 +0000872 }
873
874 void emitCxxPredicateExpr(raw_ostream &OS, RuleMatcher &Rule,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000875 unsigned InsnVarID_,
876 unsigned OpIdx_) const override {
877 unsigned InsnVarID = Rule.getInsnVarID(*InsnMatcher);
878 InsnMatcher->emitCxxPredicateExpr(OS, Rule, InsnVarID);
Daniel Sandersbee57392017-04-04 13:25:23 +0000879 }
880};
881
Daniel Sanders43c882c2017-02-01 10:53:10 +0000882//===- Actions ------------------------------------------------------------===//
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000883class OperandRenderer {
884public:
Daniel Sanderscc36dbf2017-06-27 10:11:39 +0000885 enum RendererKind {
886 OR_Copy,
887 OR_CopySubReg,
888 OR_Imm,
889 OR_Register,
890 OR_ComplexPattern
891 };
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000892
893protected:
894 RendererKind Kind;
895
896public:
897 OperandRenderer(RendererKind Kind) : Kind(Kind) {}
898 virtual ~OperandRenderer() {}
899
900 RendererKind getKind() const { return Kind; }
901
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000902 virtual void emitCxxRenderStmts(raw_ostream &OS, RuleMatcher &Rule) const = 0;
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000903};
904
905/// A CopyRenderer emits code to copy a single operand from an existing
906/// instruction to the one being built.
907class CopyRenderer : public OperandRenderer {
908protected:
909 /// The matcher for the instruction that this operand is copied from.
910 /// This provides the facility for looking up an a operand by it's name so
911 /// that it can be used as a source for the instruction being built.
912 const InstructionMatcher &Matched;
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000913 /// The name of the operand.
914 const StringRef SymbolicName;
915
916public:
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000917 CopyRenderer(const InstructionMatcher &Matched, StringRef SymbolicName)
918 : OperandRenderer(OR_Copy), Matched(Matched), SymbolicName(SymbolicName) {
919 }
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000920
921 static bool classof(const OperandRenderer *R) {
922 return R->getKind() == OR_Copy;
923 }
924
925 const StringRef getSymbolicName() const { return SymbolicName; }
926
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000927 void emitCxxRenderStmts(raw_ostream &OS, RuleMatcher &Rule) const override {
928 const OperandMatcher &Operand = Matched.getOperand(SymbolicName);
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000929 unsigned InsnVarID =
930 Rule.getInsnVarID(Operand.getInstructionMatcher());
931 std::string OperandExpr = Operand.getOperandExpr(InsnVarID);
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000932 OS << " MIB.add(" << OperandExpr << "/*" << SymbolicName << "*/);\n";
933 }
934};
935
Daniel Sanderscc36dbf2017-06-27 10:11:39 +0000936/// A CopySubRegRenderer emits code to copy a single register operand from an
937/// existing instruction to the one being built and indicate that only a
938/// subregister should be copied.
939class CopySubRegRenderer : public OperandRenderer {
940protected:
941 /// The matcher for the instruction that this operand is copied from.
942 /// This provides the facility for looking up an a operand by it's name so
943 /// that it can be used as a source for the instruction being built.
944 const InstructionMatcher &Matched;
945 /// The name of the operand.
946 const StringRef SymbolicName;
947 /// The subregister to extract.
948 const CodeGenSubRegIndex *SubReg;
949
950public:
951 CopySubRegRenderer(const InstructionMatcher &Matched, StringRef SymbolicName,
952 const CodeGenSubRegIndex *SubReg)
953 : OperandRenderer(OR_CopySubReg), Matched(Matched),
954 SymbolicName(SymbolicName), SubReg(SubReg) {}
955
956 static bool classof(const OperandRenderer *R) {
957 return R->getKind() == OR_CopySubReg;
958 }
959
960 const StringRef getSymbolicName() const { return SymbolicName; }
961
962 void emitCxxRenderStmts(raw_ostream &OS, RuleMatcher &Rule) const override {
963 const OperandMatcher &Operand = Matched.getOperand(SymbolicName);
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000964 unsigned InsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
965 std::string OperandExpr = Operand.getOperandExpr(InsnVarID);
Daniel Sanderscc36dbf2017-06-27 10:11:39 +0000966 OS << " MIB.addReg(" << OperandExpr << ".getReg() /*" << SymbolicName
967 << "*/, 0, " << SubReg->EnumValue << ");\n";
968 }
969};
970
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000971/// Adds a specific physical register to the instruction being built.
972/// This is typically useful for WZR/XZR on AArch64.
973class AddRegisterRenderer : public OperandRenderer {
974protected:
975 const Record *RegisterDef;
976
977public:
978 AddRegisterRenderer(const Record *RegisterDef)
979 : OperandRenderer(OR_Register), RegisterDef(RegisterDef) {}
980
981 static bool classof(const OperandRenderer *R) {
982 return R->getKind() == OR_Register;
983 }
984
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000985 void emitCxxRenderStmts(raw_ostream &OS, RuleMatcher &Rule) const override {
Diana Picus8abcbbb2017-05-02 09:40:49 +0000986 OS << " MIB.addReg(" << (RegisterDef->getValue("Namespace")
987 ? RegisterDef->getValueAsString("Namespace")
988 : "")
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000989 << "::" << RegisterDef->getName() << ");\n";
990 }
991};
992
Daniel Sanders0ed28822017-04-12 08:23:08 +0000993/// Adds a specific immediate to the instruction being built.
994class ImmRenderer : public OperandRenderer {
995protected:
996 int64_t Imm;
997
998public:
999 ImmRenderer(int64_t Imm)
1000 : OperandRenderer(OR_Imm), Imm(Imm) {}
1001
1002 static bool classof(const OperandRenderer *R) {
1003 return R->getKind() == OR_Imm;
1004 }
1005
1006 void emitCxxRenderStmts(raw_ostream &OS, RuleMatcher &Rule) const override {
1007 OS << " MIB.addImm(" << Imm << ");\n";
1008 }
1009};
1010
Daniel Sanders2deea182017-04-22 15:11:04 +00001011/// Adds operands by calling a renderer function supplied by the ComplexPattern
1012/// matcher function.
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001013class RenderComplexPatternOperand : public OperandRenderer {
1014private:
1015 const Record &TheDef;
Daniel Sanders2deea182017-04-22 15:11:04 +00001016 /// The name of the operand.
1017 const StringRef SymbolicName;
1018 /// The renderer number. This must be unique within a rule since it's used to
1019 /// identify a temporary variable to hold the renderer function.
1020 unsigned RendererID;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001021
1022 unsigned getNumOperands() const {
1023 return TheDef.getValueAsDag("Operands")->getNumArgs();
1024 }
1025
1026public:
Daniel Sanders2deea182017-04-22 15:11:04 +00001027 RenderComplexPatternOperand(const Record &TheDef, StringRef SymbolicName,
1028 unsigned RendererID)
1029 : OperandRenderer(OR_ComplexPattern), TheDef(TheDef),
1030 SymbolicName(SymbolicName), RendererID(RendererID) {}
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001031
1032 static bool classof(const OperandRenderer *R) {
1033 return R->getKind() == OR_ComplexPattern;
1034 }
1035
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001036 void emitCxxRenderStmts(raw_ostream &OS, RuleMatcher &Rule) const override {
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001037 OS << " State.Renderers[" << RendererID << "](MIB);\n";
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001038 }
1039};
1040
Ahmed Bougacha56ca3a92017-02-04 00:47:10 +00001041/// An action taken when all Matcher predicates succeeded for a parent rule.
1042///
1043/// Typical actions include:
1044/// * Changing the opcode of an instruction.
1045/// * Adding an operand to an instruction.
Daniel Sanders43c882c2017-02-01 10:53:10 +00001046class MatchAction {
1047public:
1048 virtual ~MatchAction() {}
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001049
1050 /// Emit the C++ statements to implement the action.
1051 ///
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001052 /// \param RecycleVarName If given, it's an instruction to recycle. The
1053 /// requirements on the instruction vary from action to
1054 /// action.
1055 virtual void emitCxxActionStmts(raw_ostream &OS, RuleMatcher &Rule,
1056 StringRef RecycleVarName) const = 0;
Daniel Sanders43c882c2017-02-01 10:53:10 +00001057};
1058
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +00001059/// Generates a comment describing the matched rule being acted upon.
1060class DebugCommentAction : public MatchAction {
1061private:
1062 const PatternToMatch &P;
1063
1064public:
1065 DebugCommentAction(const PatternToMatch &P) : P(P) {}
1066
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001067 void emitCxxActionStmts(raw_ostream &OS, RuleMatcher &Rule,
1068 StringRef RecycleVarName) const override {
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001069 OS << " // " << *P.getSrcPattern() << " => " << *P.getDstPattern() << "\n";
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +00001070 }
1071};
1072
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001073/// Generates code to build an instruction or mutate an existing instruction
1074/// into the desired instruction when this is possible.
1075class BuildMIAction : public MatchAction {
Daniel Sanders43c882c2017-02-01 10:53:10 +00001076private:
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00001077 std::string Name;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001078 const CodeGenInstruction *I;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001079 const InstructionMatcher &Matched;
1080 std::vector<std::unique_ptr<OperandRenderer>> OperandRenderers;
1081
1082 /// True if the instruction can be built solely by mutating the opcode.
1083 bool canMutate() const {
Daniel Sanderse9fdba32017-04-29 17:30:09 +00001084 if (OperandRenderers.size() != Matched.getNumOperands())
1085 return false;
1086
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001087 for (const auto &Renderer : enumerate(OperandRenderers)) {
Zachary Turner309a0882017-03-13 16:24:10 +00001088 if (const auto *Copy = dyn_cast<CopyRenderer>(&*Renderer.value())) {
Daniel Sanders3016d3c2017-04-22 14:31:28 +00001089 const OperandMatcher &OM = Matched.getOperand(Copy->getSymbolicName());
1090 if (&Matched != &OM.getInstructionMatcher() ||
1091 OM.getOperandIndex() != Renderer.index())
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001092 return false;
1093 } else
1094 return false;
1095 }
1096
1097 return true;
1098 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001099
Daniel Sanders43c882c2017-02-01 10:53:10 +00001100public:
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00001101 BuildMIAction(const StringRef Name, const CodeGenInstruction *I,
1102 const InstructionMatcher &Matched)
1103 : Name(Name), I(I), Matched(Matched) {}
Daniel Sanders43c882c2017-02-01 10:53:10 +00001104
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001105 template <class Kind, class... Args>
1106 Kind &addRenderer(Args&&... args) {
1107 OperandRenderers.emplace_back(
1108 llvm::make_unique<Kind>(std::forward<Args>(args)...));
1109 return *static_cast<Kind *>(OperandRenderers.back().get());
1110 }
1111
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001112 void emitCxxActionStmts(raw_ostream &OS, RuleMatcher &Rule,
1113 StringRef RecycleVarName) const override {
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001114 if (canMutate()) {
Tim Northover4340d642017-03-20 21:58:23 +00001115 OS << " " << RecycleVarName << ".setDesc(TII.get(" << I->Namespace
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001116 << "::" << I->TheDef->getName() << "));\n";
Tim Northover4340d642017-03-20 21:58:23 +00001117
1118 if (!I->ImplicitDefs.empty() || !I->ImplicitUses.empty()) {
1119 OS << " auto MIB = MachineInstrBuilder(MF, &" << RecycleVarName
1120 << ");\n";
1121
1122 for (auto Def : I->ImplicitDefs) {
Diana Picus8abcbbb2017-05-02 09:40:49 +00001123 auto Namespace = Def->getValue("Namespace")
1124 ? Def->getValueAsString("Namespace")
1125 : "";
Tim Northover4340d642017-03-20 21:58:23 +00001126 OS << " MIB.addDef(" << Namespace << "::" << Def->getName()
1127 << ", RegState::Implicit);\n";
1128 }
1129 for (auto Use : I->ImplicitUses) {
Diana Picus8abcbbb2017-05-02 09:40:49 +00001130 auto Namespace = Use->getValue("Namespace")
1131 ? Use->getValueAsString("Namespace")
1132 : "";
Tim Northover4340d642017-03-20 21:58:23 +00001133 OS << " MIB.addUse(" << Namespace << "::" << Use->getName()
1134 << ", RegState::Implicit);\n";
1135 }
1136 }
1137
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00001138 OS << " MachineInstr &" << Name << " = " << RecycleVarName << ";\n";
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001139 return;
1140 }
1141
1142 // TODO: Simple permutation looks like it could be almost as common as
1143 // mutation due to commutative operations.
1144
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001145 OS << " MachineInstrBuilder MIB = BuildMI(*I.getParent(), I, "
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001146 "I.getDebugLoc(), TII.get("
1147 << I->Namespace << "::" << I->TheDef->getName() << "));\n";
1148 for (const auto &Renderer : OperandRenderers)
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001149 Renderer->emitCxxRenderStmts(OS, Rule);
Daniel Sandersbee57392017-04-04 13:25:23 +00001150 OS << " for (const auto *FromMI : ";
1151 Rule.emitCxxCapturedInsnList(OS);
1152 OS << ")\n";
1153 OS << " for (const auto &MMO : FromMI->memoperands())\n";
1154 OS << " MIB.addMemOperand(MMO);\n";
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001155 OS << " " << RecycleVarName << ".eraseFromParent();\n";
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00001156 OS << " MachineInstr &" << Name << " = *MIB;\n";
1157 }
1158};
1159
1160/// Generates code to constrain the operands of an output instruction to the
1161/// register classes specified by the definition of that instruction.
1162class ConstrainOperandsToDefinitionAction : public MatchAction {
1163 std::string Name;
1164
1165public:
1166 ConstrainOperandsToDefinitionAction(const StringRef Name) : Name(Name) {}
1167
1168 void emitCxxActionStmts(raw_ostream &OS, RuleMatcher &Rule,
1169 StringRef RecycleVarName) const override {
Daniel Sanders32291982017-06-28 13:50:04 +00001170 OS << " constrainSelectedInstRegOperands(" << Name
1171 << ", TII, TRI, RBI);\n";
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00001172 }
1173};
1174
1175/// Generates code to constrain the specified operand of an output instruction
1176/// to the specified register class.
1177class ConstrainOperandToRegClassAction : public MatchAction {
1178 std::string Name;
1179 unsigned OpIdx;
1180 const CodeGenRegisterClass &RC;
1181
1182public:
1183 ConstrainOperandToRegClassAction(const StringRef Name, unsigned OpIdx,
1184 const CodeGenRegisterClass &RC)
1185 : Name(Name), OpIdx(OpIdx), RC(RC) {}
1186
1187 void emitCxxActionStmts(raw_ostream &OS, RuleMatcher &Rule,
1188 StringRef RecycleVarName) const override {
1189 OS << " constrainOperandRegToRegClass(" << Name << ", " << OpIdx
1190 << ", " << RC.getQualifiedName() << "RegClass, TII, TRI, RBI);\n";
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001191 }
1192};
1193
Daniel Sandersbdfebb82017-03-15 20:18:38 +00001194InstructionMatcher &RuleMatcher::addInstructionMatcher() {
1195 Matchers.emplace_back(new InstructionMatcher());
1196 return *Matchers.back();
1197}
Ahmed Bougacha56ca3a92017-02-04 00:47:10 +00001198
Daniel Sanderse7b0d662017-04-21 15:59:56 +00001199void RuleMatcher::addRequiredFeature(Record *Feature) {
1200 RequiredFeatures.push_back(Feature);
1201}
1202
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001203const std::vector<Record *> &RuleMatcher::getRequiredFeatures() const {
1204 return RequiredFeatures;
1205}
1206
Daniel Sandersbdfebb82017-03-15 20:18:38 +00001207template <class Kind, class... Args>
1208Kind &RuleMatcher::addAction(Args &&... args) {
1209 Actions.emplace_back(llvm::make_unique<Kind>(std::forward<Args>(args)...));
1210 return *static_cast<Kind *>(Actions.back().get());
1211}
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001212
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001213unsigned
1214RuleMatcher::implicitlyDefineInsnVar(const InstructionMatcher &Matcher) {
1215 unsigned NewInsnVarID = NextInsnVarID++;
1216 InsnVariableIDs[&Matcher] = NewInsnVarID;
1217 return NewInsnVarID;
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001218}
1219
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001220unsigned RuleMatcher::defineInsnVar(raw_ostream &OS,
1221 const InstructionMatcher &Matcher,
1222 unsigned InsnID, unsigned OpIdx) {
1223 unsigned NewInsnVarID = implicitlyDefineInsnVar(Matcher);
1224 OS << " GIM_RecordInsn, /*DefineMI*/" << NewInsnVarID << ", /*MI*/"
1225 << InsnID << ", /*OpIdx*/" << OpIdx << ", // MIs[" << NewInsnVarID
1226 << "]\n";
1227 return NewInsnVarID;
1228}
1229
1230unsigned RuleMatcher::getInsnVarID(const InstructionMatcher &InsnMatcher) const {
1231 const auto &I = InsnVariableIDs.find(&InsnMatcher);
1232 if (I != InsnVariableIDs.end())
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001233 return I->second;
1234 llvm_unreachable("Matched Insn was not captured in a local variable");
1235}
1236
Daniel Sanders32291982017-06-28 13:50:04 +00001237/// Emit a C++ initializer_list containing references to every matched
1238/// instruction.
Daniel Sandersbee57392017-04-04 13:25:23 +00001239void RuleMatcher::emitCxxCapturedInsnList(raw_ostream &OS) {
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001240 SmallVector<unsigned, 2> IDs;
1241 for (const auto &Pair : InsnVariableIDs)
1242 IDs.push_back(Pair.second);
1243 std::sort(IDs.begin(), IDs.end());
Daniel Sanders9e4817d2017-04-04 14:27:06 +00001244
1245 OS << "{";
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001246 for (const auto &ID : IDs)
1247 OS << "State.MIs[" << ID << "], ";
Daniel Sandersbee57392017-04-04 13:25:23 +00001248 OS << "}";
1249}
1250
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001251/// Emit C++ statements to check the shape of the match and capture
1252/// instructions into local variables.
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001253void RuleMatcher::emitCxxCaptureStmts(raw_ostream &OS) {
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001254 assert(Matchers.size() == 1 && "Cannot handle multi-root matchers yet");
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001255 unsigned InsnVarID = implicitlyDefineInsnVar(*Matchers.front());
1256 Matchers.front()->emitCxxCaptureStmts(OS, *this, InsnVarID);
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001257}
1258
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001259void RuleMatcher::emit(raw_ostream &OS) {
Daniel Sandersbdfebb82017-03-15 20:18:38 +00001260 if (Matchers.empty())
1261 llvm_unreachable("Unexpected empty matcher!");
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001262
Daniel Sandersbdfebb82017-03-15 20:18:38 +00001263 // The representation supports rules that require multiple roots such as:
1264 // %ptr(p0) = ...
1265 // %elt0(s32) = G_LOAD %ptr
1266 // %1(p0) = G_ADD %ptr, 4
1267 // %elt1(s32) = G_LOAD p0 %1
1268 // which could be usefully folded into:
1269 // %ptr(p0) = ...
1270 // %elt0(s32), %elt1(s32) = TGT_LOAD_PAIR %ptr
1271 // on some targets but we don't need to make use of that yet.
1272 assert(Matchers.size() == 1 && "Cannot handle multi-root matchers yet");
Daniel Sanderse7b0d662017-04-21 15:59:56 +00001273
Daniel Sandersc60abe32017-07-04 15:31:50 +00001274 OS << " const static int64_t MatchTable" << CurrentMatchTableID << "[] = {\n";
Daniel Sanderse7b0d662017-04-21 15:59:56 +00001275 if (!RequiredFeatures.empty()) {
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001276 OS << " GIM_CheckFeatures, " << getNameForFeatureBitset(RequiredFeatures)
1277 << ",\n";
Daniel Sanderse7b0d662017-04-21 15:59:56 +00001278 }
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001279
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001280
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001281 emitCxxCaptureStmts(OS);
1282
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001283 Matchers.front()->emitCxxPredicateExpr(OS, *this,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001284 getInsnVarID(*Matchers.front()));
1285
1286 OS << " GIM_Accept,\n"
1287 << " };\n"
1288 << " State.MIs.clear();\n"
1289 << " State.MIs.push_back(&I);\n"
1290 << " if (executeMatchTable(*this, State, MatcherInfo, MatchTable"
Daniel Sandersc60abe32017-07-04 15:31:50 +00001291 << CurrentMatchTableID << ", MRI, TRI, RBI, AvailableFeatures)) {\n";
Daniel Sandersbdfebb82017-03-15 20:18:38 +00001292
Daniel Sandersbee57392017-04-04 13:25:23 +00001293 // We must also check if it's safe to fold the matched instructions.
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001294 if (InsnVariableIDs.size() >= 2) {
Galina Kistanova1754fee2017-05-25 01:51:53 +00001295 // Invert the map to create stable ordering (by var names)
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001296 SmallVector<unsigned, 2> InsnIDs;
1297 for (const auto &Pair : InsnVariableIDs) {
Daniel Sandersbee57392017-04-04 13:25:23 +00001298 // Skip the root node since it isn't moving anywhere. Everything else is
1299 // sinking to meet it.
1300 if (Pair.first == Matchers.front().get())
1301 continue;
1302
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001303 InsnIDs.push_back(Pair.second);
Galina Kistanova1754fee2017-05-25 01:51:53 +00001304 }
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001305 std::sort(InsnIDs.begin(), InsnIDs.end());
Galina Kistanova1754fee2017-05-25 01:51:53 +00001306
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001307 for (const auto &InsnID : InsnIDs) {
Daniel Sandersbee57392017-04-04 13:25:23 +00001308 // Reject the difficult cases until we have a more accurate check.
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001309 OS << " if (!isObviouslySafeToFold(*State.MIs[" << InsnID << "]))\n"
1310 << " return false;\n";
Daniel Sandersbee57392017-04-04 13:25:23 +00001311
1312 // FIXME: Emit checks to determine it's _actually_ safe to fold and/or
1313 // account for unsafe cases.
1314 //
1315 // Example:
1316 // MI1--> %0 = ...
1317 // %1 = ... %0
1318 // MI0--> %2 = ... %0
1319 // It's not safe to erase MI1. We currently handle this by not
1320 // erasing %0 (even when it's dead).
1321 //
1322 // Example:
1323 // MI1--> %0 = load volatile @a
1324 // %1 = load volatile @a
1325 // MI0--> %2 = ... %0
1326 // It's not safe to sink %0's def past %1. We currently handle
1327 // this by rejecting all loads.
1328 //
1329 // Example:
1330 // MI1--> %0 = load @a
1331 // %1 = store @a
1332 // MI0--> %2 = ... %0
1333 // It's not safe to sink %0's def past %1. We currently handle
1334 // this by rejecting all loads.
1335 //
1336 // Example:
1337 // G_CONDBR %cond, @BB1
1338 // BB0:
1339 // MI1--> %0 = load @a
1340 // G_BR @BB1
1341 // BB1:
1342 // MI0--> %2 = ... %0
1343 // It's not always safe to sink %0 across control flow. In this
1344 // case it may introduce a memory fault. We currentl handle this
1345 // by rejecting all loads.
1346 }
1347 }
1348
Daniel Sandersbdfebb82017-03-15 20:18:38 +00001349 for (const auto &MA : Actions) {
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001350 MA->emitCxxActionStmts(OS, *this, "I");
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001351 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001352
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001353 OS << " return true;\n";
1354 OS << " }\n\n";
Daniel Sandersbdfebb82017-03-15 20:18:38 +00001355}
Daniel Sanders43c882c2017-02-01 10:53:10 +00001356
Daniel Sandersbdfebb82017-03-15 20:18:38 +00001357bool RuleMatcher::isHigherPriorityThan(const RuleMatcher &B) const {
1358 // Rules involving more match roots have higher priority.
1359 if (Matchers.size() > B.Matchers.size())
1360 return true;
1361 if (Matchers.size() < B.Matchers.size())
Daniel Sanders759ff412017-02-24 13:58:11 +00001362 return false;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001363
Daniel Sandersbdfebb82017-03-15 20:18:38 +00001364 for (const auto &Matcher : zip(Matchers, B.Matchers)) {
1365 if (std::get<0>(Matcher)->isHigherPriorityThan(*std::get<1>(Matcher)))
1366 return true;
1367 if (std::get<1>(Matcher)->isHigherPriorityThan(*std::get<0>(Matcher)))
1368 return false;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001369 }
Daniel Sandersbdfebb82017-03-15 20:18:38 +00001370
1371 return false;
Simon Pilgrima7d1da82017-03-15 22:50:47 +00001372}
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001373
Daniel Sanders2deea182017-04-22 15:11:04 +00001374unsigned RuleMatcher::countRendererFns() const {
Daniel Sandersbdfebb82017-03-15 20:18:38 +00001375 return std::accumulate(
1376 Matchers.begin(), Matchers.end(), 0,
1377 [](unsigned A, const std::unique_ptr<InstructionMatcher> &Matcher) {
Daniel Sanders2deea182017-04-22 15:11:04 +00001378 return A + Matcher->countRendererFns();
Daniel Sandersbdfebb82017-03-15 20:18:38 +00001379 });
1380}
1381
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001382//===- GlobalISelEmitter class --------------------------------------------===//
1383
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00001384class GlobalISelEmitter {
1385public:
1386 explicit GlobalISelEmitter(RecordKeeper &RK);
1387 void run(raw_ostream &OS);
1388
1389private:
1390 const RecordKeeper &RK;
1391 const CodeGenDAGPatterns CGP;
1392 const CodeGenTarget &Target;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00001393 CodeGenRegBank CGRegs;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00001394
1395 /// Keep track of the equivalence between SDNodes and Instruction.
1396 /// This is defined using 'GINodeEquiv' in the target description.
1397 DenseMap<Record *, const CodeGenInstruction *> NodeEquivs;
1398
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001399 /// Keep track of the equivalence between ComplexPattern's and
1400 /// GIComplexOperandMatcher. Map entries are specified by subclassing
1401 /// GIComplexPatternEquiv.
1402 DenseMap<const Record *, const Record *> ComplexPatternEquivs;
1403
Daniel Sanderse7b0d662017-04-21 15:59:56 +00001404 // Map of predicates to their subtarget features.
Daniel Sanderse9fdba32017-04-29 17:30:09 +00001405 SubtargetFeatureInfoMap SubtargetFeatures;
Daniel Sanderse7b0d662017-04-21 15:59:56 +00001406
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00001407 void gatherNodeEquivs();
Daniel Sandersbdfebb82017-03-15 20:18:38 +00001408 const CodeGenInstruction *findNodeEquiv(Record *N) const;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00001409
Daniel Sanderse7b0d662017-04-21 15:59:56 +00001410 Error importRulePredicates(RuleMatcher &M, ArrayRef<Init *> Predicates);
Daniel Sandersffc7d582017-03-29 15:37:18 +00001411 Expected<InstructionMatcher &>
Daniel Sandersc270c502017-03-30 09:36:33 +00001412 createAndImportSelDAGMatcher(InstructionMatcher &InsnMatcher,
1413 const TreePatternNode *Src) const;
1414 Error importChildMatcher(InstructionMatcher &InsnMatcher,
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001415 const TreePatternNode *SrcChild, unsigned OpIdx,
Daniel Sandersc270c502017-03-30 09:36:33 +00001416 unsigned &TempOpIdx) const;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00001417 Expected<BuildMIAction &>
1418 createAndImportInstructionRenderer(RuleMatcher &M, const TreePatternNode *Dst,
1419 const InstructionMatcher &InsnMatcher);
Daniel Sandersc270c502017-03-30 09:36:33 +00001420 Error importExplicitUseRenderer(BuildMIAction &DstMIBuilder,
1421 TreePatternNode *DstChild,
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001422 const InstructionMatcher &InsnMatcher) const;
Diana Picus382602f2017-05-17 08:57:28 +00001423 Error importDefaultOperandRenderers(BuildMIAction &DstMIBuilder,
1424 DagInit *DefaultOps) const;
Daniel Sandersc270c502017-03-30 09:36:33 +00001425 Error
Daniel Sandersffc7d582017-03-29 15:37:18 +00001426 importImplicitDefRenderers(BuildMIAction &DstMIBuilder,
1427 const std::vector<Record *> &ImplicitDefs) const;
1428
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00001429 /// Analyze pattern \p P, returning a matcher for it if possible.
1430 /// Otherwise, return an Error explaining why we don't support it.
1431 Expected<RuleMatcher> runOnPattern(const PatternToMatch &P);
Daniel Sanderse7b0d662017-04-21 15:59:56 +00001432
1433 void declareSubtargetFeature(Record *Predicate);
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00001434};
1435
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001436void GlobalISelEmitter::gatherNodeEquivs() {
1437 assert(NodeEquivs.empty());
1438 for (Record *Equiv : RK.getAllDerivedDefinitions("GINodeEquiv"))
1439 NodeEquivs[Equiv->getValueAsDef("Node")] =
1440 &Target.getInstruction(Equiv->getValueAsDef("I"));
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001441
1442 assert(ComplexPatternEquivs.empty());
1443 for (Record *Equiv : RK.getAllDerivedDefinitions("GIComplexPatternEquiv")) {
1444 Record *SelDAGEquiv = Equiv->getValueAsDef("SelDAGEquivalent");
1445 if (!SelDAGEquiv)
1446 continue;
1447 ComplexPatternEquivs[SelDAGEquiv] = Equiv;
1448 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001449}
1450
Daniel Sandersbdfebb82017-03-15 20:18:38 +00001451const CodeGenInstruction *GlobalISelEmitter::findNodeEquiv(Record *N) const {
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001452 return NodeEquivs.lookup(N);
1453}
1454
1455GlobalISelEmitter::GlobalISelEmitter(RecordKeeper &RK)
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00001456 : RK(RK), CGP(RK), Target(CGP.getTargetInfo()), CGRegs(RK) {}
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001457
1458//===- Emitter ------------------------------------------------------------===//
1459
Daniel Sandersc270c502017-03-30 09:36:33 +00001460Error
Daniel Sandersffc7d582017-03-29 15:37:18 +00001461GlobalISelEmitter::importRulePredicates(RuleMatcher &M,
Daniel Sanderse7b0d662017-04-21 15:59:56 +00001462 ArrayRef<Init *> Predicates) {
1463 for (const Init *Predicate : Predicates) {
1464 const DefInit *PredicateDef = static_cast<const DefInit *>(Predicate);
1465 declareSubtargetFeature(PredicateDef->getDef());
1466 M.addRequiredFeature(PredicateDef->getDef());
1467 }
1468
Daniel Sandersc270c502017-03-30 09:36:33 +00001469 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00001470}
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001471
Daniel Sandersc270c502017-03-30 09:36:33 +00001472Expected<InstructionMatcher &> GlobalISelEmitter::createAndImportSelDAGMatcher(
1473 InstructionMatcher &InsnMatcher, const TreePatternNode *Src) const {
Daniel Sandersffc7d582017-03-29 15:37:18 +00001474 // Start with the defined operands (i.e., the results of the root operator).
1475 if (Src->getExtTypes().size() > 1)
1476 return failedImport("Src pattern has multiple results");
1477
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001478 if (Src->isLeaf()) {
1479 Init *SrcInit = Src->getLeafValue();
Daniel Sanders3334cc02017-05-23 20:02:48 +00001480 if (isa<IntInit>(SrcInit)) {
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001481 InsnMatcher.addPredicate<InstructionOpcodeMatcher>(
1482 &Target.getInstruction(RK.getDef("G_CONSTANT")));
1483 } else
Daniel Sanders32291982017-06-28 13:50:04 +00001484 return failedImport(
1485 "Unable to deduce gMIR opcode to handle Src (which is a leaf)");
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001486 } else {
1487 auto SrcGIOrNull = findNodeEquiv(Src->getOperator());
1488 if (!SrcGIOrNull)
1489 return failedImport("Pattern operator lacks an equivalent Instruction" +
1490 explainOperator(Src->getOperator()));
1491 auto &SrcGI = *SrcGIOrNull;
Daniel Sandersffc7d582017-03-29 15:37:18 +00001492
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001493 // The operators look good: match the opcode
1494 InsnMatcher.addPredicate<InstructionOpcodeMatcher>(&SrcGI);
1495 }
Daniel Sandersffc7d582017-03-29 15:37:18 +00001496
1497 unsigned OpIdx = 0;
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001498 unsigned TempOpIdx = 0;
Daniel Sandersffc7d582017-03-29 15:37:18 +00001499 for (const EEVT::TypeSet &Ty : Src->getExtTypes()) {
1500 auto OpTyOrNone = MVTToLLT(Ty.getConcrete());
1501
1502 if (!OpTyOrNone)
1503 return failedImport(
1504 "Result of Src pattern operator has an unsupported type");
1505
1506 // Results don't have a name unless they are the root node. The caller will
1507 // set the name if appropriate.
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001508 OperandMatcher &OM = InsnMatcher.addOperand(OpIdx++, "", TempOpIdx);
Daniel Sandersffc7d582017-03-29 15:37:18 +00001509 OM.addPredicate<LLTOperandMatcher>(*OpTyOrNone);
1510 }
1511
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001512 if (Src->isLeaf()) {
1513 Init *SrcInit = Src->getLeafValue();
1514 if (IntInit *SrcIntInit = dyn_cast<IntInit>(SrcInit)) {
1515 OperandMatcher &OM = InsnMatcher.addOperand(OpIdx++, "", TempOpIdx);
1516 OM.addPredicate<LiteralIntOperandMatcher>(SrcIntInit->getValue());
1517 } else
Daniel Sanders32291982017-06-28 13:50:04 +00001518 return failedImport(
1519 "Unable to deduce gMIR opcode to handle Src (which is a leaf)");
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001520 } else {
1521 // Match the used operands (i.e. the children of the operator).
1522 for (unsigned i = 0, e = Src->getNumChildren(); i != e; ++i) {
1523 if (auto Error = importChildMatcher(InsnMatcher, Src->getChild(i),
1524 OpIdx++, TempOpIdx))
1525 return std::move(Error);
1526 }
Daniel Sandersffc7d582017-03-29 15:37:18 +00001527 }
1528
1529 return InsnMatcher;
1530}
1531
Daniel Sandersc270c502017-03-30 09:36:33 +00001532Error GlobalISelEmitter::importChildMatcher(InstructionMatcher &InsnMatcher,
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001533 const TreePatternNode *SrcChild,
Daniel Sandersc270c502017-03-30 09:36:33 +00001534 unsigned OpIdx,
1535 unsigned &TempOpIdx) const {
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001536 OperandMatcher &OM =
1537 InsnMatcher.addOperand(OpIdx, SrcChild->getName(), TempOpIdx);
Daniel Sandersffc7d582017-03-29 15:37:18 +00001538
1539 if (SrcChild->hasAnyPredicate())
Daniel Sandersd0656a32017-04-13 09:45:37 +00001540 return failedImport("Src pattern child has predicate (" +
1541 explainPredicates(SrcChild) + ")");
Daniel Sandersffc7d582017-03-29 15:37:18 +00001542
1543 ArrayRef<EEVT::TypeSet> ChildTypes = SrcChild->getExtTypes();
1544 if (ChildTypes.size() != 1)
1545 return failedImport("Src pattern child has multiple results");
1546
1547 // Check MBB's before the type check since they are not a known type.
1548 if (!SrcChild->isLeaf()) {
1549 if (SrcChild->getOperator()->isSubClassOf("SDNode")) {
1550 auto &ChildSDNI = CGP.getSDNodeInfo(SrcChild->getOperator());
1551 if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") {
1552 OM.addPredicate<MBBOperandMatcher>();
Daniel Sandersc270c502017-03-30 09:36:33 +00001553 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00001554 }
1555 }
Daniel Sandersffc7d582017-03-29 15:37:18 +00001556 }
1557
1558 auto OpTyOrNone = MVTToLLT(ChildTypes.front().getConcrete());
1559 if (!OpTyOrNone)
Daniel Sandersc244ff62017-05-22 10:14:33 +00001560 return failedImport("Src operand has an unsupported type");
Daniel Sandersffc7d582017-03-29 15:37:18 +00001561 OM.addPredicate<LLTOperandMatcher>(*OpTyOrNone);
1562
Daniel Sandersbee57392017-04-04 13:25:23 +00001563 // Check for nested instructions.
1564 if (!SrcChild->isLeaf()) {
1565 // Map the node to a gMIR instruction.
1566 InstructionOperandMatcher &InsnOperand =
1567 OM.addPredicate<InstructionOperandMatcher>();
1568 auto InsnMatcherOrError =
1569 createAndImportSelDAGMatcher(InsnOperand.getInsnMatcher(), SrcChild);
1570 if (auto Error = InsnMatcherOrError.takeError())
1571 return Error;
1572
1573 return Error::success();
1574 }
1575
Daniel Sandersffc7d582017-03-29 15:37:18 +00001576 // Check for constant immediates.
1577 if (auto *ChildInt = dyn_cast<IntInit>(SrcChild->getLeafValue())) {
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001578 OM.addPredicate<ConstantIntOperandMatcher>(ChildInt->getValue());
Daniel Sandersc270c502017-03-30 09:36:33 +00001579 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00001580 }
1581
1582 // Check for def's like register classes or ComplexPattern's.
1583 if (auto *ChildDefInit = dyn_cast<DefInit>(SrcChild->getLeafValue())) {
1584 auto *ChildRec = ChildDefInit->getDef();
1585
1586 // Check for register classes.
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00001587 if (ChildRec->isSubClassOf("RegisterClass") ||
1588 ChildRec->isSubClassOf("RegisterOperand")) {
Daniel Sandersffc7d582017-03-29 15:37:18 +00001589 OM.addPredicate<RegisterBankOperandMatcher>(
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00001590 Target.getRegisterClass(getInitValueAsRegClass(ChildDefInit)));
Daniel Sanders658541f2017-04-22 15:53:21 +00001591 return Error::success();
1592 }
1593
Daniel Sandersffc7d582017-03-29 15:37:18 +00001594 // Check for ComplexPattern's.
1595 if (ChildRec->isSubClassOf("ComplexPattern")) {
1596 const auto &ComplexPattern = ComplexPatternEquivs.find(ChildRec);
1597 if (ComplexPattern == ComplexPatternEquivs.end())
Daniel Sandersd0656a32017-04-13 09:45:37 +00001598 return failedImport("SelectionDAG ComplexPattern (" +
1599 ChildRec->getName() + ") not mapped to GlobalISel");
Daniel Sandersffc7d582017-03-29 15:37:18 +00001600
Daniel Sanders2deea182017-04-22 15:11:04 +00001601 OM.addPredicate<ComplexPatternOperandMatcher>(OM,
1602 *ComplexPattern->second);
1603 TempOpIdx++;
Daniel Sandersc270c502017-03-30 09:36:33 +00001604 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00001605 }
1606
Daniel Sandersd0656a32017-04-13 09:45:37 +00001607 if (ChildRec->isSubClassOf("ImmLeaf")) {
1608 return failedImport(
1609 "Src pattern child def is an unsupported tablegen class (ImmLeaf)");
1610 }
1611
Daniel Sandersffc7d582017-03-29 15:37:18 +00001612 return failedImport(
1613 "Src pattern child def is an unsupported tablegen class");
1614 }
1615
1616 return failedImport("Src pattern child is an unsupported kind");
1617}
1618
Daniel Sandersc270c502017-03-30 09:36:33 +00001619Error GlobalISelEmitter::importExplicitUseRenderer(
Daniel Sandersffc7d582017-03-29 15:37:18 +00001620 BuildMIAction &DstMIBuilder, TreePatternNode *DstChild,
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001621 const InstructionMatcher &InsnMatcher) const {
Daniel Sandersffc7d582017-03-29 15:37:18 +00001622 // The only non-leaf child we accept is 'bb': it's an operator because
1623 // BasicBlockSDNode isn't inline, but in MI it's just another operand.
1624 if (!DstChild->isLeaf()) {
1625 if (DstChild->getOperator()->isSubClassOf("SDNode")) {
1626 auto &ChildSDNI = CGP.getSDNodeInfo(DstChild->getOperator());
1627 if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") {
1628 DstMIBuilder.addRenderer<CopyRenderer>(InsnMatcher,
1629 DstChild->getName());
Daniel Sandersc270c502017-03-30 09:36:33 +00001630 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00001631 }
1632 }
1633 return failedImport("Dst pattern child isn't a leaf node or an MBB");
1634 }
1635
1636 // Otherwise, we're looking for a bog-standard RegisterClass operand.
1637 if (DstChild->hasAnyPredicate())
Daniel Sandersd0656a32017-04-13 09:45:37 +00001638 return failedImport("Dst pattern child has predicate (" +
1639 explainPredicates(DstChild) + ")");
Daniel Sandersffc7d582017-03-29 15:37:18 +00001640
1641 if (auto *ChildDefInit = dyn_cast<DefInit>(DstChild->getLeafValue())) {
1642 auto *ChildRec = ChildDefInit->getDef();
1643
1644 ArrayRef<EEVT::TypeSet> ChildTypes = DstChild->getExtTypes();
1645 if (ChildTypes.size() != 1)
1646 return failedImport("Dst pattern child has multiple results");
1647
1648 auto OpTyOrNone = MVTToLLT(ChildTypes.front().getConcrete());
1649 if (!OpTyOrNone)
1650 return failedImport("Dst operand has an unsupported type");
1651
1652 if (ChildRec->isSubClassOf("Register")) {
1653 DstMIBuilder.addRenderer<AddRegisterRenderer>(ChildRec);
Daniel Sandersc270c502017-03-30 09:36:33 +00001654 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00001655 }
1656
Daniel Sanders658541f2017-04-22 15:53:21 +00001657 if (ChildRec->isSubClassOf("RegisterClass") ||
1658 ChildRec->isSubClassOf("RegisterOperand")) {
Daniel Sandersffc7d582017-03-29 15:37:18 +00001659 DstMIBuilder.addRenderer<CopyRenderer>(InsnMatcher, DstChild->getName());
Daniel Sandersc270c502017-03-30 09:36:33 +00001660 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00001661 }
1662
1663 if (ChildRec->isSubClassOf("ComplexPattern")) {
1664 const auto &ComplexPattern = ComplexPatternEquivs.find(ChildRec);
1665 if (ComplexPattern == ComplexPatternEquivs.end())
1666 return failedImport(
1667 "SelectionDAG ComplexPattern not mapped to GlobalISel");
1668
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001669 const OperandMatcher &OM = InsnMatcher.getOperand(DstChild->getName());
Daniel Sandersffc7d582017-03-29 15:37:18 +00001670 DstMIBuilder.addRenderer<RenderComplexPatternOperand>(
Daniel Sanders2deea182017-04-22 15:11:04 +00001671 *ComplexPattern->second, DstChild->getName(),
1672 OM.getAllocatedTemporariesBaseID());
Daniel Sandersc270c502017-03-30 09:36:33 +00001673 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00001674 }
1675
Daniel Sandersd0656a32017-04-13 09:45:37 +00001676 if (ChildRec->isSubClassOf("SDNodeXForm"))
1677 return failedImport("Dst pattern child def is an unsupported tablegen "
1678 "class (SDNodeXForm)");
1679
Daniel Sandersffc7d582017-03-29 15:37:18 +00001680 return failedImport(
1681 "Dst pattern child def is an unsupported tablegen class");
1682 }
1683
1684 return failedImport("Dst pattern child is an unsupported kind");
1685}
1686
Daniel Sandersc270c502017-03-30 09:36:33 +00001687Expected<BuildMIAction &> GlobalISelEmitter::createAndImportInstructionRenderer(
Daniel Sandersffc7d582017-03-29 15:37:18 +00001688 RuleMatcher &M, const TreePatternNode *Dst,
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00001689 const InstructionMatcher &InsnMatcher) {
Daniel Sandersffc7d582017-03-29 15:37:18 +00001690 Record *DstOp = Dst->getOperator();
Daniel Sandersd0656a32017-04-13 09:45:37 +00001691 if (!DstOp->isSubClassOf("Instruction")) {
1692 if (DstOp->isSubClassOf("ValueType"))
1693 return failedImport(
1694 "Pattern operator isn't an instruction (it's a ValueType)");
Daniel Sandersffc7d582017-03-29 15:37:18 +00001695 return failedImport("Pattern operator isn't an instruction");
Daniel Sandersd0656a32017-04-13 09:45:37 +00001696 }
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00001697 CodeGenInstruction *DstI = &Target.getInstruction(DstOp);
Daniel Sandersffc7d582017-03-29 15:37:18 +00001698
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00001699 unsigned DstINumUses = DstI->Operands.size() - DstI->Operands.NumDefs;
1700 unsigned ExpectedDstINumUses = Dst->getNumChildren();
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00001701 bool IsExtractSubReg = false;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00001702
1703 // COPY_TO_REGCLASS is just a copy with a ConstrainOperandToRegClassAction
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00001704 // attached. Similarly for EXTRACT_SUBREG except that's a subregister copy.
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00001705 if (DstI->TheDef->getName() == "COPY_TO_REGCLASS") {
1706 DstI = &Target.getInstruction(RK.getDef("COPY"));
1707 DstINumUses--; // Ignore the class constraint.
1708 ExpectedDstINumUses--;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00001709 } else if (DstI->TheDef->getName() == "EXTRACT_SUBREG") {
1710 DstI = &Target.getInstruction(RK.getDef("COPY"));
1711 IsExtractSubReg = true;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00001712 }
1713
1714 auto &DstMIBuilder = M.addAction<BuildMIAction>("NewI", DstI, InsnMatcher);
Daniel Sandersffc7d582017-03-29 15:37:18 +00001715
1716 // Render the explicit defs.
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00001717 for (unsigned I = 0; I < DstI->Operands.NumDefs; ++I) {
1718 const CGIOperandList::OperandInfo &DstIOperand = DstI->Operands[I];
Daniel Sandersffc7d582017-03-29 15:37:18 +00001719 DstMIBuilder.addRenderer<CopyRenderer>(InsnMatcher, DstIOperand.Name);
1720 }
1721
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00001722 // EXTRACT_SUBREG needs to use a subregister COPY.
1723 if (IsExtractSubReg) {
1724 if (!Dst->getChild(0)->isLeaf())
1725 return failedImport("EXTRACT_SUBREG child #1 is not a leaf");
1726
Daniel Sanders32291982017-06-28 13:50:04 +00001727 if (DefInit *SubRegInit =
1728 dyn_cast<DefInit>(Dst->getChild(1)->getLeafValue())) {
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00001729 CodeGenRegisterClass *RC = CGRegs.getRegClass(
1730 getInitValueAsRegClass(Dst->getChild(0)->getLeafValue()));
1731 CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef());
1732
1733 const auto &SrcRCDstRCPair =
1734 RC->getMatchingSubClassWithSubRegs(CGRegs, SubIdx);
1735 if (SrcRCDstRCPair.hasValue()) {
1736 assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
1737 if (SrcRCDstRCPair->first != RC)
1738 return failedImport("EXTRACT_SUBREG requires an additional COPY");
1739 }
1740
1741 DstMIBuilder.addRenderer<CopySubRegRenderer>(
1742 InsnMatcher, Dst->getChild(0)->getName(), SubIdx);
1743 return DstMIBuilder;
1744 }
1745
1746 return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
1747 }
1748
Daniel Sandersffc7d582017-03-29 15:37:18 +00001749 // Render the explicit uses.
Daniel Sanders0ed28822017-04-12 08:23:08 +00001750 unsigned Child = 0;
Diana Picus382602f2017-05-17 08:57:28 +00001751 unsigned NumDefaultOps = 0;
Daniel Sanders0ed28822017-04-12 08:23:08 +00001752 for (unsigned I = 0; I != DstINumUses; ++I) {
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00001753 const CGIOperandList::OperandInfo &DstIOperand =
1754 DstI->Operands[DstI->Operands.NumDefs + I];
Daniel Sanders0ed28822017-04-12 08:23:08 +00001755
Diana Picus382602f2017-05-17 08:57:28 +00001756 // If the operand has default values, introduce them now.
1757 // FIXME: Until we have a decent test case that dictates we should do
1758 // otherwise, we're going to assume that operands with default values cannot
1759 // be specified in the patterns. Therefore, adding them will not cause us to
1760 // end up with too many rendered operands.
1761 if (DstIOperand.Rec->isSubClassOf("OperandWithDefaultOps")) {
Daniel Sanders0ed28822017-04-12 08:23:08 +00001762 DagInit *DefaultOps = DstIOperand.Rec->getValueAsDag("DefaultOps");
Diana Picus382602f2017-05-17 08:57:28 +00001763 if (auto Error = importDefaultOperandRenderers(DstMIBuilder, DefaultOps))
1764 return std::move(Error);
1765 ++NumDefaultOps;
Daniel Sanders0ed28822017-04-12 08:23:08 +00001766 continue;
1767 }
1768
1769 if (auto Error = importExplicitUseRenderer(
1770 DstMIBuilder, Dst->getChild(Child), InsnMatcher))
Daniel Sandersffc7d582017-03-29 15:37:18 +00001771 return std::move(Error);
Daniel Sanders0ed28822017-04-12 08:23:08 +00001772 ++Child;
Daniel Sandersffc7d582017-03-29 15:37:18 +00001773 }
1774
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00001775 if (NumDefaultOps + ExpectedDstINumUses != DstINumUses)
Diana Picuseb2057c2017-05-17 09:25:08 +00001776 return failedImport("Expected " + llvm::to_string(DstINumUses) +
Diana Picus382602f2017-05-17 08:57:28 +00001777 " used operands but found " +
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00001778 llvm::to_string(ExpectedDstINumUses) +
Diana Picuseb2057c2017-05-17 09:25:08 +00001779 " explicit ones and " + llvm::to_string(NumDefaultOps) +
Diana Picus382602f2017-05-17 08:57:28 +00001780 " default ones");
1781
Daniel Sandersffc7d582017-03-29 15:37:18 +00001782 return DstMIBuilder;
1783}
1784
Diana Picus382602f2017-05-17 08:57:28 +00001785Error GlobalISelEmitter::importDefaultOperandRenderers(
1786 BuildMIAction &DstMIBuilder, DagInit *DefaultOps) const {
Craig Topper481ff702017-05-29 21:49:34 +00001787 for (const auto *DefaultOp : DefaultOps->getArgs()) {
Diana Picus382602f2017-05-17 08:57:28 +00001788 // Look through ValueType operators.
1789 if (const DagInit *DefaultDagOp = dyn_cast<DagInit>(DefaultOp)) {
1790 if (const DefInit *DefaultDagOperator =
1791 dyn_cast<DefInit>(DefaultDagOp->getOperator())) {
1792 if (DefaultDagOperator->getDef()->isSubClassOf("ValueType"))
1793 DefaultOp = DefaultDagOp->getArg(0);
1794 }
1795 }
1796
1797 if (const DefInit *DefaultDefOp = dyn_cast<DefInit>(DefaultOp)) {
1798 DstMIBuilder.addRenderer<AddRegisterRenderer>(DefaultDefOp->getDef());
1799 continue;
1800 }
1801
1802 if (const IntInit *DefaultIntOp = dyn_cast<IntInit>(DefaultOp)) {
1803 DstMIBuilder.addRenderer<ImmRenderer>(DefaultIntOp->getValue());
1804 continue;
1805 }
1806
1807 return failedImport("Could not add default op");
1808 }
1809
1810 return Error::success();
1811}
1812
Daniel Sandersc270c502017-03-30 09:36:33 +00001813Error GlobalISelEmitter::importImplicitDefRenderers(
Daniel Sandersffc7d582017-03-29 15:37:18 +00001814 BuildMIAction &DstMIBuilder,
1815 const std::vector<Record *> &ImplicitDefs) const {
1816 if (!ImplicitDefs.empty())
1817 return failedImport("Pattern defines a physical register");
Daniel Sandersc270c502017-03-30 09:36:33 +00001818 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00001819}
1820
1821Expected<RuleMatcher> GlobalISelEmitter::runOnPattern(const PatternToMatch &P) {
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001822 // Keep track of the matchers and actions to emit.
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +00001823 RuleMatcher M;
1824 M.addAction<DebugCommentAction>(P);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001825
Daniel Sandersc270c502017-03-30 09:36:33 +00001826 if (auto Error = importRulePredicates(M, P.getPredicates()->getValues()))
Daniel Sandersffc7d582017-03-29 15:37:18 +00001827 return std::move(Error);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001828
1829 // Next, analyze the pattern operators.
1830 TreePatternNode *Src = P.getSrcPattern();
1831 TreePatternNode *Dst = P.getDstPattern();
1832
1833 // If the root of either pattern isn't a simple operator, ignore it.
Daniel Sandersd0656a32017-04-13 09:45:37 +00001834 if (auto Err = isTrivialOperatorNode(Dst))
1835 return failedImport("Dst pattern root isn't a trivial operator (" +
1836 toString(std::move(Err)) + ")");
1837 if (auto Err = isTrivialOperatorNode(Src))
1838 return failedImport("Src pattern root isn't a trivial operator (" +
1839 toString(std::move(Err)) + ")");
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001840
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001841 if (Dst->isLeaf())
1842 return failedImport("Dst pattern root isn't a known leaf");
1843
Daniel Sandersbee57392017-04-04 13:25:23 +00001844 // Start with the defined operands (i.e., the results of the root operator).
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001845 Record *DstOp = Dst->getOperator();
1846 if (!DstOp->isSubClassOf("Instruction"))
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00001847 return failedImport("Pattern operator isn't an instruction");
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001848
1849 auto &DstI = Target.getInstruction(DstOp);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001850 if (DstI.Operands.NumDefs != Src->getExtTypes().size())
Daniel Sandersd0656a32017-04-13 09:45:37 +00001851 return failedImport("Src pattern results and dst MI defs are different (" +
1852 to_string(Src->getExtTypes().size()) + " def(s) vs " +
1853 to_string(DstI.Operands.NumDefs) + " def(s))");
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001854
Daniel Sandersffc7d582017-03-29 15:37:18 +00001855 InstructionMatcher &InsnMatcherTemp = M.addInstructionMatcher();
Daniel Sandersc270c502017-03-30 09:36:33 +00001856 auto InsnMatcherOrError = createAndImportSelDAGMatcher(InsnMatcherTemp, Src);
Daniel Sandersffc7d582017-03-29 15:37:18 +00001857 if (auto Error = InsnMatcherOrError.takeError())
1858 return std::move(Error);
1859 InstructionMatcher &InsnMatcher = InsnMatcherOrError.get();
1860
1861 // The root of the match also has constraints on the register bank so that it
1862 // matches the result instruction.
1863 unsigned OpIdx = 0;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001864 for (const EEVT::TypeSet &Ty : Src->getExtTypes()) {
Daniel Sandersffc7d582017-03-29 15:37:18 +00001865 (void)Ty;
1866
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001867 const auto &DstIOperand = DstI.Operands[OpIdx];
1868 Record *DstIOpRec = DstIOperand.Rec;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00001869 if (DstI.TheDef->getName() == "COPY_TO_REGCLASS") {
1870 DstIOpRec = getInitValueAsRegClass(Dst->getChild(1)->getLeafValue());
1871
1872 if (DstIOpRec == nullptr)
1873 return failedImport(
1874 "COPY_TO_REGCLASS operand #1 isn't a register class");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00001875 } else if (DstI.TheDef->getName() == "EXTRACT_SUBREG") {
1876 if (!Dst->getChild(0)->isLeaf())
1877 return failedImport("EXTRACT_SUBREG operand #0 isn't a leaf");
1878
Daniel Sanders32291982017-06-28 13:50:04 +00001879 // We can assume that a subregister is in the same bank as it's super
1880 // register.
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00001881 DstIOpRec = getInitValueAsRegClass(Dst->getChild(0)->getLeafValue());
1882
1883 if (DstIOpRec == nullptr)
1884 return failedImport(
1885 "EXTRACT_SUBREG operand #0 isn't a register class");
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00001886 } else if (DstIOpRec->isSubClassOf("RegisterOperand"))
Daniel Sanders658541f2017-04-22 15:53:21 +00001887 DstIOpRec = DstIOpRec->getValueAsDef("RegClass");
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00001888 else if (!DstIOpRec->isSubClassOf("RegisterClass"))
Daniel Sanders32291982017-06-28 13:50:04 +00001889 return failedImport("Dst MI def isn't a register class" +
1890 to_string(*Dst));
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001891
Daniel Sandersffc7d582017-03-29 15:37:18 +00001892 OperandMatcher &OM = InsnMatcher.getOperand(OpIdx);
1893 OM.setSymbolicName(DstIOperand.Name);
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001894 OM.addPredicate<RegisterBankOperandMatcher>(
1895 Target.getRegisterClass(DstIOpRec));
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001896 ++OpIdx;
1897 }
1898
Daniel Sandersc270c502017-03-30 09:36:33 +00001899 auto DstMIBuilderOrError =
1900 createAndImportInstructionRenderer(M, Dst, InsnMatcher);
Daniel Sandersffc7d582017-03-29 15:37:18 +00001901 if (auto Error = DstMIBuilderOrError.takeError())
1902 return std::move(Error);
1903 BuildMIAction &DstMIBuilder = DstMIBuilderOrError.get();
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001904
Daniel Sandersffc7d582017-03-29 15:37:18 +00001905 // Render the implicit defs.
1906 // These are only added to the root of the result.
Daniel Sandersc270c502017-03-30 09:36:33 +00001907 if (auto Error = importImplicitDefRenderers(DstMIBuilder, P.getDstRegs()))
Daniel Sandersffc7d582017-03-29 15:37:18 +00001908 return std::move(Error);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001909
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00001910 // Constrain the registers to classes. This is normally derived from the
1911 // emitted instruction but a few instructions require special handling.
1912 if (DstI.TheDef->getName() == "COPY_TO_REGCLASS") {
1913 // COPY_TO_REGCLASS does not provide operand constraints itself but the
1914 // result is constrained to the class given by the second child.
1915 Record *DstIOpRec =
1916 getInitValueAsRegClass(Dst->getChild(1)->getLeafValue());
1917
1918 if (DstIOpRec == nullptr)
1919 return failedImport("COPY_TO_REGCLASS operand #1 isn't a register class");
1920
1921 M.addAction<ConstrainOperandToRegClassAction>(
1922 "NewI", 0, Target.getRegisterClass(DstIOpRec));
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00001923
1924 // We're done with this pattern! It's eligible for GISel emission; return
1925 // it.
1926 ++NumPatternImported;
1927 return std::move(M);
1928 }
1929
1930 if (DstI.TheDef->getName() == "EXTRACT_SUBREG") {
1931 // EXTRACT_SUBREG selects into a subregister COPY but unlike most
1932 // instructions, the result register class is controlled by the
1933 // subregisters of the operand. As a result, we must constrain the result
1934 // class rather than check that it's already the right one.
1935 if (!Dst->getChild(0)->isLeaf())
1936 return failedImport("EXTRACT_SUBREG child #1 is not a leaf");
1937
Daniel Sanders320390b2017-06-28 15:16:03 +00001938 DefInit *SubRegInit = dyn_cast<DefInit>(Dst->getChild(1)->getLeafValue());
1939 if (!SubRegInit)
1940 return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00001941
Daniel Sanders320390b2017-06-28 15:16:03 +00001942 // Constrain the result to the same register bank as the operand.
1943 Record *DstIOpRec =
1944 getInitValueAsRegClass(Dst->getChild(0)->getLeafValue());
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00001945
Daniel Sanders320390b2017-06-28 15:16:03 +00001946 if (DstIOpRec == nullptr)
1947 return failedImport("EXTRACT_SUBREG operand #1 isn't a register class");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00001948
Daniel Sanders320390b2017-06-28 15:16:03 +00001949 CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef());
1950 CodeGenRegisterClass *SrcRC = CGRegs.getRegClass(
1951 getInitValueAsRegClass(Dst->getChild(0)->getLeafValue()));
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00001952
Daniel Sanders320390b2017-06-28 15:16:03 +00001953 // It would be nice to leave this constraint implicit but we're required
1954 // to pick a register class so constrain the result to a register class
1955 // that can hold the correct MVT.
1956 //
1957 // FIXME: This may introduce an extra copy if the chosen class doesn't
1958 // actually contain the subregisters.
1959 assert(Src->getExtTypes().size() == 1 &&
1960 "Expected Src of EXTRACT_SUBREG to have one result type");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00001961
Daniel Sanders320390b2017-06-28 15:16:03 +00001962 const auto &SrcRCDstRCPair =
1963 SrcRC->getMatchingSubClassWithSubRegs(CGRegs, SubIdx);
1964 assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
1965 M.addAction<ConstrainOperandToRegClassAction>("NewI", 0,
1966 *SrcRCDstRCPair->second);
1967 M.addAction<ConstrainOperandToRegClassAction>("NewI", 1,
1968 *SrcRCDstRCPair->first);
1969 } else
1970 M.addAction<ConstrainOperandsToDefinitionAction>("NewI");
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00001971
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00001972 // We're done with this pattern! It's eligible for GISel emission; return it.
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00001973 ++NumPatternImported;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00001974 return std::move(M);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001975}
1976
1977void GlobalISelEmitter::run(raw_ostream &OS) {
1978 // Track the GINodeEquiv definitions.
1979 gatherNodeEquivs();
1980
1981 emitSourceFileHeader(("Global Instruction Selector for the " +
1982 Target.getName() + " target").str(), OS);
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00001983 std::vector<RuleMatcher> Rules;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001984 // Look through the SelectionDAG patterns we found, possibly emitting some.
1985 for (const PatternToMatch &Pat : CGP.ptms()) {
1986 ++NumPatternTotal;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00001987 auto MatcherOrErr = runOnPattern(Pat);
1988
1989 // The pattern analysis can fail, indicating an unsupported pattern.
1990 // Report that if we've been asked to do so.
1991 if (auto Err = MatcherOrErr.takeError()) {
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001992 if (WarnOnSkippedPatterns) {
1993 PrintWarning(Pat.getSrcRecord()->getLoc(),
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00001994 "Skipped pattern: " + toString(std::move(Err)));
1995 } else {
1996 consumeError(std::move(Err));
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001997 }
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00001998 ++NumPatternImportsSkipped;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00001999 continue;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002000 }
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002001
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00002002 Rules.push_back(std::move(MatcherOrErr.get()));
2003 }
2004
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002005 std::stable_sort(Rules.begin(), Rules.end(),
2006 [&](const RuleMatcher &A, const RuleMatcher &B) {
Daniel Sanders759ff412017-02-24 13:58:11 +00002007 if (A.isHigherPriorityThan(B)) {
2008 assert(!B.isHigherPriorityThan(A) && "Cannot be more important "
2009 "and less important at "
2010 "the same time");
2011 return true;
2012 }
2013 return false;
2014 });
2015
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002016 std::vector<Record *> ComplexPredicates =
2017 RK.getAllDerivedDefinitions("GIComplexOperandMatcher");
2018 std::sort(ComplexPredicates.begin(), ComplexPredicates.end(),
2019 [](const Record *A, const Record *B) {
2020 if (A->getName() < B->getName())
2021 return true;
2022 return false;
2023 });
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002024 unsigned MaxTemporaries = 0;
2025 for (const auto &Rule : Rules)
Daniel Sanders2deea182017-04-22 15:11:04 +00002026 MaxTemporaries = std::max(MaxTemporaries, Rule.countRendererFns());
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002027
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002028 OS << "#ifdef GET_GLOBALISEL_PREDICATE_BITSET\n"
2029 << "const unsigned MAX_SUBTARGET_PREDICATES = " << SubtargetFeatures.size()
2030 << ";\n"
2031 << "using PredicateBitset = "
2032 "llvm::PredicateBitsetImpl<MAX_SUBTARGET_PREDICATES>;\n"
2033 << "#endif // ifdef GET_GLOBALISEL_PREDICATE_BITSET\n\n";
2034
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002035 OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n"
2036 << " mutable MatcherState State;\n"
2037 << " typedef "
2038 "ComplexRendererFn("
2039 << Target.getName()
2040 << "InstructionSelector::*ComplexMatcherMemFn)(MachineOperand &) const;\n"
2041 << "const MatcherInfoTy<PredicateBitset, ComplexMatcherMemFn> "
2042 "MatcherInfo;\n"
2043 << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n\n";
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002044
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002045 OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n"
2046 << ", State(" << MaxTemporaries << "),\n"
2047 << "MatcherInfo({TypeObjects, FeatureBitsets, {\n"
2048 << " nullptr, // GICP_Invalid\n";
2049 for (const auto &Record : ComplexPredicates)
2050 OS << " &" << Target.getName()
2051 << "InstructionSelector::" << Record->getValueAsString("MatcherFn")
2052 << ", // " << Record->getName() << "\n";
2053 OS << "}})\n"
2054 << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n\n";
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002055
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002056 OS << "#ifdef GET_GLOBALISEL_IMPL\n";
2057 SubtargetFeatureInfo::emitSubtargetFeatureBitEnumeration(SubtargetFeatures,
2058 OS);
Daniel Sanderse9fdba32017-04-29 17:30:09 +00002059
2060 // Separate subtarget features by how often they must be recomputed.
2061 SubtargetFeatureInfoMap ModuleFeatures;
2062 std::copy_if(SubtargetFeatures.begin(), SubtargetFeatures.end(),
2063 std::inserter(ModuleFeatures, ModuleFeatures.end()),
2064 [](const SubtargetFeatureInfoMap::value_type &X) {
2065 return !X.second.mustRecomputePerFunction();
2066 });
2067 SubtargetFeatureInfoMap FunctionFeatures;
2068 std::copy_if(SubtargetFeatures.begin(), SubtargetFeatures.end(),
2069 std::inserter(FunctionFeatures, FunctionFeatures.end()),
2070 [](const SubtargetFeatureInfoMap::value_type &X) {
2071 return X.second.mustRecomputePerFunction();
2072 });
2073
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002074 SubtargetFeatureInfo::emitComputeAvailableFeatures(
Daniel Sanderse9fdba32017-04-29 17:30:09 +00002075 Target.getName(), "InstructionSelector", "computeAvailableModuleFeatures",
2076 ModuleFeatures, OS);
2077 SubtargetFeatureInfo::emitComputeAvailableFeatures(
2078 Target.getName(), "InstructionSelector",
2079 "computeAvailableFunctionFeatures", FunctionFeatures, OS,
2080 "const MachineFunction *MF");
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002081
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002082 // Emit a table containing the LLT objects needed by the matcher and an enum
2083 // for the matcher to reference them with.
2084 std::vector<LLTCodeGen> TypeObjects = {
2085 LLT::scalar(8), LLT::scalar(16), LLT::scalar(32),
2086 LLT::scalar(64), LLT::scalar(80), LLT::vector(8, 1),
2087 LLT::vector(16, 1), LLT::vector(32, 1), LLT::vector(64, 1),
2088 LLT::vector(8, 8), LLT::vector(16, 8), LLT::vector(32, 8),
2089 LLT::vector(64, 8), LLT::vector(4, 16), LLT::vector(8, 16),
2090 LLT::vector(16, 16), LLT::vector(32, 16), LLT::vector(2, 32),
2091 LLT::vector(4, 32), LLT::vector(8, 32), LLT::vector(16, 32),
2092 LLT::vector(2, 64), LLT::vector(4, 64), LLT::vector(8, 64),
2093 };
2094 std::sort(TypeObjects.begin(), TypeObjects.end());
2095 OS << "enum {\n";
2096 for (const auto &TypeObject : TypeObjects) {
2097 OS << " ";
2098 TypeObject.emitCxxEnumValue(OS);
2099 OS << ",\n";
2100 }
2101 OS << "};\n"
2102 << "const static LLT TypeObjects[] = {\n";
2103 for (const auto &TypeObject : TypeObjects) {
2104 OS << " ";
2105 TypeObject.emitCxxConstructorCall(OS);
2106 OS << ",\n";
2107 }
2108 OS << "};\n\n";
2109
2110 // Emit a table containing the PredicateBitsets objects needed by the matcher
2111 // and an enum for the matcher to reference them with.
2112 std::vector<std::vector<Record *>> FeatureBitsets;
2113 for (auto &Rule : Rules)
2114 FeatureBitsets.push_back(Rule.getRequiredFeatures());
2115 std::sort(
2116 FeatureBitsets.begin(), FeatureBitsets.end(),
2117 [&](const std::vector<Record *> &A, const std::vector<Record *> &B) {
2118 if (A.size() < B.size())
2119 return true;
2120 if (A.size() > B.size())
2121 return false;
2122 for (const auto &Pair : zip(A, B)) {
2123 if (std::get<0>(Pair)->getName() < std::get<1>(Pair)->getName())
2124 return true;
2125 if (std::get<0>(Pair)->getName() > std::get<1>(Pair)->getName())
2126 return false;
2127 }
2128 return false;
2129 });
2130 FeatureBitsets.erase(
2131 std::unique(FeatureBitsets.begin(), FeatureBitsets.end()),
2132 FeatureBitsets.end());
2133 OS << "enum {\n"
2134 << " GIFBS_Invalid,\n";
2135 for (const auto &FeatureBitset : FeatureBitsets) {
2136 if (FeatureBitset.empty())
2137 continue;
2138 OS << " " << getNameForFeatureBitset(FeatureBitset) << ",\n";
2139 }
2140 OS << "};\n"
2141 << "const static PredicateBitset FeatureBitsets[] {\n"
2142 << " {}, // GIFBS_Invalid\n";
2143 for (const auto &FeatureBitset : FeatureBitsets) {
2144 if (FeatureBitset.empty())
2145 continue;
2146 OS << " {";
2147 for (const auto &Feature : FeatureBitset) {
2148 const auto &I = SubtargetFeatures.find(Feature);
2149 assert(I != SubtargetFeatures.end() && "Didn't import predicate?");
2150 OS << I->second.getEnumBitName() << ", ";
2151 }
2152 OS << "},\n";
2153 }
2154 OS << "};\n\n";
2155
2156 // Emit complex predicate table and an enum to reference them with.
2157 OS << "enum {\n"
2158 << " GICP_Invalid,\n";
2159 for (const auto &Record : ComplexPredicates)
2160 OS << " GICP_" << Record->getName() << ",\n";
2161 OS << "};\n"
2162 << "// See constructor for table contents\n\n";
2163
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002164 OS << "bool " << Target.getName()
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002165 << "InstructionSelector::selectImpl(MachineInstr &I) const {\n"
2166 << " MachineFunction &MF = *I.getParent()->getParent();\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002167 << " MachineRegisterInfo &MRI = MF.getRegInfo();\n"
Daniel Sanders32291982017-06-28 13:50:04 +00002168 << " // FIXME: This should be computed on a per-function basis rather "
2169 "than per-insn.\n"
2170 << " AvailableFunctionFeatures = computeAvailableFunctionFeatures(&STI, "
2171 "&MF);\n"
Daniel Sanderse9fdba32017-04-29 17:30:09 +00002172 << " const PredicateBitset AvailableFeatures = getAvailableFeatures();\n";
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002173
Daniel Sandersb96f40d2017-03-20 15:20:42 +00002174 for (auto &Rule : Rules) {
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002175 Rule.emit(OS);
Daniel Sandersc60abe32017-07-04 15:31:50 +00002176 ++CurrentMatchTableID;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002177 ++NumPatternEmitted;
Daniel Sandersc60abe32017-07-04 15:31:50 +00002178 assert(CurrentMatchTableID == NumPatternEmitted &&
2179 "Statistic deviates from number of emitted tables");
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002180 }
2181
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002182 OS << " return false;\n"
2183 << "}\n"
2184 << "#endif // ifdef GET_GLOBALISEL_IMPL\n";
Daniel Sanderse9fdba32017-04-29 17:30:09 +00002185
2186 OS << "#ifdef GET_GLOBALISEL_PREDICATES_DECL\n"
2187 << "PredicateBitset AvailableModuleFeatures;\n"
2188 << "mutable PredicateBitset AvailableFunctionFeatures;\n"
2189 << "PredicateBitset getAvailableFeatures() const {\n"
2190 << " return AvailableModuleFeatures | AvailableFunctionFeatures;\n"
2191 << "}\n"
2192 << "PredicateBitset\n"
2193 << "computeAvailableModuleFeatures(const " << Target.getName()
2194 << "Subtarget *Subtarget) const;\n"
2195 << "PredicateBitset\n"
2196 << "computeAvailableFunctionFeatures(const " << Target.getName()
2197 << "Subtarget *Subtarget,\n"
2198 << " const MachineFunction *MF) const;\n"
2199 << "#endif // ifdef GET_GLOBALISEL_PREDICATES_DECL\n";
2200
2201 OS << "#ifdef GET_GLOBALISEL_PREDICATES_INIT\n"
2202 << "AvailableModuleFeatures(computeAvailableModuleFeatures(&STI)),\n"
2203 << "AvailableFunctionFeatures()\n"
2204 << "#endif // ifdef GET_GLOBALISEL_PREDICATES_INIT\n";
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002205}
2206
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002207void GlobalISelEmitter::declareSubtargetFeature(Record *Predicate) {
2208 if (SubtargetFeatures.count(Predicate) == 0)
2209 SubtargetFeatures.emplace(
2210 Predicate, SubtargetFeatureInfo(Predicate, SubtargetFeatures.size()));
2211}
2212
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002213} // end anonymous namespace
2214
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002215//===----------------------------------------------------------------------===//
2216
2217namespace llvm {
2218void EmitGlobalISel(RecordKeeper &RK, raw_ostream &OS) {
2219 GlobalISelEmitter(RK).run(OS);
2220}
2221} // End llvm namespace