blob: 9181272adc22d66107e17878b2dd30ea3b3343b0 [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");
56
Daniel Sanders0848b232017-03-27 13:15:13 +000057cl::OptionCategory GlobalISelEmitterCat("Options for -gen-global-isel");
58
Ahmed Bougacha36f70352016-12-21 23:26:20 +000059static cl::opt<bool> WarnOnSkippedPatterns(
60 "warn-on-skipped-patterns",
61 cl::desc("Explain why a pattern was skipped for inclusion "
62 "in the GlobalISel selector"),
Daniel Sanders0848b232017-03-27 13:15:13 +000063 cl::init(false), cl::cat(GlobalISelEmitterCat));
Ahmed Bougacha36f70352016-12-21 23:26:20 +000064
Daniel Sandersbdfebb82017-03-15 20:18:38 +000065namespace {
Ahmed Bougacha36f70352016-12-21 23:26:20 +000066//===- Helper functions ---------------------------------------------------===//
67
Daniel Sanders52b4ce72017-03-07 23:20:35 +000068/// This class stands in for LLT wherever we want to tablegen-erate an
69/// equivalent at compiler run-time.
70class LLTCodeGen {
71private:
72 LLT Ty;
73
74public:
75 LLTCodeGen(const LLT &Ty) : Ty(Ty) {}
76
Daniel Sanders7aac7cc2017-07-20 09:25:44 +000077 std::string getCxxEnumValue() const {
78 std::string Str;
79 raw_string_ostream OS(Str);
80
81 emitCxxEnumValue(OS);
82 return OS.str();
83 }
84
Daniel Sanders6ab0daa2017-07-04 14:35:06 +000085 void emitCxxEnumValue(raw_ostream &OS) const {
86 if (Ty.isScalar()) {
87 OS << "GILLT_s" << Ty.getSizeInBits();
88 return;
89 }
90 if (Ty.isVector()) {
91 OS << "GILLT_v" << Ty.getNumElements() << "s" << Ty.getScalarSizeInBits();
92 return;
93 }
94 llvm_unreachable("Unhandled LLT");
95 }
96
Daniel Sanders52b4ce72017-03-07 23:20:35 +000097 void emitCxxConstructorCall(raw_ostream &OS) const {
98 if (Ty.isScalar()) {
99 OS << "LLT::scalar(" << Ty.getSizeInBits() << ")";
100 return;
101 }
102 if (Ty.isVector()) {
Daniel Sanders32291982017-06-28 13:50:04 +0000103 OS << "LLT::vector(" << Ty.getNumElements() << ", "
104 << Ty.getScalarSizeInBits() << ")";
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000105 return;
106 }
107 llvm_unreachable("Unhandled LLT");
108 }
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000109
110 const LLT &get() const { return Ty; }
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000111
112 /// This ordering is used for std::unique() and std::sort(). There's no
113 /// particular logic behind the order.
114 bool operator<(const LLTCodeGen &Other) const {
115 if (!Ty.isValid())
116 return Other.Ty.isValid();
117 if (Ty.isScalar()) {
118 if (!Other.Ty.isValid())
119 return false;
120 if (Other.Ty.isScalar())
121 return Ty.getSizeInBits() < Other.Ty.getSizeInBits();
122 return false;
123 }
124 if (Ty.isVector()) {
125 if (!Other.Ty.isValid() || Other.Ty.isScalar())
126 return false;
127 if (Other.Ty.isVector()) {
128 if (Ty.getNumElements() < Other.Ty.getNumElements())
129 return true;
130 if (Ty.getNumElements() > Other.Ty.getNumElements())
131 return false;
132 return Ty.getSizeInBits() < Other.Ty.getSizeInBits();
133 }
134 return false;
135 }
136 llvm_unreachable("Unhandled LLT");
137 }
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000138};
139
140class InstructionMatcher;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000141/// Convert an MVT to an equivalent LLT if possible, or the invalid LLT() for
142/// MVTs that don't map cleanly to an LLT (e.g., iPTR, *any, ...).
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000143static Optional<LLTCodeGen> MVTToLLT(MVT::SimpleValueType SVT) {
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000144 MVT VT(SVT);
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000145 if (VT.isVector() && VT.getVectorNumElements() != 1)
Daniel Sanders32291982017-06-28 13:50:04 +0000146 return LLTCodeGen(
147 LLT::vector(VT.getVectorNumElements(), VT.getScalarSizeInBits()));
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000148 if (VT.isInteger() || VT.isFloatingPoint())
149 return LLTCodeGen(LLT::scalar(VT.getSizeInBits()));
150 return None;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000151}
152
Daniel Sandersd0656a32017-04-13 09:45:37 +0000153static std::string explainPredicates(const TreePatternNode *N) {
154 std::string Explanation = "";
155 StringRef Separator = "";
156 for (const auto &P : N->getPredicateFns()) {
157 Explanation +=
158 (Separator + P.getOrigPatFragRecord()->getRecord()->getName()).str();
159 if (P.isAlwaysTrue())
160 Explanation += " always-true";
161 if (P.isImmediatePattern())
162 Explanation += " immediate";
163 }
164 return Explanation;
165}
166
Daniel Sandersd0656a32017-04-13 09:45:37 +0000167std::string explainOperator(Record *Operator) {
168 if (Operator->isSubClassOf("SDNode"))
Craig Topper2b8419a2017-05-31 19:01:11 +0000169 return (" (" + Operator->getValueAsString("Opcode") + ")").str();
Daniel Sandersd0656a32017-04-13 09:45:37 +0000170
171 if (Operator->isSubClassOf("Intrinsic"))
172 return (" (Operator is an Intrinsic, " + Operator->getName() + ")").str();
173
174 return " (Operator not understood)";
175}
176
177/// Helper function to let the emitter report skip reason error messages.
178static Error failedImport(const Twine &Reason) {
179 return make_error<StringError>(Reason, inconvertibleErrorCode());
180}
181
182static Error isTrivialOperatorNode(const TreePatternNode *N) {
183 std::string Explanation = "";
184 std::string Separator = "";
185 if (N->isLeaf()) {
Daniel Sanders3334cc02017-05-23 20:02:48 +0000186 if (isa<IntInit>(N->getLeafValue()))
Daniel Sanders452c8ae2017-05-23 19:33:16 +0000187 return Error::success();
188
Daniel Sandersd0656a32017-04-13 09:45:37 +0000189 Explanation = "Is a leaf";
190 Separator = ", ";
191 }
192
193 if (N->hasAnyPredicate()) {
194 Explanation = Separator + "Has a predicate (" + explainPredicates(N) + ")";
195 Separator = ", ";
196 }
197
198 if (N->getTransformFn()) {
199 Explanation += Separator + "Has a transform function";
200 Separator = ", ";
201 }
202
203 if (!N->isLeaf() && !N->hasAnyPredicate() && !N->getTransformFn())
204 return Error::success();
205
206 return failedImport(Explanation);
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000207}
208
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +0000209static Record *getInitValueAsRegClass(Init *V) {
210 if (DefInit *VDefInit = dyn_cast<DefInit>(V)) {
211 if (VDefInit->getDef()->isSubClassOf("RegisterOperand"))
212 return VDefInit->getDef()->getValueAsDef("RegClass");
213 if (VDefInit->getDef()->isSubClassOf("RegisterClass"))
214 return VDefInit->getDef();
215 }
216 return nullptr;
217}
218
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000219std::string
220getNameForFeatureBitset(const std::vector<Record *> &FeatureBitset) {
221 std::string Name = "GIFBS";
222 for (const auto &Feature : FeatureBitset)
223 Name += ("_" + Feature->getName()).str();
224 return Name;
225}
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000226
227//===- MatchTable Helpers -------------------------------------------------===//
228
229class MatchTable;
230
231/// A record to be stored in a MatchTable.
232///
233/// This class represents any and all output that may be required to emit the
234/// MatchTable. Instances are most often configured to represent an opcode or
235/// value that will be emitted to the table with some formatting but it can also
236/// represent commas, comments, and other formatting instructions.
237struct MatchTableRecord {
238 enum RecordFlagsBits {
239 MTRF_None = 0x0,
240 /// Causes EmitStr to be formatted as comment when emitted.
241 MTRF_Comment = 0x1,
242 /// Causes the record value to be followed by a comma when emitted.
243 MTRF_CommaFollows = 0x2,
244 /// Causes the record value to be followed by a line break when emitted.
245 MTRF_LineBreakFollows = 0x4,
246 /// Indicates that the record defines a label and causes an additional
247 /// comment to be emitted containing the index of the label.
248 MTRF_Label = 0x8,
249 /// Causes the record to be emitted as the index of the label specified by
250 /// LabelID along with a comment indicating where that label is.
251 MTRF_JumpTarget = 0x10,
252 /// Causes the formatter to add a level of indentation before emitting the
253 /// record.
254 MTRF_Indent = 0x20,
255 /// Causes the formatter to remove a level of indentation after emitting the
256 /// record.
257 MTRF_Outdent = 0x40,
258 };
259
260 /// When MTRF_Label or MTRF_JumpTarget is used, indicates a label id to
261 /// reference or define.
262 unsigned LabelID;
263 /// The string to emit. Depending on the MTRF_* flags it may be a comment, a
264 /// value, a label name.
265 std::string EmitStr;
266
267private:
268 /// The number of MatchTable elements described by this record. Comments are 0
269 /// while values are typically 1. Values >1 may occur when we need to emit
270 /// values that exceed the size of a MatchTable element.
271 unsigned NumElements;
272
273public:
274 /// A bitfield of RecordFlagsBits flags.
275 unsigned Flags;
276
277 MatchTableRecord(Optional<unsigned> LabelID_, StringRef EmitStr,
278 unsigned NumElements, unsigned Flags)
279 : LabelID(LabelID_.hasValue() ? LabelID_.getValue() : ~0u),
280 EmitStr(EmitStr), NumElements(NumElements), Flags(Flags) {
281 assert((!LabelID_.hasValue() || LabelID != ~0u) &&
282 "This value is reserved for non-labels");
283 }
284
285 void emit(raw_ostream &OS, bool LineBreakNextAfterThis,
286 const MatchTable &Table) const;
287 unsigned size() const { return NumElements; }
288};
289
290/// Holds the contents of a generated MatchTable to enable formatting and the
291/// necessary index tracking needed to support GIM_Try.
292class MatchTable {
293 /// An unique identifier for the table. The generated table will be named
294 /// MatchTable${ID}.
295 unsigned ID;
296 /// The records that make up the table. Also includes comments describing the
297 /// values being emitted and line breaks to format it.
298 std::vector<MatchTableRecord> Contents;
299 /// The currently defined labels.
300 DenseMap<unsigned, unsigned> LabelMap;
301 /// Tracks the sum of MatchTableRecord::NumElements as the table is built.
302 unsigned CurrentSize;
303
Daniel Sanders8e82af22017-07-27 11:03:45 +0000304 /// A unique identifier for a MatchTable label.
305 static unsigned CurrentLabelID;
306
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000307public:
308 static MatchTableRecord LineBreak;
309 static MatchTableRecord Comment(StringRef Comment) {
310 return MatchTableRecord(None, Comment, 0, MatchTableRecord::MTRF_Comment);
311 }
312 static MatchTableRecord Opcode(StringRef Opcode, int IndentAdjust = 0) {
313 unsigned ExtraFlags = 0;
314 if (IndentAdjust > 0)
315 ExtraFlags |= MatchTableRecord::MTRF_Indent;
316 if (IndentAdjust < 0)
317 ExtraFlags |= MatchTableRecord::MTRF_Outdent;
318
319 return MatchTableRecord(None, Opcode, 1,
320 MatchTableRecord::MTRF_CommaFollows | ExtraFlags);
321 }
322 static MatchTableRecord NamedValue(StringRef NamedValue) {
323 return MatchTableRecord(None, NamedValue, 1,
324 MatchTableRecord::MTRF_CommaFollows);
325 }
326 static MatchTableRecord NamedValue(StringRef Namespace,
327 StringRef NamedValue) {
328 return MatchTableRecord(None, (Namespace + "::" + NamedValue).str(), 1,
329 MatchTableRecord::MTRF_CommaFollows);
330 }
331 static MatchTableRecord IntValue(int64_t IntValue) {
332 return MatchTableRecord(None, llvm::to_string(IntValue), 1,
333 MatchTableRecord::MTRF_CommaFollows);
334 }
335 static MatchTableRecord Label(unsigned LabelID) {
336 return MatchTableRecord(LabelID, "Label " + llvm::to_string(LabelID), 0,
337 MatchTableRecord::MTRF_Label |
338 MatchTableRecord::MTRF_Comment |
339 MatchTableRecord::MTRF_LineBreakFollows);
340 }
341 static MatchTableRecord JumpTarget(unsigned LabelID) {
Daniel Sanders8e82af22017-07-27 11:03:45 +0000342 return MatchTableRecord(LabelID, "Label " + llvm::to_string(LabelID), 1,
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000343 MatchTableRecord::MTRF_JumpTarget |
344 MatchTableRecord::MTRF_Comment |
345 MatchTableRecord::MTRF_CommaFollows);
346 }
347
348 MatchTable(unsigned ID) : ID(ID), CurrentSize(0) {}
349
350 void push_back(const MatchTableRecord &Value) {
351 if (Value.Flags & MatchTableRecord::MTRF_Label)
352 defineLabel(Value.LabelID);
353 Contents.push_back(Value);
354 CurrentSize += Value.size();
355 }
356
Daniel Sanders8e82af22017-07-27 11:03:45 +0000357 unsigned allocateLabelID() const { return CurrentLabelID++; }
358
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000359 void defineLabel(unsigned LabelID) {
Daniel Sanders8e82af22017-07-27 11:03:45 +0000360 LabelMap.insert(std::make_pair(LabelID, CurrentSize));
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000361 }
362
363 unsigned getLabelIndex(unsigned LabelID) const {
364 const auto I = LabelMap.find(LabelID);
365 assert(I != LabelMap.end() && "Use of undeclared label");
366 return I->second;
367 }
368
Daniel Sanders8e82af22017-07-27 11:03:45 +0000369 void emitUse(raw_ostream &OS) const { OS << "MatchTable" << ID; }
370
371 void emitDeclaration(raw_ostream &OS) const {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000372 unsigned Indentation = 4;
Daniel Sanderscbbbfe42017-07-27 12:47:31 +0000373 OS << " constexpr static int64_t MatchTable" << ID << "[] = {";
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000374 LineBreak.emit(OS, true, *this);
375 OS << std::string(Indentation, ' ');
376
377 for (auto I = Contents.begin(), E = Contents.end(); I != E;
378 ++I) {
379 bool LineBreakIsNext = false;
380 const auto &NextI = std::next(I);
381
382 if (NextI != E) {
383 if (NextI->EmitStr == "" &&
384 NextI->Flags == MatchTableRecord::MTRF_LineBreakFollows)
385 LineBreakIsNext = true;
386 }
387
388 if (I->Flags & MatchTableRecord::MTRF_Indent)
389 Indentation += 2;
390
391 I->emit(OS, LineBreakIsNext, *this);
392 if (I->Flags & MatchTableRecord::MTRF_LineBreakFollows)
393 OS << std::string(Indentation, ' ');
394
395 if (I->Flags & MatchTableRecord::MTRF_Outdent)
396 Indentation -= 2;
397 }
398 OS << "};\n";
399 }
400};
401
Daniel Sanders8e82af22017-07-27 11:03:45 +0000402unsigned MatchTable::CurrentLabelID = 0;
403
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000404MatchTableRecord MatchTable::LineBreak = {
405 None, "" /* Emit String */, 0 /* Elements */,
406 MatchTableRecord::MTRF_LineBreakFollows};
407
408void MatchTableRecord::emit(raw_ostream &OS, bool LineBreakIsNextAfterThis,
409 const MatchTable &Table) const {
410 bool UseLineComment =
411 LineBreakIsNextAfterThis | (Flags & MTRF_LineBreakFollows);
412 if (Flags & (MTRF_JumpTarget | MTRF_CommaFollows))
413 UseLineComment = false;
414
415 if (Flags & MTRF_Comment)
416 OS << (UseLineComment ? "// " : "/*");
417
418 OS << EmitStr;
419 if (Flags & MTRF_Label)
420 OS << ": @" << Table.getLabelIndex(LabelID);
421
422 if (Flags & MTRF_Comment && !UseLineComment)
423 OS << "*/";
424
425 if (Flags & MTRF_JumpTarget) {
426 if (Flags & MTRF_Comment)
427 OS << " ";
428 OS << Table.getLabelIndex(LabelID);
429 }
430
431 if (Flags & MTRF_CommaFollows) {
432 OS << ",";
433 if (!LineBreakIsNextAfterThis && !(Flags & MTRF_LineBreakFollows))
434 OS << " ";
435 }
436
437 if (Flags & MTRF_LineBreakFollows)
438 OS << "\n";
439}
440
441MatchTable &operator<<(MatchTable &Table, const MatchTableRecord &Value) {
442 Table.push_back(Value);
443 return Table;
444}
445
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000446//===- Matchers -----------------------------------------------------------===//
447
Daniel Sandersbee57392017-04-04 13:25:23 +0000448class OperandMatcher;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000449class MatchAction;
450
451/// Generates code to check that a match rule matches.
452class RuleMatcher {
453 /// A list of matchers that all need to succeed for the current rule to match.
454 /// FIXME: This currently supports a single match position but could be
455 /// extended to support multiple positions to support div/rem fusion or
456 /// load-multiple instructions.
457 std::vector<std::unique_ptr<InstructionMatcher>> Matchers;
458
459 /// A list of actions that need to be taken when all predicates in this rule
460 /// have succeeded.
461 std::vector<std::unique_ptr<MatchAction>> Actions;
462
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000463 /// A map of instruction matchers to the local variables created by
Daniel Sanders9d662d22017-07-06 10:06:12 +0000464 /// emitCaptureOpcodes().
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000465 std::map<const InstructionMatcher *, unsigned> InsnVariableIDs;
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000466
467 /// ID for the next instruction variable defined with defineInsnVar()
468 unsigned NextInsnVarID;
469
Daniel Sanderse7b0d662017-04-21 15:59:56 +0000470 std::vector<Record *> RequiredFeatures;
471
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000472public:
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000473 RuleMatcher()
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000474 : Matchers(), Actions(), InsnVariableIDs(), NextInsnVarID(0) {}
Zachary Turnerb7dbd872017-03-20 19:56:52 +0000475 RuleMatcher(RuleMatcher &&Other) = default;
476 RuleMatcher &operator=(RuleMatcher &&Other) = default;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000477
478 InstructionMatcher &addInstructionMatcher();
Daniel Sanderse7b0d662017-04-21 15:59:56 +0000479 void addRequiredFeature(Record *Feature);
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000480 const std::vector<Record *> &getRequiredFeatures() const;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000481
482 template <class Kind, class... Args> Kind &addAction(Args &&... args);
483
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000484 /// Define an instruction without emitting any code to do so.
485 /// This is used for the root of the match.
486 unsigned implicitlyDefineInsnVar(const InstructionMatcher &Matcher);
487 /// Define an instruction and emit corresponding state-machine opcodes.
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000488 unsigned defineInsnVar(MatchTable &Table, const InstructionMatcher &Matcher,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000489 unsigned InsnVarID, unsigned OpIdx);
490 unsigned getInsnVarID(const InstructionMatcher &InsnMatcher) const;
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000491
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000492 void emitCaptureOpcodes(MatchTable &Table);
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000493
Daniel Sanders8e82af22017-07-27 11:03:45 +0000494 void emit(MatchTable &Table);
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000495
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000496 /// Compare the priority of this object and B.
497 ///
498 /// Returns true if this object is more important than B.
499 bool isHigherPriorityThan(const RuleMatcher &B) const;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000500
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000501 /// Report the maximum number of temporary operands needed by the rule
502 /// matcher.
503 unsigned countRendererFns() const;
Daniel Sanders2deea182017-04-22 15:11:04 +0000504
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000505 // FIXME: Remove this as soon as possible
506 InstructionMatcher &insnmatcher_front() const { return *Matchers.front(); }
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000507};
508
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000509template <class PredicateTy> class PredicateListMatcher {
510private:
511 typedef std::vector<std::unique_ptr<PredicateTy>> PredicateVec;
512 PredicateVec Predicates;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000513
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000514public:
515 /// Construct a new operand predicate and add it to the matcher.
516 template <class Kind, class... Args>
517 Kind &addPredicate(Args&&... args) {
Ahmed Bougachab67a3ce2017-01-26 22:07:37 +0000518 Predicates.emplace_back(
519 llvm::make_unique<Kind>(std::forward<Args>(args)...));
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000520 return *static_cast<Kind *>(Predicates.back().get());
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000521 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000522
Daniel Sanders32291982017-06-28 13:50:04 +0000523 typename PredicateVec::const_iterator predicates_begin() const {
524 return Predicates.begin();
525 }
526 typename PredicateVec::const_iterator predicates_end() const {
527 return Predicates.end();
528 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000529 iterator_range<typename PredicateVec::const_iterator> predicates() const {
530 return make_range(predicates_begin(), predicates_end());
531 }
Daniel Sanders32291982017-06-28 13:50:04 +0000532 typename PredicateVec::size_type predicates_size() const {
533 return Predicates.size();
534 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000535
Daniel Sanders9d662d22017-07-06 10:06:12 +0000536 /// Emit MatchTable opcodes that tests whether all the predicates are met.
Ahmed Bougachab67a3ce2017-01-26 22:07:37 +0000537 template <class... Args>
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000538 void emitPredicateListOpcodes(MatchTable &Table, Args &&... args) const {
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000539 if (Predicates.empty()) {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000540 Table << MatchTable::Comment("No predicates") << MatchTable::LineBreak;
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000541 return;
542 }
543
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000544 for (const auto &Predicate : predicates())
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000545 Predicate->emitPredicateOpcodes(Table, std::forward<Args>(args)...);
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000546 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000547};
548
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000549/// Generates code to check a predicate of an operand.
550///
551/// Typical predicates include:
552/// * Operand is a particular register.
553/// * Operand is assigned a particular register bank.
554/// * Operand is an MBB.
555class OperandPredicateMatcher {
556public:
Daniel Sanders759ff412017-02-24 13:58:11 +0000557 /// This enum is used for RTTI and also defines the priority that is given to
558 /// the predicate when generating the matcher code. Kinds with higher priority
559 /// must be tested first.
560 ///
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000561 /// The relative priority of OPM_LLT, OPM_RegBank, and OPM_MBB do not matter
562 /// but OPM_Int must have priority over OPM_RegBank since constant integers
563 /// are represented by a virtual register defined by a G_CONSTANT instruction.
Daniel Sanders759ff412017-02-24 13:58:11 +0000564 enum PredicateKind {
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000565 OPM_ComplexPattern,
Daniel Sandersbee57392017-04-04 13:25:23 +0000566 OPM_Instruction,
Daniel Sandersfe12c0f2017-07-11 08:57:29 +0000567 OPM_IntrinsicID,
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000568 OPM_Int,
Daniel Sanders452c8ae2017-05-23 19:33:16 +0000569 OPM_LiteralInt,
Daniel Sanders759ff412017-02-24 13:58:11 +0000570 OPM_LLT,
571 OPM_RegBank,
572 OPM_MBB,
573 };
574
575protected:
576 PredicateKind Kind;
577
578public:
579 OperandPredicateMatcher(PredicateKind Kind) : Kind(Kind) {}
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000580 virtual ~OperandPredicateMatcher() {}
581
Daniel Sanders759ff412017-02-24 13:58:11 +0000582 PredicateKind getKind() const { return Kind; }
583
Daniel Sandersbee57392017-04-04 13:25:23 +0000584 /// Return the OperandMatcher for the specified operand or nullptr if there
585 /// isn't one by that name in this operand predicate matcher.
586 ///
587 /// InstructionOperandMatcher is the only subclass that can return non-null
588 /// for this.
589 virtual Optional<const OperandMatcher *>
Daniel Sandersdb7ed372017-04-04 13:52:00 +0000590 getOptionalOperand(StringRef SymbolicName) const {
Daniel Sandersbee57392017-04-04 13:25:23 +0000591 assert(!SymbolicName.empty() && "Cannot lookup unnamed operand");
592 return None;
593 }
594
Daniel Sanders9d662d22017-07-06 10:06:12 +0000595 /// Emit MatchTable opcodes to capture instructions into the MIs table.
Daniel Sandersbee57392017-04-04 13:25:23 +0000596 ///
Daniel Sanders9d662d22017-07-06 10:06:12 +0000597 /// Only InstructionOperandMatcher needs to do anything for this method the
598 /// rest just walk the tree.
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000599 virtual void emitCaptureOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders9d662d22017-07-06 10:06:12 +0000600 unsigned InsnVarID, unsigned OpIdx) const {}
Daniel Sandersbee57392017-04-04 13:25:23 +0000601
Daniel Sanders9d662d22017-07-06 10:06:12 +0000602 /// Emit MatchTable opcodes that check the predicate for the given operand.
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000603 virtual void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000604 unsigned InsnVarID,
605 unsigned OpIdx) const = 0;
Daniel Sanders759ff412017-02-24 13:58:11 +0000606
607 /// Compare the priority of this object and B.
608 ///
609 /// Returns true if this object is more important than B.
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000610 virtual bool isHigherPriorityThan(const OperandPredicateMatcher &B) const {
611 return Kind < B.Kind;
Daniel Sanders759ff412017-02-24 13:58:11 +0000612 };
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000613
614 /// Report the maximum number of temporary operands needed by the predicate
615 /// matcher.
Daniel Sanders2deea182017-04-22 15:11:04 +0000616 virtual unsigned countRendererFns() const { return 0; }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000617};
618
619/// Generates code to check that an operand is a particular LLT.
620class LLTOperandMatcher : public OperandPredicateMatcher {
621protected:
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000622 LLTCodeGen Ty;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000623
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000624public:
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000625 LLTOperandMatcher(const LLTCodeGen &Ty)
Daniel Sanders759ff412017-02-24 13:58:11 +0000626 : OperandPredicateMatcher(OPM_LLT), Ty(Ty) {}
627
628 static bool classof(const OperandPredicateMatcher *P) {
629 return P->getKind() == OPM_LLT;
630 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000631
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000632 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000633 unsigned InsnVarID, unsigned OpIdx) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000634 Table << MatchTable::Opcode("GIM_CheckType") << MatchTable::Comment("MI")
635 << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Op")
636 << MatchTable::IntValue(OpIdx) << MatchTable::Comment("Type")
637 << MatchTable::NamedValue(Ty.getCxxEnumValue())
638 << MatchTable::LineBreak;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000639 }
640};
641
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000642/// Generates code to check that an operand is a particular target constant.
643class ComplexPatternOperandMatcher : public OperandPredicateMatcher {
644protected:
Daniel Sanders4f3eb242017-04-05 13:14:03 +0000645 const OperandMatcher &Operand;
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000646 const Record &TheDef;
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000647
Daniel Sanders4f3eb242017-04-05 13:14:03 +0000648 unsigned getAllocatedTemporariesBaseID() const;
649
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000650public:
Daniel Sanders4f3eb242017-04-05 13:14:03 +0000651 ComplexPatternOperandMatcher(const OperandMatcher &Operand,
652 const Record &TheDef)
653 : OperandPredicateMatcher(OPM_ComplexPattern), Operand(Operand),
654 TheDef(TheDef) {}
655
656 static bool classof(const OperandPredicateMatcher *P) {
657 return P->getKind() == OPM_ComplexPattern;
658 }
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000659
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000660 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000661 unsigned InsnVarID, unsigned OpIdx) const override {
Daniel Sanders2deea182017-04-22 15:11:04 +0000662 unsigned ID = getAllocatedTemporariesBaseID();
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000663 Table << MatchTable::Opcode("GIM_CheckComplexPattern")
664 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
665 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
666 << MatchTable::Comment("Renderer") << MatchTable::IntValue(ID)
667 << MatchTable::NamedValue(("GICP_" + TheDef.getName()).str())
668 << MatchTable::LineBreak;
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000669 }
670
Daniel Sanders2deea182017-04-22 15:11:04 +0000671 unsigned countRendererFns() const override {
672 return 1;
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000673 }
674};
675
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000676/// Generates code to check that an operand is in a particular register bank.
677class RegisterBankOperandMatcher : public OperandPredicateMatcher {
678protected:
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000679 const CodeGenRegisterClass &RC;
680
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000681public:
Daniel Sanders759ff412017-02-24 13:58:11 +0000682 RegisterBankOperandMatcher(const CodeGenRegisterClass &RC)
683 : OperandPredicateMatcher(OPM_RegBank), RC(RC) {}
684
685 static bool classof(const OperandPredicateMatcher *P) {
686 return P->getKind() == OPM_RegBank;
687 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000688
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000689 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000690 unsigned InsnVarID, unsigned OpIdx) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000691 Table << MatchTable::Opcode("GIM_CheckRegBankForClass")
692 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
693 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
694 << MatchTable::Comment("RC")
695 << MatchTable::NamedValue(RC.getQualifiedName() + "RegClassID")
696 << MatchTable::LineBreak;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000697 }
698};
699
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000700/// Generates code to check that an operand is a basic block.
701class MBBOperandMatcher : public OperandPredicateMatcher {
702public:
Daniel Sanders759ff412017-02-24 13:58:11 +0000703 MBBOperandMatcher() : OperandPredicateMatcher(OPM_MBB) {}
704
705 static bool classof(const OperandPredicateMatcher *P) {
706 return P->getKind() == OPM_MBB;
707 }
708
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000709 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000710 unsigned InsnVarID, unsigned OpIdx) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000711 Table << MatchTable::Opcode("GIM_CheckIsMBB") << MatchTable::Comment("MI")
712 << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Op")
713 << MatchTable::IntValue(OpIdx) << MatchTable::LineBreak;
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000714 }
715};
716
Daniel Sanders452c8ae2017-05-23 19:33:16 +0000717/// Generates code to check that an operand is a G_CONSTANT with a particular
718/// int.
719class ConstantIntOperandMatcher : public OperandPredicateMatcher {
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000720protected:
721 int64_t Value;
722
723public:
Daniel Sanders452c8ae2017-05-23 19:33:16 +0000724 ConstantIntOperandMatcher(int64_t Value)
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000725 : OperandPredicateMatcher(OPM_Int), Value(Value) {}
726
727 static bool classof(const OperandPredicateMatcher *P) {
728 return P->getKind() == OPM_Int;
729 }
730
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000731 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000732 unsigned InsnVarID, unsigned OpIdx) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000733 Table << MatchTable::Opcode("GIM_CheckConstantInt")
734 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
735 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
736 << MatchTable::IntValue(Value) << MatchTable::LineBreak;
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000737 }
738};
739
Daniel Sanders452c8ae2017-05-23 19:33:16 +0000740/// Generates code to check that an operand is a raw int (where MO.isImm() or
741/// MO.isCImm() is true).
742class LiteralIntOperandMatcher : public OperandPredicateMatcher {
743protected:
744 int64_t Value;
745
746public:
747 LiteralIntOperandMatcher(int64_t Value)
748 : OperandPredicateMatcher(OPM_LiteralInt), Value(Value) {}
749
750 static bool classof(const OperandPredicateMatcher *P) {
751 return P->getKind() == OPM_LiteralInt;
752 }
753
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000754 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000755 unsigned InsnVarID, unsigned OpIdx) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000756 Table << MatchTable::Opcode("GIM_CheckLiteralInt")
757 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
758 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
759 << MatchTable::IntValue(Value) << MatchTable::LineBreak;
Daniel Sanders452c8ae2017-05-23 19:33:16 +0000760 }
761};
762
Daniel Sandersfe12c0f2017-07-11 08:57:29 +0000763/// Generates code to check that an operand is an intrinsic ID.
764class IntrinsicIDOperandMatcher : public OperandPredicateMatcher {
765protected:
766 const CodeGenIntrinsic *II;
767
768public:
769 IntrinsicIDOperandMatcher(const CodeGenIntrinsic *II)
770 : OperandPredicateMatcher(OPM_IntrinsicID), II(II) {}
771
772 static bool classof(const OperandPredicateMatcher *P) {
773 return P->getKind() == OPM_IntrinsicID;
774 }
775
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000776 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sandersfe12c0f2017-07-11 08:57:29 +0000777 unsigned InsnVarID, unsigned OpIdx) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000778 Table << MatchTable::Opcode("GIM_CheckIntrinsicID")
779 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
780 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
781 << MatchTable::NamedValue("Intrinsic::" + II->EnumName)
782 << MatchTable::LineBreak;
Daniel Sandersfe12c0f2017-07-11 08:57:29 +0000783 }
784};
785
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000786/// Generates code to check that a set of predicates match for a particular
787/// operand.
788class OperandMatcher : public PredicateListMatcher<OperandPredicateMatcher> {
789protected:
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000790 InstructionMatcher &Insn;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000791 unsigned OpIdx;
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000792 std::string SymbolicName;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000793
Daniel Sanders4f3eb242017-04-05 13:14:03 +0000794 /// The index of the first temporary variable allocated to this operand. The
795 /// number of allocated temporaries can be found with
Daniel Sanders2deea182017-04-22 15:11:04 +0000796 /// countRendererFns().
Daniel Sanders4f3eb242017-04-05 13:14:03 +0000797 unsigned AllocatedTemporariesBaseID;
798
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000799public:
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000800 OperandMatcher(InstructionMatcher &Insn, unsigned OpIdx,
Daniel Sanders4f3eb242017-04-05 13:14:03 +0000801 const std::string &SymbolicName,
802 unsigned AllocatedTemporariesBaseID)
803 : Insn(Insn), OpIdx(OpIdx), SymbolicName(SymbolicName),
804 AllocatedTemporariesBaseID(AllocatedTemporariesBaseID) {}
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000805
806 bool hasSymbolicName() const { return !SymbolicName.empty(); }
807 const StringRef getSymbolicName() const { return SymbolicName; }
Daniel Sandersffc7d582017-03-29 15:37:18 +0000808 void setSymbolicName(StringRef Name) {
809 assert(SymbolicName.empty() && "Operand already has a symbolic name");
810 SymbolicName = Name;
811 }
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000812 unsigned getOperandIndex() const { return OpIdx; }
813
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000814 std::string getOperandExpr(unsigned InsnVarID) const {
815 return "State.MIs[" + llvm::to_string(InsnVarID) + "]->getOperand(" +
816 llvm::to_string(OpIdx) + ")";
Daniel Sanderse604ef52017-02-20 15:30:43 +0000817 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000818
Daniel Sandersbee57392017-04-04 13:25:23 +0000819 Optional<const OperandMatcher *>
820 getOptionalOperand(StringRef DesiredSymbolicName) const {
821 assert(!DesiredSymbolicName.empty() && "Cannot lookup unnamed operand");
822 if (DesiredSymbolicName == SymbolicName)
823 return this;
824 for (const auto &OP : predicates()) {
825 const auto &MaybeOperand = OP->getOptionalOperand(DesiredSymbolicName);
826 if (MaybeOperand.hasValue())
827 return MaybeOperand.getValue();
828 }
829 return None;
830 }
831
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000832 InstructionMatcher &getInstructionMatcher() const { return Insn; }
833
Daniel Sanders9d662d22017-07-06 10:06:12 +0000834 /// Emit MatchTable opcodes to capture instructions into the MIs table.
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000835 void emitCaptureOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders9d662d22017-07-06 10:06:12 +0000836 unsigned InsnVarID) const {
Daniel Sandersbee57392017-04-04 13:25:23 +0000837 for (const auto &Predicate : predicates())
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000838 Predicate->emitCaptureOpcodes(Table, Rule, InsnVarID, OpIdx);
Daniel Sandersbee57392017-04-04 13:25:23 +0000839 }
840
Daniel Sanders9d662d22017-07-06 10:06:12 +0000841 /// Emit MatchTable opcodes that test whether the instruction named in
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000842 /// InsnVarID matches all the predicates and all the operands.
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000843 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000844 unsigned InsnVarID) const {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000845 std::string Comment;
846 raw_string_ostream CommentOS(Comment);
847 CommentOS << "MIs[" << InsnVarID << "] ";
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000848 if (SymbolicName.empty())
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000849 CommentOS << "Operand " << OpIdx;
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000850 else
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000851 CommentOS << SymbolicName;
852 Table << MatchTable::Comment(CommentOS.str()) << MatchTable::LineBreak;
853
854 emitPredicateListOpcodes(Table, Rule, InsnVarID, OpIdx);
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000855 }
Daniel Sanders759ff412017-02-24 13:58:11 +0000856
857 /// Compare the priority of this object and B.
858 ///
859 /// Returns true if this object is more important than B.
860 bool isHigherPriorityThan(const OperandMatcher &B) const {
861 // Operand matchers involving more predicates have higher priority.
862 if (predicates_size() > B.predicates_size())
863 return true;
864 if (predicates_size() < B.predicates_size())
865 return false;
866
867 // This assumes that predicates are added in a consistent order.
868 for (const auto &Predicate : zip(predicates(), B.predicates())) {
869 if (std::get<0>(Predicate)->isHigherPriorityThan(*std::get<1>(Predicate)))
870 return true;
871 if (std::get<1>(Predicate)->isHigherPriorityThan(*std::get<0>(Predicate)))
872 return false;
873 }
874
875 return false;
876 };
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000877
878 /// Report the maximum number of temporary operands needed by the operand
879 /// matcher.
Daniel Sanders2deea182017-04-22 15:11:04 +0000880 unsigned countRendererFns() const {
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000881 return std::accumulate(
882 predicates().begin(), predicates().end(), 0,
883 [](unsigned A,
884 const std::unique_ptr<OperandPredicateMatcher> &Predicate) {
Daniel Sanders2deea182017-04-22 15:11:04 +0000885 return A + Predicate->countRendererFns();
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000886 });
887 }
Daniel Sanders4f3eb242017-04-05 13:14:03 +0000888
889 unsigned getAllocatedTemporariesBaseID() const {
890 return AllocatedTemporariesBaseID;
891 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000892};
893
Daniel Sanders4f3eb242017-04-05 13:14:03 +0000894unsigned ComplexPatternOperandMatcher::getAllocatedTemporariesBaseID() const {
895 return Operand.getAllocatedTemporariesBaseID();
896}
897
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000898/// Generates code to check a predicate on an instruction.
899///
900/// Typical predicates include:
901/// * The opcode of the instruction is a particular value.
902/// * The nsw/nuw flag is/isn't set.
903class InstructionPredicateMatcher {
Daniel Sanders759ff412017-02-24 13:58:11 +0000904protected:
905 /// This enum is used for RTTI and also defines the priority that is given to
906 /// the predicate when generating the matcher code. Kinds with higher priority
907 /// must be tested first.
908 enum PredicateKind {
909 IPM_Opcode,
910 };
911
912 PredicateKind Kind;
913
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000914public:
Daniel Sanders8d4d72f2017-02-24 14:53:35 +0000915 InstructionPredicateMatcher(PredicateKind Kind) : Kind(Kind) {}
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000916 virtual ~InstructionPredicateMatcher() {}
917
Daniel Sanders759ff412017-02-24 13:58:11 +0000918 PredicateKind getKind() const { return Kind; }
919
Daniel Sanders9d662d22017-07-06 10:06:12 +0000920 /// Emit MatchTable opcodes that test whether the instruction named in
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000921 /// InsnVarID matches the predicate.
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000922 virtual void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000923 unsigned InsnVarID) const = 0;
Daniel Sanders759ff412017-02-24 13:58:11 +0000924
925 /// Compare the priority of this object and B.
926 ///
927 /// Returns true if this object is more important than B.
Daniel Sanders32291982017-06-28 13:50:04 +0000928 virtual bool
929 isHigherPriorityThan(const InstructionPredicateMatcher &B) const {
Daniel Sanders759ff412017-02-24 13:58:11 +0000930 return Kind < B.Kind;
931 };
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000932
933 /// Report the maximum number of temporary operands needed by the predicate
934 /// matcher.
Daniel Sanders2deea182017-04-22 15:11:04 +0000935 virtual unsigned countRendererFns() const { return 0; }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000936};
937
938/// Generates code to check the opcode of an instruction.
939class InstructionOpcodeMatcher : public InstructionPredicateMatcher {
940protected:
941 const CodeGenInstruction *I;
942
943public:
Daniel Sanders8d4d72f2017-02-24 14:53:35 +0000944 InstructionOpcodeMatcher(const CodeGenInstruction *I)
945 : InstructionPredicateMatcher(IPM_Opcode), I(I) {}
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000946
Daniel Sanders759ff412017-02-24 13:58:11 +0000947 static bool classof(const InstructionPredicateMatcher *P) {
948 return P->getKind() == IPM_Opcode;
949 }
950
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000951 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000952 unsigned InsnVarID) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000953 Table << MatchTable::Opcode("GIM_CheckOpcode") << MatchTable::Comment("MI")
954 << MatchTable::IntValue(InsnVarID)
955 << MatchTable::NamedValue(I->Namespace, I->TheDef->getName())
956 << MatchTable::LineBreak;
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000957 }
Daniel Sanders759ff412017-02-24 13:58:11 +0000958
959 /// Compare the priority of this object and B.
960 ///
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000961 /// Returns true if this object is more important than B.
Daniel Sanders32291982017-06-28 13:50:04 +0000962 bool
963 isHigherPriorityThan(const InstructionPredicateMatcher &B) const override {
Daniel Sanders759ff412017-02-24 13:58:11 +0000964 if (InstructionPredicateMatcher::isHigherPriorityThan(B))
965 return true;
966 if (B.InstructionPredicateMatcher::isHigherPriorityThan(*this))
967 return false;
968
969 // Prioritize opcodes for cosmetic reasons in the generated source. Although
970 // this is cosmetic at the moment, we may want to drive a similar ordering
971 // using instruction frequency information to improve compile time.
972 if (const InstructionOpcodeMatcher *BO =
973 dyn_cast<InstructionOpcodeMatcher>(&B))
974 return I->TheDef->getName() < BO->I->TheDef->getName();
975
976 return false;
977 };
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000978};
979
980/// Generates code to check that a set of predicates and operands match for a
981/// particular instruction.
982///
983/// Typical predicates include:
984/// * Has a specific opcode.
985/// * Has an nsw/nuw flag or doesn't.
986class InstructionMatcher
987 : public PredicateListMatcher<InstructionPredicateMatcher> {
988protected:
Daniel Sanders4f3eb242017-04-05 13:14:03 +0000989 typedef std::vector<std::unique_ptr<OperandMatcher>> OperandVec;
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000990
991 /// The operands to match. All rendered operands must be present even if the
992 /// condition is always true.
993 OperandVec Operands;
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000994
995public:
996 /// Add an operand to the matcher.
Daniel Sanders4f3eb242017-04-05 13:14:03 +0000997 OperandMatcher &addOperand(unsigned OpIdx, const std::string &SymbolicName,
998 unsigned AllocatedTemporariesBaseID) {
999 Operands.emplace_back(new OperandMatcher(*this, OpIdx, SymbolicName,
1000 AllocatedTemporariesBaseID));
1001 return *Operands.back();
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001002 }
1003
Daniel Sandersffc7d582017-03-29 15:37:18 +00001004 OperandMatcher &getOperand(unsigned OpIdx) {
1005 auto I = std::find_if(Operands.begin(), Operands.end(),
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001006 [&OpIdx](const std::unique_ptr<OperandMatcher> &X) {
1007 return X->getOperandIndex() == OpIdx;
Daniel Sandersffc7d582017-03-29 15:37:18 +00001008 });
1009 if (I != Operands.end())
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001010 return **I;
Daniel Sandersffc7d582017-03-29 15:37:18 +00001011 llvm_unreachable("Failed to lookup operand");
1012 }
1013
Daniel Sandersbee57392017-04-04 13:25:23 +00001014 Optional<const OperandMatcher *>
1015 getOptionalOperand(StringRef SymbolicName) const {
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001016 assert(!SymbolicName.empty() && "Cannot lookup unnamed operand");
Daniel Sandersbee57392017-04-04 13:25:23 +00001017 for (const auto &Operand : Operands) {
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001018 const auto &OM = Operand->getOptionalOperand(SymbolicName);
Daniel Sandersbee57392017-04-04 13:25:23 +00001019 if (OM.hasValue())
1020 return OM.getValue();
1021 }
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001022 return None;
1023 }
1024
Daniel Sandersdb7ed372017-04-04 13:52:00 +00001025 const OperandMatcher &getOperand(StringRef SymbolicName) const {
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001026 Optional<const OperandMatcher *>OM = getOptionalOperand(SymbolicName);
1027 if (OM.hasValue())
1028 return *OM.getValue();
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001029 llvm_unreachable("Failed to lookup operand");
1030 }
1031
1032 unsigned getNumOperands() const { return Operands.size(); }
Daniel Sandersbee57392017-04-04 13:25:23 +00001033 OperandVec::iterator operands_begin() { return Operands.begin(); }
1034 OperandVec::iterator operands_end() { return Operands.end(); }
1035 iterator_range<OperandVec::iterator> operands() {
1036 return make_range(operands_begin(), operands_end());
1037 }
Daniel Sandersffc7d582017-03-29 15:37:18 +00001038 OperandVec::const_iterator operands_begin() const { return Operands.begin(); }
1039 OperandVec::const_iterator operands_end() const { return Operands.end(); }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001040 iterator_range<OperandVec::const_iterator> operands() const {
1041 return make_range(operands_begin(), operands_end());
1042 }
1043
Daniel Sanders9d662d22017-07-06 10:06:12 +00001044 /// Emit MatchTable opcodes to check the shape of the match and capture
1045 /// instructions into the MIs table.
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001046 void emitCaptureOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders9d662d22017-07-06 10:06:12 +00001047 unsigned InsnID) {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001048 Table << MatchTable::Opcode("GIM_CheckNumOperands")
1049 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnID)
1050 << MatchTable::Comment("Expected")
1051 << MatchTable::IntValue(getNumOperands()) << MatchTable::LineBreak;
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001052 for (const auto &Operand : Operands)
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001053 Operand->emitCaptureOpcodes(Table, Rule, InsnID);
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001054 }
1055
Daniel Sanders9d662d22017-07-06 10:06:12 +00001056 /// Emit MatchTable opcodes that test whether the instruction named in
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001057 /// InsnVarName matches all the predicates and all the operands.
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001058 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001059 unsigned InsnVarID) const {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001060 emitPredicateListOpcodes(Table, Rule, InsnVarID);
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001061 for (const auto &Operand : Operands)
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001062 Operand->emitPredicateOpcodes(Table, Rule, InsnVarID);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001063 }
Daniel Sanders759ff412017-02-24 13:58:11 +00001064
1065 /// Compare the priority of this object and B.
1066 ///
1067 /// Returns true if this object is more important than B.
1068 bool isHigherPriorityThan(const InstructionMatcher &B) const {
1069 // Instruction matchers involving more operands have higher priority.
1070 if (Operands.size() > B.Operands.size())
1071 return true;
1072 if (Operands.size() < B.Operands.size())
1073 return false;
1074
1075 for (const auto &Predicate : zip(predicates(), B.predicates())) {
1076 if (std::get<0>(Predicate)->isHigherPriorityThan(*std::get<1>(Predicate)))
1077 return true;
1078 if (std::get<1>(Predicate)->isHigherPriorityThan(*std::get<0>(Predicate)))
1079 return false;
1080 }
1081
1082 for (const auto &Operand : zip(Operands, B.Operands)) {
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001083 if (std::get<0>(Operand)->isHigherPriorityThan(*std::get<1>(Operand)))
Daniel Sanders759ff412017-02-24 13:58:11 +00001084 return true;
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001085 if (std::get<1>(Operand)->isHigherPriorityThan(*std::get<0>(Operand)))
Daniel Sanders759ff412017-02-24 13:58:11 +00001086 return false;
1087 }
1088
1089 return false;
1090 };
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001091
1092 /// Report the maximum number of temporary operands needed by the instruction
1093 /// matcher.
Daniel Sanders2deea182017-04-22 15:11:04 +00001094 unsigned countRendererFns() const {
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001095 return std::accumulate(predicates().begin(), predicates().end(), 0,
1096 [](unsigned A,
1097 const std::unique_ptr<InstructionPredicateMatcher>
1098 &Predicate) {
Daniel Sanders2deea182017-04-22 15:11:04 +00001099 return A + Predicate->countRendererFns();
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001100 }) +
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001101 std::accumulate(
1102 Operands.begin(), Operands.end(), 0,
1103 [](unsigned A, const std::unique_ptr<OperandMatcher> &Operand) {
Daniel Sanders2deea182017-04-22 15:11:04 +00001104 return A + Operand->countRendererFns();
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001105 });
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001106 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001107};
1108
Daniel Sandersbee57392017-04-04 13:25:23 +00001109/// Generates code to check that the operand is a register defined by an
1110/// instruction that matches the given instruction matcher.
1111///
1112/// For example, the pattern:
1113/// (set $dst, (G_MUL (G_ADD $src1, $src2), $src3))
1114/// would use an InstructionOperandMatcher for operand 1 of the G_MUL to match
1115/// the:
1116/// (G_ADD $src1, $src2)
1117/// subpattern.
1118class InstructionOperandMatcher : public OperandPredicateMatcher {
1119protected:
1120 std::unique_ptr<InstructionMatcher> InsnMatcher;
1121
1122public:
1123 InstructionOperandMatcher()
1124 : OperandPredicateMatcher(OPM_Instruction),
1125 InsnMatcher(new InstructionMatcher()) {}
1126
1127 static bool classof(const OperandPredicateMatcher *P) {
1128 return P->getKind() == OPM_Instruction;
1129 }
1130
1131 InstructionMatcher &getInsnMatcher() const { return *InsnMatcher; }
1132
1133 Optional<const OperandMatcher *>
1134 getOptionalOperand(StringRef SymbolicName) const override {
1135 assert(!SymbolicName.empty() && "Cannot lookup unnamed operand");
1136 return InsnMatcher->getOptionalOperand(SymbolicName);
1137 }
1138
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001139 void emitCaptureOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders9d662d22017-07-06 10:06:12 +00001140 unsigned InsnID, unsigned OpIdx) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001141 unsigned InsnVarID = Rule.defineInsnVar(Table, *InsnMatcher, InsnID, OpIdx);
1142 InsnMatcher->emitCaptureOpcodes(Table, Rule, InsnVarID);
Daniel Sandersbee57392017-04-04 13:25:23 +00001143 }
1144
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001145 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001146 unsigned InsnVarID_,
1147 unsigned OpIdx_) const override {
1148 unsigned InsnVarID = Rule.getInsnVarID(*InsnMatcher);
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001149 InsnMatcher->emitPredicateOpcodes(Table, Rule, InsnVarID);
Daniel Sandersbee57392017-04-04 13:25:23 +00001150 }
1151};
1152
Daniel Sanders43c882c2017-02-01 10:53:10 +00001153//===- Actions ------------------------------------------------------------===//
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001154class OperandRenderer {
1155public:
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00001156 enum RendererKind {
1157 OR_Copy,
1158 OR_CopySubReg,
1159 OR_Imm,
1160 OR_Register,
1161 OR_ComplexPattern
1162 };
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001163
1164protected:
1165 RendererKind Kind;
1166
1167public:
1168 OperandRenderer(RendererKind Kind) : Kind(Kind) {}
1169 virtual ~OperandRenderer() {}
1170
1171 RendererKind getKind() const { return Kind; }
1172
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001173 virtual void emitRenderOpcodes(MatchTable &Table,
1174 RuleMatcher &Rule) const = 0;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001175};
1176
1177/// A CopyRenderer emits code to copy a single operand from an existing
1178/// instruction to the one being built.
1179class CopyRenderer : public OperandRenderer {
1180protected:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001181 unsigned NewInsnID;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001182 /// The matcher for the instruction that this operand is copied from.
1183 /// This provides the facility for looking up an a operand by it's name so
1184 /// that it can be used as a source for the instruction being built.
1185 const InstructionMatcher &Matched;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001186 /// The name of the operand.
1187 const StringRef SymbolicName;
1188
1189public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001190 CopyRenderer(unsigned NewInsnID, const InstructionMatcher &Matched,
1191 StringRef SymbolicName)
1192 : OperandRenderer(OR_Copy), NewInsnID(NewInsnID), Matched(Matched),
1193 SymbolicName(SymbolicName) {}
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001194
1195 static bool classof(const OperandRenderer *R) {
1196 return R->getKind() == OR_Copy;
1197 }
1198
1199 const StringRef getSymbolicName() const { return SymbolicName; }
1200
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001201 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001202 const OperandMatcher &Operand = Matched.getOperand(SymbolicName);
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001203 unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001204 Table << MatchTable::Opcode("GIR_Copy") << MatchTable::Comment("NewInsnID")
1205 << MatchTable::IntValue(NewInsnID) << MatchTable::Comment("OldInsnID")
1206 << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
1207 << MatchTable::IntValue(Operand.getOperandIndex())
1208 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001209 }
1210};
1211
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00001212/// A CopySubRegRenderer emits code to copy a single register operand from an
1213/// existing instruction to the one being built and indicate that only a
1214/// subregister should be copied.
1215class CopySubRegRenderer : public OperandRenderer {
1216protected:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001217 unsigned NewInsnID;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00001218 /// The matcher for the instruction that this operand is copied from.
1219 /// This provides the facility for looking up an a operand by it's name so
1220 /// that it can be used as a source for the instruction being built.
1221 const InstructionMatcher &Matched;
1222 /// The name of the operand.
1223 const StringRef SymbolicName;
1224 /// The subregister to extract.
1225 const CodeGenSubRegIndex *SubReg;
1226
1227public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001228 CopySubRegRenderer(unsigned NewInsnID, const InstructionMatcher &Matched,
1229 StringRef SymbolicName, const CodeGenSubRegIndex *SubReg)
1230 : OperandRenderer(OR_CopySubReg), NewInsnID(NewInsnID), Matched(Matched),
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00001231 SymbolicName(SymbolicName), SubReg(SubReg) {}
1232
1233 static bool classof(const OperandRenderer *R) {
1234 return R->getKind() == OR_CopySubReg;
1235 }
1236
1237 const StringRef getSymbolicName() const { return SymbolicName; }
1238
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001239 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00001240 const OperandMatcher &Operand = Matched.getOperand(SymbolicName);
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001241 unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001242 Table << MatchTable::Opcode("GIR_CopySubReg")
1243 << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
1244 << MatchTable::Comment("OldInsnID")
1245 << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
1246 << MatchTable::IntValue(Operand.getOperandIndex())
1247 << MatchTable::Comment("SubRegIdx")
1248 << MatchTable::IntValue(SubReg->EnumValue)
1249 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00001250 }
1251};
1252
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001253/// Adds a specific physical register to the instruction being built.
1254/// This is typically useful for WZR/XZR on AArch64.
1255class AddRegisterRenderer : public OperandRenderer {
1256protected:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001257 unsigned InsnID;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001258 const Record *RegisterDef;
1259
1260public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001261 AddRegisterRenderer(unsigned InsnID, const Record *RegisterDef)
1262 : OperandRenderer(OR_Register), InsnID(InsnID), RegisterDef(RegisterDef) {
1263 }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001264
1265 static bool classof(const OperandRenderer *R) {
1266 return R->getKind() == OR_Register;
1267 }
1268
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001269 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
1270 Table << MatchTable::Opcode("GIR_AddRegister")
1271 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1272 << MatchTable::NamedValue(
1273 (RegisterDef->getValue("Namespace")
1274 ? RegisterDef->getValueAsString("Namespace")
1275 : ""),
1276 RegisterDef->getName())
1277 << MatchTable::LineBreak;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001278 }
1279};
1280
Daniel Sanders0ed28822017-04-12 08:23:08 +00001281/// Adds a specific immediate to the instruction being built.
1282class ImmRenderer : public OperandRenderer {
1283protected:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001284 unsigned InsnID;
Daniel Sanders0ed28822017-04-12 08:23:08 +00001285 int64_t Imm;
1286
1287public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001288 ImmRenderer(unsigned InsnID, int64_t Imm)
1289 : OperandRenderer(OR_Imm), InsnID(InsnID), Imm(Imm) {}
Daniel Sanders0ed28822017-04-12 08:23:08 +00001290
1291 static bool classof(const OperandRenderer *R) {
1292 return R->getKind() == OR_Imm;
1293 }
1294
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001295 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
1296 Table << MatchTable::Opcode("GIR_AddImm") << MatchTable::Comment("InsnID")
1297 << MatchTable::IntValue(InsnID) << MatchTable::Comment("Imm")
1298 << MatchTable::IntValue(Imm) << MatchTable::LineBreak;
Daniel Sanders0ed28822017-04-12 08:23:08 +00001299 }
1300};
1301
Daniel Sanders2deea182017-04-22 15:11:04 +00001302/// Adds operands by calling a renderer function supplied by the ComplexPattern
1303/// matcher function.
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001304class RenderComplexPatternOperand : public OperandRenderer {
1305private:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001306 unsigned InsnID;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001307 const Record &TheDef;
Daniel Sanders2deea182017-04-22 15:11:04 +00001308 /// The name of the operand.
1309 const StringRef SymbolicName;
1310 /// The renderer number. This must be unique within a rule since it's used to
1311 /// identify a temporary variable to hold the renderer function.
1312 unsigned RendererID;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001313
1314 unsigned getNumOperands() const {
1315 return TheDef.getValueAsDag("Operands")->getNumArgs();
1316 }
1317
1318public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001319 RenderComplexPatternOperand(unsigned InsnID, const Record &TheDef,
1320 StringRef SymbolicName, unsigned RendererID)
1321 : OperandRenderer(OR_ComplexPattern), InsnID(InsnID), TheDef(TheDef),
Daniel Sanders2deea182017-04-22 15:11:04 +00001322 SymbolicName(SymbolicName), RendererID(RendererID) {}
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001323
1324 static bool classof(const OperandRenderer *R) {
1325 return R->getKind() == OR_ComplexPattern;
1326 }
1327
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001328 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
1329 Table << MatchTable::Opcode("GIR_ComplexRenderer")
1330 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1331 << MatchTable::Comment("RendererID")
1332 << MatchTable::IntValue(RendererID) << MatchTable::LineBreak;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001333 }
1334};
1335
Ahmed Bougacha56ca3a92017-02-04 00:47:10 +00001336/// An action taken when all Matcher predicates succeeded for a parent rule.
1337///
1338/// Typical actions include:
1339/// * Changing the opcode of an instruction.
1340/// * Adding an operand to an instruction.
Daniel Sanders43c882c2017-02-01 10:53:10 +00001341class MatchAction {
1342public:
1343 virtual ~MatchAction() {}
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001344
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001345 /// Emit the MatchTable opcodes to implement the action.
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001346 ///
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001347 /// \param RecycleInsnID If given, it's an instruction to recycle. The
1348 /// requirements on the instruction vary from action to
1349 /// action.
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001350 virtual void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule,
1351 unsigned RecycleInsnID) const = 0;
Daniel Sanders43c882c2017-02-01 10:53:10 +00001352};
1353
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +00001354/// Generates a comment describing the matched rule being acted upon.
1355class DebugCommentAction : public MatchAction {
1356private:
1357 const PatternToMatch &P;
1358
1359public:
1360 DebugCommentAction(const PatternToMatch &P) : P(P) {}
1361
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001362 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule,
1363 unsigned RecycleInsnID) const override {
1364 Table << MatchTable::Comment(llvm::to_string(*P.getSrcPattern()) + " => " +
1365 llvm::to_string(*P.getDstPattern()))
1366 << MatchTable::LineBreak;
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +00001367 }
1368};
1369
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001370/// Generates code to build an instruction or mutate an existing instruction
1371/// into the desired instruction when this is possible.
1372class BuildMIAction : public MatchAction {
Daniel Sanders43c882c2017-02-01 10:53:10 +00001373private:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001374 unsigned InsnID;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001375 const CodeGenInstruction *I;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001376 const InstructionMatcher &Matched;
1377 std::vector<std::unique_ptr<OperandRenderer>> OperandRenderers;
1378
1379 /// True if the instruction can be built solely by mutating the opcode.
1380 bool canMutate() const {
Daniel Sanderse9fdba32017-04-29 17:30:09 +00001381 if (OperandRenderers.size() != Matched.getNumOperands())
1382 return false;
1383
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001384 for (const auto &Renderer : enumerate(OperandRenderers)) {
Zachary Turner309a0882017-03-13 16:24:10 +00001385 if (const auto *Copy = dyn_cast<CopyRenderer>(&*Renderer.value())) {
Daniel Sanders3016d3c2017-04-22 14:31:28 +00001386 const OperandMatcher &OM = Matched.getOperand(Copy->getSymbolicName());
1387 if (&Matched != &OM.getInstructionMatcher() ||
1388 OM.getOperandIndex() != Renderer.index())
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001389 return false;
1390 } else
1391 return false;
1392 }
1393
1394 return true;
1395 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001396
Daniel Sanders43c882c2017-02-01 10:53:10 +00001397public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001398 BuildMIAction(unsigned InsnID, const CodeGenInstruction *I,
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00001399 const InstructionMatcher &Matched)
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001400 : InsnID(InsnID), I(I), Matched(Matched) {}
Daniel Sanders43c882c2017-02-01 10:53:10 +00001401
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001402 template <class Kind, class... Args>
1403 Kind &addRenderer(Args&&... args) {
1404 OperandRenderers.emplace_back(
1405 llvm::make_unique<Kind>(std::forward<Args>(args)...));
1406 return *static_cast<Kind *>(OperandRenderers.back().get());
1407 }
1408
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001409 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule,
1410 unsigned RecycleInsnID) const override {
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001411 if (canMutate()) {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001412 Table << MatchTable::Opcode("GIR_MutateOpcode")
1413 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1414 << MatchTable::Comment("RecycleInsnID")
1415 << MatchTable::IntValue(RecycleInsnID)
1416 << MatchTable::Comment("Opcode")
1417 << MatchTable::NamedValue(I->Namespace, I->TheDef->getName())
1418 << MatchTable::LineBreak;
Tim Northover4340d642017-03-20 21:58:23 +00001419
1420 if (!I->ImplicitDefs.empty() || !I->ImplicitUses.empty()) {
Tim Northover4340d642017-03-20 21:58:23 +00001421 for (auto Def : I->ImplicitDefs) {
Diana Picus8abcbbb2017-05-02 09:40:49 +00001422 auto Namespace = Def->getValue("Namespace")
1423 ? Def->getValueAsString("Namespace")
1424 : "";
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001425 Table << MatchTable::Opcode("GIR_AddImplicitDef")
1426 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1427 << MatchTable::NamedValue(Namespace, Def->getName())
1428 << MatchTable::LineBreak;
Tim Northover4340d642017-03-20 21:58:23 +00001429 }
1430 for (auto Use : I->ImplicitUses) {
Diana Picus8abcbbb2017-05-02 09:40:49 +00001431 auto Namespace = Use->getValue("Namespace")
1432 ? Use->getValueAsString("Namespace")
1433 : "";
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001434 Table << MatchTable::Opcode("GIR_AddImplicitUse")
1435 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1436 << MatchTable::NamedValue(Namespace, Use->getName())
1437 << MatchTable::LineBreak;
Tim Northover4340d642017-03-20 21:58:23 +00001438 }
1439 }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001440 return;
1441 }
1442
1443 // TODO: Simple permutation looks like it could be almost as common as
1444 // mutation due to commutative operations.
1445
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001446 Table << MatchTable::Opcode("GIR_BuildMI") << MatchTable::Comment("InsnID")
1447 << MatchTable::IntValue(InsnID) << MatchTable::Comment("Opcode")
1448 << MatchTable::NamedValue(I->Namespace, I->TheDef->getName())
1449 << MatchTable::LineBreak;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001450 for (const auto &Renderer : OperandRenderers)
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001451 Renderer->emitRenderOpcodes(Table, Rule);
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001452
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001453 Table << MatchTable::Opcode("GIR_MergeMemOperands")
1454 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1455 << MatchTable::LineBreak << MatchTable::Opcode("GIR_EraseFromParent")
1456 << MatchTable::Comment("InsnID")
1457 << MatchTable::IntValue(RecycleInsnID) << MatchTable::LineBreak;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00001458 }
1459};
1460
1461/// Generates code to constrain the operands of an output instruction to the
1462/// register classes specified by the definition of that instruction.
1463class ConstrainOperandsToDefinitionAction : public MatchAction {
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001464 unsigned InsnID;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00001465
1466public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001467 ConstrainOperandsToDefinitionAction(unsigned InsnID) : InsnID(InsnID) {}
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00001468
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001469 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule,
1470 unsigned RecycleInsnID) const override {
1471 Table << MatchTable::Opcode("GIR_ConstrainSelectedInstOperands")
1472 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1473 << MatchTable::LineBreak;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00001474 }
1475};
1476
1477/// Generates code to constrain the specified operand of an output instruction
1478/// to the specified register class.
1479class ConstrainOperandToRegClassAction : public MatchAction {
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001480 unsigned InsnID;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00001481 unsigned OpIdx;
1482 const CodeGenRegisterClass &RC;
1483
1484public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001485 ConstrainOperandToRegClassAction(unsigned InsnID, unsigned OpIdx,
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00001486 const CodeGenRegisterClass &RC)
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001487 : InsnID(InsnID), OpIdx(OpIdx), RC(RC) {}
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00001488
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001489 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule,
1490 unsigned RecycleInsnID) const override {
1491 Table << MatchTable::Opcode("GIR_ConstrainOperandRC")
1492 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1493 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1494 << MatchTable::Comment("RC " + RC.getName())
1495 << MatchTable::IntValue(RC.EnumValue) << MatchTable::LineBreak;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001496 }
1497};
1498
Daniel Sandersbdfebb82017-03-15 20:18:38 +00001499InstructionMatcher &RuleMatcher::addInstructionMatcher() {
1500 Matchers.emplace_back(new InstructionMatcher());
1501 return *Matchers.back();
1502}
Ahmed Bougacha56ca3a92017-02-04 00:47:10 +00001503
Daniel Sanderse7b0d662017-04-21 15:59:56 +00001504void RuleMatcher::addRequiredFeature(Record *Feature) {
1505 RequiredFeatures.push_back(Feature);
1506}
1507
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001508const std::vector<Record *> &RuleMatcher::getRequiredFeatures() const {
1509 return RequiredFeatures;
1510}
1511
Daniel Sandersbdfebb82017-03-15 20:18:38 +00001512template <class Kind, class... Args>
1513Kind &RuleMatcher::addAction(Args &&... args) {
1514 Actions.emplace_back(llvm::make_unique<Kind>(std::forward<Args>(args)...));
1515 return *static_cast<Kind *>(Actions.back().get());
1516}
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001517
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001518unsigned
1519RuleMatcher::implicitlyDefineInsnVar(const InstructionMatcher &Matcher) {
1520 unsigned NewInsnVarID = NextInsnVarID++;
1521 InsnVariableIDs[&Matcher] = NewInsnVarID;
1522 return NewInsnVarID;
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001523}
1524
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001525unsigned RuleMatcher::defineInsnVar(MatchTable &Table,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001526 const InstructionMatcher &Matcher,
1527 unsigned InsnID, unsigned OpIdx) {
1528 unsigned NewInsnVarID = implicitlyDefineInsnVar(Matcher);
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001529 Table << MatchTable::Opcode("GIM_RecordInsn")
1530 << MatchTable::Comment("DefineMI") << MatchTable::IntValue(NewInsnVarID)
1531 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnID)
1532 << MatchTable::Comment("OpIdx") << MatchTable::IntValue(OpIdx)
1533 << MatchTable::Comment("MIs[" + llvm::to_string(NewInsnVarID) + "]")
1534 << MatchTable::LineBreak;
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001535 return NewInsnVarID;
1536}
1537
1538unsigned RuleMatcher::getInsnVarID(const InstructionMatcher &InsnMatcher) const {
1539 const auto &I = InsnVariableIDs.find(&InsnMatcher);
1540 if (I != InsnVariableIDs.end())
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001541 return I->second;
1542 llvm_unreachable("Matched Insn was not captured in a local variable");
1543}
1544
Daniel Sanders9d662d22017-07-06 10:06:12 +00001545/// Emit MatchTable opcodes to check the shape of the match and capture
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001546/// instructions into local variables.
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001547void RuleMatcher::emitCaptureOpcodes(MatchTable &Table) {
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001548 assert(Matchers.size() == 1 && "Cannot handle multi-root matchers yet");
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001549 unsigned InsnVarID = implicitlyDefineInsnVar(*Matchers.front());
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001550 Matchers.front()->emitCaptureOpcodes(Table, *this, InsnVarID);
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001551}
1552
Daniel Sanders8e82af22017-07-27 11:03:45 +00001553void RuleMatcher::emit(MatchTable &Table) {
Daniel Sandersbdfebb82017-03-15 20:18:38 +00001554 if (Matchers.empty())
1555 llvm_unreachable("Unexpected empty matcher!");
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001556
Daniel Sandersbdfebb82017-03-15 20:18:38 +00001557 // The representation supports rules that require multiple roots such as:
1558 // %ptr(p0) = ...
1559 // %elt0(s32) = G_LOAD %ptr
1560 // %1(p0) = G_ADD %ptr, 4
1561 // %elt1(s32) = G_LOAD p0 %1
1562 // which could be usefully folded into:
1563 // %ptr(p0) = ...
1564 // %elt0(s32), %elt1(s32) = TGT_LOAD_PAIR %ptr
1565 // on some targets but we don't need to make use of that yet.
1566 assert(Matchers.size() == 1 && "Cannot handle multi-root matchers yet");
Daniel Sanderse7b0d662017-04-21 15:59:56 +00001567
Daniel Sanders8e82af22017-07-27 11:03:45 +00001568 unsigned LabelID = Table.allocateLabelID();
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001569 Table << MatchTable::Opcode("GIM_Try", +1)
Daniel Sanders8e82af22017-07-27 11:03:45 +00001570 << MatchTable::Comment("On fail goto") << MatchTable::JumpTarget(LabelID)
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001571 << MatchTable::LineBreak;
1572
Daniel Sanderse7b0d662017-04-21 15:59:56 +00001573 if (!RequiredFeatures.empty()) {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001574 Table << MatchTable::Opcode("GIM_CheckFeatures")
1575 << MatchTable::NamedValue(getNameForFeatureBitset(RequiredFeatures))
1576 << MatchTable::LineBreak;
Daniel Sanderse7b0d662017-04-21 15:59:56 +00001577 }
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001578
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001579 emitCaptureOpcodes(Table);
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001580
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001581 Matchers.front()->emitPredicateOpcodes(Table, *this,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001582 getInsnVarID(*Matchers.front()));
1583
Daniel Sandersbee57392017-04-04 13:25:23 +00001584 // We must also check if it's safe to fold the matched instructions.
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001585 if (InsnVariableIDs.size() >= 2) {
Galina Kistanova1754fee2017-05-25 01:51:53 +00001586 // Invert the map to create stable ordering (by var names)
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001587 SmallVector<unsigned, 2> InsnIDs;
1588 for (const auto &Pair : InsnVariableIDs) {
Daniel Sandersbee57392017-04-04 13:25:23 +00001589 // Skip the root node since it isn't moving anywhere. Everything else is
1590 // sinking to meet it.
1591 if (Pair.first == Matchers.front().get())
1592 continue;
1593
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001594 InsnIDs.push_back(Pair.second);
Galina Kistanova1754fee2017-05-25 01:51:53 +00001595 }
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001596 std::sort(InsnIDs.begin(), InsnIDs.end());
Galina Kistanova1754fee2017-05-25 01:51:53 +00001597
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001598 for (const auto &InsnID : InsnIDs) {
Daniel Sandersbee57392017-04-04 13:25:23 +00001599 // Reject the difficult cases until we have a more accurate check.
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001600 Table << MatchTable::Opcode("GIM_CheckIsSafeToFold")
1601 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1602 << MatchTable::LineBreak;
Daniel Sandersbee57392017-04-04 13:25:23 +00001603
1604 // FIXME: Emit checks to determine it's _actually_ safe to fold and/or
1605 // account for unsafe cases.
1606 //
1607 // Example:
1608 // MI1--> %0 = ...
1609 // %1 = ... %0
1610 // MI0--> %2 = ... %0
1611 // It's not safe to erase MI1. We currently handle this by not
1612 // erasing %0 (even when it's dead).
1613 //
1614 // Example:
1615 // MI1--> %0 = load volatile @a
1616 // %1 = load volatile @a
1617 // MI0--> %2 = ... %0
1618 // It's not safe to sink %0's def past %1. We currently handle
1619 // this by rejecting all loads.
1620 //
1621 // Example:
1622 // MI1--> %0 = load @a
1623 // %1 = store @a
1624 // MI0--> %2 = ... %0
1625 // It's not safe to sink %0's def past %1. We currently handle
1626 // this by rejecting all loads.
1627 //
1628 // Example:
1629 // G_CONDBR %cond, @BB1
1630 // BB0:
1631 // MI1--> %0 = load @a
1632 // G_BR @BB1
1633 // BB1:
1634 // MI0--> %2 = ... %0
1635 // It's not always safe to sink %0 across control flow. In this
1636 // case it may introduce a memory fault. We currentl handle this
1637 // by rejecting all loads.
1638 }
1639 }
1640
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001641 for (const auto &MA : Actions)
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001642 MA->emitActionOpcodes(Table, *this, 0);
1643 Table << MatchTable::Opcode("GIR_Done", -1) << MatchTable::LineBreak
Daniel Sanders8e82af22017-07-27 11:03:45 +00001644 << MatchTable::Label(LabelID);
Daniel Sandersbdfebb82017-03-15 20:18:38 +00001645}
Daniel Sanders43c882c2017-02-01 10:53:10 +00001646
Daniel Sandersbdfebb82017-03-15 20:18:38 +00001647bool RuleMatcher::isHigherPriorityThan(const RuleMatcher &B) const {
1648 // Rules involving more match roots have higher priority.
1649 if (Matchers.size() > B.Matchers.size())
1650 return true;
1651 if (Matchers.size() < B.Matchers.size())
Daniel Sanders759ff412017-02-24 13:58:11 +00001652 return false;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001653
Daniel Sandersbdfebb82017-03-15 20:18:38 +00001654 for (const auto &Matcher : zip(Matchers, B.Matchers)) {
1655 if (std::get<0>(Matcher)->isHigherPriorityThan(*std::get<1>(Matcher)))
1656 return true;
1657 if (std::get<1>(Matcher)->isHigherPriorityThan(*std::get<0>(Matcher)))
1658 return false;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001659 }
Daniel Sandersbdfebb82017-03-15 20:18:38 +00001660
1661 return false;
Simon Pilgrima7d1da82017-03-15 22:50:47 +00001662}
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001663
Daniel Sanders2deea182017-04-22 15:11:04 +00001664unsigned RuleMatcher::countRendererFns() const {
Daniel Sandersbdfebb82017-03-15 20:18:38 +00001665 return std::accumulate(
1666 Matchers.begin(), Matchers.end(), 0,
1667 [](unsigned A, const std::unique_ptr<InstructionMatcher> &Matcher) {
Daniel Sanders2deea182017-04-22 15:11:04 +00001668 return A + Matcher->countRendererFns();
Daniel Sandersbdfebb82017-03-15 20:18:38 +00001669 });
1670}
1671
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001672//===- GlobalISelEmitter class --------------------------------------------===//
1673
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00001674class GlobalISelEmitter {
1675public:
1676 explicit GlobalISelEmitter(RecordKeeper &RK);
1677 void run(raw_ostream &OS);
1678
1679private:
1680 const RecordKeeper &RK;
1681 const CodeGenDAGPatterns CGP;
1682 const CodeGenTarget &Target;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00001683 CodeGenRegBank CGRegs;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00001684
1685 /// Keep track of the equivalence between SDNodes and Instruction.
1686 /// This is defined using 'GINodeEquiv' in the target description.
1687 DenseMap<Record *, const CodeGenInstruction *> NodeEquivs;
1688
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001689 /// Keep track of the equivalence between ComplexPattern's and
1690 /// GIComplexOperandMatcher. Map entries are specified by subclassing
1691 /// GIComplexPatternEquiv.
1692 DenseMap<const Record *, const Record *> ComplexPatternEquivs;
1693
Daniel Sanderse7b0d662017-04-21 15:59:56 +00001694 // Map of predicates to their subtarget features.
Daniel Sanderse9fdba32017-04-29 17:30:09 +00001695 SubtargetFeatureInfoMap SubtargetFeatures;
Daniel Sanderse7b0d662017-04-21 15:59:56 +00001696
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00001697 void gatherNodeEquivs();
Daniel Sandersbdfebb82017-03-15 20:18:38 +00001698 const CodeGenInstruction *findNodeEquiv(Record *N) const;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00001699
Daniel Sanderse7b0d662017-04-21 15:59:56 +00001700 Error importRulePredicates(RuleMatcher &M, ArrayRef<Init *> Predicates);
Daniel Sandersffc7d582017-03-29 15:37:18 +00001701 Expected<InstructionMatcher &>
Daniel Sandersc270c502017-03-30 09:36:33 +00001702 createAndImportSelDAGMatcher(InstructionMatcher &InsnMatcher,
Daniel Sanders57938df2017-07-11 10:40:18 +00001703 const TreePatternNode *Src,
1704 unsigned &TempOpIdx) const;
Daniel Sandersc270c502017-03-30 09:36:33 +00001705 Error importChildMatcher(InstructionMatcher &InsnMatcher,
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001706 const TreePatternNode *SrcChild, unsigned OpIdx,
Daniel Sandersc270c502017-03-30 09:36:33 +00001707 unsigned &TempOpIdx) const;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00001708 Expected<BuildMIAction &>
1709 createAndImportInstructionRenderer(RuleMatcher &M, const TreePatternNode *Dst,
1710 const InstructionMatcher &InsnMatcher);
Daniel Sandersc270c502017-03-30 09:36:33 +00001711 Error importExplicitUseRenderer(BuildMIAction &DstMIBuilder,
1712 TreePatternNode *DstChild,
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001713 const InstructionMatcher &InsnMatcher) const;
Diana Picus382602f2017-05-17 08:57:28 +00001714 Error importDefaultOperandRenderers(BuildMIAction &DstMIBuilder,
1715 DagInit *DefaultOps) const;
Daniel Sandersc270c502017-03-30 09:36:33 +00001716 Error
Daniel Sandersffc7d582017-03-29 15:37:18 +00001717 importImplicitDefRenderers(BuildMIAction &DstMIBuilder,
1718 const std::vector<Record *> &ImplicitDefs) const;
1719
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00001720 /// Analyze pattern \p P, returning a matcher for it if possible.
1721 /// Otherwise, return an Error explaining why we don't support it.
1722 Expected<RuleMatcher> runOnPattern(const PatternToMatch &P);
Daniel Sanderse7b0d662017-04-21 15:59:56 +00001723
1724 void declareSubtargetFeature(Record *Predicate);
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00001725};
1726
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001727void GlobalISelEmitter::gatherNodeEquivs() {
1728 assert(NodeEquivs.empty());
1729 for (Record *Equiv : RK.getAllDerivedDefinitions("GINodeEquiv"))
1730 NodeEquivs[Equiv->getValueAsDef("Node")] =
1731 &Target.getInstruction(Equiv->getValueAsDef("I"));
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001732
1733 assert(ComplexPatternEquivs.empty());
1734 for (Record *Equiv : RK.getAllDerivedDefinitions("GIComplexPatternEquiv")) {
1735 Record *SelDAGEquiv = Equiv->getValueAsDef("SelDAGEquivalent");
1736 if (!SelDAGEquiv)
1737 continue;
1738 ComplexPatternEquivs[SelDAGEquiv] = Equiv;
1739 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001740}
1741
Daniel Sandersbdfebb82017-03-15 20:18:38 +00001742const CodeGenInstruction *GlobalISelEmitter::findNodeEquiv(Record *N) const {
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001743 return NodeEquivs.lookup(N);
1744}
1745
1746GlobalISelEmitter::GlobalISelEmitter(RecordKeeper &RK)
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00001747 : RK(RK), CGP(RK), Target(CGP.getTargetInfo()), CGRegs(RK) {}
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001748
1749//===- Emitter ------------------------------------------------------------===//
1750
Daniel Sandersc270c502017-03-30 09:36:33 +00001751Error
Daniel Sandersffc7d582017-03-29 15:37:18 +00001752GlobalISelEmitter::importRulePredicates(RuleMatcher &M,
Daniel Sanderse7b0d662017-04-21 15:59:56 +00001753 ArrayRef<Init *> Predicates) {
1754 for (const Init *Predicate : Predicates) {
1755 const DefInit *PredicateDef = static_cast<const DefInit *>(Predicate);
1756 declareSubtargetFeature(PredicateDef->getDef());
1757 M.addRequiredFeature(PredicateDef->getDef());
1758 }
1759
Daniel Sandersc270c502017-03-30 09:36:33 +00001760 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00001761}
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001762
Daniel Sanders57938df2017-07-11 10:40:18 +00001763Expected<InstructionMatcher &>
1764GlobalISelEmitter::createAndImportSelDAGMatcher(InstructionMatcher &InsnMatcher,
1765 const TreePatternNode *Src,
1766 unsigned &TempOpIdx) const {
Daniel Sanders85ffd362017-07-06 08:12:20 +00001767 const CodeGenInstruction *SrcGIOrNull = nullptr;
1768
Daniel Sandersffc7d582017-03-29 15:37:18 +00001769 // Start with the defined operands (i.e., the results of the root operator).
1770 if (Src->getExtTypes().size() > 1)
1771 return failedImport("Src pattern has multiple results");
1772
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001773 if (Src->isLeaf()) {
1774 Init *SrcInit = Src->getLeafValue();
Daniel Sanders3334cc02017-05-23 20:02:48 +00001775 if (isa<IntInit>(SrcInit)) {
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001776 InsnMatcher.addPredicate<InstructionOpcodeMatcher>(
1777 &Target.getInstruction(RK.getDef("G_CONSTANT")));
1778 } else
Daniel Sanders32291982017-06-28 13:50:04 +00001779 return failedImport(
1780 "Unable to deduce gMIR opcode to handle Src (which is a leaf)");
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001781 } else {
Daniel Sanders85ffd362017-07-06 08:12:20 +00001782 SrcGIOrNull = findNodeEquiv(Src->getOperator());
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001783 if (!SrcGIOrNull)
1784 return failedImport("Pattern operator lacks an equivalent Instruction" +
1785 explainOperator(Src->getOperator()));
1786 auto &SrcGI = *SrcGIOrNull;
Daniel Sandersffc7d582017-03-29 15:37:18 +00001787
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001788 // The operators look good: match the opcode
1789 InsnMatcher.addPredicate<InstructionOpcodeMatcher>(&SrcGI);
1790 }
Daniel Sandersffc7d582017-03-29 15:37:18 +00001791
1792 unsigned OpIdx = 0;
1793 for (const EEVT::TypeSet &Ty : Src->getExtTypes()) {
1794 auto OpTyOrNone = MVTToLLT(Ty.getConcrete());
1795
1796 if (!OpTyOrNone)
1797 return failedImport(
1798 "Result of Src pattern operator has an unsupported type");
1799
1800 // Results don't have a name unless they are the root node. The caller will
1801 // set the name if appropriate.
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001802 OperandMatcher &OM = InsnMatcher.addOperand(OpIdx++, "", TempOpIdx);
Daniel Sandersffc7d582017-03-29 15:37:18 +00001803 OM.addPredicate<LLTOperandMatcher>(*OpTyOrNone);
1804 }
1805
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001806 if (Src->isLeaf()) {
1807 Init *SrcInit = Src->getLeafValue();
1808 if (IntInit *SrcIntInit = dyn_cast<IntInit>(SrcInit)) {
1809 OperandMatcher &OM = InsnMatcher.addOperand(OpIdx++, "", TempOpIdx);
1810 OM.addPredicate<LiteralIntOperandMatcher>(SrcIntInit->getValue());
1811 } else
Daniel Sanders32291982017-06-28 13:50:04 +00001812 return failedImport(
1813 "Unable to deduce gMIR opcode to handle Src (which is a leaf)");
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001814 } else {
Daniel Sanders85ffd362017-07-06 08:12:20 +00001815 assert(SrcGIOrNull &&
1816 "Expected to have already found an equivalent Instruction");
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001817 // Match the used operands (i.e. the children of the operator).
1818 for (unsigned i = 0, e = Src->getNumChildren(); i != e; ++i) {
Daniel Sanders85ffd362017-07-06 08:12:20 +00001819 TreePatternNode *SrcChild = Src->getChild(i);
1820
1821 // For G_INTRINSIC, the operand immediately following the defs is an
1822 // intrinsic ID.
1823 if (SrcGIOrNull->TheDef->getName() == "G_INTRINSIC" && i == 0) {
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00001824 if (const CodeGenIntrinsic *II = Src->getIntrinsicInfo(CGP)) {
Daniel Sanders85ffd362017-07-06 08:12:20 +00001825 OperandMatcher &OM =
1826 InsnMatcher.addOperand(OpIdx++, SrcChild->getName(), TempOpIdx);
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00001827 OM.addPredicate<IntrinsicIDOperandMatcher>(II);
Daniel Sanders85ffd362017-07-06 08:12:20 +00001828 continue;
1829 }
1830
1831 return failedImport("Expected IntInit containing instrinsic ID)");
1832 }
1833
1834 if (auto Error =
1835 importChildMatcher(InsnMatcher, SrcChild, OpIdx++, TempOpIdx))
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001836 return std::move(Error);
1837 }
Daniel Sandersffc7d582017-03-29 15:37:18 +00001838 }
1839
1840 return InsnMatcher;
1841}
1842
Daniel Sandersc270c502017-03-30 09:36:33 +00001843Error GlobalISelEmitter::importChildMatcher(InstructionMatcher &InsnMatcher,
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001844 const TreePatternNode *SrcChild,
Daniel Sandersc270c502017-03-30 09:36:33 +00001845 unsigned OpIdx,
1846 unsigned &TempOpIdx) const {
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001847 OperandMatcher &OM =
1848 InsnMatcher.addOperand(OpIdx, SrcChild->getName(), TempOpIdx);
Daniel Sandersffc7d582017-03-29 15:37:18 +00001849
1850 if (SrcChild->hasAnyPredicate())
Daniel Sandersd0656a32017-04-13 09:45:37 +00001851 return failedImport("Src pattern child has predicate (" +
1852 explainPredicates(SrcChild) + ")");
Daniel Sandersffc7d582017-03-29 15:37:18 +00001853
1854 ArrayRef<EEVT::TypeSet> ChildTypes = SrcChild->getExtTypes();
1855 if (ChildTypes.size() != 1)
1856 return failedImport("Src pattern child has multiple results");
1857
1858 // Check MBB's before the type check since they are not a known type.
1859 if (!SrcChild->isLeaf()) {
1860 if (SrcChild->getOperator()->isSubClassOf("SDNode")) {
1861 auto &ChildSDNI = CGP.getSDNodeInfo(SrcChild->getOperator());
1862 if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") {
1863 OM.addPredicate<MBBOperandMatcher>();
Daniel Sandersc270c502017-03-30 09:36:33 +00001864 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00001865 }
1866 }
Daniel Sandersffc7d582017-03-29 15:37:18 +00001867 }
1868
1869 auto OpTyOrNone = MVTToLLT(ChildTypes.front().getConcrete());
1870 if (!OpTyOrNone)
Daniel Sanders85ffd362017-07-06 08:12:20 +00001871 return failedImport("Src operand has an unsupported type (" + to_string(*SrcChild) + ")");
Daniel Sandersffc7d582017-03-29 15:37:18 +00001872 OM.addPredicate<LLTOperandMatcher>(*OpTyOrNone);
1873
Daniel Sandersbee57392017-04-04 13:25:23 +00001874 // Check for nested instructions.
1875 if (!SrcChild->isLeaf()) {
1876 // Map the node to a gMIR instruction.
1877 InstructionOperandMatcher &InsnOperand =
1878 OM.addPredicate<InstructionOperandMatcher>();
Daniel Sanders57938df2017-07-11 10:40:18 +00001879 auto InsnMatcherOrError = createAndImportSelDAGMatcher(
1880 InsnOperand.getInsnMatcher(), SrcChild, TempOpIdx);
Daniel Sandersbee57392017-04-04 13:25:23 +00001881 if (auto Error = InsnMatcherOrError.takeError())
1882 return Error;
1883
1884 return Error::success();
1885 }
1886
Daniel Sandersffc7d582017-03-29 15:37:18 +00001887 // Check for constant immediates.
1888 if (auto *ChildInt = dyn_cast<IntInit>(SrcChild->getLeafValue())) {
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001889 OM.addPredicate<ConstantIntOperandMatcher>(ChildInt->getValue());
Daniel Sandersc270c502017-03-30 09:36:33 +00001890 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00001891 }
1892
1893 // Check for def's like register classes or ComplexPattern's.
1894 if (auto *ChildDefInit = dyn_cast<DefInit>(SrcChild->getLeafValue())) {
1895 auto *ChildRec = ChildDefInit->getDef();
1896
1897 // Check for register classes.
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00001898 if (ChildRec->isSubClassOf("RegisterClass") ||
1899 ChildRec->isSubClassOf("RegisterOperand")) {
Daniel Sandersffc7d582017-03-29 15:37:18 +00001900 OM.addPredicate<RegisterBankOperandMatcher>(
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00001901 Target.getRegisterClass(getInitValueAsRegClass(ChildDefInit)));
Daniel Sanders658541f2017-04-22 15:53:21 +00001902 return Error::success();
1903 }
1904
Daniel Sandersffc7d582017-03-29 15:37:18 +00001905 // Check for ComplexPattern's.
1906 if (ChildRec->isSubClassOf("ComplexPattern")) {
1907 const auto &ComplexPattern = ComplexPatternEquivs.find(ChildRec);
1908 if (ComplexPattern == ComplexPatternEquivs.end())
Daniel Sandersd0656a32017-04-13 09:45:37 +00001909 return failedImport("SelectionDAG ComplexPattern (" +
1910 ChildRec->getName() + ") not mapped to GlobalISel");
Daniel Sandersffc7d582017-03-29 15:37:18 +00001911
Daniel Sanders2deea182017-04-22 15:11:04 +00001912 OM.addPredicate<ComplexPatternOperandMatcher>(OM,
1913 *ComplexPattern->second);
1914 TempOpIdx++;
Daniel Sandersc270c502017-03-30 09:36:33 +00001915 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00001916 }
1917
Daniel Sandersd0656a32017-04-13 09:45:37 +00001918 if (ChildRec->isSubClassOf("ImmLeaf")) {
1919 return failedImport(
1920 "Src pattern child def is an unsupported tablegen class (ImmLeaf)");
1921 }
1922
Daniel Sandersffc7d582017-03-29 15:37:18 +00001923 return failedImport(
1924 "Src pattern child def is an unsupported tablegen class");
1925 }
1926
1927 return failedImport("Src pattern child is an unsupported kind");
1928}
1929
Daniel Sandersc270c502017-03-30 09:36:33 +00001930Error GlobalISelEmitter::importExplicitUseRenderer(
Daniel Sandersffc7d582017-03-29 15:37:18 +00001931 BuildMIAction &DstMIBuilder, TreePatternNode *DstChild,
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001932 const InstructionMatcher &InsnMatcher) const {
Daniel Sandersffc7d582017-03-29 15:37:18 +00001933 // The only non-leaf child we accept is 'bb': it's an operator because
1934 // BasicBlockSDNode isn't inline, but in MI it's just another operand.
1935 if (!DstChild->isLeaf()) {
1936 if (DstChild->getOperator()->isSubClassOf("SDNode")) {
1937 auto &ChildSDNI = CGP.getSDNodeInfo(DstChild->getOperator());
1938 if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") {
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001939 DstMIBuilder.addRenderer<CopyRenderer>(0, InsnMatcher,
Daniel Sandersffc7d582017-03-29 15:37:18 +00001940 DstChild->getName());
Daniel Sandersc270c502017-03-30 09:36:33 +00001941 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00001942 }
1943 }
1944 return failedImport("Dst pattern child isn't a leaf node or an MBB");
1945 }
1946
1947 // Otherwise, we're looking for a bog-standard RegisterClass operand.
1948 if (DstChild->hasAnyPredicate())
Daniel Sandersd0656a32017-04-13 09:45:37 +00001949 return failedImport("Dst pattern child has predicate (" +
1950 explainPredicates(DstChild) + ")");
Daniel Sandersffc7d582017-03-29 15:37:18 +00001951
1952 if (auto *ChildDefInit = dyn_cast<DefInit>(DstChild->getLeafValue())) {
1953 auto *ChildRec = ChildDefInit->getDef();
1954
1955 ArrayRef<EEVT::TypeSet> ChildTypes = DstChild->getExtTypes();
1956 if (ChildTypes.size() != 1)
1957 return failedImport("Dst pattern child has multiple results");
1958
1959 auto OpTyOrNone = MVTToLLT(ChildTypes.front().getConcrete());
1960 if (!OpTyOrNone)
1961 return failedImport("Dst operand has an unsupported type");
1962
1963 if (ChildRec->isSubClassOf("Register")) {
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001964 DstMIBuilder.addRenderer<AddRegisterRenderer>(0, ChildRec);
Daniel Sandersc270c502017-03-30 09:36:33 +00001965 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00001966 }
1967
Daniel Sanders658541f2017-04-22 15:53:21 +00001968 if (ChildRec->isSubClassOf("RegisterClass") ||
1969 ChildRec->isSubClassOf("RegisterOperand")) {
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001970 DstMIBuilder.addRenderer<CopyRenderer>(0, InsnMatcher,
1971 DstChild->getName());
Daniel Sandersc270c502017-03-30 09:36:33 +00001972 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00001973 }
1974
1975 if (ChildRec->isSubClassOf("ComplexPattern")) {
1976 const auto &ComplexPattern = ComplexPatternEquivs.find(ChildRec);
1977 if (ComplexPattern == ComplexPatternEquivs.end())
1978 return failedImport(
1979 "SelectionDAG ComplexPattern not mapped to GlobalISel");
1980
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001981 const OperandMatcher &OM = InsnMatcher.getOperand(DstChild->getName());
Daniel Sandersffc7d582017-03-29 15:37:18 +00001982 DstMIBuilder.addRenderer<RenderComplexPatternOperand>(
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001983 0, *ComplexPattern->second, DstChild->getName(),
Daniel Sanders2deea182017-04-22 15:11:04 +00001984 OM.getAllocatedTemporariesBaseID());
Daniel Sandersc270c502017-03-30 09:36:33 +00001985 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00001986 }
1987
Daniel Sandersd0656a32017-04-13 09:45:37 +00001988 if (ChildRec->isSubClassOf("SDNodeXForm"))
1989 return failedImport("Dst pattern child def is an unsupported tablegen "
1990 "class (SDNodeXForm)");
1991
Daniel Sandersffc7d582017-03-29 15:37:18 +00001992 return failedImport(
1993 "Dst pattern child def is an unsupported tablegen class");
1994 }
1995
1996 return failedImport("Dst pattern child is an unsupported kind");
1997}
1998
Daniel Sandersc270c502017-03-30 09:36:33 +00001999Expected<BuildMIAction &> GlobalISelEmitter::createAndImportInstructionRenderer(
Daniel Sandersffc7d582017-03-29 15:37:18 +00002000 RuleMatcher &M, const TreePatternNode *Dst,
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002001 const InstructionMatcher &InsnMatcher) {
Daniel Sandersffc7d582017-03-29 15:37:18 +00002002 Record *DstOp = Dst->getOperator();
Daniel Sandersd0656a32017-04-13 09:45:37 +00002003 if (!DstOp->isSubClassOf("Instruction")) {
2004 if (DstOp->isSubClassOf("ValueType"))
2005 return failedImport(
2006 "Pattern operator isn't an instruction (it's a ValueType)");
Daniel Sandersffc7d582017-03-29 15:37:18 +00002007 return failedImport("Pattern operator isn't an instruction");
Daniel Sandersd0656a32017-04-13 09:45:37 +00002008 }
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002009 CodeGenInstruction *DstI = &Target.getInstruction(DstOp);
Daniel Sandersffc7d582017-03-29 15:37:18 +00002010
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002011 unsigned DstINumUses = DstI->Operands.size() - DstI->Operands.NumDefs;
2012 unsigned ExpectedDstINumUses = Dst->getNumChildren();
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002013 bool IsExtractSubReg = false;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002014
2015 // COPY_TO_REGCLASS is just a copy with a ConstrainOperandToRegClassAction
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002016 // attached. Similarly for EXTRACT_SUBREG except that's a subregister copy.
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002017 if (DstI->TheDef->getName() == "COPY_TO_REGCLASS") {
2018 DstI = &Target.getInstruction(RK.getDef("COPY"));
2019 DstINumUses--; // Ignore the class constraint.
2020 ExpectedDstINumUses--;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002021 } else if (DstI->TheDef->getName() == "EXTRACT_SUBREG") {
2022 DstI = &Target.getInstruction(RK.getDef("COPY"));
2023 IsExtractSubReg = true;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002024 }
2025
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002026 auto &DstMIBuilder = M.addAction<BuildMIAction>(0, DstI, InsnMatcher);
Daniel Sandersffc7d582017-03-29 15:37:18 +00002027
2028 // Render the explicit defs.
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002029 for (unsigned I = 0; I < DstI->Operands.NumDefs; ++I) {
2030 const CGIOperandList::OperandInfo &DstIOperand = DstI->Operands[I];
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002031 DstMIBuilder.addRenderer<CopyRenderer>(0, InsnMatcher, DstIOperand.Name);
Daniel Sandersffc7d582017-03-29 15:37:18 +00002032 }
2033
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002034 // EXTRACT_SUBREG needs to use a subregister COPY.
2035 if (IsExtractSubReg) {
2036 if (!Dst->getChild(0)->isLeaf())
2037 return failedImport("EXTRACT_SUBREG child #1 is not a leaf");
2038
Daniel Sanders32291982017-06-28 13:50:04 +00002039 if (DefInit *SubRegInit =
2040 dyn_cast<DefInit>(Dst->getChild(1)->getLeafValue())) {
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002041 CodeGenRegisterClass *RC = CGRegs.getRegClass(
2042 getInitValueAsRegClass(Dst->getChild(0)->getLeafValue()));
2043 CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef());
2044
2045 const auto &SrcRCDstRCPair =
2046 RC->getMatchingSubClassWithSubRegs(CGRegs, SubIdx);
2047 if (SrcRCDstRCPair.hasValue()) {
2048 assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
2049 if (SrcRCDstRCPair->first != RC)
2050 return failedImport("EXTRACT_SUBREG requires an additional COPY");
2051 }
2052
2053 DstMIBuilder.addRenderer<CopySubRegRenderer>(
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002054 0, InsnMatcher, Dst->getChild(0)->getName(), SubIdx);
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002055 return DstMIBuilder;
2056 }
2057
2058 return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
2059 }
2060
Daniel Sandersffc7d582017-03-29 15:37:18 +00002061 // Render the explicit uses.
Daniel Sanders0ed28822017-04-12 08:23:08 +00002062 unsigned Child = 0;
Diana Picus382602f2017-05-17 08:57:28 +00002063 unsigned NumDefaultOps = 0;
Daniel Sanders0ed28822017-04-12 08:23:08 +00002064 for (unsigned I = 0; I != DstINumUses; ++I) {
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002065 const CGIOperandList::OperandInfo &DstIOperand =
2066 DstI->Operands[DstI->Operands.NumDefs + I];
Daniel Sanders0ed28822017-04-12 08:23:08 +00002067
Diana Picus382602f2017-05-17 08:57:28 +00002068 // If the operand has default values, introduce them now.
2069 // FIXME: Until we have a decent test case that dictates we should do
2070 // otherwise, we're going to assume that operands with default values cannot
2071 // be specified in the patterns. Therefore, adding them will not cause us to
2072 // end up with too many rendered operands.
2073 if (DstIOperand.Rec->isSubClassOf("OperandWithDefaultOps")) {
Daniel Sanders0ed28822017-04-12 08:23:08 +00002074 DagInit *DefaultOps = DstIOperand.Rec->getValueAsDag("DefaultOps");
Diana Picus382602f2017-05-17 08:57:28 +00002075 if (auto Error = importDefaultOperandRenderers(DstMIBuilder, DefaultOps))
2076 return std::move(Error);
2077 ++NumDefaultOps;
Daniel Sanders0ed28822017-04-12 08:23:08 +00002078 continue;
2079 }
2080
2081 if (auto Error = importExplicitUseRenderer(
2082 DstMIBuilder, Dst->getChild(Child), InsnMatcher))
Daniel Sandersffc7d582017-03-29 15:37:18 +00002083 return std::move(Error);
Daniel Sanders0ed28822017-04-12 08:23:08 +00002084 ++Child;
Daniel Sandersffc7d582017-03-29 15:37:18 +00002085 }
2086
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002087 if (NumDefaultOps + ExpectedDstINumUses != DstINumUses)
Diana Picuseb2057c2017-05-17 09:25:08 +00002088 return failedImport("Expected " + llvm::to_string(DstINumUses) +
Diana Picus382602f2017-05-17 08:57:28 +00002089 " used operands but found " +
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002090 llvm::to_string(ExpectedDstINumUses) +
Diana Picuseb2057c2017-05-17 09:25:08 +00002091 " explicit ones and " + llvm::to_string(NumDefaultOps) +
Diana Picus382602f2017-05-17 08:57:28 +00002092 " default ones");
2093
Daniel Sandersffc7d582017-03-29 15:37:18 +00002094 return DstMIBuilder;
2095}
2096
Diana Picus382602f2017-05-17 08:57:28 +00002097Error GlobalISelEmitter::importDefaultOperandRenderers(
2098 BuildMIAction &DstMIBuilder, DagInit *DefaultOps) const {
Craig Topper481ff702017-05-29 21:49:34 +00002099 for (const auto *DefaultOp : DefaultOps->getArgs()) {
Diana Picus382602f2017-05-17 08:57:28 +00002100 // Look through ValueType operators.
2101 if (const DagInit *DefaultDagOp = dyn_cast<DagInit>(DefaultOp)) {
2102 if (const DefInit *DefaultDagOperator =
2103 dyn_cast<DefInit>(DefaultDagOp->getOperator())) {
2104 if (DefaultDagOperator->getDef()->isSubClassOf("ValueType"))
2105 DefaultOp = DefaultDagOp->getArg(0);
2106 }
2107 }
2108
2109 if (const DefInit *DefaultDefOp = dyn_cast<DefInit>(DefaultOp)) {
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002110 DstMIBuilder.addRenderer<AddRegisterRenderer>(0, DefaultDefOp->getDef());
Diana Picus382602f2017-05-17 08:57:28 +00002111 continue;
2112 }
2113
2114 if (const IntInit *DefaultIntOp = dyn_cast<IntInit>(DefaultOp)) {
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002115 DstMIBuilder.addRenderer<ImmRenderer>(0, DefaultIntOp->getValue());
Diana Picus382602f2017-05-17 08:57:28 +00002116 continue;
2117 }
2118
2119 return failedImport("Could not add default op");
2120 }
2121
2122 return Error::success();
2123}
2124
Daniel Sandersc270c502017-03-30 09:36:33 +00002125Error GlobalISelEmitter::importImplicitDefRenderers(
Daniel Sandersffc7d582017-03-29 15:37:18 +00002126 BuildMIAction &DstMIBuilder,
2127 const std::vector<Record *> &ImplicitDefs) const {
2128 if (!ImplicitDefs.empty())
2129 return failedImport("Pattern defines a physical register");
Daniel Sandersc270c502017-03-30 09:36:33 +00002130 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00002131}
2132
2133Expected<RuleMatcher> GlobalISelEmitter::runOnPattern(const PatternToMatch &P) {
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002134 // Keep track of the matchers and actions to emit.
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +00002135 RuleMatcher M;
2136 M.addAction<DebugCommentAction>(P);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002137
Daniel Sandersc270c502017-03-30 09:36:33 +00002138 if (auto Error = importRulePredicates(M, P.getPredicates()->getValues()))
Daniel Sandersffc7d582017-03-29 15:37:18 +00002139 return std::move(Error);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002140
2141 // Next, analyze the pattern operators.
2142 TreePatternNode *Src = P.getSrcPattern();
2143 TreePatternNode *Dst = P.getDstPattern();
2144
2145 // If the root of either pattern isn't a simple operator, ignore it.
Daniel Sandersd0656a32017-04-13 09:45:37 +00002146 if (auto Err = isTrivialOperatorNode(Dst))
2147 return failedImport("Dst pattern root isn't a trivial operator (" +
2148 toString(std::move(Err)) + ")");
2149 if (auto Err = isTrivialOperatorNode(Src))
2150 return failedImport("Src pattern root isn't a trivial operator (" +
2151 toString(std::move(Err)) + ")");
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002152
Daniel Sanders452c8ae2017-05-23 19:33:16 +00002153 if (Dst->isLeaf())
2154 return failedImport("Dst pattern root isn't a known leaf");
2155
Daniel Sandersbee57392017-04-04 13:25:23 +00002156 // Start with the defined operands (i.e., the results of the root operator).
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002157 Record *DstOp = Dst->getOperator();
2158 if (!DstOp->isSubClassOf("Instruction"))
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002159 return failedImport("Pattern operator isn't an instruction");
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002160
2161 auto &DstI = Target.getInstruction(DstOp);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002162 if (DstI.Operands.NumDefs != Src->getExtTypes().size())
Daniel Sandersd0656a32017-04-13 09:45:37 +00002163 return failedImport("Src pattern results and dst MI defs are different (" +
2164 to_string(Src->getExtTypes().size()) + " def(s) vs " +
2165 to_string(DstI.Operands.NumDefs) + " def(s))");
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002166
Daniel Sandersffc7d582017-03-29 15:37:18 +00002167 InstructionMatcher &InsnMatcherTemp = M.addInstructionMatcher();
Daniel Sanders57938df2017-07-11 10:40:18 +00002168 unsigned TempOpIdx = 0;
2169 auto InsnMatcherOrError =
2170 createAndImportSelDAGMatcher(InsnMatcherTemp, Src, TempOpIdx);
Daniel Sandersffc7d582017-03-29 15:37:18 +00002171 if (auto Error = InsnMatcherOrError.takeError())
2172 return std::move(Error);
2173 InstructionMatcher &InsnMatcher = InsnMatcherOrError.get();
2174
2175 // The root of the match also has constraints on the register bank so that it
2176 // matches the result instruction.
2177 unsigned OpIdx = 0;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002178 for (const EEVT::TypeSet &Ty : Src->getExtTypes()) {
Daniel Sandersffc7d582017-03-29 15:37:18 +00002179 (void)Ty;
2180
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002181 const auto &DstIOperand = DstI.Operands[OpIdx];
2182 Record *DstIOpRec = DstIOperand.Rec;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002183 if (DstI.TheDef->getName() == "COPY_TO_REGCLASS") {
2184 DstIOpRec = getInitValueAsRegClass(Dst->getChild(1)->getLeafValue());
2185
2186 if (DstIOpRec == nullptr)
2187 return failedImport(
2188 "COPY_TO_REGCLASS operand #1 isn't a register class");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002189 } else if (DstI.TheDef->getName() == "EXTRACT_SUBREG") {
2190 if (!Dst->getChild(0)->isLeaf())
2191 return failedImport("EXTRACT_SUBREG operand #0 isn't a leaf");
2192
Daniel Sanders32291982017-06-28 13:50:04 +00002193 // We can assume that a subregister is in the same bank as it's super
2194 // register.
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002195 DstIOpRec = getInitValueAsRegClass(Dst->getChild(0)->getLeafValue());
2196
2197 if (DstIOpRec == nullptr)
2198 return failedImport(
2199 "EXTRACT_SUBREG operand #0 isn't a register class");
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002200 } else if (DstIOpRec->isSubClassOf("RegisterOperand"))
Daniel Sanders658541f2017-04-22 15:53:21 +00002201 DstIOpRec = DstIOpRec->getValueAsDef("RegClass");
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002202 else if (!DstIOpRec->isSubClassOf("RegisterClass"))
Daniel Sanders32291982017-06-28 13:50:04 +00002203 return failedImport("Dst MI def isn't a register class" +
2204 to_string(*Dst));
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002205
Daniel Sandersffc7d582017-03-29 15:37:18 +00002206 OperandMatcher &OM = InsnMatcher.getOperand(OpIdx);
2207 OM.setSymbolicName(DstIOperand.Name);
Daniel Sandersdc662ff2017-01-26 11:10:14 +00002208 OM.addPredicate<RegisterBankOperandMatcher>(
2209 Target.getRegisterClass(DstIOpRec));
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002210 ++OpIdx;
2211 }
2212
Daniel Sandersc270c502017-03-30 09:36:33 +00002213 auto DstMIBuilderOrError =
2214 createAndImportInstructionRenderer(M, Dst, InsnMatcher);
Daniel Sandersffc7d582017-03-29 15:37:18 +00002215 if (auto Error = DstMIBuilderOrError.takeError())
2216 return std::move(Error);
2217 BuildMIAction &DstMIBuilder = DstMIBuilderOrError.get();
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002218
Daniel Sandersffc7d582017-03-29 15:37:18 +00002219 // Render the implicit defs.
2220 // These are only added to the root of the result.
Daniel Sandersc270c502017-03-30 09:36:33 +00002221 if (auto Error = importImplicitDefRenderers(DstMIBuilder, P.getDstRegs()))
Daniel Sandersffc7d582017-03-29 15:37:18 +00002222 return std::move(Error);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002223
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002224 // Constrain the registers to classes. This is normally derived from the
2225 // emitted instruction but a few instructions require special handling.
2226 if (DstI.TheDef->getName() == "COPY_TO_REGCLASS") {
2227 // COPY_TO_REGCLASS does not provide operand constraints itself but the
2228 // result is constrained to the class given by the second child.
2229 Record *DstIOpRec =
2230 getInitValueAsRegClass(Dst->getChild(1)->getLeafValue());
2231
2232 if (DstIOpRec == nullptr)
2233 return failedImport("COPY_TO_REGCLASS operand #1 isn't a register class");
2234
2235 M.addAction<ConstrainOperandToRegClassAction>(
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002236 0, 0, Target.getRegisterClass(DstIOpRec));
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002237
2238 // We're done with this pattern! It's eligible for GISel emission; return
2239 // it.
2240 ++NumPatternImported;
2241 return std::move(M);
2242 }
2243
2244 if (DstI.TheDef->getName() == "EXTRACT_SUBREG") {
2245 // EXTRACT_SUBREG selects into a subregister COPY but unlike most
2246 // instructions, the result register class is controlled by the
2247 // subregisters of the operand. As a result, we must constrain the result
2248 // class rather than check that it's already the right one.
2249 if (!Dst->getChild(0)->isLeaf())
2250 return failedImport("EXTRACT_SUBREG child #1 is not a leaf");
2251
Daniel Sanders320390b2017-06-28 15:16:03 +00002252 DefInit *SubRegInit = dyn_cast<DefInit>(Dst->getChild(1)->getLeafValue());
2253 if (!SubRegInit)
2254 return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002255
Daniel Sanders320390b2017-06-28 15:16:03 +00002256 // Constrain the result to the same register bank as the operand.
2257 Record *DstIOpRec =
2258 getInitValueAsRegClass(Dst->getChild(0)->getLeafValue());
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002259
Daniel Sanders320390b2017-06-28 15:16:03 +00002260 if (DstIOpRec == nullptr)
2261 return failedImport("EXTRACT_SUBREG operand #1 isn't a register class");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002262
Daniel Sanders320390b2017-06-28 15:16:03 +00002263 CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef());
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002264 CodeGenRegisterClass *SrcRC = CGRegs.getRegClass(DstIOpRec);
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002265
Daniel Sanders320390b2017-06-28 15:16:03 +00002266 // It would be nice to leave this constraint implicit but we're required
2267 // to pick a register class so constrain the result to a register class
2268 // that can hold the correct MVT.
2269 //
2270 // FIXME: This may introduce an extra copy if the chosen class doesn't
2271 // actually contain the subregisters.
2272 assert(Src->getExtTypes().size() == 1 &&
2273 "Expected Src of EXTRACT_SUBREG to have one result type");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002274
Daniel Sanders320390b2017-06-28 15:16:03 +00002275 const auto &SrcRCDstRCPair =
2276 SrcRC->getMatchingSubClassWithSubRegs(CGRegs, SubIdx);
2277 assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002278 M.addAction<ConstrainOperandToRegClassAction>(0, 0, *SrcRCDstRCPair->second);
2279 M.addAction<ConstrainOperandToRegClassAction>(0, 1, *SrcRCDstRCPair->first);
2280
2281 // We're done with this pattern! It's eligible for GISel emission; return
2282 // it.
2283 ++NumPatternImported;
2284 return std::move(M);
2285 }
2286
2287 M.addAction<ConstrainOperandsToDefinitionAction>(0);
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002288
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002289 // We're done with this pattern! It's eligible for GISel emission; return it.
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00002290 ++NumPatternImported;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002291 return std::move(M);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002292}
2293
2294void GlobalISelEmitter::run(raw_ostream &OS) {
2295 // Track the GINodeEquiv definitions.
2296 gatherNodeEquivs();
2297
2298 emitSourceFileHeader(("Global Instruction Selector for the " +
2299 Target.getName() + " target").str(), OS);
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00002300 std::vector<RuleMatcher> Rules;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002301 // Look through the SelectionDAG patterns we found, possibly emitting some.
2302 for (const PatternToMatch &Pat : CGP.ptms()) {
2303 ++NumPatternTotal;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002304 auto MatcherOrErr = runOnPattern(Pat);
2305
2306 // The pattern analysis can fail, indicating an unsupported pattern.
2307 // Report that if we've been asked to do so.
2308 if (auto Err = MatcherOrErr.takeError()) {
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002309 if (WarnOnSkippedPatterns) {
2310 PrintWarning(Pat.getSrcRecord()->getLoc(),
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002311 "Skipped pattern: " + toString(std::move(Err)));
2312 } else {
2313 consumeError(std::move(Err));
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002314 }
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00002315 ++NumPatternImportsSkipped;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002316 continue;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002317 }
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002318
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00002319 Rules.push_back(std::move(MatcherOrErr.get()));
2320 }
2321
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002322 std::stable_sort(Rules.begin(), Rules.end(),
2323 [&](const RuleMatcher &A, const RuleMatcher &B) {
Daniel Sanders759ff412017-02-24 13:58:11 +00002324 if (A.isHigherPriorityThan(B)) {
2325 assert(!B.isHigherPriorityThan(A) && "Cannot be more important "
2326 "and less important at "
2327 "the same time");
2328 return true;
2329 }
2330 return false;
2331 });
2332
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002333 std::vector<Record *> ComplexPredicates =
2334 RK.getAllDerivedDefinitions("GIComplexOperandMatcher");
2335 std::sort(ComplexPredicates.begin(), ComplexPredicates.end(),
2336 [](const Record *A, const Record *B) {
2337 if (A->getName() < B->getName())
2338 return true;
2339 return false;
2340 });
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002341 unsigned MaxTemporaries = 0;
2342 for (const auto &Rule : Rules)
Daniel Sanders2deea182017-04-22 15:11:04 +00002343 MaxTemporaries = std::max(MaxTemporaries, Rule.countRendererFns());
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002344
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002345 OS << "#ifdef GET_GLOBALISEL_PREDICATE_BITSET\n"
2346 << "const unsigned MAX_SUBTARGET_PREDICATES = " << SubtargetFeatures.size()
2347 << ";\n"
2348 << "using PredicateBitset = "
2349 "llvm::PredicateBitsetImpl<MAX_SUBTARGET_PREDICATES>;\n"
2350 << "#endif // ifdef GET_GLOBALISEL_PREDICATE_BITSET\n\n";
2351
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002352 OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n"
2353 << " mutable MatcherState State;\n"
2354 << " typedef "
2355 "ComplexRendererFn("
2356 << Target.getName()
2357 << "InstructionSelector::*ComplexMatcherMemFn)(MachineOperand &) const;\n"
2358 << "const MatcherInfoTy<PredicateBitset, ComplexMatcherMemFn> "
2359 "MatcherInfo;\n"
2360 << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n\n";
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002361
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002362 OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n"
2363 << ", State(" << MaxTemporaries << "),\n"
2364 << "MatcherInfo({TypeObjects, FeatureBitsets, {\n"
2365 << " nullptr, // GICP_Invalid\n";
2366 for (const auto &Record : ComplexPredicates)
2367 OS << " &" << Target.getName()
2368 << "InstructionSelector::" << Record->getValueAsString("MatcherFn")
2369 << ", // " << Record->getName() << "\n";
2370 OS << "}})\n"
2371 << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n\n";
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002372
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002373 OS << "#ifdef GET_GLOBALISEL_IMPL\n";
2374 SubtargetFeatureInfo::emitSubtargetFeatureBitEnumeration(SubtargetFeatures,
2375 OS);
Daniel Sanderse9fdba32017-04-29 17:30:09 +00002376
2377 // Separate subtarget features by how often they must be recomputed.
2378 SubtargetFeatureInfoMap ModuleFeatures;
2379 std::copy_if(SubtargetFeatures.begin(), SubtargetFeatures.end(),
2380 std::inserter(ModuleFeatures, ModuleFeatures.end()),
2381 [](const SubtargetFeatureInfoMap::value_type &X) {
2382 return !X.second.mustRecomputePerFunction();
2383 });
2384 SubtargetFeatureInfoMap FunctionFeatures;
2385 std::copy_if(SubtargetFeatures.begin(), SubtargetFeatures.end(),
2386 std::inserter(FunctionFeatures, FunctionFeatures.end()),
2387 [](const SubtargetFeatureInfoMap::value_type &X) {
2388 return X.second.mustRecomputePerFunction();
2389 });
2390
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002391 SubtargetFeatureInfo::emitComputeAvailableFeatures(
Daniel Sanderse9fdba32017-04-29 17:30:09 +00002392 Target.getName(), "InstructionSelector", "computeAvailableModuleFeatures",
2393 ModuleFeatures, OS);
2394 SubtargetFeatureInfo::emitComputeAvailableFeatures(
2395 Target.getName(), "InstructionSelector",
2396 "computeAvailableFunctionFeatures", FunctionFeatures, OS,
2397 "const MachineFunction *MF");
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002398
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002399 // Emit a table containing the LLT objects needed by the matcher and an enum
2400 // for the matcher to reference them with.
2401 std::vector<LLTCodeGen> TypeObjects = {
2402 LLT::scalar(8), LLT::scalar(16), LLT::scalar(32),
2403 LLT::scalar(64), LLT::scalar(80), LLT::vector(8, 1),
2404 LLT::vector(16, 1), LLT::vector(32, 1), LLT::vector(64, 1),
2405 LLT::vector(8, 8), LLT::vector(16, 8), LLT::vector(32, 8),
2406 LLT::vector(64, 8), LLT::vector(4, 16), LLT::vector(8, 16),
2407 LLT::vector(16, 16), LLT::vector(32, 16), LLT::vector(2, 32),
2408 LLT::vector(4, 32), LLT::vector(8, 32), LLT::vector(16, 32),
2409 LLT::vector(2, 64), LLT::vector(4, 64), LLT::vector(8, 64),
2410 };
2411 std::sort(TypeObjects.begin(), TypeObjects.end());
2412 OS << "enum {\n";
2413 for (const auto &TypeObject : TypeObjects) {
2414 OS << " ";
2415 TypeObject.emitCxxEnumValue(OS);
2416 OS << ",\n";
2417 }
2418 OS << "};\n"
2419 << "const static LLT TypeObjects[] = {\n";
2420 for (const auto &TypeObject : TypeObjects) {
2421 OS << " ";
2422 TypeObject.emitCxxConstructorCall(OS);
2423 OS << ",\n";
2424 }
2425 OS << "};\n\n";
2426
2427 // Emit a table containing the PredicateBitsets objects needed by the matcher
2428 // and an enum for the matcher to reference them with.
2429 std::vector<std::vector<Record *>> FeatureBitsets;
2430 for (auto &Rule : Rules)
2431 FeatureBitsets.push_back(Rule.getRequiredFeatures());
2432 std::sort(
2433 FeatureBitsets.begin(), FeatureBitsets.end(),
2434 [&](const std::vector<Record *> &A, const std::vector<Record *> &B) {
2435 if (A.size() < B.size())
2436 return true;
2437 if (A.size() > B.size())
2438 return false;
2439 for (const auto &Pair : zip(A, B)) {
2440 if (std::get<0>(Pair)->getName() < std::get<1>(Pair)->getName())
2441 return true;
2442 if (std::get<0>(Pair)->getName() > std::get<1>(Pair)->getName())
2443 return false;
2444 }
2445 return false;
2446 });
2447 FeatureBitsets.erase(
2448 std::unique(FeatureBitsets.begin(), FeatureBitsets.end()),
2449 FeatureBitsets.end());
2450 OS << "enum {\n"
2451 << " GIFBS_Invalid,\n";
2452 for (const auto &FeatureBitset : FeatureBitsets) {
2453 if (FeatureBitset.empty())
2454 continue;
2455 OS << " " << getNameForFeatureBitset(FeatureBitset) << ",\n";
2456 }
2457 OS << "};\n"
2458 << "const static PredicateBitset FeatureBitsets[] {\n"
2459 << " {}, // GIFBS_Invalid\n";
2460 for (const auto &FeatureBitset : FeatureBitsets) {
2461 if (FeatureBitset.empty())
2462 continue;
2463 OS << " {";
2464 for (const auto &Feature : FeatureBitset) {
2465 const auto &I = SubtargetFeatures.find(Feature);
2466 assert(I != SubtargetFeatures.end() && "Didn't import predicate?");
2467 OS << I->second.getEnumBitName() << ", ";
2468 }
2469 OS << "},\n";
2470 }
2471 OS << "};\n\n";
2472
2473 // Emit complex predicate table and an enum to reference them with.
2474 OS << "enum {\n"
2475 << " GICP_Invalid,\n";
2476 for (const auto &Record : ComplexPredicates)
2477 OS << " GICP_" << Record->getName() << ",\n";
2478 OS << "};\n"
2479 << "// See constructor for table contents\n\n";
2480
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002481 OS << "bool " << Target.getName()
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002482 << "InstructionSelector::selectImpl(MachineInstr &I) const {\n"
2483 << " MachineFunction &MF = *I.getParent()->getParent();\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002484 << " MachineRegisterInfo &MRI = MF.getRegInfo();\n"
Daniel Sanders32291982017-06-28 13:50:04 +00002485 << " // FIXME: This should be computed on a per-function basis rather "
2486 "than per-insn.\n"
2487 << " AvailableFunctionFeatures = computeAvailableFunctionFeatures(&STI, "
2488 "&MF);\n"
Daniel Sandersa6cfce62017-07-05 14:50:18 +00002489 << " const PredicateBitset AvailableFeatures = getAvailableFeatures();\n"
2490 << " NewMIVector OutMIs;\n"
2491 << " State.MIs.clear();\n"
2492 << " State.MIs.push_back(&I);\n\n";
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002493
Daniel Sanders8e82af22017-07-27 11:03:45 +00002494 MatchTable Table(0);
Daniel Sandersb96f40d2017-03-20 15:20:42 +00002495 for (auto &Rule : Rules) {
Daniel Sanders8e82af22017-07-27 11:03:45 +00002496 Rule.emit(Table);
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002497 ++NumPatternEmitted;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002498 }
Daniel Sanders8e82af22017-07-27 11:03:45 +00002499 Table << MatchTable::Opcode("GIM_Reject") << MatchTable::LineBreak;
2500 Table.emitDeclaration(OS);
2501 OS << " if (executeMatchTable(*this, OutMIs, State, MatcherInfo, ";
2502 Table.emitUse(OS);
2503 OS << ", TII, MRI, TRI, RBI, AvailableFeatures)) {\n"
2504 << " return true;\n"
2505 << " }\n\n";
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002506
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002507 OS << " return false;\n"
2508 << "}\n"
2509 << "#endif // ifdef GET_GLOBALISEL_IMPL\n";
Daniel Sanderse9fdba32017-04-29 17:30:09 +00002510
2511 OS << "#ifdef GET_GLOBALISEL_PREDICATES_DECL\n"
2512 << "PredicateBitset AvailableModuleFeatures;\n"
2513 << "mutable PredicateBitset AvailableFunctionFeatures;\n"
2514 << "PredicateBitset getAvailableFeatures() const {\n"
2515 << " return AvailableModuleFeatures | AvailableFunctionFeatures;\n"
2516 << "}\n"
2517 << "PredicateBitset\n"
2518 << "computeAvailableModuleFeatures(const " << Target.getName()
2519 << "Subtarget *Subtarget) const;\n"
2520 << "PredicateBitset\n"
2521 << "computeAvailableFunctionFeatures(const " << Target.getName()
2522 << "Subtarget *Subtarget,\n"
2523 << " const MachineFunction *MF) const;\n"
2524 << "#endif // ifdef GET_GLOBALISEL_PREDICATES_DECL\n";
2525
2526 OS << "#ifdef GET_GLOBALISEL_PREDICATES_INIT\n"
2527 << "AvailableModuleFeatures(computeAvailableModuleFeatures(&STI)),\n"
2528 << "AvailableFunctionFeatures()\n"
2529 << "#endif // ifdef GET_GLOBALISEL_PREDICATES_INIT\n";
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002530}
2531
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002532void GlobalISelEmitter::declareSubtargetFeature(Record *Predicate) {
2533 if (SubtargetFeatures.count(Predicate) == 0)
2534 SubtargetFeatures.emplace(
2535 Predicate, SubtargetFeatureInfo(Predicate, SubtargetFeatures.size()));
2536}
2537
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002538} // end anonymous namespace
2539
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002540//===----------------------------------------------------------------------===//
2541
2542namespace llvm {
2543void EmitGlobalISel(RecordKeeper &RK, raw_ostream &OS) {
2544 GlobalISelEmitter(RK).run(OS);
2545}
2546} // End llvm namespace