blob: f75456db87059dab3ee0e789f6183f5c64e748f1 [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 Sanders11300ce2017-10-13 21:28:03 +000068
69/// Get the name of the enum value used to number the predicate function.
70std::string getEnumNameForPredicate(const TreePredicateFn &Predicate) {
Simon Pilgrim6ecae9f2017-10-14 21:27:53 +000071 return "GIPFP_" + Predicate.getImmTypeIdentifier().str() + "_" +
Daniel Sanders11300ce2017-10-13 21:28:03 +000072 Predicate.getFnName();
73}
74
75/// Get the opcode used to check this predicate.
76std::string getMatchOpcodeForPredicate(const TreePredicateFn &Predicate) {
Simon Pilgrim6ecae9f2017-10-14 21:27:53 +000077 return "GIM_Check" + Predicate.getImmTypeIdentifier().str() + "ImmPredicate";
Daniel Sanders11300ce2017-10-13 21:28:03 +000078}
79
Daniel Sanders52b4ce72017-03-07 23:20:35 +000080/// This class stands in for LLT wherever we want to tablegen-erate an
81/// equivalent at compiler run-time.
82class LLTCodeGen {
83private:
84 LLT Ty;
85
86public:
87 LLTCodeGen(const LLT &Ty) : Ty(Ty) {}
88
Daniel Sanders7aac7cc2017-07-20 09:25:44 +000089 std::string getCxxEnumValue() const {
90 std::string Str;
91 raw_string_ostream OS(Str);
92
93 emitCxxEnumValue(OS);
94 return OS.str();
95 }
96
Daniel Sanders6ab0daa2017-07-04 14:35:06 +000097 void emitCxxEnumValue(raw_ostream &OS) const {
98 if (Ty.isScalar()) {
99 OS << "GILLT_s" << Ty.getSizeInBits();
100 return;
101 }
102 if (Ty.isVector()) {
103 OS << "GILLT_v" << Ty.getNumElements() << "s" << Ty.getScalarSizeInBits();
104 return;
105 }
Daniel Sandersa71f4542017-10-16 00:56:30 +0000106 if (Ty.isPointer()) {
107 OS << "GILLT_p" << Ty.getAddressSpace();
108 if (Ty.getSizeInBits() > 0)
109 OS << "s" << Ty.getSizeInBits();
110 return;
111 }
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000112 llvm_unreachable("Unhandled LLT");
113 }
114
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000115 void emitCxxConstructorCall(raw_ostream &OS) const {
116 if (Ty.isScalar()) {
117 OS << "LLT::scalar(" << Ty.getSizeInBits() << ")";
118 return;
119 }
120 if (Ty.isVector()) {
Daniel Sanders32291982017-06-28 13:50:04 +0000121 OS << "LLT::vector(" << Ty.getNumElements() << ", "
122 << Ty.getScalarSizeInBits() << ")";
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000123 return;
124 }
Daniel Sandersa71f4542017-10-16 00:56:30 +0000125 if (Ty.isPointer() && Ty.getSizeInBits() > 0) {
126 OS << "LLT::pointer(" << Ty.getAddressSpace() << ", "
127 << Ty.getSizeInBits() << ")";
128 return;
129 }
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000130 llvm_unreachable("Unhandled LLT");
131 }
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000132
133 const LLT &get() const { return Ty; }
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000134
135 /// This ordering is used for std::unique() and std::sort(). There's no
Daniel Sanders032e7f22017-08-17 13:18:35 +0000136 /// particular logic behind the order but either A < B or B < A must be
137 /// true if A != B.
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000138 bool operator<(const LLTCodeGen &Other) const {
Daniel Sanders032e7f22017-08-17 13:18:35 +0000139 if (Ty.isValid() != Other.Ty.isValid())
140 return Ty.isValid() < Other.Ty.isValid();
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000141 if (!Ty.isValid())
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000142 return false;
Daniel Sanders032e7f22017-08-17 13:18:35 +0000143
144 if (Ty.isVector() != Other.Ty.isVector())
145 return Ty.isVector() < Other.Ty.isVector();
146 if (Ty.isScalar() != Other.Ty.isScalar())
147 return Ty.isScalar() < Other.Ty.isScalar();
148 if (Ty.isPointer() != Other.Ty.isPointer())
149 return Ty.isPointer() < Other.Ty.isPointer();
150
151 if (Ty.isPointer() && Ty.getAddressSpace() != Other.Ty.getAddressSpace())
152 return Ty.getAddressSpace() < Other.Ty.getAddressSpace();
153
154 if (Ty.isVector() && Ty.getNumElements() != Other.Ty.getNumElements())
155 return Ty.getNumElements() < Other.Ty.getNumElements();
156
157 return Ty.getSizeInBits() < Other.Ty.getSizeInBits();
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000158 }
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000159};
160
161class InstructionMatcher;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000162/// Convert an MVT to an equivalent LLT if possible, or the invalid LLT() for
163/// MVTs that don't map cleanly to an LLT (e.g., iPTR, *any, ...).
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000164static Optional<LLTCodeGen> MVTToLLT(MVT::SimpleValueType SVT) {
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000165 MVT VT(SVT);
Daniel Sandersa71f4542017-10-16 00:56:30 +0000166
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000167 if (VT.isVector() && VT.getVectorNumElements() != 1)
Daniel Sanders32291982017-06-28 13:50:04 +0000168 return LLTCodeGen(
169 LLT::vector(VT.getVectorNumElements(), VT.getScalarSizeInBits()));
Daniel Sandersa71f4542017-10-16 00:56:30 +0000170
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000171 if (VT.isInteger() || VT.isFloatingPoint())
172 return LLTCodeGen(LLT::scalar(VT.getSizeInBits()));
173 return None;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000174}
175
Daniel Sandersd0656a32017-04-13 09:45:37 +0000176static std::string explainPredicates(const TreePatternNode *N) {
177 std::string Explanation = "";
178 StringRef Separator = "";
179 for (const auto &P : N->getPredicateFns()) {
180 Explanation +=
181 (Separator + P.getOrigPatFragRecord()->getRecord()->getName()).str();
182 if (P.isAlwaysTrue())
183 Explanation += " always-true";
184 if (P.isImmediatePattern())
185 Explanation += " immediate";
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000186
187 if (P.isUnindexed())
188 Explanation += " unindexed";
189
190 if (P.isNonExtLoad())
191 Explanation += " non-extload";
192 if (P.isAnyExtLoad())
193 Explanation += " extload";
194 if (P.isSignExtLoad())
195 Explanation += " sextload";
196 if (P.isZeroExtLoad())
197 Explanation += " zextload";
198
199 if (P.isNonTruncStore())
200 Explanation += " non-truncstore";
201 if (P.isTruncStore())
202 Explanation += " truncstore";
203
204 if (Record *VT = P.getMemoryVT())
205 Explanation += (" MemVT=" + VT->getName()).str();
206 if (Record *VT = P.getScalarMemoryVT())
207 Explanation += (" ScalarVT(MemVT)=" + VT->getName()).str();
Daniel Sandersd0656a32017-04-13 09:45:37 +0000208 }
209 return Explanation;
210}
211
Daniel Sandersd0656a32017-04-13 09:45:37 +0000212std::string explainOperator(Record *Operator) {
213 if (Operator->isSubClassOf("SDNode"))
Craig Topper2b8419a2017-05-31 19:01:11 +0000214 return (" (" + Operator->getValueAsString("Opcode") + ")").str();
Daniel Sandersd0656a32017-04-13 09:45:37 +0000215
216 if (Operator->isSubClassOf("Intrinsic"))
217 return (" (Operator is an Intrinsic, " + Operator->getName() + ")").str();
218
Daniel Sandersdf39cba2017-10-15 18:22:54 +0000219 if (Operator->isSubClassOf("ComplexPattern"))
220 return (" (Operator is an unmapped ComplexPattern, " + Operator->getName() +
221 ")")
222 .str();
223
224 return (" (Operator " + Operator->getName() + " not understood)").str();
Daniel Sandersd0656a32017-04-13 09:45:37 +0000225}
226
227/// Helper function to let the emitter report skip reason error messages.
228static Error failedImport(const Twine &Reason) {
229 return make_error<StringError>(Reason, inconvertibleErrorCode());
230}
231
232static Error isTrivialOperatorNode(const TreePatternNode *N) {
233 std::string Explanation = "";
234 std::string Separator = "";
Daniel Sanders2c269f62017-08-24 09:11:20 +0000235
236 bool HasUnsupportedPredicate = false;
237 for (const auto &Predicate : N->getPredicateFns()) {
238 if (Predicate.isAlwaysTrue())
239 continue;
240
241 if (Predicate.isImmediatePattern())
242 continue;
243
Daniel Sandersa71f4542017-10-16 00:56:30 +0000244 if (Predicate.isLoad() && Predicate.isUnindexed())
245 continue;
246
247 if (Predicate.isNonExtLoad())
248 continue;
Daniel Sandersd66e0902017-10-23 18:19:24 +0000249
250 if (Predicate.isStore() && Predicate.isUnindexed())
251 continue;
252
253 if (Predicate.isNonTruncStore())
254 continue;
255
Daniel Sanders2c269f62017-08-24 09:11:20 +0000256 HasUnsupportedPredicate = true;
Daniel Sandersd0656a32017-04-13 09:45:37 +0000257 Explanation = Separator + "Has a predicate (" + explainPredicates(N) + ")";
258 Separator = ", ";
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000259 Explanation += (Separator + "first-failing:" +
260 Predicate.getOrigPatFragRecord()->getRecord()->getName())
261 .str();
Daniel Sanders2c269f62017-08-24 09:11:20 +0000262 break;
Daniel Sandersd0656a32017-04-13 09:45:37 +0000263 }
264
265 if (N->getTransformFn()) {
266 Explanation += Separator + "Has a transform function";
267 Separator = ", ";
268 }
269
Daniel Sanders2c269f62017-08-24 09:11:20 +0000270 if (!HasUnsupportedPredicate && !N->getTransformFn())
Daniel Sandersd0656a32017-04-13 09:45:37 +0000271 return Error::success();
272
273 return failedImport(Explanation);
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000274}
275
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +0000276static Record *getInitValueAsRegClass(Init *V) {
277 if (DefInit *VDefInit = dyn_cast<DefInit>(V)) {
278 if (VDefInit->getDef()->isSubClassOf("RegisterOperand"))
279 return VDefInit->getDef()->getValueAsDef("RegClass");
280 if (VDefInit->getDef()->isSubClassOf("RegisterClass"))
281 return VDefInit->getDef();
282 }
283 return nullptr;
284}
285
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000286std::string
287getNameForFeatureBitset(const std::vector<Record *> &FeatureBitset) {
288 std::string Name = "GIFBS";
289 for (const auto &Feature : FeatureBitset)
290 Name += ("_" + Feature->getName()).str();
291 return Name;
292}
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000293
294//===- MatchTable Helpers -------------------------------------------------===//
295
296class MatchTable;
297
298/// A record to be stored in a MatchTable.
299///
300/// This class represents any and all output that may be required to emit the
301/// MatchTable. Instances are most often configured to represent an opcode or
302/// value that will be emitted to the table with some formatting but it can also
303/// represent commas, comments, and other formatting instructions.
304struct MatchTableRecord {
305 enum RecordFlagsBits {
306 MTRF_None = 0x0,
307 /// Causes EmitStr to be formatted as comment when emitted.
308 MTRF_Comment = 0x1,
309 /// Causes the record value to be followed by a comma when emitted.
310 MTRF_CommaFollows = 0x2,
311 /// Causes the record value to be followed by a line break when emitted.
312 MTRF_LineBreakFollows = 0x4,
313 /// Indicates that the record defines a label and causes an additional
314 /// comment to be emitted containing the index of the label.
315 MTRF_Label = 0x8,
316 /// Causes the record to be emitted as the index of the label specified by
317 /// LabelID along with a comment indicating where that label is.
318 MTRF_JumpTarget = 0x10,
319 /// Causes the formatter to add a level of indentation before emitting the
320 /// record.
321 MTRF_Indent = 0x20,
322 /// Causes the formatter to remove a level of indentation after emitting the
323 /// record.
324 MTRF_Outdent = 0x40,
325 };
326
327 /// When MTRF_Label or MTRF_JumpTarget is used, indicates a label id to
328 /// reference or define.
329 unsigned LabelID;
330 /// The string to emit. Depending on the MTRF_* flags it may be a comment, a
331 /// value, a label name.
332 std::string EmitStr;
333
334private:
335 /// The number of MatchTable elements described by this record. Comments are 0
336 /// while values are typically 1. Values >1 may occur when we need to emit
337 /// values that exceed the size of a MatchTable element.
338 unsigned NumElements;
339
340public:
341 /// A bitfield of RecordFlagsBits flags.
342 unsigned Flags;
343
344 MatchTableRecord(Optional<unsigned> LabelID_, StringRef EmitStr,
345 unsigned NumElements, unsigned Flags)
346 : LabelID(LabelID_.hasValue() ? LabelID_.getValue() : ~0u),
347 EmitStr(EmitStr), NumElements(NumElements), Flags(Flags) {
348 assert((!LabelID_.hasValue() || LabelID != ~0u) &&
349 "This value is reserved for non-labels");
350 }
351
352 void emit(raw_ostream &OS, bool LineBreakNextAfterThis,
353 const MatchTable &Table) const;
354 unsigned size() const { return NumElements; }
355};
356
357/// Holds the contents of a generated MatchTable to enable formatting and the
358/// necessary index tracking needed to support GIM_Try.
359class MatchTable {
360 /// An unique identifier for the table. The generated table will be named
361 /// MatchTable${ID}.
362 unsigned ID;
363 /// The records that make up the table. Also includes comments describing the
364 /// values being emitted and line breaks to format it.
365 std::vector<MatchTableRecord> Contents;
366 /// The currently defined labels.
367 DenseMap<unsigned, unsigned> LabelMap;
368 /// Tracks the sum of MatchTableRecord::NumElements as the table is built.
369 unsigned CurrentSize;
370
Daniel Sanders8e82af22017-07-27 11:03:45 +0000371 /// A unique identifier for a MatchTable label.
372 static unsigned CurrentLabelID;
373
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000374public:
375 static MatchTableRecord LineBreak;
376 static MatchTableRecord Comment(StringRef Comment) {
377 return MatchTableRecord(None, Comment, 0, MatchTableRecord::MTRF_Comment);
378 }
379 static MatchTableRecord Opcode(StringRef Opcode, int IndentAdjust = 0) {
380 unsigned ExtraFlags = 0;
381 if (IndentAdjust > 0)
382 ExtraFlags |= MatchTableRecord::MTRF_Indent;
383 if (IndentAdjust < 0)
384 ExtraFlags |= MatchTableRecord::MTRF_Outdent;
385
386 return MatchTableRecord(None, Opcode, 1,
387 MatchTableRecord::MTRF_CommaFollows | ExtraFlags);
388 }
389 static MatchTableRecord NamedValue(StringRef NamedValue) {
390 return MatchTableRecord(None, NamedValue, 1,
391 MatchTableRecord::MTRF_CommaFollows);
392 }
393 static MatchTableRecord NamedValue(StringRef Namespace,
394 StringRef NamedValue) {
395 return MatchTableRecord(None, (Namespace + "::" + NamedValue).str(), 1,
396 MatchTableRecord::MTRF_CommaFollows);
397 }
398 static MatchTableRecord IntValue(int64_t IntValue) {
399 return MatchTableRecord(None, llvm::to_string(IntValue), 1,
400 MatchTableRecord::MTRF_CommaFollows);
401 }
402 static MatchTableRecord Label(unsigned LabelID) {
403 return MatchTableRecord(LabelID, "Label " + llvm::to_string(LabelID), 0,
404 MatchTableRecord::MTRF_Label |
405 MatchTableRecord::MTRF_Comment |
406 MatchTableRecord::MTRF_LineBreakFollows);
407 }
408 static MatchTableRecord JumpTarget(unsigned LabelID) {
Daniel Sanders8e82af22017-07-27 11:03:45 +0000409 return MatchTableRecord(LabelID, "Label " + llvm::to_string(LabelID), 1,
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000410 MatchTableRecord::MTRF_JumpTarget |
411 MatchTableRecord::MTRF_Comment |
412 MatchTableRecord::MTRF_CommaFollows);
413 }
414
415 MatchTable(unsigned ID) : ID(ID), CurrentSize(0) {}
416
417 void push_back(const MatchTableRecord &Value) {
418 if (Value.Flags & MatchTableRecord::MTRF_Label)
419 defineLabel(Value.LabelID);
420 Contents.push_back(Value);
421 CurrentSize += Value.size();
422 }
423
Daniel Sanders8e82af22017-07-27 11:03:45 +0000424 unsigned allocateLabelID() const { return CurrentLabelID++; }
425
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000426 void defineLabel(unsigned LabelID) {
Daniel Sanders8e82af22017-07-27 11:03:45 +0000427 LabelMap.insert(std::make_pair(LabelID, CurrentSize));
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000428 }
429
430 unsigned getLabelIndex(unsigned LabelID) const {
431 const auto I = LabelMap.find(LabelID);
432 assert(I != LabelMap.end() && "Use of undeclared label");
433 return I->second;
434 }
435
Daniel Sanders8e82af22017-07-27 11:03:45 +0000436 void emitUse(raw_ostream &OS) const { OS << "MatchTable" << ID; }
437
438 void emitDeclaration(raw_ostream &OS) const {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000439 unsigned Indentation = 4;
Daniel Sanderscbbbfe42017-07-27 12:47:31 +0000440 OS << " constexpr static int64_t MatchTable" << ID << "[] = {";
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000441 LineBreak.emit(OS, true, *this);
442 OS << std::string(Indentation, ' ');
443
444 for (auto I = Contents.begin(), E = Contents.end(); I != E;
445 ++I) {
446 bool LineBreakIsNext = false;
447 const auto &NextI = std::next(I);
448
449 if (NextI != E) {
450 if (NextI->EmitStr == "" &&
451 NextI->Flags == MatchTableRecord::MTRF_LineBreakFollows)
452 LineBreakIsNext = true;
453 }
454
455 if (I->Flags & MatchTableRecord::MTRF_Indent)
456 Indentation += 2;
457
458 I->emit(OS, LineBreakIsNext, *this);
459 if (I->Flags & MatchTableRecord::MTRF_LineBreakFollows)
460 OS << std::string(Indentation, ' ');
461
462 if (I->Flags & MatchTableRecord::MTRF_Outdent)
463 Indentation -= 2;
464 }
465 OS << "};\n";
466 }
467};
468
Daniel Sanders8e82af22017-07-27 11:03:45 +0000469unsigned MatchTable::CurrentLabelID = 0;
470
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000471MatchTableRecord MatchTable::LineBreak = {
472 None, "" /* Emit String */, 0 /* Elements */,
473 MatchTableRecord::MTRF_LineBreakFollows};
474
475void MatchTableRecord::emit(raw_ostream &OS, bool LineBreakIsNextAfterThis,
476 const MatchTable &Table) const {
477 bool UseLineComment =
478 LineBreakIsNextAfterThis | (Flags & MTRF_LineBreakFollows);
479 if (Flags & (MTRF_JumpTarget | MTRF_CommaFollows))
480 UseLineComment = false;
481
482 if (Flags & MTRF_Comment)
483 OS << (UseLineComment ? "// " : "/*");
484
485 OS << EmitStr;
486 if (Flags & MTRF_Label)
487 OS << ": @" << Table.getLabelIndex(LabelID);
488
489 if (Flags & MTRF_Comment && !UseLineComment)
490 OS << "*/";
491
492 if (Flags & MTRF_JumpTarget) {
493 if (Flags & MTRF_Comment)
494 OS << " ";
495 OS << Table.getLabelIndex(LabelID);
496 }
497
498 if (Flags & MTRF_CommaFollows) {
499 OS << ",";
500 if (!LineBreakIsNextAfterThis && !(Flags & MTRF_LineBreakFollows))
501 OS << " ";
502 }
503
504 if (Flags & MTRF_LineBreakFollows)
505 OS << "\n";
506}
507
508MatchTable &operator<<(MatchTable &Table, const MatchTableRecord &Value) {
509 Table.push_back(Value);
510 return Table;
511}
512
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000513//===- Matchers -----------------------------------------------------------===//
514
Daniel Sandersbee57392017-04-04 13:25:23 +0000515class OperandMatcher;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000516class MatchAction;
517
518/// Generates code to check that a match rule matches.
519class RuleMatcher {
520 /// A list of matchers that all need to succeed for the current rule to match.
521 /// FIXME: This currently supports a single match position but could be
522 /// extended to support multiple positions to support div/rem fusion or
523 /// load-multiple instructions.
524 std::vector<std::unique_ptr<InstructionMatcher>> Matchers;
525
526 /// A list of actions that need to be taken when all predicates in this rule
527 /// have succeeded.
528 std::vector<std::unique_ptr<MatchAction>> Actions;
529
Daniel Sanders078572b2017-08-02 11:03:36 +0000530 typedef std::map<const InstructionMatcher *, unsigned>
531 DefinedInsnVariablesMap;
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000532 /// A map of instruction matchers to the local variables created by
Daniel Sanders9d662d22017-07-06 10:06:12 +0000533 /// emitCaptureOpcodes().
Daniel Sanders078572b2017-08-02 11:03:36 +0000534 DefinedInsnVariablesMap InsnVariableIDs;
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000535
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000536 /// A map of named operands defined by the matchers that may be referenced by
537 /// the renderers.
538 StringMap<OperandMatcher *> DefinedOperands;
539
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000540 /// ID for the next instruction variable defined with defineInsnVar()
541 unsigned NextInsnVarID;
542
Daniel Sanderse7b0d662017-04-21 15:59:56 +0000543 std::vector<Record *> RequiredFeatures;
544
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000545 ArrayRef<SMLoc> SrcLoc;
546
Daniel Sandersdf39cba2017-10-15 18:22:54 +0000547 typedef std::tuple<Record *, unsigned, unsigned>
548 DefinedComplexPatternSubOperand;
549 typedef StringMap<DefinedComplexPatternSubOperand>
550 DefinedComplexPatternSubOperandMap;
551 /// A map of Symbolic Names to ComplexPattern sub-operands.
552 DefinedComplexPatternSubOperandMap ComplexSubOperands;
553
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000554public:
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000555 RuleMatcher(ArrayRef<SMLoc> SrcLoc)
556 : Matchers(), Actions(), InsnVariableIDs(), DefinedOperands(),
Daniel Sandersdf39cba2017-10-15 18:22:54 +0000557 NextInsnVarID(0), SrcLoc(SrcLoc), ComplexSubOperands() {}
Zachary Turnerb7dbd872017-03-20 19:56:52 +0000558 RuleMatcher(RuleMatcher &&Other) = default;
559 RuleMatcher &operator=(RuleMatcher &&Other) = default;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000560
Daniel Sanders05540042017-08-08 10:44:31 +0000561 InstructionMatcher &addInstructionMatcher(StringRef SymbolicName);
Daniel Sanderse7b0d662017-04-21 15:59:56 +0000562 void addRequiredFeature(Record *Feature);
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000563 const std::vector<Record *> &getRequiredFeatures() const;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000564
565 template <class Kind, class... Args> Kind &addAction(Args &&... args);
566
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000567 /// Define an instruction without emitting any code to do so.
568 /// This is used for the root of the match.
569 unsigned implicitlyDefineInsnVar(const InstructionMatcher &Matcher);
570 /// Define an instruction and emit corresponding state-machine opcodes.
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000571 unsigned defineInsnVar(MatchTable &Table, const InstructionMatcher &Matcher,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000572 unsigned InsnVarID, unsigned OpIdx);
573 unsigned getInsnVarID(const InstructionMatcher &InsnMatcher) const;
Daniel Sanders078572b2017-08-02 11:03:36 +0000574 DefinedInsnVariablesMap::const_iterator defined_insn_vars_begin() const {
575 return InsnVariableIDs.begin();
576 }
577 DefinedInsnVariablesMap::const_iterator defined_insn_vars_end() const {
578 return InsnVariableIDs.end();
579 }
580 iterator_range<typename DefinedInsnVariablesMap::const_iterator>
581 defined_insn_vars() const {
582 return make_range(defined_insn_vars_begin(), defined_insn_vars_end());
583 }
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000584
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000585 void defineOperand(StringRef SymbolicName, OperandMatcher &OM);
586
Daniel Sandersdf39cba2017-10-15 18:22:54 +0000587 void defineComplexSubOperand(StringRef SymbolicName, Record *ComplexPattern,
588 unsigned RendererID, unsigned SubOperandID) {
589 assert(ComplexSubOperands.count(SymbolicName) == 0 && "Already defined");
590 ComplexSubOperands[SymbolicName] =
591 std::make_tuple(ComplexPattern, RendererID, SubOperandID);
592 }
593 Optional<DefinedComplexPatternSubOperand>
594 getComplexSubOperand(StringRef SymbolicName) const {
595 const auto &I = ComplexSubOperands.find(SymbolicName);
596 if (I == ComplexSubOperands.end())
597 return None;
598 return I->second;
599 }
600
Daniel Sanders05540042017-08-08 10:44:31 +0000601 const InstructionMatcher &getInstructionMatcher(StringRef SymbolicName) const;
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000602 const OperandMatcher &getOperandMatcher(StringRef Name) const;
Daniel Sanders05540042017-08-08 10:44:31 +0000603
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000604 void emitCaptureOpcodes(MatchTable &Table);
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000605
Daniel Sanders8e82af22017-07-27 11:03:45 +0000606 void emit(MatchTable &Table);
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000607
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000608 /// Compare the priority of this object and B.
609 ///
610 /// Returns true if this object is more important than B.
611 bool isHigherPriorityThan(const RuleMatcher &B) const;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000612
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000613 /// Report the maximum number of temporary operands needed by the rule
614 /// matcher.
615 unsigned countRendererFns() const;
Daniel Sanders2deea182017-04-22 15:11:04 +0000616
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000617 // FIXME: Remove this as soon as possible
618 InstructionMatcher &insnmatcher_front() const { return *Matchers.front(); }
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000619};
620
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000621template <class PredicateTy> class PredicateListMatcher {
622private:
623 typedef std::vector<std::unique_ptr<PredicateTy>> PredicateVec;
624 PredicateVec Predicates;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000625
Daniel Sanders2c269f62017-08-24 09:11:20 +0000626 /// Template instantiations should specialize this to return a string to use
627 /// for the comment emitted when there are no predicates.
628 std::string getNoPredicateComment() const;
629
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000630public:
631 /// Construct a new operand predicate and add it to the matcher.
632 template <class Kind, class... Args>
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000633 Optional<Kind *> addPredicate(Args&&... args) {
Ahmed Bougachab67a3ce2017-01-26 22:07:37 +0000634 Predicates.emplace_back(
635 llvm::make_unique<Kind>(std::forward<Args>(args)...));
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000636 return static_cast<Kind *>(Predicates.back().get());
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000637 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000638
Daniel Sanders32291982017-06-28 13:50:04 +0000639 typename PredicateVec::const_iterator predicates_begin() const {
640 return Predicates.begin();
641 }
642 typename PredicateVec::const_iterator predicates_end() const {
643 return Predicates.end();
644 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000645 iterator_range<typename PredicateVec::const_iterator> predicates() const {
646 return make_range(predicates_begin(), predicates_end());
647 }
Daniel Sanders32291982017-06-28 13:50:04 +0000648 typename PredicateVec::size_type predicates_size() const {
649 return Predicates.size();
650 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000651
Daniel Sanders9d662d22017-07-06 10:06:12 +0000652 /// Emit MatchTable opcodes that tests whether all the predicates are met.
Ahmed Bougachab67a3ce2017-01-26 22:07:37 +0000653 template <class... Args>
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000654 void emitPredicateListOpcodes(MatchTable &Table, Args &&... args) const {
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000655 if (Predicates.empty()) {
Daniel Sanders2c269f62017-08-24 09:11:20 +0000656 Table << MatchTable::Comment(getNoPredicateComment())
657 << MatchTable::LineBreak;
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000658 return;
659 }
660
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000661 for (const auto &Predicate : predicates())
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000662 Predicate->emitPredicateOpcodes(Table, std::forward<Args>(args)...);
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000663 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000664};
665
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000666/// Generates code to check a predicate of an operand.
667///
668/// Typical predicates include:
669/// * Operand is a particular register.
670/// * Operand is assigned a particular register bank.
671/// * Operand is an MBB.
672class OperandPredicateMatcher {
673public:
Daniel Sanders759ff412017-02-24 13:58:11 +0000674 /// This enum is used for RTTI and also defines the priority that is given to
675 /// the predicate when generating the matcher code. Kinds with higher priority
676 /// must be tested first.
677 ///
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000678 /// The relative priority of OPM_LLT, OPM_RegBank, and OPM_MBB do not matter
679 /// but OPM_Int must have priority over OPM_RegBank since constant integers
680 /// are represented by a virtual register defined by a G_CONSTANT instruction.
Daniel Sanders759ff412017-02-24 13:58:11 +0000681 enum PredicateKind {
Daniel Sanders1e4569f2017-10-20 20:55:29 +0000682 OPM_SameOperand,
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000683 OPM_ComplexPattern,
Daniel Sandersfe12c0f2017-07-11 08:57:29 +0000684 OPM_IntrinsicID,
Daniel Sanders05540042017-08-08 10:44:31 +0000685 OPM_Instruction,
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000686 OPM_Int,
Daniel Sanders452c8ae2017-05-23 19:33:16 +0000687 OPM_LiteralInt,
Daniel Sanders759ff412017-02-24 13:58:11 +0000688 OPM_LLT,
Daniel Sandersa71f4542017-10-16 00:56:30 +0000689 OPM_PointerToAny,
Daniel Sanders759ff412017-02-24 13:58:11 +0000690 OPM_RegBank,
691 OPM_MBB,
692 };
693
694protected:
695 PredicateKind Kind;
696
697public:
698 OperandPredicateMatcher(PredicateKind Kind) : Kind(Kind) {}
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000699 virtual ~OperandPredicateMatcher() {}
700
Daniel Sanders759ff412017-02-24 13:58:11 +0000701 PredicateKind getKind() const { return Kind; }
702
Daniel Sanders9d662d22017-07-06 10:06:12 +0000703 /// Emit MatchTable opcodes to capture instructions into the MIs table.
Daniel Sandersbee57392017-04-04 13:25:23 +0000704 ///
Daniel Sanders9d662d22017-07-06 10:06:12 +0000705 /// Only InstructionOperandMatcher needs to do anything for this method the
706 /// rest just walk the tree.
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000707 virtual void emitCaptureOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders9d662d22017-07-06 10:06:12 +0000708 unsigned InsnVarID, unsigned OpIdx) const {}
Daniel Sandersbee57392017-04-04 13:25:23 +0000709
Daniel Sanders9d662d22017-07-06 10:06:12 +0000710 /// Emit MatchTable opcodes that check the predicate for the given operand.
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000711 virtual void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000712 unsigned InsnVarID,
713 unsigned OpIdx) const = 0;
Daniel Sanders759ff412017-02-24 13:58:11 +0000714
715 /// Compare the priority of this object and B.
716 ///
717 /// Returns true if this object is more important than B.
Daniel Sanders05540042017-08-08 10:44:31 +0000718 virtual bool isHigherPriorityThan(const OperandPredicateMatcher &B) const;
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000719
720 /// Report the maximum number of temporary operands needed by the predicate
721 /// matcher.
Daniel Sanders2deea182017-04-22 15:11:04 +0000722 virtual unsigned countRendererFns() const { return 0; }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000723};
724
Daniel Sanders2c269f62017-08-24 09:11:20 +0000725template <>
726std::string
727PredicateListMatcher<OperandPredicateMatcher>::getNoPredicateComment() const {
728 return "No operand predicates";
729}
730
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000731/// Generates code to check that a register operand is defined by the same exact
732/// one as another.
733class SameOperandMatcher : public OperandPredicateMatcher {
Daniel Sanders1e4569f2017-10-20 20:55:29 +0000734 std::string MatchingName;
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000735
736public:
Daniel Sanders1e4569f2017-10-20 20:55:29 +0000737 SameOperandMatcher(StringRef MatchingName)
738 : OperandPredicateMatcher(OPM_SameOperand), MatchingName(MatchingName) {}
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000739
740 static bool classof(const OperandPredicateMatcher *P) {
Daniel Sanders1e4569f2017-10-20 20:55:29 +0000741 return P->getKind() == OPM_SameOperand;
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000742 }
743
744 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
745 unsigned InsnVarID, unsigned OpIdx) const override;
746};
747
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000748/// Generates code to check that an operand is a particular LLT.
749class LLTOperandMatcher : public OperandPredicateMatcher {
750protected:
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000751 LLTCodeGen Ty;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000752
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000753public:
Daniel Sanders032e7f22017-08-17 13:18:35 +0000754 static std::set<LLTCodeGen> KnownTypes;
755
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000756 LLTOperandMatcher(const LLTCodeGen &Ty)
Daniel Sanders032e7f22017-08-17 13:18:35 +0000757 : OperandPredicateMatcher(OPM_LLT), Ty(Ty) {
758 KnownTypes.insert(Ty);
759 }
Daniel Sanders759ff412017-02-24 13:58:11 +0000760
761 static bool classof(const OperandPredicateMatcher *P) {
762 return P->getKind() == OPM_LLT;
763 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000764
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000765 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000766 unsigned InsnVarID, unsigned OpIdx) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000767 Table << MatchTable::Opcode("GIM_CheckType") << MatchTable::Comment("MI")
768 << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Op")
769 << MatchTable::IntValue(OpIdx) << MatchTable::Comment("Type")
770 << MatchTable::NamedValue(Ty.getCxxEnumValue())
771 << MatchTable::LineBreak;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000772 }
773};
774
Daniel Sanders032e7f22017-08-17 13:18:35 +0000775std::set<LLTCodeGen> LLTOperandMatcher::KnownTypes;
776
Daniel Sandersa71f4542017-10-16 00:56:30 +0000777/// Generates code to check that an operand is a pointer to any address space.
778///
779/// In SelectionDAG, the types did not describe pointers or address spaces. As a
780/// result, iN is used to describe a pointer of N bits to any address space and
781/// PatFrag predicates are typically used to constrain the address space. There's
782/// no reliable means to derive the missing type information from the pattern so
783/// imported rules must test the components of a pointer separately.
784///
Daniel Sandersea8711b2017-10-16 03:36:29 +0000785/// If SizeInBits is zero, then the pointer size will be obtained from the
786/// subtarget.
Daniel Sandersa71f4542017-10-16 00:56:30 +0000787class PointerToAnyOperandMatcher : public OperandPredicateMatcher {
788protected:
789 unsigned SizeInBits;
790
791public:
792 PointerToAnyOperandMatcher(unsigned SizeInBits)
793 : OperandPredicateMatcher(OPM_PointerToAny), SizeInBits(SizeInBits) {}
794
795 static bool classof(const OperandPredicateMatcher *P) {
796 return P->getKind() == OPM_PointerToAny;
797 }
798
799 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
800 unsigned InsnVarID, unsigned OpIdx) const override {
801 Table << MatchTable::Opcode("GIM_CheckPointerToAny") << MatchTable::Comment("MI")
802 << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Op")
803 << MatchTable::IntValue(OpIdx) << MatchTable::Comment("SizeInBits")
804 << MatchTable::IntValue(SizeInBits) << MatchTable::LineBreak;
805 }
806};
807
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000808/// Generates code to check that an operand is a particular target constant.
809class ComplexPatternOperandMatcher : public OperandPredicateMatcher {
810protected:
Daniel Sanders4f3eb242017-04-05 13:14:03 +0000811 const OperandMatcher &Operand;
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000812 const Record &TheDef;
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000813
Daniel Sanders4f3eb242017-04-05 13:14:03 +0000814 unsigned getAllocatedTemporariesBaseID() const;
815
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000816public:
Daniel Sanders4f3eb242017-04-05 13:14:03 +0000817 ComplexPatternOperandMatcher(const OperandMatcher &Operand,
818 const Record &TheDef)
819 : OperandPredicateMatcher(OPM_ComplexPattern), Operand(Operand),
820 TheDef(TheDef) {}
821
822 static bool classof(const OperandPredicateMatcher *P) {
823 return P->getKind() == OPM_ComplexPattern;
824 }
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000825
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000826 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000827 unsigned InsnVarID, unsigned OpIdx) const override {
Daniel Sanders2deea182017-04-22 15:11:04 +0000828 unsigned ID = getAllocatedTemporariesBaseID();
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000829 Table << MatchTable::Opcode("GIM_CheckComplexPattern")
830 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
831 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
832 << MatchTable::Comment("Renderer") << MatchTable::IntValue(ID)
833 << MatchTable::NamedValue(("GICP_" + TheDef.getName()).str())
834 << MatchTable::LineBreak;
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000835 }
836
Daniel Sanders2deea182017-04-22 15:11:04 +0000837 unsigned countRendererFns() const override {
838 return 1;
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000839 }
840};
841
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000842/// Generates code to check that an operand is in a particular register bank.
843class RegisterBankOperandMatcher : public OperandPredicateMatcher {
844protected:
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000845 const CodeGenRegisterClass &RC;
846
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000847public:
Daniel Sanders759ff412017-02-24 13:58:11 +0000848 RegisterBankOperandMatcher(const CodeGenRegisterClass &RC)
849 : OperandPredicateMatcher(OPM_RegBank), RC(RC) {}
850
851 static bool classof(const OperandPredicateMatcher *P) {
852 return P->getKind() == OPM_RegBank;
853 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000854
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000855 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000856 unsigned InsnVarID, unsigned OpIdx) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000857 Table << MatchTable::Opcode("GIM_CheckRegBankForClass")
858 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
859 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
860 << MatchTable::Comment("RC")
861 << MatchTable::NamedValue(RC.getQualifiedName() + "RegClassID")
862 << MatchTable::LineBreak;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000863 }
864};
865
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000866/// Generates code to check that an operand is a basic block.
867class MBBOperandMatcher : public OperandPredicateMatcher {
868public:
Daniel Sanders759ff412017-02-24 13:58:11 +0000869 MBBOperandMatcher() : OperandPredicateMatcher(OPM_MBB) {}
870
871 static bool classof(const OperandPredicateMatcher *P) {
872 return P->getKind() == OPM_MBB;
873 }
874
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000875 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000876 unsigned InsnVarID, unsigned OpIdx) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000877 Table << MatchTable::Opcode("GIM_CheckIsMBB") << MatchTable::Comment("MI")
878 << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Op")
879 << MatchTable::IntValue(OpIdx) << MatchTable::LineBreak;
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000880 }
881};
882
Daniel Sanders452c8ae2017-05-23 19:33:16 +0000883/// Generates code to check that an operand is a G_CONSTANT with a particular
884/// int.
885class ConstantIntOperandMatcher : public OperandPredicateMatcher {
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000886protected:
887 int64_t Value;
888
889public:
Daniel Sanders452c8ae2017-05-23 19:33:16 +0000890 ConstantIntOperandMatcher(int64_t Value)
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000891 : OperandPredicateMatcher(OPM_Int), Value(Value) {}
892
893 static bool classof(const OperandPredicateMatcher *P) {
894 return P->getKind() == OPM_Int;
895 }
896
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000897 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000898 unsigned InsnVarID, unsigned OpIdx) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000899 Table << MatchTable::Opcode("GIM_CheckConstantInt")
900 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
901 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
902 << MatchTable::IntValue(Value) << MatchTable::LineBreak;
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000903 }
904};
905
Daniel Sanders452c8ae2017-05-23 19:33:16 +0000906/// Generates code to check that an operand is a raw int (where MO.isImm() or
907/// MO.isCImm() is true).
908class LiteralIntOperandMatcher : public OperandPredicateMatcher {
909protected:
910 int64_t Value;
911
912public:
913 LiteralIntOperandMatcher(int64_t Value)
914 : OperandPredicateMatcher(OPM_LiteralInt), Value(Value) {}
915
916 static bool classof(const OperandPredicateMatcher *P) {
917 return P->getKind() == OPM_LiteralInt;
918 }
919
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000920 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000921 unsigned InsnVarID, unsigned OpIdx) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000922 Table << MatchTable::Opcode("GIM_CheckLiteralInt")
923 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
924 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
925 << MatchTable::IntValue(Value) << MatchTable::LineBreak;
Daniel Sanders452c8ae2017-05-23 19:33:16 +0000926 }
927};
928
Daniel Sandersfe12c0f2017-07-11 08:57:29 +0000929/// Generates code to check that an operand is an intrinsic ID.
930class IntrinsicIDOperandMatcher : public OperandPredicateMatcher {
931protected:
932 const CodeGenIntrinsic *II;
933
934public:
935 IntrinsicIDOperandMatcher(const CodeGenIntrinsic *II)
936 : OperandPredicateMatcher(OPM_IntrinsicID), II(II) {}
937
938 static bool classof(const OperandPredicateMatcher *P) {
939 return P->getKind() == OPM_IntrinsicID;
940 }
941
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000942 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sandersfe12c0f2017-07-11 08:57:29 +0000943 unsigned InsnVarID, unsigned OpIdx) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000944 Table << MatchTable::Opcode("GIM_CheckIntrinsicID")
945 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
946 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
947 << MatchTable::NamedValue("Intrinsic::" + II->EnumName)
948 << MatchTable::LineBreak;
Daniel Sandersfe12c0f2017-07-11 08:57:29 +0000949 }
950};
951
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000952/// Generates code to check that a set of predicates match for a particular
953/// operand.
954class OperandMatcher : public PredicateListMatcher<OperandPredicateMatcher> {
955protected:
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000956 InstructionMatcher &Insn;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000957 unsigned OpIdx;
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000958 std::string SymbolicName;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000959
Daniel Sanders4f3eb242017-04-05 13:14:03 +0000960 /// The index of the first temporary variable allocated to this operand. The
961 /// number of allocated temporaries can be found with
Daniel Sanders2deea182017-04-22 15:11:04 +0000962 /// countRendererFns().
Daniel Sanders4f3eb242017-04-05 13:14:03 +0000963 unsigned AllocatedTemporariesBaseID;
964
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000965public:
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000966 OperandMatcher(InstructionMatcher &Insn, unsigned OpIdx,
Daniel Sanders4f3eb242017-04-05 13:14:03 +0000967 const std::string &SymbolicName,
968 unsigned AllocatedTemporariesBaseID)
969 : Insn(Insn), OpIdx(OpIdx), SymbolicName(SymbolicName),
970 AllocatedTemporariesBaseID(AllocatedTemporariesBaseID) {}
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000971
972 bool hasSymbolicName() const { return !SymbolicName.empty(); }
973 const StringRef getSymbolicName() const { return SymbolicName; }
Daniel Sandersffc7d582017-03-29 15:37:18 +0000974 void setSymbolicName(StringRef Name) {
975 assert(SymbolicName.empty() && "Operand already has a symbolic name");
976 SymbolicName = Name;
977 }
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000978 unsigned getOperandIndex() const { return OpIdx; }
979
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000980 std::string getOperandExpr(unsigned InsnVarID) const {
981 return "State.MIs[" + llvm::to_string(InsnVarID) + "]->getOperand(" +
982 llvm::to_string(OpIdx) + ")";
Daniel Sanderse604ef52017-02-20 15:30:43 +0000983 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000984
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000985 InstructionMatcher &getInstructionMatcher() const { return Insn; }
986
Daniel Sandersa71f4542017-10-16 00:56:30 +0000987 Error addTypeCheckPredicate(const TypeSetByHwMode &VTy,
Reid Klecknercfdd4a22017-10-16 20:31:16 +0000988 bool OperandIsAPointer);
Daniel Sandersa71f4542017-10-16 00:56:30 +0000989
Daniel Sanders9d662d22017-07-06 10:06:12 +0000990 /// Emit MatchTable opcodes to capture instructions into the MIs table.
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000991 void emitCaptureOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders9d662d22017-07-06 10:06:12 +0000992 unsigned InsnVarID) const {
Daniel Sandersbee57392017-04-04 13:25:23 +0000993 for (const auto &Predicate : predicates())
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000994 Predicate->emitCaptureOpcodes(Table, Rule, InsnVarID, OpIdx);
Daniel Sandersbee57392017-04-04 13:25:23 +0000995 }
996
Daniel Sanders9d662d22017-07-06 10:06:12 +0000997 /// Emit MatchTable opcodes that test whether the instruction named in
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000998 /// InsnVarID matches all the predicates and all the operands.
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000999 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001000 unsigned InsnVarID) const {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001001 std::string Comment;
1002 raw_string_ostream CommentOS(Comment);
1003 CommentOS << "MIs[" << InsnVarID << "] ";
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001004 if (SymbolicName.empty())
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001005 CommentOS << "Operand " << OpIdx;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001006 else
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001007 CommentOS << SymbolicName;
1008 Table << MatchTable::Comment(CommentOS.str()) << MatchTable::LineBreak;
1009
1010 emitPredicateListOpcodes(Table, Rule, InsnVarID, OpIdx);
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001011 }
Daniel Sanders759ff412017-02-24 13:58:11 +00001012
1013 /// Compare the priority of this object and B.
1014 ///
1015 /// Returns true if this object is more important than B.
1016 bool isHigherPriorityThan(const OperandMatcher &B) const {
1017 // Operand matchers involving more predicates have higher priority.
1018 if (predicates_size() > B.predicates_size())
1019 return true;
1020 if (predicates_size() < B.predicates_size())
1021 return false;
1022
1023 // This assumes that predicates are added in a consistent order.
1024 for (const auto &Predicate : zip(predicates(), B.predicates())) {
1025 if (std::get<0>(Predicate)->isHigherPriorityThan(*std::get<1>(Predicate)))
1026 return true;
1027 if (std::get<1>(Predicate)->isHigherPriorityThan(*std::get<0>(Predicate)))
1028 return false;
1029 }
1030
1031 return false;
1032 };
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001033
1034 /// Report the maximum number of temporary operands needed by the operand
1035 /// matcher.
Daniel Sanders2deea182017-04-22 15:11:04 +00001036 unsigned countRendererFns() const {
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001037 return std::accumulate(
1038 predicates().begin(), predicates().end(), 0,
1039 [](unsigned A,
1040 const std::unique_ptr<OperandPredicateMatcher> &Predicate) {
Daniel Sanders2deea182017-04-22 15:11:04 +00001041 return A + Predicate->countRendererFns();
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001042 });
1043 }
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001044
1045 unsigned getAllocatedTemporariesBaseID() const {
1046 return AllocatedTemporariesBaseID;
1047 }
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001048
1049 bool isSameAsAnotherOperand() const {
1050 for (const auto &Predicate : predicates())
1051 if (isa<SameOperandMatcher>(Predicate))
1052 return true;
1053 return false;
1054 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001055};
1056
Reid Klecknercfdd4a22017-10-16 20:31:16 +00001057// Specialize OperandMatcher::addPredicate() to refrain from adding redundant
1058// predicates.
1059template <>
1060template <class Kind, class... Args>
1061Optional<Kind *>
1062PredicateListMatcher<OperandPredicateMatcher>::addPredicate(Args &&... args) {
1063 if (static_cast<OperandMatcher *>(this)->isSameAsAnotherOperand())
1064 return None;
1065 Predicates.emplace_back(llvm::make_unique<Kind>(std::forward<Args>(args)...));
1066 return static_cast<Kind *>(Predicates.back().get());
1067}
1068
1069Error OperandMatcher::addTypeCheckPredicate(const TypeSetByHwMode &VTy,
1070 bool OperandIsAPointer) {
1071 if (!VTy.isMachineValueType())
1072 return failedImport("unsupported typeset");
1073
1074 if (VTy.getMachineValueType() == MVT::iPTR && OperandIsAPointer) {
1075 addPredicate<PointerToAnyOperandMatcher>(0);
1076 return Error::success();
1077 }
1078
1079 auto OpTyOrNone = MVTToLLT(VTy.getMachineValueType().SimpleTy);
1080 if (!OpTyOrNone)
1081 return failedImport("unsupported type");
1082
1083 if (OperandIsAPointer)
1084 addPredicate<PointerToAnyOperandMatcher>(OpTyOrNone->get().getSizeInBits());
1085 else
1086 addPredicate<LLTOperandMatcher>(*OpTyOrNone);
1087 return Error::success();
1088}
1089
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001090unsigned ComplexPatternOperandMatcher::getAllocatedTemporariesBaseID() const {
1091 return Operand.getAllocatedTemporariesBaseID();
1092}
1093
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001094/// Generates code to check a predicate on an instruction.
1095///
1096/// Typical predicates include:
1097/// * The opcode of the instruction is a particular value.
1098/// * The nsw/nuw flag is/isn't set.
1099class InstructionPredicateMatcher {
Daniel Sanders759ff412017-02-24 13:58:11 +00001100protected:
1101 /// This enum is used for RTTI and also defines the priority that is given to
1102 /// the predicate when generating the matcher code. Kinds with higher priority
1103 /// must be tested first.
1104 enum PredicateKind {
1105 IPM_Opcode,
Daniel Sanders2c269f62017-08-24 09:11:20 +00001106 IPM_ImmPredicate,
Daniel Sanders39690bd2017-10-15 02:41:12 +00001107 IPM_NonAtomicMMO,
Daniel Sanders759ff412017-02-24 13:58:11 +00001108 };
1109
1110 PredicateKind Kind;
1111
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001112public:
Daniel Sanders8d4d72f2017-02-24 14:53:35 +00001113 InstructionPredicateMatcher(PredicateKind Kind) : Kind(Kind) {}
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001114 virtual ~InstructionPredicateMatcher() {}
1115
Daniel Sanders759ff412017-02-24 13:58:11 +00001116 PredicateKind getKind() const { return Kind; }
1117
Daniel Sanders9d662d22017-07-06 10:06:12 +00001118 /// Emit MatchTable opcodes that test whether the instruction named in
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001119 /// InsnVarID matches the predicate.
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001120 virtual void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001121 unsigned InsnVarID) const = 0;
Daniel Sanders759ff412017-02-24 13:58:11 +00001122
1123 /// Compare the priority of this object and B.
1124 ///
1125 /// Returns true if this object is more important than B.
Daniel Sanders32291982017-06-28 13:50:04 +00001126 virtual bool
1127 isHigherPriorityThan(const InstructionPredicateMatcher &B) const {
Daniel Sanders759ff412017-02-24 13:58:11 +00001128 return Kind < B.Kind;
1129 };
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001130
1131 /// Report the maximum number of temporary operands needed by the predicate
1132 /// matcher.
Daniel Sanders2deea182017-04-22 15:11:04 +00001133 virtual unsigned countRendererFns() const { return 0; }
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001134};
1135
Daniel Sanders2c269f62017-08-24 09:11:20 +00001136template <>
1137std::string
1138PredicateListMatcher<InstructionPredicateMatcher>::getNoPredicateComment() const {
1139 return "No instruction predicates";
1140}
1141
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001142/// Generates code to check the opcode of an instruction.
1143class InstructionOpcodeMatcher : public InstructionPredicateMatcher {
1144protected:
1145 const CodeGenInstruction *I;
1146
1147public:
Daniel Sanders8d4d72f2017-02-24 14:53:35 +00001148 InstructionOpcodeMatcher(const CodeGenInstruction *I)
1149 : InstructionPredicateMatcher(IPM_Opcode), I(I) {}
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001150
Daniel Sanders759ff412017-02-24 13:58:11 +00001151 static bool classof(const InstructionPredicateMatcher *P) {
1152 return P->getKind() == IPM_Opcode;
1153 }
1154
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001155 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001156 unsigned InsnVarID) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001157 Table << MatchTable::Opcode("GIM_CheckOpcode") << MatchTable::Comment("MI")
1158 << MatchTable::IntValue(InsnVarID)
1159 << MatchTable::NamedValue(I->Namespace, I->TheDef->getName())
1160 << MatchTable::LineBreak;
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001161 }
Daniel Sanders759ff412017-02-24 13:58:11 +00001162
1163 /// Compare the priority of this object and B.
1164 ///
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001165 /// Returns true if this object is more important than B.
Daniel Sanders32291982017-06-28 13:50:04 +00001166 bool
1167 isHigherPriorityThan(const InstructionPredicateMatcher &B) const override {
Daniel Sanders759ff412017-02-24 13:58:11 +00001168 if (InstructionPredicateMatcher::isHigherPriorityThan(B))
1169 return true;
1170 if (B.InstructionPredicateMatcher::isHigherPriorityThan(*this))
1171 return false;
1172
1173 // Prioritize opcodes for cosmetic reasons in the generated source. Although
1174 // this is cosmetic at the moment, we may want to drive a similar ordering
1175 // using instruction frequency information to improve compile time.
1176 if (const InstructionOpcodeMatcher *BO =
1177 dyn_cast<InstructionOpcodeMatcher>(&B))
1178 return I->TheDef->getName() < BO->I->TheDef->getName();
1179
1180 return false;
1181 };
Daniel Sanders05540042017-08-08 10:44:31 +00001182
1183 bool isConstantInstruction() const {
1184 return I->TheDef->getName() == "G_CONSTANT";
1185 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001186};
1187
Daniel Sanders2c269f62017-08-24 09:11:20 +00001188/// Generates code to check that this instruction is a constant whose value
1189/// meets an immediate predicate.
1190///
1191/// Immediates are slightly odd since they are typically used like an operand
1192/// but are represented as an operator internally. We typically write simm8:$src
1193/// in a tablegen pattern, but this is just syntactic sugar for
1194/// (imm:i32)<<P:Predicate_simm8>>:$imm which more directly describes the nodes
1195/// that will be matched and the predicate (which is attached to the imm
1196/// operator) that will be tested. In SelectionDAG this describes a
1197/// ConstantSDNode whose internal value will be tested using the simm8 predicate.
1198///
1199/// The corresponding GlobalISel representation is %1 = G_CONSTANT iN Value. In
1200/// this representation, the immediate could be tested with an
1201/// InstructionMatcher, InstructionOpcodeMatcher, OperandMatcher, and a
1202/// OperandPredicateMatcher-subclass to check the Value meets the predicate but
1203/// there are two implementation issues with producing that matcher
1204/// configuration from the SelectionDAG pattern:
1205/// * ImmLeaf is a PatFrag whose root is an InstructionMatcher. This means that
1206/// were we to sink the immediate predicate to the operand we would have to
1207/// have two partial implementations of PatFrag support, one for immediates
1208/// and one for non-immediates.
1209/// * At the point we handle the predicate, the OperandMatcher hasn't been
1210/// created yet. If we were to sink the predicate to the OperandMatcher we
1211/// would also have to complicate (or duplicate) the code that descends and
1212/// creates matchers for the subtree.
1213/// Overall, it's simpler to handle it in the place it was found.
1214class InstructionImmPredicateMatcher : public InstructionPredicateMatcher {
1215protected:
1216 TreePredicateFn Predicate;
1217
1218public:
1219 InstructionImmPredicateMatcher(const TreePredicateFn &Predicate)
1220 : InstructionPredicateMatcher(IPM_ImmPredicate), Predicate(Predicate) {}
1221
1222 static bool classof(const InstructionPredicateMatcher *P) {
1223 return P->getKind() == IPM_ImmPredicate;
1224 }
1225
1226 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
1227 unsigned InsnVarID) const override {
Daniel Sanders11300ce2017-10-13 21:28:03 +00001228 Table << MatchTable::Opcode(getMatchOpcodeForPredicate(Predicate))
Daniel Sanders2c269f62017-08-24 09:11:20 +00001229 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1230 << MatchTable::Comment("Predicate")
Daniel Sanders11300ce2017-10-13 21:28:03 +00001231 << MatchTable::NamedValue(getEnumNameForPredicate(Predicate))
Daniel Sanders2c269f62017-08-24 09:11:20 +00001232 << MatchTable::LineBreak;
1233 }
1234};
1235
Daniel Sanders39690bd2017-10-15 02:41:12 +00001236/// Generates code to check that a memory instruction has a non-atomic MachineMemoryOperand.
1237class NonAtomicMMOPredicateMatcher : public InstructionPredicateMatcher {
1238public:
1239 NonAtomicMMOPredicateMatcher()
1240 : InstructionPredicateMatcher(IPM_NonAtomicMMO) {}
1241
1242 static bool classof(const InstructionPredicateMatcher *P) {
1243 return P->getKind() == IPM_NonAtomicMMO;
1244 }
1245
1246 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
1247 unsigned InsnVarID) const override {
1248 Table << MatchTable::Opcode("GIM_CheckNonAtomic")
1249 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1250 << MatchTable::LineBreak;
1251 }
1252};
1253
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001254/// Generates code to check that a set of predicates and operands match for a
1255/// particular instruction.
1256///
1257/// Typical predicates include:
1258/// * Has a specific opcode.
1259/// * Has an nsw/nuw flag or doesn't.
1260class InstructionMatcher
1261 : public PredicateListMatcher<InstructionPredicateMatcher> {
1262protected:
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001263 typedef std::vector<std::unique_ptr<OperandMatcher>> OperandVec;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001264
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001265 RuleMatcher &Rule;
1266
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001267 /// The operands to match. All rendered operands must be present even if the
1268 /// condition is always true.
1269 OperandVec Operands;
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001270
Daniel Sanders05540042017-08-08 10:44:31 +00001271 std::string SymbolicName;
1272
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001273public:
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001274 InstructionMatcher(RuleMatcher &Rule, StringRef SymbolicName)
1275 : Rule(Rule), SymbolicName(SymbolicName) {}
1276
1277 RuleMatcher &getRuleMatcher() const { return Rule; }
Daniel Sanders05540042017-08-08 10:44:31 +00001278
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001279 /// Add an operand to the matcher.
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001280 OperandMatcher &addOperand(unsigned OpIdx, const std::string &SymbolicName,
1281 unsigned AllocatedTemporariesBaseID) {
1282 Operands.emplace_back(new OperandMatcher(*this, OpIdx, SymbolicName,
1283 AllocatedTemporariesBaseID));
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001284 if (!SymbolicName.empty())
1285 Rule.defineOperand(SymbolicName, *Operands.back());
1286
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001287 return *Operands.back();
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001288 }
1289
Daniel Sandersffc7d582017-03-29 15:37:18 +00001290 OperandMatcher &getOperand(unsigned OpIdx) {
1291 auto I = std::find_if(Operands.begin(), Operands.end(),
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001292 [&OpIdx](const std::unique_ptr<OperandMatcher> &X) {
1293 return X->getOperandIndex() == OpIdx;
Daniel Sandersffc7d582017-03-29 15:37:18 +00001294 });
1295 if (I != Operands.end())
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001296 return **I;
Daniel Sandersffc7d582017-03-29 15:37:18 +00001297 llvm_unreachable("Failed to lookup operand");
1298 }
1299
Daniel Sanders05540042017-08-08 10:44:31 +00001300 StringRef getSymbolicName() const { return SymbolicName; }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001301 unsigned getNumOperands() const { return Operands.size(); }
Daniel Sandersbee57392017-04-04 13:25:23 +00001302 OperandVec::iterator operands_begin() { return Operands.begin(); }
1303 OperandVec::iterator operands_end() { return Operands.end(); }
1304 iterator_range<OperandVec::iterator> operands() {
1305 return make_range(operands_begin(), operands_end());
1306 }
Daniel Sandersffc7d582017-03-29 15:37:18 +00001307 OperandVec::const_iterator operands_begin() const { return Operands.begin(); }
1308 OperandVec::const_iterator operands_end() const { return Operands.end(); }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001309 iterator_range<OperandVec::const_iterator> operands() const {
1310 return make_range(operands_begin(), operands_end());
1311 }
1312
Daniel Sanders9d662d22017-07-06 10:06:12 +00001313 /// Emit MatchTable opcodes to check the shape of the match and capture
1314 /// instructions into the MIs table.
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001315 void emitCaptureOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders9d662d22017-07-06 10:06:12 +00001316 unsigned InsnID) {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001317 Table << MatchTable::Opcode("GIM_CheckNumOperands")
1318 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnID)
1319 << MatchTable::Comment("Expected")
1320 << MatchTable::IntValue(getNumOperands()) << MatchTable::LineBreak;
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001321 for (const auto &Operand : Operands)
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001322 Operand->emitCaptureOpcodes(Table, Rule, InsnID);
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001323 }
1324
Daniel Sanders9d662d22017-07-06 10:06:12 +00001325 /// Emit MatchTable opcodes that test whether the instruction named in
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001326 /// InsnVarName matches all the predicates and all the operands.
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001327 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001328 unsigned InsnVarID) const {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001329 emitPredicateListOpcodes(Table, Rule, InsnVarID);
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001330 for (const auto &Operand : Operands)
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001331 Operand->emitPredicateOpcodes(Table, Rule, InsnVarID);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001332 }
Daniel Sanders759ff412017-02-24 13:58:11 +00001333
1334 /// Compare the priority of this object and B.
1335 ///
1336 /// Returns true if this object is more important than B.
1337 bool isHigherPriorityThan(const InstructionMatcher &B) const {
1338 // Instruction matchers involving more operands have higher priority.
1339 if (Operands.size() > B.Operands.size())
1340 return true;
1341 if (Operands.size() < B.Operands.size())
1342 return false;
1343
1344 for (const auto &Predicate : zip(predicates(), B.predicates())) {
1345 if (std::get<0>(Predicate)->isHigherPriorityThan(*std::get<1>(Predicate)))
1346 return true;
1347 if (std::get<1>(Predicate)->isHigherPriorityThan(*std::get<0>(Predicate)))
1348 return false;
1349 }
1350
1351 for (const auto &Operand : zip(Operands, B.Operands)) {
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001352 if (std::get<0>(Operand)->isHigherPriorityThan(*std::get<1>(Operand)))
Daniel Sanders759ff412017-02-24 13:58:11 +00001353 return true;
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001354 if (std::get<1>(Operand)->isHigherPriorityThan(*std::get<0>(Operand)))
Daniel Sanders759ff412017-02-24 13:58:11 +00001355 return false;
1356 }
1357
1358 return false;
1359 };
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001360
1361 /// Report the maximum number of temporary operands needed by the instruction
1362 /// matcher.
Daniel Sanders2deea182017-04-22 15:11:04 +00001363 unsigned countRendererFns() const {
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001364 return std::accumulate(predicates().begin(), predicates().end(), 0,
1365 [](unsigned A,
1366 const std::unique_ptr<InstructionPredicateMatcher>
1367 &Predicate) {
Daniel Sanders2deea182017-04-22 15:11:04 +00001368 return A + Predicate->countRendererFns();
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001369 }) +
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001370 std::accumulate(
1371 Operands.begin(), Operands.end(), 0,
1372 [](unsigned A, const std::unique_ptr<OperandMatcher> &Operand) {
Daniel Sanders2deea182017-04-22 15:11:04 +00001373 return A + Operand->countRendererFns();
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001374 });
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001375 }
Daniel Sanders05540042017-08-08 10:44:31 +00001376
1377 bool isConstantInstruction() const {
1378 for (const auto &P : predicates())
1379 if (const InstructionOpcodeMatcher *Opcode =
1380 dyn_cast<InstructionOpcodeMatcher>(P.get()))
1381 return Opcode->isConstantInstruction();
1382 return false;
1383 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001384};
1385
Daniel Sandersbee57392017-04-04 13:25:23 +00001386/// Generates code to check that the operand is a register defined by an
1387/// instruction that matches the given instruction matcher.
1388///
1389/// For example, the pattern:
1390/// (set $dst, (G_MUL (G_ADD $src1, $src2), $src3))
1391/// would use an InstructionOperandMatcher for operand 1 of the G_MUL to match
1392/// the:
1393/// (G_ADD $src1, $src2)
1394/// subpattern.
1395class InstructionOperandMatcher : public OperandPredicateMatcher {
1396protected:
1397 std::unique_ptr<InstructionMatcher> InsnMatcher;
1398
1399public:
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001400 InstructionOperandMatcher(RuleMatcher &Rule, StringRef SymbolicName)
Daniel Sandersbee57392017-04-04 13:25:23 +00001401 : OperandPredicateMatcher(OPM_Instruction),
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001402 InsnMatcher(new InstructionMatcher(Rule, SymbolicName)) {}
Daniel Sandersbee57392017-04-04 13:25:23 +00001403
1404 static bool classof(const OperandPredicateMatcher *P) {
1405 return P->getKind() == OPM_Instruction;
1406 }
1407
1408 InstructionMatcher &getInsnMatcher() const { return *InsnMatcher; }
1409
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001410 void emitCaptureOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders9d662d22017-07-06 10:06:12 +00001411 unsigned InsnID, unsigned OpIdx) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001412 unsigned InsnVarID = Rule.defineInsnVar(Table, *InsnMatcher, InsnID, OpIdx);
1413 InsnMatcher->emitCaptureOpcodes(Table, Rule, InsnVarID);
Daniel Sandersbee57392017-04-04 13:25:23 +00001414 }
1415
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001416 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001417 unsigned InsnVarID_,
1418 unsigned OpIdx_) const override {
1419 unsigned InsnVarID = Rule.getInsnVarID(*InsnMatcher);
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001420 InsnMatcher->emitPredicateOpcodes(Table, Rule, InsnVarID);
Daniel Sandersbee57392017-04-04 13:25:23 +00001421 }
1422};
1423
Daniel Sanders43c882c2017-02-01 10:53:10 +00001424//===- Actions ------------------------------------------------------------===//
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001425class OperandRenderer {
1426public:
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00001427 enum RendererKind {
1428 OR_Copy,
Daniel Sandersd66e0902017-10-23 18:19:24 +00001429 OR_CopyOrAddZeroReg,
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00001430 OR_CopySubReg,
Daniel Sanders05540042017-08-08 10:44:31 +00001431 OR_CopyConstantAsImm,
Daniel Sanders11300ce2017-10-13 21:28:03 +00001432 OR_CopyFConstantAsFPImm,
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00001433 OR_Imm,
1434 OR_Register,
1435 OR_ComplexPattern
1436 };
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001437
1438protected:
1439 RendererKind Kind;
1440
1441public:
1442 OperandRenderer(RendererKind Kind) : Kind(Kind) {}
1443 virtual ~OperandRenderer() {}
1444
1445 RendererKind getKind() const { return Kind; }
1446
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001447 virtual void emitRenderOpcodes(MatchTable &Table,
1448 RuleMatcher &Rule) const = 0;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001449};
1450
1451/// A CopyRenderer emits code to copy a single operand from an existing
1452/// instruction to the one being built.
1453class CopyRenderer : public OperandRenderer {
1454protected:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001455 unsigned NewInsnID;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001456 /// The name of the operand.
1457 const StringRef SymbolicName;
1458
1459public:
Daniel Sandersbd83ad42017-10-24 01:48:34 +00001460 CopyRenderer(unsigned NewInsnID, StringRef SymbolicName)
1461 : OperandRenderer(OR_Copy), NewInsnID(NewInsnID),
Daniel Sanders05540042017-08-08 10:44:31 +00001462 SymbolicName(SymbolicName) {
1463 assert(!SymbolicName.empty() && "Cannot copy from an unspecified source");
1464 }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001465
1466 static bool classof(const OperandRenderer *R) {
1467 return R->getKind() == OR_Copy;
1468 }
1469
1470 const StringRef getSymbolicName() const { return SymbolicName; }
1471
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001472 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001473 const OperandMatcher &Operand = Rule.getOperandMatcher(SymbolicName);
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001474 unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001475 Table << MatchTable::Opcode("GIR_Copy") << MatchTable::Comment("NewInsnID")
1476 << MatchTable::IntValue(NewInsnID) << MatchTable::Comment("OldInsnID")
1477 << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
1478 << MatchTable::IntValue(Operand.getOperandIndex())
1479 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001480 }
1481};
1482
Daniel Sandersd66e0902017-10-23 18:19:24 +00001483/// A CopyOrAddZeroRegRenderer emits code to copy a single operand from an
1484/// existing instruction to the one being built. If the operand turns out to be
1485/// a 'G_CONSTANT 0' then it replaces the operand with a zero register.
1486class CopyOrAddZeroRegRenderer : public OperandRenderer {
1487protected:
1488 unsigned NewInsnID;
1489 /// The name of the operand.
1490 const StringRef SymbolicName;
1491 const Record *ZeroRegisterDef;
1492
1493public:
1494 CopyOrAddZeroRegRenderer(unsigned NewInsnID,
Daniel Sandersd66e0902017-10-23 18:19:24 +00001495 StringRef SymbolicName, Record *ZeroRegisterDef)
1496 : OperandRenderer(OR_CopyOrAddZeroReg), NewInsnID(NewInsnID),
1497 SymbolicName(SymbolicName), ZeroRegisterDef(ZeroRegisterDef) {
1498 assert(!SymbolicName.empty() && "Cannot copy from an unspecified source");
1499 }
1500
1501 static bool classof(const OperandRenderer *R) {
1502 return R->getKind() == OR_CopyOrAddZeroReg;
1503 }
1504
1505 const StringRef getSymbolicName() const { return SymbolicName; }
1506
1507 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
1508 const OperandMatcher &Operand = Rule.getOperandMatcher(SymbolicName);
1509 unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
1510 Table << MatchTable::Opcode("GIR_CopyOrAddZeroReg")
1511 << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
1512 << MatchTable::Comment("OldInsnID")
1513 << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
1514 << MatchTable::IntValue(Operand.getOperandIndex())
1515 << MatchTable::NamedValue(
1516 (ZeroRegisterDef->getValue("Namespace")
1517 ? ZeroRegisterDef->getValueAsString("Namespace")
1518 : ""),
1519 ZeroRegisterDef->getName())
1520 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
1521 }
1522};
1523
Daniel Sanders05540042017-08-08 10:44:31 +00001524/// A CopyConstantAsImmRenderer emits code to render a G_CONSTANT instruction to
1525/// an extended immediate operand.
1526class CopyConstantAsImmRenderer : public OperandRenderer {
1527protected:
1528 unsigned NewInsnID;
1529 /// The name of the operand.
1530 const std::string SymbolicName;
1531 bool Signed;
1532
1533public:
1534 CopyConstantAsImmRenderer(unsigned NewInsnID, StringRef SymbolicName)
1535 : OperandRenderer(OR_CopyConstantAsImm), NewInsnID(NewInsnID),
1536 SymbolicName(SymbolicName), Signed(true) {}
1537
1538 static bool classof(const OperandRenderer *R) {
1539 return R->getKind() == OR_CopyConstantAsImm;
1540 }
1541
1542 const StringRef getSymbolicName() const { return SymbolicName; }
1543
1544 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
1545 const InstructionMatcher &InsnMatcher = Rule.getInstructionMatcher(SymbolicName);
1546 unsigned OldInsnVarID = Rule.getInsnVarID(InsnMatcher);
1547 Table << MatchTable::Opcode(Signed ? "GIR_CopyConstantAsSImm"
1548 : "GIR_CopyConstantAsUImm")
1549 << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
1550 << MatchTable::Comment("OldInsnID")
1551 << MatchTable::IntValue(OldInsnVarID)
1552 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
1553 }
1554};
1555
Daniel Sanders11300ce2017-10-13 21:28:03 +00001556/// A CopyFConstantAsFPImmRenderer emits code to render a G_FCONSTANT
1557/// instruction to an extended immediate operand.
1558class CopyFConstantAsFPImmRenderer : public OperandRenderer {
1559protected:
1560 unsigned NewInsnID;
1561 /// The name of the operand.
1562 const std::string SymbolicName;
1563
1564public:
1565 CopyFConstantAsFPImmRenderer(unsigned NewInsnID, StringRef SymbolicName)
1566 : OperandRenderer(OR_CopyFConstantAsFPImm), NewInsnID(NewInsnID),
1567 SymbolicName(SymbolicName) {}
1568
1569 static bool classof(const OperandRenderer *R) {
1570 return R->getKind() == OR_CopyFConstantAsFPImm;
1571 }
1572
1573 const StringRef getSymbolicName() const { return SymbolicName; }
1574
1575 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
1576 const InstructionMatcher &InsnMatcher = Rule.getInstructionMatcher(SymbolicName);
1577 unsigned OldInsnVarID = Rule.getInsnVarID(InsnMatcher);
1578 Table << MatchTable::Opcode("GIR_CopyFConstantAsFPImm")
1579 << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
1580 << MatchTable::Comment("OldInsnID")
1581 << MatchTable::IntValue(OldInsnVarID)
1582 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
1583 }
1584};
1585
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00001586/// A CopySubRegRenderer emits code to copy a single register operand from an
1587/// existing instruction to the one being built and indicate that only a
1588/// subregister should be copied.
1589class CopySubRegRenderer : public OperandRenderer {
1590protected:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001591 unsigned NewInsnID;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00001592 /// The name of the operand.
1593 const StringRef SymbolicName;
1594 /// The subregister to extract.
1595 const CodeGenSubRegIndex *SubReg;
1596
1597public:
Daniel Sandersbd83ad42017-10-24 01:48:34 +00001598 CopySubRegRenderer(unsigned NewInsnID, StringRef SymbolicName,
1599 const CodeGenSubRegIndex *SubReg)
1600 : OperandRenderer(OR_CopySubReg), NewInsnID(NewInsnID),
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00001601 SymbolicName(SymbolicName), SubReg(SubReg) {}
1602
1603 static bool classof(const OperandRenderer *R) {
1604 return R->getKind() == OR_CopySubReg;
1605 }
1606
1607 const StringRef getSymbolicName() const { return SymbolicName; }
1608
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001609 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001610 const OperandMatcher &Operand = Rule.getOperandMatcher(SymbolicName);
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001611 unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001612 Table << MatchTable::Opcode("GIR_CopySubReg")
1613 << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
1614 << MatchTable::Comment("OldInsnID")
1615 << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
1616 << MatchTable::IntValue(Operand.getOperandIndex())
1617 << MatchTable::Comment("SubRegIdx")
1618 << MatchTable::IntValue(SubReg->EnumValue)
1619 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00001620 }
1621};
1622
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001623/// Adds a specific physical register to the instruction being built.
1624/// This is typically useful for WZR/XZR on AArch64.
1625class AddRegisterRenderer : public OperandRenderer {
1626protected:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001627 unsigned InsnID;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001628 const Record *RegisterDef;
1629
1630public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001631 AddRegisterRenderer(unsigned InsnID, const Record *RegisterDef)
1632 : OperandRenderer(OR_Register), InsnID(InsnID), RegisterDef(RegisterDef) {
1633 }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001634
1635 static bool classof(const OperandRenderer *R) {
1636 return R->getKind() == OR_Register;
1637 }
1638
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001639 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
1640 Table << MatchTable::Opcode("GIR_AddRegister")
1641 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1642 << MatchTable::NamedValue(
1643 (RegisterDef->getValue("Namespace")
1644 ? RegisterDef->getValueAsString("Namespace")
1645 : ""),
1646 RegisterDef->getName())
1647 << MatchTable::LineBreak;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001648 }
1649};
1650
Daniel Sanders0ed28822017-04-12 08:23:08 +00001651/// Adds a specific immediate to the instruction being built.
1652class ImmRenderer : public OperandRenderer {
1653protected:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001654 unsigned InsnID;
Daniel Sanders0ed28822017-04-12 08:23:08 +00001655 int64_t Imm;
1656
1657public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001658 ImmRenderer(unsigned InsnID, int64_t Imm)
1659 : OperandRenderer(OR_Imm), InsnID(InsnID), Imm(Imm) {}
Daniel Sanders0ed28822017-04-12 08:23:08 +00001660
1661 static bool classof(const OperandRenderer *R) {
1662 return R->getKind() == OR_Imm;
1663 }
1664
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001665 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
1666 Table << MatchTable::Opcode("GIR_AddImm") << MatchTable::Comment("InsnID")
1667 << MatchTable::IntValue(InsnID) << MatchTable::Comment("Imm")
1668 << MatchTable::IntValue(Imm) << MatchTable::LineBreak;
Daniel Sanders0ed28822017-04-12 08:23:08 +00001669 }
1670};
1671
Daniel Sanders2deea182017-04-22 15:11:04 +00001672/// Adds operands by calling a renderer function supplied by the ComplexPattern
1673/// matcher function.
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001674class RenderComplexPatternOperand : public OperandRenderer {
1675private:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001676 unsigned InsnID;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001677 const Record &TheDef;
Daniel Sanders2deea182017-04-22 15:11:04 +00001678 /// The name of the operand.
1679 const StringRef SymbolicName;
1680 /// The renderer number. This must be unique within a rule since it's used to
1681 /// identify a temporary variable to hold the renderer function.
1682 unsigned RendererID;
Daniel Sandersdf39cba2017-10-15 18:22:54 +00001683 /// When provided, this is the suboperand of the ComplexPattern operand to
1684 /// render. Otherwise all the suboperands will be rendered.
1685 Optional<unsigned> SubOperand;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001686
1687 unsigned getNumOperands() const {
1688 return TheDef.getValueAsDag("Operands")->getNumArgs();
1689 }
1690
1691public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001692 RenderComplexPatternOperand(unsigned InsnID, const Record &TheDef,
Daniel Sandersdf39cba2017-10-15 18:22:54 +00001693 StringRef SymbolicName, unsigned RendererID,
1694 Optional<unsigned> SubOperand = None)
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001695 : OperandRenderer(OR_ComplexPattern), InsnID(InsnID), TheDef(TheDef),
Daniel Sandersdf39cba2017-10-15 18:22:54 +00001696 SymbolicName(SymbolicName), RendererID(RendererID),
1697 SubOperand(SubOperand) {}
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001698
1699 static bool classof(const OperandRenderer *R) {
1700 return R->getKind() == OR_ComplexPattern;
1701 }
1702
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001703 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sandersdf39cba2017-10-15 18:22:54 +00001704 Table << MatchTable::Opcode(SubOperand.hasValue() ? "GIR_ComplexSubOperandRenderer"
1705 : "GIR_ComplexRenderer")
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001706 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1707 << MatchTable::Comment("RendererID")
Daniel Sandersdf39cba2017-10-15 18:22:54 +00001708 << MatchTable::IntValue(RendererID);
1709 if (SubOperand.hasValue())
1710 Table << MatchTable::Comment("SubOperand")
1711 << MatchTable::IntValue(SubOperand.getValue());
1712 Table << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001713 }
1714};
1715
Ahmed Bougacha56ca3a92017-02-04 00:47:10 +00001716/// An action taken when all Matcher predicates succeeded for a parent rule.
1717///
1718/// Typical actions include:
1719/// * Changing the opcode of an instruction.
1720/// * Adding an operand to an instruction.
Daniel Sanders43c882c2017-02-01 10:53:10 +00001721class MatchAction {
1722public:
1723 virtual ~MatchAction() {}
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001724
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001725 /// Emit the MatchTable opcodes to implement the action.
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001726 ///
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001727 /// \param RecycleInsnID If given, it's an instruction to recycle. The
1728 /// requirements on the instruction vary from action to
1729 /// action.
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001730 virtual void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule,
1731 unsigned RecycleInsnID) const = 0;
Daniel Sanders43c882c2017-02-01 10:53:10 +00001732};
1733
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +00001734/// Generates a comment describing the matched rule being acted upon.
1735class DebugCommentAction : public MatchAction {
1736private:
1737 const PatternToMatch &P;
1738
1739public:
1740 DebugCommentAction(const PatternToMatch &P) : P(P) {}
1741
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001742 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule,
1743 unsigned RecycleInsnID) const override {
1744 Table << MatchTable::Comment(llvm::to_string(*P.getSrcPattern()) + " => " +
1745 llvm::to_string(*P.getDstPattern()))
1746 << MatchTable::LineBreak;
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +00001747 }
1748};
1749
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001750/// Generates code to build an instruction or mutate an existing instruction
1751/// into the desired instruction when this is possible.
1752class BuildMIAction : public MatchAction {
Daniel Sanders43c882c2017-02-01 10:53:10 +00001753private:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001754 unsigned InsnID;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001755 const CodeGenInstruction *I;
Daniel Sanders64f745c2017-10-24 17:08:43 +00001756 const InstructionMatcher *Matched;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001757 std::vector<std::unique_ptr<OperandRenderer>> OperandRenderers;
1758
1759 /// True if the instruction can be built solely by mutating the opcode.
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001760 bool canMutate(RuleMatcher &Rule) const {
Daniel Sandersab1d1192017-10-24 18:11:54 +00001761 if (!Matched)
1762 return false;
1763
Daniel Sanders64f745c2017-10-24 17:08:43 +00001764 if (OperandRenderers.size() != Matched->getNumOperands())
Daniel Sanderse9fdba32017-04-29 17:30:09 +00001765 return false;
1766
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001767 for (const auto &Renderer : enumerate(OperandRenderers)) {
Zachary Turner309a0882017-03-13 16:24:10 +00001768 if (const auto *Copy = dyn_cast<CopyRenderer>(&*Renderer.value())) {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001769 const OperandMatcher &OM = Rule.getOperandMatcher(Copy->getSymbolicName());
Daniel Sandersab1d1192017-10-24 18:11:54 +00001770 if (Matched != &OM.getInstructionMatcher() ||
Daniel Sanders3016d3c2017-04-22 14:31:28 +00001771 OM.getOperandIndex() != Renderer.index())
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001772 return false;
1773 } else
1774 return false;
1775 }
1776
1777 return true;
1778 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001779
Daniel Sanders43c882c2017-02-01 10:53:10 +00001780public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001781 BuildMIAction(unsigned InsnID, const CodeGenInstruction *I,
Daniel Sanders64f745c2017-10-24 17:08:43 +00001782 const InstructionMatcher *Matched)
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001783 : InsnID(InsnID), I(I), Matched(Matched) {}
Daniel Sanders43c882c2017-02-01 10:53:10 +00001784
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001785 template <class Kind, class... Args>
1786 Kind &addRenderer(Args&&... args) {
1787 OperandRenderers.emplace_back(
1788 llvm::make_unique<Kind>(std::forward<Args>(args)...));
1789 return *static_cast<Kind *>(OperandRenderers.back().get());
1790 }
1791
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001792 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule,
1793 unsigned RecycleInsnID) const override {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001794 if (canMutate(Rule)) {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001795 Table << MatchTable::Opcode("GIR_MutateOpcode")
1796 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1797 << MatchTable::Comment("RecycleInsnID")
1798 << MatchTable::IntValue(RecycleInsnID)
1799 << MatchTable::Comment("Opcode")
1800 << MatchTable::NamedValue(I->Namespace, I->TheDef->getName())
1801 << MatchTable::LineBreak;
Tim Northover4340d642017-03-20 21:58:23 +00001802
1803 if (!I->ImplicitDefs.empty() || !I->ImplicitUses.empty()) {
Tim Northover4340d642017-03-20 21:58:23 +00001804 for (auto Def : I->ImplicitDefs) {
Diana Picus8abcbbb2017-05-02 09:40:49 +00001805 auto Namespace = Def->getValue("Namespace")
1806 ? Def->getValueAsString("Namespace")
1807 : "";
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001808 Table << MatchTable::Opcode("GIR_AddImplicitDef")
1809 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1810 << MatchTable::NamedValue(Namespace, Def->getName())
1811 << MatchTable::LineBreak;
Tim Northover4340d642017-03-20 21:58:23 +00001812 }
1813 for (auto Use : I->ImplicitUses) {
Diana Picus8abcbbb2017-05-02 09:40:49 +00001814 auto Namespace = Use->getValue("Namespace")
1815 ? Use->getValueAsString("Namespace")
1816 : "";
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001817 Table << MatchTable::Opcode("GIR_AddImplicitUse")
1818 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1819 << MatchTable::NamedValue(Namespace, Use->getName())
1820 << MatchTable::LineBreak;
Tim Northover4340d642017-03-20 21:58:23 +00001821 }
1822 }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001823 return;
1824 }
1825
1826 // TODO: Simple permutation looks like it could be almost as common as
1827 // mutation due to commutative operations.
1828
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001829 Table << MatchTable::Opcode("GIR_BuildMI") << MatchTable::Comment("InsnID")
1830 << MatchTable::IntValue(InsnID) << MatchTable::Comment("Opcode")
1831 << MatchTable::NamedValue(I->Namespace, I->TheDef->getName())
1832 << MatchTable::LineBreak;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001833 for (const auto &Renderer : OperandRenderers)
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001834 Renderer->emitRenderOpcodes(Table, Rule);
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001835
Florian Hahn3bc3ec62017-08-03 14:48:22 +00001836 if (I->mayLoad || I->mayStore) {
1837 Table << MatchTable::Opcode("GIR_MergeMemOperands")
1838 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1839 << MatchTable::Comment("MergeInsnID's");
1840 // Emit the ID's for all the instructions that are matched by this rule.
1841 // TODO: Limit this to matched instructions that mayLoad/mayStore or have
1842 // some other means of having a memoperand. Also limit this to
1843 // emitted instructions that expect to have a memoperand too. For
1844 // example, (G_SEXT (G_LOAD x)) that results in separate load and
1845 // sign-extend instructions shouldn't put the memoperand on the
1846 // sign-extend since it has no effect there.
1847 std::vector<unsigned> MergeInsnIDs;
1848 for (const auto &IDMatcherPair : Rule.defined_insn_vars())
1849 MergeInsnIDs.push_back(IDMatcherPair.second);
1850 std::sort(MergeInsnIDs.begin(), MergeInsnIDs.end());
1851 for (const auto &MergeInsnID : MergeInsnIDs)
1852 Table << MatchTable::IntValue(MergeInsnID);
Daniel Sanders05540042017-08-08 10:44:31 +00001853 Table << MatchTable::NamedValue("GIU_MergeMemOperands_EndOfList")
1854 << MatchTable::LineBreak;
Florian Hahn3bc3ec62017-08-03 14:48:22 +00001855 }
1856
1857 Table << MatchTable::Opcode("GIR_EraseFromParent")
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001858 << MatchTable::Comment("InsnID")
1859 << MatchTable::IntValue(RecycleInsnID) << MatchTable::LineBreak;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00001860 }
1861};
1862
1863/// Generates code to constrain the operands of an output instruction to the
1864/// register classes specified by the definition of that instruction.
1865class ConstrainOperandsToDefinitionAction : public MatchAction {
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001866 unsigned InsnID;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00001867
1868public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001869 ConstrainOperandsToDefinitionAction(unsigned InsnID) : InsnID(InsnID) {}
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00001870
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001871 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule,
1872 unsigned RecycleInsnID) const override {
1873 Table << MatchTable::Opcode("GIR_ConstrainSelectedInstOperands")
1874 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1875 << MatchTable::LineBreak;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00001876 }
1877};
1878
1879/// Generates code to constrain the specified operand of an output instruction
1880/// to the specified register class.
1881class ConstrainOperandToRegClassAction : public MatchAction {
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001882 unsigned InsnID;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00001883 unsigned OpIdx;
1884 const CodeGenRegisterClass &RC;
1885
1886public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001887 ConstrainOperandToRegClassAction(unsigned InsnID, unsigned OpIdx,
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00001888 const CodeGenRegisterClass &RC)
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001889 : InsnID(InsnID), OpIdx(OpIdx), RC(RC) {}
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00001890
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001891 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule,
1892 unsigned RecycleInsnID) const override {
1893 Table << MatchTable::Opcode("GIR_ConstrainOperandRC")
1894 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1895 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1896 << MatchTable::Comment("RC " + RC.getName())
1897 << MatchTable::IntValue(RC.EnumValue) << MatchTable::LineBreak;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001898 }
1899};
1900
Daniel Sanders05540042017-08-08 10:44:31 +00001901InstructionMatcher &RuleMatcher::addInstructionMatcher(StringRef SymbolicName) {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001902 Matchers.emplace_back(new InstructionMatcher(*this, SymbolicName));
Daniel Sandersbdfebb82017-03-15 20:18:38 +00001903 return *Matchers.back();
1904}
Ahmed Bougacha56ca3a92017-02-04 00:47:10 +00001905
Daniel Sanderse7b0d662017-04-21 15:59:56 +00001906void RuleMatcher::addRequiredFeature(Record *Feature) {
1907 RequiredFeatures.push_back(Feature);
1908}
1909
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001910const std::vector<Record *> &RuleMatcher::getRequiredFeatures() const {
1911 return RequiredFeatures;
1912}
1913
Daniel Sandersbdfebb82017-03-15 20:18:38 +00001914template <class Kind, class... Args>
1915Kind &RuleMatcher::addAction(Args &&... args) {
1916 Actions.emplace_back(llvm::make_unique<Kind>(std::forward<Args>(args)...));
1917 return *static_cast<Kind *>(Actions.back().get());
1918}
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001919
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001920unsigned
1921RuleMatcher::implicitlyDefineInsnVar(const InstructionMatcher &Matcher) {
1922 unsigned NewInsnVarID = NextInsnVarID++;
1923 InsnVariableIDs[&Matcher] = NewInsnVarID;
1924 return NewInsnVarID;
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001925}
1926
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001927unsigned RuleMatcher::defineInsnVar(MatchTable &Table,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001928 const InstructionMatcher &Matcher,
1929 unsigned InsnID, unsigned OpIdx) {
1930 unsigned NewInsnVarID = implicitlyDefineInsnVar(Matcher);
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001931 Table << MatchTable::Opcode("GIM_RecordInsn")
1932 << MatchTable::Comment("DefineMI") << MatchTable::IntValue(NewInsnVarID)
1933 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnID)
1934 << MatchTable::Comment("OpIdx") << MatchTable::IntValue(OpIdx)
1935 << MatchTable::Comment("MIs[" + llvm::to_string(NewInsnVarID) + "]")
1936 << MatchTable::LineBreak;
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001937 return NewInsnVarID;
1938}
1939
1940unsigned RuleMatcher::getInsnVarID(const InstructionMatcher &InsnMatcher) const {
1941 const auto &I = InsnVariableIDs.find(&InsnMatcher);
1942 if (I != InsnVariableIDs.end())
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001943 return I->second;
1944 llvm_unreachable("Matched Insn was not captured in a local variable");
1945}
1946
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001947void RuleMatcher::defineOperand(StringRef SymbolicName, OperandMatcher &OM) {
1948 if (DefinedOperands.find(SymbolicName) == DefinedOperands.end()) {
1949 DefinedOperands[SymbolicName] = &OM;
1950 return;
1951 }
1952
1953 // If the operand is already defined, then we must ensure both references in
1954 // the matcher have the exact same node.
1955 OM.addPredicate<SameOperandMatcher>(OM.getSymbolicName());
1956}
1957
Daniel Sanders05540042017-08-08 10:44:31 +00001958const InstructionMatcher &
1959RuleMatcher::getInstructionMatcher(StringRef SymbolicName) const {
1960 for (const auto &I : InsnVariableIDs)
1961 if (I.first->getSymbolicName() == SymbolicName)
1962 return *I.first;
1963 llvm_unreachable(
1964 ("Failed to lookup instruction " + SymbolicName).str().c_str());
1965}
1966
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001967const OperandMatcher &
1968RuleMatcher::getOperandMatcher(StringRef Name) const {
1969 const auto &I = DefinedOperands.find(Name);
1970
1971 if (I == DefinedOperands.end())
1972 PrintFatalError(SrcLoc, "Operand " + Name + " was not declared in matcher");
1973
1974 return *I->second;
1975}
1976
Daniel Sanders9d662d22017-07-06 10:06:12 +00001977/// Emit MatchTable opcodes to check the shape of the match and capture
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001978/// instructions into local variables.
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001979void RuleMatcher::emitCaptureOpcodes(MatchTable &Table) {
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001980 assert(Matchers.size() == 1 && "Cannot handle multi-root matchers yet");
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001981 unsigned InsnVarID = implicitlyDefineInsnVar(*Matchers.front());
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001982 Matchers.front()->emitCaptureOpcodes(Table, *this, InsnVarID);
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001983}
1984
Daniel Sanders8e82af22017-07-27 11:03:45 +00001985void RuleMatcher::emit(MatchTable &Table) {
Daniel Sandersbdfebb82017-03-15 20:18:38 +00001986 if (Matchers.empty())
1987 llvm_unreachable("Unexpected empty matcher!");
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001988
Daniel Sandersbdfebb82017-03-15 20:18:38 +00001989 // The representation supports rules that require multiple roots such as:
1990 // %ptr(p0) = ...
1991 // %elt0(s32) = G_LOAD %ptr
1992 // %1(p0) = G_ADD %ptr, 4
1993 // %elt1(s32) = G_LOAD p0 %1
1994 // which could be usefully folded into:
1995 // %ptr(p0) = ...
1996 // %elt0(s32), %elt1(s32) = TGT_LOAD_PAIR %ptr
1997 // on some targets but we don't need to make use of that yet.
1998 assert(Matchers.size() == 1 && "Cannot handle multi-root matchers yet");
Daniel Sanderse7b0d662017-04-21 15:59:56 +00001999
Daniel Sanders8e82af22017-07-27 11:03:45 +00002000 unsigned LabelID = Table.allocateLabelID();
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002001 Table << MatchTable::Opcode("GIM_Try", +1)
Daniel Sanders8e82af22017-07-27 11:03:45 +00002002 << MatchTable::Comment("On fail goto") << MatchTable::JumpTarget(LabelID)
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002003 << MatchTable::LineBreak;
2004
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002005 if (!RequiredFeatures.empty()) {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002006 Table << MatchTable::Opcode("GIM_CheckFeatures")
2007 << MatchTable::NamedValue(getNameForFeatureBitset(RequiredFeatures))
2008 << MatchTable::LineBreak;
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002009 }
Daniel Sandersb96f40d2017-03-20 15:20:42 +00002010
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002011 emitCaptureOpcodes(Table);
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002012
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002013 Matchers.front()->emitPredicateOpcodes(Table, *this,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002014 getInsnVarID(*Matchers.front()));
2015
Daniel Sandersbee57392017-04-04 13:25:23 +00002016 // We must also check if it's safe to fold the matched instructions.
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002017 if (InsnVariableIDs.size() >= 2) {
Galina Kistanova1754fee2017-05-25 01:51:53 +00002018 // Invert the map to create stable ordering (by var names)
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002019 SmallVector<unsigned, 2> InsnIDs;
2020 for (const auto &Pair : InsnVariableIDs) {
Daniel Sandersbee57392017-04-04 13:25:23 +00002021 // Skip the root node since it isn't moving anywhere. Everything else is
2022 // sinking to meet it.
2023 if (Pair.first == Matchers.front().get())
2024 continue;
2025
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002026 InsnIDs.push_back(Pair.second);
Galina Kistanova1754fee2017-05-25 01:51:53 +00002027 }
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002028 std::sort(InsnIDs.begin(), InsnIDs.end());
Galina Kistanova1754fee2017-05-25 01:51:53 +00002029
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002030 for (const auto &InsnID : InsnIDs) {
Daniel Sandersbee57392017-04-04 13:25:23 +00002031 // Reject the difficult cases until we have a more accurate check.
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002032 Table << MatchTable::Opcode("GIM_CheckIsSafeToFold")
2033 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2034 << MatchTable::LineBreak;
Daniel Sandersbee57392017-04-04 13:25:23 +00002035
2036 // FIXME: Emit checks to determine it's _actually_ safe to fold and/or
2037 // account for unsafe cases.
2038 //
2039 // Example:
2040 // MI1--> %0 = ...
2041 // %1 = ... %0
2042 // MI0--> %2 = ... %0
2043 // It's not safe to erase MI1. We currently handle this by not
2044 // erasing %0 (even when it's dead).
2045 //
2046 // Example:
2047 // MI1--> %0 = load volatile @a
2048 // %1 = load volatile @a
2049 // MI0--> %2 = ... %0
2050 // It's not safe to sink %0's def past %1. We currently handle
2051 // this by rejecting all loads.
2052 //
2053 // Example:
2054 // MI1--> %0 = load @a
2055 // %1 = store @a
2056 // MI0--> %2 = ... %0
2057 // It's not safe to sink %0's def past %1. We currently handle
2058 // this by rejecting all loads.
2059 //
2060 // Example:
2061 // G_CONDBR %cond, @BB1
2062 // BB0:
2063 // MI1--> %0 = load @a
2064 // G_BR @BB1
2065 // BB1:
2066 // MI0--> %2 = ... %0
2067 // It's not always safe to sink %0 across control flow. In this
2068 // case it may introduce a memory fault. We currentl handle this
2069 // by rejecting all loads.
2070 }
2071 }
2072
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002073 for (const auto &MA : Actions)
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002074 MA->emitActionOpcodes(Table, *this, 0);
2075 Table << MatchTable::Opcode("GIR_Done", -1) << MatchTable::LineBreak
Daniel Sanders8e82af22017-07-27 11:03:45 +00002076 << MatchTable::Label(LabelID);
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002077}
Daniel Sanders43c882c2017-02-01 10:53:10 +00002078
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002079bool RuleMatcher::isHigherPriorityThan(const RuleMatcher &B) const {
2080 // Rules involving more match roots have higher priority.
2081 if (Matchers.size() > B.Matchers.size())
2082 return true;
2083 if (Matchers.size() < B.Matchers.size())
Daniel Sanders759ff412017-02-24 13:58:11 +00002084 return false;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002085
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002086 for (const auto &Matcher : zip(Matchers, B.Matchers)) {
2087 if (std::get<0>(Matcher)->isHigherPriorityThan(*std::get<1>(Matcher)))
2088 return true;
2089 if (std::get<1>(Matcher)->isHigherPriorityThan(*std::get<0>(Matcher)))
2090 return false;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002091 }
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002092
2093 return false;
Simon Pilgrima7d1da82017-03-15 22:50:47 +00002094}
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002095
Daniel Sanders2deea182017-04-22 15:11:04 +00002096unsigned RuleMatcher::countRendererFns() const {
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002097 return std::accumulate(
2098 Matchers.begin(), Matchers.end(), 0,
2099 [](unsigned A, const std::unique_ptr<InstructionMatcher> &Matcher) {
Daniel Sanders2deea182017-04-22 15:11:04 +00002100 return A + Matcher->countRendererFns();
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002101 });
2102}
2103
Daniel Sanders05540042017-08-08 10:44:31 +00002104bool OperandPredicateMatcher::isHigherPriorityThan(
2105 const OperandPredicateMatcher &B) const {
2106 // Generally speaking, an instruction is more important than an Int or a
2107 // LiteralInt because it can cover more nodes but theres an exception to
2108 // this. G_CONSTANT's are less important than either of those two because they
2109 // are more permissive.
Daniel Sandersedd07842017-08-17 09:26:14 +00002110
2111 const InstructionOperandMatcher *AOM =
2112 dyn_cast<InstructionOperandMatcher>(this);
2113 const InstructionOperandMatcher *BOM =
2114 dyn_cast<InstructionOperandMatcher>(&B);
2115 bool AIsConstantInsn = AOM && AOM->getInsnMatcher().isConstantInstruction();
2116 bool BIsConstantInsn = BOM && BOM->getInsnMatcher().isConstantInstruction();
2117
2118 if (AOM && BOM) {
2119 // The relative priorities between a G_CONSTANT and any other instruction
2120 // don't actually matter but this code is needed to ensure a strict weak
2121 // ordering. This is particularly important on Windows where the rules will
2122 // be incorrectly sorted without it.
2123 if (AIsConstantInsn != BIsConstantInsn)
2124 return AIsConstantInsn < BIsConstantInsn;
2125 return false;
Daniel Sanders05540042017-08-08 10:44:31 +00002126 }
Daniel Sandersedd07842017-08-17 09:26:14 +00002127
2128 if (AOM && AIsConstantInsn && (B.Kind == OPM_Int || B.Kind == OPM_LiteralInt))
2129 return false;
2130 if (BOM && BIsConstantInsn && (Kind == OPM_Int || Kind == OPM_LiteralInt))
2131 return true;
Daniel Sanders05540042017-08-08 10:44:31 +00002132
2133 return Kind < B.Kind;
Daniel Sanders75b84fc2017-08-08 13:21:26 +00002134}
Daniel Sanders05540042017-08-08 10:44:31 +00002135
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002136void SameOperandMatcher::emitPredicateOpcodes(MatchTable &Table,
2137 RuleMatcher &Rule,
2138 unsigned InsnVarID,
2139 unsigned OpIdx) const {
Daniel Sanders1e4569f2017-10-20 20:55:29 +00002140 const OperandMatcher &OtherOM = Rule.getOperandMatcher(MatchingName);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002141 unsigned OtherInsnVarID = Rule.getInsnVarID(OtherOM.getInstructionMatcher());
2142
2143 Table << MatchTable::Opcode("GIM_CheckIsSameOperand")
2144 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
2145 << MatchTable::Comment("OpIdx") << MatchTable::IntValue(OpIdx)
2146 << MatchTable::Comment("OtherMI")
2147 << MatchTable::IntValue(OtherInsnVarID)
2148 << MatchTable::Comment("OtherOpIdx")
2149 << MatchTable::IntValue(OtherOM.getOperandIndex())
2150 << MatchTable::LineBreak;
2151}
2152
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002153//===- GlobalISelEmitter class --------------------------------------------===//
2154
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002155class GlobalISelEmitter {
2156public:
2157 explicit GlobalISelEmitter(RecordKeeper &RK);
2158 void run(raw_ostream &OS);
2159
2160private:
2161 const RecordKeeper &RK;
2162 const CodeGenDAGPatterns CGP;
2163 const CodeGenTarget &Target;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002164 CodeGenRegBank CGRegs;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002165
Daniel Sanders39690bd2017-10-15 02:41:12 +00002166 /// Keep track of the equivalence between SDNodes and Instruction by mapping
2167 /// SDNodes to the GINodeEquiv mapping. We need to map to the GINodeEquiv to
2168 /// check for attributes on the relation such as CheckMMOIsNonAtomic.
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002169 /// This is defined using 'GINodeEquiv' in the target description.
Daniel Sanders39690bd2017-10-15 02:41:12 +00002170 DenseMap<Record *, Record *> NodeEquivs;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002171
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002172 /// Keep track of the equivalence between ComplexPattern's and
2173 /// GIComplexOperandMatcher. Map entries are specified by subclassing
2174 /// GIComplexPatternEquiv.
2175 DenseMap<const Record *, const Record *> ComplexPatternEquivs;
2176
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002177 // Map of predicates to their subtarget features.
Daniel Sanderse9fdba32017-04-29 17:30:09 +00002178 SubtargetFeatureInfoMap SubtargetFeatures;
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002179
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002180 void gatherNodeEquivs();
Daniel Sanders39690bd2017-10-15 02:41:12 +00002181 Record *findNodeEquiv(Record *N) const;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002182
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002183 Error importRulePredicates(RuleMatcher &M, ArrayRef<Predicate> Predicates);
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002184 Expected<InstructionMatcher &> createAndImportSelDAGMatcher(
2185 RuleMatcher &Rule, InstructionMatcher &InsnMatcher,
2186 const TreePatternNode *Src, unsigned &TempOpIdx) const;
2187 Error importComplexPatternOperandMatcher(OperandMatcher &OM, Record *R,
2188 unsigned &TempOpIdx) const;
2189 Error importChildMatcher(RuleMatcher &Rule, InstructionMatcher &InsnMatcher,
Daniel Sandersa71f4542017-10-16 00:56:30 +00002190 const TreePatternNode *SrcChild,
2191 bool OperandIsAPointer, unsigned OpIdx,
Daniel Sandersc270c502017-03-30 09:36:33 +00002192 unsigned &TempOpIdx) const;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002193 Expected<BuildMIAction &>
2194 createAndImportInstructionRenderer(RuleMatcher &M, const TreePatternNode *Dst,
2195 const InstructionMatcher &InsnMatcher);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002196 Error importExplicitUseRenderer(RuleMatcher &Rule,
2197 BuildMIAction &DstMIBuilder,
Daniel Sandersc270c502017-03-30 09:36:33 +00002198 TreePatternNode *DstChild,
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002199 const InstructionMatcher &InsnMatcher) const;
Diana Picus382602f2017-05-17 08:57:28 +00002200 Error importDefaultOperandRenderers(BuildMIAction &DstMIBuilder,
2201 DagInit *DefaultOps) const;
Daniel Sandersc270c502017-03-30 09:36:33 +00002202 Error
Daniel Sandersffc7d582017-03-29 15:37:18 +00002203 importImplicitDefRenderers(BuildMIAction &DstMIBuilder,
2204 const std::vector<Record *> &ImplicitDefs) const;
2205
Daniel Sanders11300ce2017-10-13 21:28:03 +00002206 void emitImmPredicates(raw_ostream &OS, StringRef TypeIdentifier,
2207 StringRef Type,
Daniel Sanders649c5852017-10-13 20:42:18 +00002208 std::function<bool(const Record *R)> Filter);
2209
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002210 /// Analyze pattern \p P, returning a matcher for it if possible.
2211 /// Otherwise, return an Error explaining why we don't support it.
2212 Expected<RuleMatcher> runOnPattern(const PatternToMatch &P);
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002213
2214 void declareSubtargetFeature(Record *Predicate);
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002215};
2216
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002217void GlobalISelEmitter::gatherNodeEquivs() {
2218 assert(NodeEquivs.empty());
2219 for (Record *Equiv : RK.getAllDerivedDefinitions("GINodeEquiv"))
Daniel Sanders39690bd2017-10-15 02:41:12 +00002220 NodeEquivs[Equiv->getValueAsDef("Node")] = Equiv;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002221
2222 assert(ComplexPatternEquivs.empty());
2223 for (Record *Equiv : RK.getAllDerivedDefinitions("GIComplexPatternEquiv")) {
2224 Record *SelDAGEquiv = Equiv->getValueAsDef("SelDAGEquivalent");
2225 if (!SelDAGEquiv)
2226 continue;
2227 ComplexPatternEquivs[SelDAGEquiv] = Equiv;
2228 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002229}
2230
Daniel Sanders39690bd2017-10-15 02:41:12 +00002231Record *GlobalISelEmitter::findNodeEquiv(Record *N) const {
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002232 return NodeEquivs.lookup(N);
2233}
2234
2235GlobalISelEmitter::GlobalISelEmitter(RecordKeeper &RK)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002236 : RK(RK), CGP(RK), Target(CGP.getTargetInfo()),
2237 CGRegs(RK, Target.getHwModes()) {}
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002238
2239//===- Emitter ------------------------------------------------------------===//
2240
Daniel Sandersc270c502017-03-30 09:36:33 +00002241Error
Daniel Sandersffc7d582017-03-29 15:37:18 +00002242GlobalISelEmitter::importRulePredicates(RuleMatcher &M,
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002243 ArrayRef<Predicate> Predicates) {
2244 for (const Predicate &P : Predicates) {
2245 if (!P.Def)
2246 continue;
2247 declareSubtargetFeature(P.Def);
2248 M.addRequiredFeature(P.Def);
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002249 }
2250
Daniel Sandersc270c502017-03-30 09:36:33 +00002251 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00002252}
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002253
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002254Expected<InstructionMatcher &> GlobalISelEmitter::createAndImportSelDAGMatcher(
2255 RuleMatcher &Rule, InstructionMatcher &InsnMatcher,
2256 const TreePatternNode *Src, unsigned &TempOpIdx) const {
Daniel Sanders39690bd2017-10-15 02:41:12 +00002257 Record *SrcGIEquivOrNull = nullptr;
Daniel Sanders85ffd362017-07-06 08:12:20 +00002258 const CodeGenInstruction *SrcGIOrNull = nullptr;
2259
Daniel Sandersffc7d582017-03-29 15:37:18 +00002260 // Start with the defined operands (i.e., the results of the root operator).
2261 if (Src->getExtTypes().size() > 1)
2262 return failedImport("Src pattern has multiple results");
2263
Daniel Sanders452c8ae2017-05-23 19:33:16 +00002264 if (Src->isLeaf()) {
2265 Init *SrcInit = Src->getLeafValue();
Daniel Sanders3334cc02017-05-23 20:02:48 +00002266 if (isa<IntInit>(SrcInit)) {
Daniel Sanders452c8ae2017-05-23 19:33:16 +00002267 InsnMatcher.addPredicate<InstructionOpcodeMatcher>(
2268 &Target.getInstruction(RK.getDef("G_CONSTANT")));
2269 } else
Daniel Sanders32291982017-06-28 13:50:04 +00002270 return failedImport(
2271 "Unable to deduce gMIR opcode to handle Src (which is a leaf)");
Daniel Sanders452c8ae2017-05-23 19:33:16 +00002272 } else {
Daniel Sanders39690bd2017-10-15 02:41:12 +00002273 SrcGIEquivOrNull = findNodeEquiv(Src->getOperator());
2274 if (!SrcGIEquivOrNull)
Daniel Sanders452c8ae2017-05-23 19:33:16 +00002275 return failedImport("Pattern operator lacks an equivalent Instruction" +
2276 explainOperator(Src->getOperator()));
Daniel Sanders39690bd2017-10-15 02:41:12 +00002277 SrcGIOrNull = &Target.getInstruction(SrcGIEquivOrNull->getValueAsDef("I"));
Daniel Sandersffc7d582017-03-29 15:37:18 +00002278
Daniel Sanders452c8ae2017-05-23 19:33:16 +00002279 // The operators look good: match the opcode
Daniel Sanders39690bd2017-10-15 02:41:12 +00002280 InsnMatcher.addPredicate<InstructionOpcodeMatcher>(SrcGIOrNull);
Daniel Sanders452c8ae2017-05-23 19:33:16 +00002281 }
Daniel Sandersffc7d582017-03-29 15:37:18 +00002282
2283 unsigned OpIdx = 0;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002284 for (const TypeSetByHwMode &VTy : Src->getExtTypes()) {
Daniel Sandersffc7d582017-03-29 15:37:18 +00002285 // Results don't have a name unless they are the root node. The caller will
2286 // set the name if appropriate.
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002287 OperandMatcher &OM = InsnMatcher.addOperand(OpIdx++, "", TempOpIdx);
Daniel Sandersa71f4542017-10-16 00:56:30 +00002288 if (auto Error = OM.addTypeCheckPredicate(VTy, false /* OperandIsAPointer */))
2289 return failedImport(toString(std::move(Error)) +
2290 " for result of Src pattern operator");
Daniel Sandersffc7d582017-03-29 15:37:18 +00002291 }
2292
Daniel Sanders2c269f62017-08-24 09:11:20 +00002293 for (const auto &Predicate : Src->getPredicateFns()) {
2294 if (Predicate.isAlwaysTrue())
2295 continue;
2296
2297 if (Predicate.isImmediatePattern()) {
2298 InsnMatcher.addPredicate<InstructionImmPredicateMatcher>(Predicate);
2299 continue;
2300 }
2301
Daniel Sandersa71f4542017-10-16 00:56:30 +00002302 // No check required. A G_LOAD is an unindexed load.
2303 if (Predicate.isLoad() && Predicate.isUnindexed())
2304 continue;
2305
2306 // No check required. G_LOAD by itself is a non-extending load.
2307 if (Predicate.isNonExtLoad())
2308 continue;
2309
2310 if (Predicate.isLoad() && Predicate.getMemoryVT() != nullptr) {
2311 Optional<LLTCodeGen> MemTyOrNone =
2312 MVTToLLT(getValueType(Predicate.getMemoryVT()));
2313
2314 if (!MemTyOrNone)
2315 return failedImport("MemVT could not be converted to LLT");
2316
2317 InsnMatcher.getOperand(0).addPredicate<LLTOperandMatcher>(MemTyOrNone.getValue());
2318 continue;
2319 }
2320
Daniel Sandersd66e0902017-10-23 18:19:24 +00002321 // No check required. A G_STORE is an unindexed store.
2322 if (Predicate.isStore() && Predicate.isUnindexed())
2323 continue;
2324
2325 // No check required. G_STORE by itself is a non-extending store.
2326 if (Predicate.isNonTruncStore())
2327 continue;
2328
2329 if (Predicate.isStore() && Predicate.getMemoryVT() != nullptr) {
2330 Optional<LLTCodeGen> MemTyOrNone =
2331 MVTToLLT(getValueType(Predicate.getMemoryVT()));
2332
2333 if (!MemTyOrNone)
2334 return failedImport("MemVT could not be converted to LLT");
2335
2336 InsnMatcher.getOperand(0).addPredicate<LLTOperandMatcher>(MemTyOrNone.getValue());
2337 continue;
2338 }
2339
Daniel Sanders2c269f62017-08-24 09:11:20 +00002340 return failedImport("Src pattern child has predicate (" +
2341 explainPredicates(Src) + ")");
2342 }
Daniel Sanders39690bd2017-10-15 02:41:12 +00002343 if (SrcGIEquivOrNull && SrcGIEquivOrNull->getValueAsBit("CheckMMOIsNonAtomic"))
2344 InsnMatcher.addPredicate<NonAtomicMMOPredicateMatcher>();
Daniel Sanders2c269f62017-08-24 09:11:20 +00002345
Daniel Sanders452c8ae2017-05-23 19:33:16 +00002346 if (Src->isLeaf()) {
2347 Init *SrcInit = Src->getLeafValue();
2348 if (IntInit *SrcIntInit = dyn_cast<IntInit>(SrcInit)) {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002349 OperandMatcher &OM =
2350 InsnMatcher.addOperand(OpIdx++, Src->getName(), TempOpIdx);
Daniel Sanders452c8ae2017-05-23 19:33:16 +00002351 OM.addPredicate<LiteralIntOperandMatcher>(SrcIntInit->getValue());
2352 } else
Daniel Sanders32291982017-06-28 13:50:04 +00002353 return failedImport(
2354 "Unable to deduce gMIR opcode to handle Src (which is a leaf)");
Daniel Sanders452c8ae2017-05-23 19:33:16 +00002355 } else {
Daniel Sanders85ffd362017-07-06 08:12:20 +00002356 assert(SrcGIOrNull &&
2357 "Expected to have already found an equivalent Instruction");
Daniel Sanders11300ce2017-10-13 21:28:03 +00002358 if (SrcGIOrNull->TheDef->getName() == "G_CONSTANT" ||
2359 SrcGIOrNull->TheDef->getName() == "G_FCONSTANT") {
2360 // imm/fpimm still have operands but we don't need to do anything with it
Daniel Sanders05540042017-08-08 10:44:31 +00002361 // here since we don't support ImmLeaf predicates yet. However, we still
2362 // need to note the hidden operand to get GIM_CheckNumOperands correct.
2363 InsnMatcher.addOperand(OpIdx++, "", TempOpIdx);
2364 return InsnMatcher;
2365 }
2366
Daniel Sanders452c8ae2017-05-23 19:33:16 +00002367 // Match the used operands (i.e. the children of the operator).
2368 for (unsigned i = 0, e = Src->getNumChildren(); i != e; ++i) {
Daniel Sanders85ffd362017-07-06 08:12:20 +00002369 TreePatternNode *SrcChild = Src->getChild(i);
2370
Daniel Sandersa71f4542017-10-16 00:56:30 +00002371 // SelectionDAG allows pointers to be represented with iN since it doesn't
2372 // distinguish between pointers and integers but they are different types in GlobalISel.
2373 // Coerce integers to pointers to address space 0 if the context indicates a pointer.
2374 // TODO: Find a better way to do this, SDTCisPtrTy?
2375 bool OperandIsAPointer =
Daniel Sandersd66e0902017-10-23 18:19:24 +00002376 (SrcGIOrNull->TheDef->getName() == "G_LOAD" && i == 0) ||
2377 (SrcGIOrNull->TheDef->getName() == "G_STORE" && i == 1);
Daniel Sandersa71f4542017-10-16 00:56:30 +00002378
Daniel Sanders28887fe2017-09-19 12:56:36 +00002379 // For G_INTRINSIC/G_INTRINSIC_W_SIDE_EFFECTS, the operand immediately
2380 // following the defs is an intrinsic ID.
2381 if ((SrcGIOrNull->TheDef->getName() == "G_INTRINSIC" ||
2382 SrcGIOrNull->TheDef->getName() == "G_INTRINSIC_W_SIDE_EFFECTS") &&
2383 i == 0) {
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00002384 if (const CodeGenIntrinsic *II = Src->getIntrinsicInfo(CGP)) {
Daniel Sanders85ffd362017-07-06 08:12:20 +00002385 OperandMatcher &OM =
2386 InsnMatcher.addOperand(OpIdx++, SrcChild->getName(), TempOpIdx);
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00002387 OM.addPredicate<IntrinsicIDOperandMatcher>(II);
Daniel Sanders85ffd362017-07-06 08:12:20 +00002388 continue;
2389 }
2390
2391 return failedImport("Expected IntInit containing instrinsic ID)");
2392 }
2393
Daniel Sandersa71f4542017-10-16 00:56:30 +00002394 if (auto Error =
2395 importChildMatcher(Rule, InsnMatcher, SrcChild, OperandIsAPointer,
2396 OpIdx++, TempOpIdx))
Daniel Sanders452c8ae2017-05-23 19:33:16 +00002397 return std::move(Error);
2398 }
Daniel Sandersffc7d582017-03-29 15:37:18 +00002399 }
2400
2401 return InsnMatcher;
2402}
2403
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002404Error GlobalISelEmitter::importComplexPatternOperandMatcher(
2405 OperandMatcher &OM, Record *R, unsigned &TempOpIdx) const {
2406 const auto &ComplexPattern = ComplexPatternEquivs.find(R);
2407 if (ComplexPattern == ComplexPatternEquivs.end())
2408 return failedImport("SelectionDAG ComplexPattern (" + R->getName() +
2409 ") not mapped to GlobalISel");
2410
2411 OM.addPredicate<ComplexPatternOperandMatcher>(OM, *ComplexPattern->second);
2412 TempOpIdx++;
2413 return Error::success();
2414}
2415
2416Error GlobalISelEmitter::importChildMatcher(RuleMatcher &Rule,
2417 InstructionMatcher &InsnMatcher,
Daniel Sanders452c8ae2017-05-23 19:33:16 +00002418 const TreePatternNode *SrcChild,
Daniel Sandersa71f4542017-10-16 00:56:30 +00002419 bool OperandIsAPointer,
Daniel Sandersc270c502017-03-30 09:36:33 +00002420 unsigned OpIdx,
2421 unsigned &TempOpIdx) const {
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002422 OperandMatcher &OM =
2423 InsnMatcher.addOperand(OpIdx, SrcChild->getName(), TempOpIdx);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002424 if (OM.isSameAsAnotherOperand())
2425 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00002426
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002427 ArrayRef<TypeSetByHwMode> ChildTypes = SrcChild->getExtTypes();
Daniel Sandersffc7d582017-03-29 15:37:18 +00002428 if (ChildTypes.size() != 1)
2429 return failedImport("Src pattern child has multiple results");
2430
2431 // Check MBB's before the type check since they are not a known type.
2432 if (!SrcChild->isLeaf()) {
2433 if (SrcChild->getOperator()->isSubClassOf("SDNode")) {
2434 auto &ChildSDNI = CGP.getSDNodeInfo(SrcChild->getOperator());
2435 if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") {
2436 OM.addPredicate<MBBOperandMatcher>();
Daniel Sandersc270c502017-03-30 09:36:33 +00002437 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00002438 }
2439 }
Daniel Sandersffc7d582017-03-29 15:37:18 +00002440 }
2441
Daniel Sandersa71f4542017-10-16 00:56:30 +00002442 if (auto Error =
2443 OM.addTypeCheckPredicate(ChildTypes.front(), OperandIsAPointer))
2444 return failedImport(toString(std::move(Error)) + " for Src operand (" +
2445 to_string(*SrcChild) + ")");
Daniel Sandersffc7d582017-03-29 15:37:18 +00002446
Daniel Sandersbee57392017-04-04 13:25:23 +00002447 // Check for nested instructions.
2448 if (!SrcChild->isLeaf()) {
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002449 if (SrcChild->getOperator()->isSubClassOf("ComplexPattern")) {
2450 // When a ComplexPattern is used as an operator, it should do the same
2451 // thing as when used as a leaf. However, the children of the operator
2452 // name the sub-operands that make up the complex operand and we must
2453 // prepare to reference them in the renderer too.
2454 unsigned RendererID = TempOpIdx;
2455 if (auto Error = importComplexPatternOperandMatcher(
2456 OM, SrcChild->getOperator(), TempOpIdx))
2457 return Error;
2458
2459 for (unsigned i = 0, e = SrcChild->getNumChildren(); i != e; ++i) {
2460 auto *SubOperand = SrcChild->getChild(i);
2461 if (!SubOperand->getName().empty())
2462 Rule.defineComplexSubOperand(SubOperand->getName(),
2463 SrcChild->getOperator(), RendererID, i);
2464 }
2465
2466 return Error::success();
2467 }
2468
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002469 auto MaybeInsnOperand = OM.addPredicate<InstructionOperandMatcher>(
2470 InsnMatcher.getRuleMatcher(), SrcChild->getName());
2471 if (!MaybeInsnOperand.hasValue()) {
2472 // This isn't strictly true. If the user were to provide exactly the same
2473 // matchers as the original operand then we could allow it. However, it's
2474 // simpler to not permit the redundant specification.
2475 return failedImport("Nested instruction cannot be the same as another operand");
2476 }
2477
Daniel Sandersbee57392017-04-04 13:25:23 +00002478 // Map the node to a gMIR instruction.
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002479 InstructionOperandMatcher &InsnOperand = **MaybeInsnOperand;
Daniel Sanders57938df2017-07-11 10:40:18 +00002480 auto InsnMatcherOrError = createAndImportSelDAGMatcher(
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002481 Rule, InsnOperand.getInsnMatcher(), SrcChild, TempOpIdx);
Daniel Sandersbee57392017-04-04 13:25:23 +00002482 if (auto Error = InsnMatcherOrError.takeError())
2483 return Error;
2484
2485 return Error::success();
2486 }
2487
Daniel Sandersffc7d582017-03-29 15:37:18 +00002488 // Check for constant immediates.
2489 if (auto *ChildInt = dyn_cast<IntInit>(SrcChild->getLeafValue())) {
Daniel Sanders452c8ae2017-05-23 19:33:16 +00002490 OM.addPredicate<ConstantIntOperandMatcher>(ChildInt->getValue());
Daniel Sandersc270c502017-03-30 09:36:33 +00002491 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00002492 }
2493
2494 // Check for def's like register classes or ComplexPattern's.
2495 if (auto *ChildDefInit = dyn_cast<DefInit>(SrcChild->getLeafValue())) {
2496 auto *ChildRec = ChildDefInit->getDef();
2497
2498 // Check for register classes.
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002499 if (ChildRec->isSubClassOf("RegisterClass") ||
2500 ChildRec->isSubClassOf("RegisterOperand")) {
Daniel Sandersffc7d582017-03-29 15:37:18 +00002501 OM.addPredicate<RegisterBankOperandMatcher>(
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002502 Target.getRegisterClass(getInitValueAsRegClass(ChildDefInit)));
Daniel Sanders658541f2017-04-22 15:53:21 +00002503 return Error::success();
2504 }
2505
Daniel Sanders4d4e7652017-10-09 18:14:53 +00002506 // Check for ValueType.
2507 if (ChildRec->isSubClassOf("ValueType")) {
2508 // We already added a type check as standard practice so this doesn't need
2509 // to do anything.
2510 return Error::success();
2511 }
2512
Daniel Sandersffc7d582017-03-29 15:37:18 +00002513 // Check for ComplexPattern's.
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002514 if (ChildRec->isSubClassOf("ComplexPattern"))
2515 return importComplexPatternOperandMatcher(OM, ChildRec, TempOpIdx);
Daniel Sandersffc7d582017-03-29 15:37:18 +00002516
Daniel Sandersd0656a32017-04-13 09:45:37 +00002517 if (ChildRec->isSubClassOf("ImmLeaf")) {
2518 return failedImport(
2519 "Src pattern child def is an unsupported tablegen class (ImmLeaf)");
2520 }
2521
Daniel Sandersffc7d582017-03-29 15:37:18 +00002522 return failedImport(
2523 "Src pattern child def is an unsupported tablegen class");
2524 }
2525
2526 return failedImport("Src pattern child is an unsupported kind");
2527}
2528
Daniel Sandersc270c502017-03-30 09:36:33 +00002529Error GlobalISelEmitter::importExplicitUseRenderer(
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002530 RuleMatcher &Rule, BuildMIAction &DstMIBuilder, TreePatternNode *DstChild,
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002531 const InstructionMatcher &InsnMatcher) const {
Daniel Sanders2c269f62017-08-24 09:11:20 +00002532 if (DstChild->getTransformFn() != nullptr) {
2533 return failedImport("Dst pattern child has transform fn " +
2534 DstChild->getTransformFn()->getName());
2535 }
2536
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002537 const auto &SubOperand = Rule.getComplexSubOperand(DstChild->getName());
2538 if (SubOperand.hasValue()) {
2539 DstMIBuilder.addRenderer<RenderComplexPatternOperand>(
2540 0, *std::get<0>(*SubOperand), DstChild->getName(),
2541 std::get<1>(*SubOperand), std::get<2>(*SubOperand));
2542 return Error::success();
2543 }
2544
Daniel Sandersffc7d582017-03-29 15:37:18 +00002545 if (!DstChild->isLeaf()) {
Daniel Sanders05540042017-08-08 10:44:31 +00002546 // We accept 'bb' here. It's an operator because BasicBlockSDNode isn't
2547 // inline, but in MI it's just another operand.
Daniel Sandersffc7d582017-03-29 15:37:18 +00002548 if (DstChild->getOperator()->isSubClassOf("SDNode")) {
2549 auto &ChildSDNI = CGP.getSDNodeInfo(DstChild->getOperator());
2550 if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") {
Daniel Sandersbd83ad42017-10-24 01:48:34 +00002551 DstMIBuilder.addRenderer<CopyRenderer>(0, DstChild->getName());
Daniel Sandersc270c502017-03-30 09:36:33 +00002552 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00002553 }
2554 }
Daniel Sanders05540042017-08-08 10:44:31 +00002555
2556 // Similarly, imm is an operator in TreePatternNode's view but must be
2557 // rendered as operands.
2558 // FIXME: The target should be able to choose sign-extended when appropriate
2559 // (e.g. on Mips).
2560 if (DstChild->getOperator()->getName() == "imm") {
2561 DstMIBuilder.addRenderer<CopyConstantAsImmRenderer>(0,
2562 DstChild->getName());
2563 return Error::success();
Daniel Sanders11300ce2017-10-13 21:28:03 +00002564 } else if (DstChild->getOperator()->getName() == "fpimm") {
2565 DstMIBuilder.addRenderer<CopyFConstantAsFPImmRenderer>(
2566 0, DstChild->getName());
2567 return Error::success();
Daniel Sanders05540042017-08-08 10:44:31 +00002568 }
2569
Daniel Sanders2c269f62017-08-24 09:11:20 +00002570 return failedImport("Dst pattern child isn't a leaf node or an MBB" + llvm::to_string(*DstChild));
Daniel Sandersffc7d582017-03-29 15:37:18 +00002571 }
2572
2573 // Otherwise, we're looking for a bog-standard RegisterClass operand.
Daniel Sandersffc7d582017-03-29 15:37:18 +00002574 if (auto *ChildDefInit = dyn_cast<DefInit>(DstChild->getLeafValue())) {
2575 auto *ChildRec = ChildDefInit->getDef();
2576
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002577 ArrayRef<TypeSetByHwMode> ChildTypes = DstChild->getExtTypes();
Daniel Sandersffc7d582017-03-29 15:37:18 +00002578 if (ChildTypes.size() != 1)
2579 return failedImport("Dst pattern child has multiple results");
2580
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002581 Optional<LLTCodeGen> OpTyOrNone = None;
2582 if (ChildTypes.front().isMachineValueType())
2583 OpTyOrNone = MVTToLLT(ChildTypes.front().getMachineValueType().SimpleTy);
Daniel Sandersffc7d582017-03-29 15:37:18 +00002584 if (!OpTyOrNone)
2585 return failedImport("Dst operand has an unsupported type");
2586
2587 if (ChildRec->isSubClassOf("Register")) {
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002588 DstMIBuilder.addRenderer<AddRegisterRenderer>(0, ChildRec);
Daniel Sandersc270c502017-03-30 09:36:33 +00002589 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00002590 }
2591
Daniel Sanders658541f2017-04-22 15:53:21 +00002592 if (ChildRec->isSubClassOf("RegisterClass") ||
Daniel Sanders4d4e7652017-10-09 18:14:53 +00002593 ChildRec->isSubClassOf("RegisterOperand") ||
2594 ChildRec->isSubClassOf("ValueType")) {
Daniel Sandersd66e0902017-10-23 18:19:24 +00002595 if (ChildRec->isSubClassOf("RegisterOperand") &&
2596 !ChildRec->isValueUnset("GIZeroRegister")) {
2597 DstMIBuilder.addRenderer<CopyOrAddZeroRegRenderer>(
Daniel Sandersbd83ad42017-10-24 01:48:34 +00002598 0, DstChild->getName(), ChildRec->getValueAsDef("GIZeroRegister"));
Daniel Sandersd66e0902017-10-23 18:19:24 +00002599 return Error::success();
2600 }
2601
Daniel Sandersbd83ad42017-10-24 01:48:34 +00002602 DstMIBuilder.addRenderer<CopyRenderer>(0, DstChild->getName());
Daniel Sandersc270c502017-03-30 09:36:33 +00002603 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00002604 }
2605
2606 if (ChildRec->isSubClassOf("ComplexPattern")) {
2607 const auto &ComplexPattern = ComplexPatternEquivs.find(ChildRec);
2608 if (ComplexPattern == ComplexPatternEquivs.end())
2609 return failedImport(
2610 "SelectionDAG ComplexPattern not mapped to GlobalISel");
2611
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002612 const OperandMatcher &OM = Rule.getOperandMatcher(DstChild->getName());
Daniel Sandersffc7d582017-03-29 15:37:18 +00002613 DstMIBuilder.addRenderer<RenderComplexPatternOperand>(
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002614 0, *ComplexPattern->second, DstChild->getName(),
Daniel Sanders2deea182017-04-22 15:11:04 +00002615 OM.getAllocatedTemporariesBaseID());
Daniel Sandersc270c502017-03-30 09:36:33 +00002616 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00002617 }
2618
Daniel Sandersd0656a32017-04-13 09:45:37 +00002619 if (ChildRec->isSubClassOf("SDNodeXForm"))
2620 return failedImport("Dst pattern child def is an unsupported tablegen "
2621 "class (SDNodeXForm)");
2622
Daniel Sandersffc7d582017-03-29 15:37:18 +00002623 return failedImport(
2624 "Dst pattern child def is an unsupported tablegen class");
2625 }
2626
2627 return failedImport("Dst pattern child is an unsupported kind");
2628}
2629
Daniel Sandersc270c502017-03-30 09:36:33 +00002630Expected<BuildMIAction &> GlobalISelEmitter::createAndImportInstructionRenderer(
Daniel Sandersffc7d582017-03-29 15:37:18 +00002631 RuleMatcher &M, const TreePatternNode *Dst,
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002632 const InstructionMatcher &InsnMatcher) {
Daniel Sandersffc7d582017-03-29 15:37:18 +00002633 Record *DstOp = Dst->getOperator();
Daniel Sandersd0656a32017-04-13 09:45:37 +00002634 if (!DstOp->isSubClassOf("Instruction")) {
2635 if (DstOp->isSubClassOf("ValueType"))
2636 return failedImport(
2637 "Pattern operator isn't an instruction (it's a ValueType)");
Daniel Sandersffc7d582017-03-29 15:37:18 +00002638 return failedImport("Pattern operator isn't an instruction");
Daniel Sandersd0656a32017-04-13 09:45:37 +00002639 }
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002640 CodeGenInstruction *DstI = &Target.getInstruction(DstOp);
Daniel Sandersffc7d582017-03-29 15:37:18 +00002641
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002642 unsigned DstINumUses = DstI->Operands.size() - DstI->Operands.NumDefs;
2643 unsigned ExpectedDstINumUses = Dst->getNumChildren();
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002644 bool IsExtractSubReg = false;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002645
2646 // COPY_TO_REGCLASS is just a copy with a ConstrainOperandToRegClassAction
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002647 // attached. Similarly for EXTRACT_SUBREG except that's a subregister copy.
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002648 if (DstI->TheDef->getName() == "COPY_TO_REGCLASS") {
2649 DstI = &Target.getInstruction(RK.getDef("COPY"));
2650 DstINumUses--; // Ignore the class constraint.
2651 ExpectedDstINumUses--;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002652 } else if (DstI->TheDef->getName() == "EXTRACT_SUBREG") {
2653 DstI = &Target.getInstruction(RK.getDef("COPY"));
2654 IsExtractSubReg = true;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002655 }
2656
Daniel Sanders64f745c2017-10-24 17:08:43 +00002657 auto &DstMIBuilder = M.addAction<BuildMIAction>(0, DstI, &InsnMatcher);
Daniel Sandersffc7d582017-03-29 15:37:18 +00002658
2659 // Render the explicit defs.
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002660 for (unsigned I = 0; I < DstI->Operands.NumDefs; ++I) {
2661 const CGIOperandList::OperandInfo &DstIOperand = DstI->Operands[I];
Daniel Sandersbd83ad42017-10-24 01:48:34 +00002662 DstMIBuilder.addRenderer<CopyRenderer>(0, DstIOperand.Name);
Daniel Sandersffc7d582017-03-29 15:37:18 +00002663 }
2664
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002665 // EXTRACT_SUBREG needs to use a subregister COPY.
2666 if (IsExtractSubReg) {
2667 if (!Dst->getChild(0)->isLeaf())
2668 return failedImport("EXTRACT_SUBREG child #1 is not a leaf");
2669
Daniel Sanders32291982017-06-28 13:50:04 +00002670 if (DefInit *SubRegInit =
2671 dyn_cast<DefInit>(Dst->getChild(1)->getLeafValue())) {
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002672 CodeGenRegisterClass *RC = CGRegs.getRegClass(
2673 getInitValueAsRegClass(Dst->getChild(0)->getLeafValue()));
2674 CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef());
2675
2676 const auto &SrcRCDstRCPair =
2677 RC->getMatchingSubClassWithSubRegs(CGRegs, SubIdx);
2678 if (SrcRCDstRCPair.hasValue()) {
2679 assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
2680 if (SrcRCDstRCPair->first != RC)
2681 return failedImport("EXTRACT_SUBREG requires an additional COPY");
2682 }
2683
2684 DstMIBuilder.addRenderer<CopySubRegRenderer>(
Daniel Sandersbd83ad42017-10-24 01:48:34 +00002685 0, Dst->getChild(0)->getName(), SubIdx);
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002686 return DstMIBuilder;
2687 }
2688
2689 return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
2690 }
2691
Daniel Sandersffc7d582017-03-29 15:37:18 +00002692 // Render the explicit uses.
Daniel Sanders0ed28822017-04-12 08:23:08 +00002693 unsigned Child = 0;
Diana Picus382602f2017-05-17 08:57:28 +00002694 unsigned NumDefaultOps = 0;
Daniel Sanders0ed28822017-04-12 08:23:08 +00002695 for (unsigned I = 0; I != DstINumUses; ++I) {
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002696 const CGIOperandList::OperandInfo &DstIOperand =
2697 DstI->Operands[DstI->Operands.NumDefs + I];
Daniel Sanders0ed28822017-04-12 08:23:08 +00002698
Diana Picus382602f2017-05-17 08:57:28 +00002699 // If the operand has default values, introduce them now.
2700 // FIXME: Until we have a decent test case that dictates we should do
2701 // otherwise, we're going to assume that operands with default values cannot
2702 // be specified in the patterns. Therefore, adding them will not cause us to
2703 // end up with too many rendered operands.
2704 if (DstIOperand.Rec->isSubClassOf("OperandWithDefaultOps")) {
Daniel Sanders0ed28822017-04-12 08:23:08 +00002705 DagInit *DefaultOps = DstIOperand.Rec->getValueAsDag("DefaultOps");
Diana Picus382602f2017-05-17 08:57:28 +00002706 if (auto Error = importDefaultOperandRenderers(DstMIBuilder, DefaultOps))
2707 return std::move(Error);
2708 ++NumDefaultOps;
Daniel Sanders0ed28822017-04-12 08:23:08 +00002709 continue;
2710 }
2711
2712 if (auto Error = importExplicitUseRenderer(
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002713 M, DstMIBuilder, Dst->getChild(Child), InsnMatcher))
Daniel Sandersffc7d582017-03-29 15:37:18 +00002714 return std::move(Error);
Daniel Sanders0ed28822017-04-12 08:23:08 +00002715 ++Child;
Daniel Sandersffc7d582017-03-29 15:37:18 +00002716 }
2717
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002718 if (NumDefaultOps + ExpectedDstINumUses != DstINumUses)
Diana Picuseb2057c2017-05-17 09:25:08 +00002719 return failedImport("Expected " + llvm::to_string(DstINumUses) +
Diana Picus382602f2017-05-17 08:57:28 +00002720 " used operands but found " +
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002721 llvm::to_string(ExpectedDstINumUses) +
Diana Picuseb2057c2017-05-17 09:25:08 +00002722 " explicit ones and " + llvm::to_string(NumDefaultOps) +
Diana Picus382602f2017-05-17 08:57:28 +00002723 " default ones");
2724
Daniel Sandersffc7d582017-03-29 15:37:18 +00002725 return DstMIBuilder;
2726}
2727
Diana Picus382602f2017-05-17 08:57:28 +00002728Error GlobalISelEmitter::importDefaultOperandRenderers(
2729 BuildMIAction &DstMIBuilder, DagInit *DefaultOps) const {
Craig Topper481ff702017-05-29 21:49:34 +00002730 for (const auto *DefaultOp : DefaultOps->getArgs()) {
Diana Picus382602f2017-05-17 08:57:28 +00002731 // Look through ValueType operators.
2732 if (const DagInit *DefaultDagOp = dyn_cast<DagInit>(DefaultOp)) {
2733 if (const DefInit *DefaultDagOperator =
2734 dyn_cast<DefInit>(DefaultDagOp->getOperator())) {
2735 if (DefaultDagOperator->getDef()->isSubClassOf("ValueType"))
2736 DefaultOp = DefaultDagOp->getArg(0);
2737 }
2738 }
2739
2740 if (const DefInit *DefaultDefOp = dyn_cast<DefInit>(DefaultOp)) {
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002741 DstMIBuilder.addRenderer<AddRegisterRenderer>(0, DefaultDefOp->getDef());
Diana Picus382602f2017-05-17 08:57:28 +00002742 continue;
2743 }
2744
2745 if (const IntInit *DefaultIntOp = dyn_cast<IntInit>(DefaultOp)) {
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002746 DstMIBuilder.addRenderer<ImmRenderer>(0, DefaultIntOp->getValue());
Diana Picus382602f2017-05-17 08:57:28 +00002747 continue;
2748 }
2749
2750 return failedImport("Could not add default op");
2751 }
2752
2753 return Error::success();
2754}
2755
Daniel Sandersc270c502017-03-30 09:36:33 +00002756Error GlobalISelEmitter::importImplicitDefRenderers(
Daniel Sandersffc7d582017-03-29 15:37:18 +00002757 BuildMIAction &DstMIBuilder,
2758 const std::vector<Record *> &ImplicitDefs) const {
2759 if (!ImplicitDefs.empty())
2760 return failedImport("Pattern defines a physical register");
Daniel Sandersc270c502017-03-30 09:36:33 +00002761 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00002762}
2763
2764Expected<RuleMatcher> GlobalISelEmitter::runOnPattern(const PatternToMatch &P) {
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002765 // Keep track of the matchers and actions to emit.
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002766 RuleMatcher M(P.getSrcRecord()->getLoc());
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +00002767 M.addAction<DebugCommentAction>(P);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002768
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002769 if (auto Error = importRulePredicates(M, P.getPredicates()))
Daniel Sandersffc7d582017-03-29 15:37:18 +00002770 return std::move(Error);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002771
2772 // Next, analyze the pattern operators.
2773 TreePatternNode *Src = P.getSrcPattern();
2774 TreePatternNode *Dst = P.getDstPattern();
2775
2776 // If the root of either pattern isn't a simple operator, ignore it.
Daniel Sandersd0656a32017-04-13 09:45:37 +00002777 if (auto Err = isTrivialOperatorNode(Dst))
2778 return failedImport("Dst pattern root isn't a trivial operator (" +
2779 toString(std::move(Err)) + ")");
2780 if (auto Err = isTrivialOperatorNode(Src))
2781 return failedImport("Src pattern root isn't a trivial operator (" +
2782 toString(std::move(Err)) + ")");
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002783
Daniel Sandersedd07842017-08-17 09:26:14 +00002784 InstructionMatcher &InsnMatcherTemp = M.addInstructionMatcher(Src->getName());
2785 unsigned TempOpIdx = 0;
2786 auto InsnMatcherOrError =
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002787 createAndImportSelDAGMatcher(M, InsnMatcherTemp, Src, TempOpIdx);
Daniel Sandersedd07842017-08-17 09:26:14 +00002788 if (auto Error = InsnMatcherOrError.takeError())
2789 return std::move(Error);
2790 InstructionMatcher &InsnMatcher = InsnMatcherOrError.get();
2791
2792 if (Dst->isLeaf()) {
2793 Record *RCDef = getInitValueAsRegClass(Dst->getLeafValue());
2794
2795 const CodeGenRegisterClass &RC = Target.getRegisterClass(RCDef);
2796 if (RCDef) {
2797 // We need to replace the def and all its uses with the specified
2798 // operand. However, we must also insert COPY's wherever needed.
2799 // For now, emit a copy and let the register allocator clean up.
2800 auto &DstI = Target.getInstruction(RK.getDef("COPY"));
2801 const auto &DstIOperand = DstI.Operands[0];
2802
2803 OperandMatcher &OM0 = InsnMatcher.getOperand(0);
2804 OM0.setSymbolicName(DstIOperand.Name);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002805 M.defineOperand(OM0.getSymbolicName(), OM0);
Daniel Sandersedd07842017-08-17 09:26:14 +00002806 OM0.addPredicate<RegisterBankOperandMatcher>(RC);
2807
Daniel Sanders64f745c2017-10-24 17:08:43 +00002808 auto &DstMIBuilder = M.addAction<BuildMIAction>(0, &DstI, &InsnMatcher);
Daniel Sandersbd83ad42017-10-24 01:48:34 +00002809 DstMIBuilder.addRenderer<CopyRenderer>(0, DstIOperand.Name);
2810 DstMIBuilder.addRenderer<CopyRenderer>(0, Dst->getName());
Daniel Sandersedd07842017-08-17 09:26:14 +00002811 M.addAction<ConstrainOperandToRegClassAction>(0, 0, RC);
2812
2813 // We're done with this pattern! It's eligible for GISel emission; return
2814 // it.
2815 ++NumPatternImported;
2816 return std::move(M);
2817 }
2818
Daniel Sanders452c8ae2017-05-23 19:33:16 +00002819 return failedImport("Dst pattern root isn't a known leaf");
Daniel Sandersedd07842017-08-17 09:26:14 +00002820 }
Daniel Sanders452c8ae2017-05-23 19:33:16 +00002821
Daniel Sandersbee57392017-04-04 13:25:23 +00002822 // Start with the defined operands (i.e., the results of the root operator).
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002823 Record *DstOp = Dst->getOperator();
2824 if (!DstOp->isSubClassOf("Instruction"))
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002825 return failedImport("Pattern operator isn't an instruction");
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002826
2827 auto &DstI = Target.getInstruction(DstOp);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002828 if (DstI.Operands.NumDefs != Src->getExtTypes().size())
Daniel Sandersd0656a32017-04-13 09:45:37 +00002829 return failedImport("Src pattern results and dst MI defs are different (" +
2830 to_string(Src->getExtTypes().size()) + " def(s) vs " +
2831 to_string(DstI.Operands.NumDefs) + " def(s))");
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002832
Daniel Sandersffc7d582017-03-29 15:37:18 +00002833 // The root of the match also has constraints on the register bank so that it
2834 // matches the result instruction.
2835 unsigned OpIdx = 0;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002836 for (const TypeSetByHwMode &VTy : Src->getExtTypes()) {
2837 (void)VTy;
Daniel Sandersffc7d582017-03-29 15:37:18 +00002838
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002839 const auto &DstIOperand = DstI.Operands[OpIdx];
2840 Record *DstIOpRec = DstIOperand.Rec;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002841 if (DstI.TheDef->getName() == "COPY_TO_REGCLASS") {
2842 DstIOpRec = getInitValueAsRegClass(Dst->getChild(1)->getLeafValue());
2843
2844 if (DstIOpRec == nullptr)
2845 return failedImport(
2846 "COPY_TO_REGCLASS operand #1 isn't a register class");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002847 } else if (DstI.TheDef->getName() == "EXTRACT_SUBREG") {
2848 if (!Dst->getChild(0)->isLeaf())
2849 return failedImport("EXTRACT_SUBREG operand #0 isn't a leaf");
2850
Daniel Sanders32291982017-06-28 13:50:04 +00002851 // We can assume that a subregister is in the same bank as it's super
2852 // register.
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002853 DstIOpRec = getInitValueAsRegClass(Dst->getChild(0)->getLeafValue());
2854
2855 if (DstIOpRec == nullptr)
2856 return failedImport(
2857 "EXTRACT_SUBREG operand #0 isn't a register class");
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002858 } else if (DstIOpRec->isSubClassOf("RegisterOperand"))
Daniel Sanders658541f2017-04-22 15:53:21 +00002859 DstIOpRec = DstIOpRec->getValueAsDef("RegClass");
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002860 else if (!DstIOpRec->isSubClassOf("RegisterClass"))
Daniel Sanders32291982017-06-28 13:50:04 +00002861 return failedImport("Dst MI def isn't a register class" +
2862 to_string(*Dst));
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002863
Daniel Sandersffc7d582017-03-29 15:37:18 +00002864 OperandMatcher &OM = InsnMatcher.getOperand(OpIdx);
2865 OM.setSymbolicName(DstIOperand.Name);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002866 M.defineOperand(OM.getSymbolicName(), OM);
Daniel Sandersdc662ff2017-01-26 11:10:14 +00002867 OM.addPredicate<RegisterBankOperandMatcher>(
2868 Target.getRegisterClass(DstIOpRec));
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002869 ++OpIdx;
2870 }
2871
Daniel Sandersc270c502017-03-30 09:36:33 +00002872 auto DstMIBuilderOrError =
2873 createAndImportInstructionRenderer(M, Dst, InsnMatcher);
Daniel Sandersffc7d582017-03-29 15:37:18 +00002874 if (auto Error = DstMIBuilderOrError.takeError())
2875 return std::move(Error);
2876 BuildMIAction &DstMIBuilder = DstMIBuilderOrError.get();
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002877
Daniel Sandersffc7d582017-03-29 15:37:18 +00002878 // Render the implicit defs.
2879 // These are only added to the root of the result.
Daniel Sandersc270c502017-03-30 09:36:33 +00002880 if (auto Error = importImplicitDefRenderers(DstMIBuilder, P.getDstRegs()))
Daniel Sandersffc7d582017-03-29 15:37:18 +00002881 return std::move(Error);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002882
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002883 // Constrain the registers to classes. This is normally derived from the
2884 // emitted instruction but a few instructions require special handling.
2885 if (DstI.TheDef->getName() == "COPY_TO_REGCLASS") {
2886 // COPY_TO_REGCLASS does not provide operand constraints itself but the
2887 // result is constrained to the class given by the second child.
2888 Record *DstIOpRec =
2889 getInitValueAsRegClass(Dst->getChild(1)->getLeafValue());
2890
2891 if (DstIOpRec == nullptr)
2892 return failedImport("COPY_TO_REGCLASS operand #1 isn't a register class");
2893
2894 M.addAction<ConstrainOperandToRegClassAction>(
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002895 0, 0, Target.getRegisterClass(DstIOpRec));
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002896
2897 // We're done with this pattern! It's eligible for GISel emission; return
2898 // it.
2899 ++NumPatternImported;
2900 return std::move(M);
2901 }
2902
2903 if (DstI.TheDef->getName() == "EXTRACT_SUBREG") {
2904 // EXTRACT_SUBREG selects into a subregister COPY but unlike most
2905 // instructions, the result register class is controlled by the
2906 // subregisters of the operand. As a result, we must constrain the result
2907 // class rather than check that it's already the right one.
2908 if (!Dst->getChild(0)->isLeaf())
2909 return failedImport("EXTRACT_SUBREG child #1 is not a leaf");
2910
Daniel Sanders320390b2017-06-28 15:16:03 +00002911 DefInit *SubRegInit = dyn_cast<DefInit>(Dst->getChild(1)->getLeafValue());
2912 if (!SubRegInit)
2913 return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002914
Daniel Sanders320390b2017-06-28 15:16:03 +00002915 // Constrain the result to the same register bank as the operand.
2916 Record *DstIOpRec =
2917 getInitValueAsRegClass(Dst->getChild(0)->getLeafValue());
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002918
Daniel Sanders320390b2017-06-28 15:16:03 +00002919 if (DstIOpRec == nullptr)
2920 return failedImport("EXTRACT_SUBREG operand #1 isn't a register class");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002921
Daniel Sanders320390b2017-06-28 15:16:03 +00002922 CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef());
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002923 CodeGenRegisterClass *SrcRC = CGRegs.getRegClass(DstIOpRec);
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002924
Daniel Sanders320390b2017-06-28 15:16:03 +00002925 // It would be nice to leave this constraint implicit but we're required
2926 // to pick a register class so constrain the result to a register class
2927 // that can hold the correct MVT.
2928 //
2929 // FIXME: This may introduce an extra copy if the chosen class doesn't
2930 // actually contain the subregisters.
2931 assert(Src->getExtTypes().size() == 1 &&
2932 "Expected Src of EXTRACT_SUBREG to have one result type");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002933
Daniel Sanders320390b2017-06-28 15:16:03 +00002934 const auto &SrcRCDstRCPair =
2935 SrcRC->getMatchingSubClassWithSubRegs(CGRegs, SubIdx);
2936 assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002937 M.addAction<ConstrainOperandToRegClassAction>(0, 0, *SrcRCDstRCPair->second);
2938 M.addAction<ConstrainOperandToRegClassAction>(0, 1, *SrcRCDstRCPair->first);
2939
2940 // We're done with this pattern! It's eligible for GISel emission; return
2941 // it.
2942 ++NumPatternImported;
2943 return std::move(M);
2944 }
2945
2946 M.addAction<ConstrainOperandsToDefinitionAction>(0);
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002947
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002948 // We're done with this pattern! It's eligible for GISel emission; return it.
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00002949 ++NumPatternImported;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002950 return std::move(M);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002951}
2952
Daniel Sanders649c5852017-10-13 20:42:18 +00002953// Emit imm predicate table and an enum to reference them with.
2954// The 'Predicate_' part of the name is redundant but eliminating it is more
2955// trouble than it's worth.
2956void GlobalISelEmitter::emitImmPredicates(
Daniel Sanders11300ce2017-10-13 21:28:03 +00002957 raw_ostream &OS, StringRef TypeIdentifier, StringRef Type,
2958 std::function<bool(const Record *R)> Filter) {
Daniel Sanders649c5852017-10-13 20:42:18 +00002959 std::vector<const Record *> MatchedRecords;
2960 const auto &Defs = RK.getAllDerivedDefinitions("PatFrag");
2961 std::copy_if(Defs.begin(), Defs.end(), std::back_inserter(MatchedRecords),
2962 [&](Record *Record) {
2963 return !Record->getValueAsString("ImmediateCode").empty() &&
2964 Filter(Record);
2965 });
2966
Daniel Sanders11300ce2017-10-13 21:28:03 +00002967 if (!MatchedRecords.empty()) {
2968 OS << "// PatFrag predicates.\n"
2969 << "enum {\n";
Daniel Sanders2fed4ff2017-10-13 21:51:20 +00002970 std::string EnumeratorSeparator =
Daniel Sanders11300ce2017-10-13 21:28:03 +00002971 (" = GIPFP_" + TypeIdentifier + "_Invalid + 1,\n").str();
2972 for (const auto *Record : MatchedRecords) {
2973 OS << " GIPFP_" << TypeIdentifier << "_Predicate_" << Record->getName()
2974 << EnumeratorSeparator;
2975 EnumeratorSeparator = ",\n";
2976 }
2977 OS << "};\n";
Daniel Sanders649c5852017-10-13 20:42:18 +00002978 }
Daniel Sanders11300ce2017-10-13 21:28:03 +00002979
Daniel Sanders649c5852017-10-13 20:42:18 +00002980 for (const auto *Record : MatchedRecords)
Daniel Sanders11300ce2017-10-13 21:28:03 +00002981 OS << "static bool Predicate_" << Record->getName() << "(" << Type
2982 << " Imm) {" << Record->getValueAsString("ImmediateCode") << "}\n";
2983
2984 OS << "static InstructionSelector::" << TypeIdentifier
2985 << "ImmediatePredicateFn " << TypeIdentifier << "ImmPredicateFns[] = {\n"
Daniel Sanders649c5852017-10-13 20:42:18 +00002986 << " nullptr,\n";
2987 for (const auto *Record : MatchedRecords)
2988 OS << " Predicate_" << Record->getName() << ",\n";
2989 OS << "};\n";
2990}
2991
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002992void GlobalISelEmitter::run(raw_ostream &OS) {
2993 // Track the GINodeEquiv definitions.
2994 gatherNodeEquivs();
2995
2996 emitSourceFileHeader(("Global Instruction Selector for the " +
2997 Target.getName() + " target").str(), OS);
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00002998 std::vector<RuleMatcher> Rules;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002999 // Look through the SelectionDAG patterns we found, possibly emitting some.
3000 for (const PatternToMatch &Pat : CGP.ptms()) {
3001 ++NumPatternTotal;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003002 auto MatcherOrErr = runOnPattern(Pat);
3003
3004 // The pattern analysis can fail, indicating an unsupported pattern.
3005 // Report that if we've been asked to do so.
3006 if (auto Err = MatcherOrErr.takeError()) {
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003007 if (WarnOnSkippedPatterns) {
3008 PrintWarning(Pat.getSrcRecord()->getLoc(),
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003009 "Skipped pattern: " + toString(std::move(Err)));
3010 } else {
3011 consumeError(std::move(Err));
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003012 }
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00003013 ++NumPatternImportsSkipped;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003014 continue;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003015 }
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003016
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00003017 Rules.push_back(std::move(MatcherOrErr.get()));
3018 }
3019
Daniel Sanderseb2f5f32017-08-15 15:10:31 +00003020 std::stable_sort(Rules.begin(), Rules.end(),
3021 [&](const RuleMatcher &A, const RuleMatcher &B) {
3022 if (A.isHigherPriorityThan(B)) {
3023 assert(!B.isHigherPriorityThan(A) && "Cannot be more important "
3024 "and less important at "
3025 "the same time");
3026 return true;
3027 }
3028 return false;
3029 });
Daniel Sanders759ff412017-02-24 13:58:11 +00003030
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003031 std::vector<Record *> ComplexPredicates =
3032 RK.getAllDerivedDefinitions("GIComplexOperandMatcher");
3033 std::sort(ComplexPredicates.begin(), ComplexPredicates.end(),
3034 [](const Record *A, const Record *B) {
3035 if (A->getName() < B->getName())
3036 return true;
3037 return false;
3038 });
Daniel Sanders8a4bae92017-03-14 21:32:08 +00003039 unsigned MaxTemporaries = 0;
3040 for (const auto &Rule : Rules)
Daniel Sanders2deea182017-04-22 15:11:04 +00003041 MaxTemporaries = std::max(MaxTemporaries, Rule.countRendererFns());
Daniel Sanders8a4bae92017-03-14 21:32:08 +00003042
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003043 OS << "#ifdef GET_GLOBALISEL_PREDICATE_BITSET\n"
3044 << "const unsigned MAX_SUBTARGET_PREDICATES = " << SubtargetFeatures.size()
3045 << ";\n"
3046 << "using PredicateBitset = "
3047 "llvm::PredicateBitsetImpl<MAX_SUBTARGET_PREDICATES>;\n"
3048 << "#endif // ifdef GET_GLOBALISEL_PREDICATE_BITSET\n\n";
3049
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003050 OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n"
3051 << " mutable MatcherState State;\n"
3052 << " typedef "
Daniel Sanders1e4569f2017-10-20 20:55:29 +00003053 "ComplexRendererFns("
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003054 << Target.getName()
3055 << "InstructionSelector::*ComplexMatcherMemFn)(MachineOperand &) const;\n"
Daniel Sandersea8711b2017-10-16 03:36:29 +00003056 << " const MatcherInfoTy<PredicateBitset, ComplexMatcherMemFn> "
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003057 "MatcherInfo;\n"
Daniel Sandersea8711b2017-10-16 03:36:29 +00003058 << " static " << Target.getName()
3059 << "InstructionSelector::ComplexMatcherMemFn ComplexPredicateFns[];\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003060 << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n\n";
Daniel Sanders8a4bae92017-03-14 21:32:08 +00003061
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003062 OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n"
3063 << ", State(" << MaxTemporaries << "),\n"
Daniel Sanders11300ce2017-10-13 21:28:03 +00003064 << "MatcherInfo({TypeObjects, FeatureBitsets, I64ImmPredicateFns, "
Daniel Sandersea8711b2017-10-16 03:36:29 +00003065 "APIntImmPredicateFns, APFloatImmPredicateFns, ComplexPredicateFns})\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003066 << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n\n";
Daniel Sanders8a4bae92017-03-14 21:32:08 +00003067
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003068 OS << "#ifdef GET_GLOBALISEL_IMPL\n";
3069 SubtargetFeatureInfo::emitSubtargetFeatureBitEnumeration(SubtargetFeatures,
3070 OS);
Daniel Sanderse9fdba32017-04-29 17:30:09 +00003071
3072 // Separate subtarget features by how often they must be recomputed.
3073 SubtargetFeatureInfoMap ModuleFeatures;
3074 std::copy_if(SubtargetFeatures.begin(), SubtargetFeatures.end(),
3075 std::inserter(ModuleFeatures, ModuleFeatures.end()),
3076 [](const SubtargetFeatureInfoMap::value_type &X) {
3077 return !X.second.mustRecomputePerFunction();
3078 });
3079 SubtargetFeatureInfoMap FunctionFeatures;
3080 std::copy_if(SubtargetFeatures.begin(), SubtargetFeatures.end(),
3081 std::inserter(FunctionFeatures, FunctionFeatures.end()),
3082 [](const SubtargetFeatureInfoMap::value_type &X) {
3083 return X.second.mustRecomputePerFunction();
3084 });
3085
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003086 SubtargetFeatureInfo::emitComputeAvailableFeatures(
Daniel Sanderse9fdba32017-04-29 17:30:09 +00003087 Target.getName(), "InstructionSelector", "computeAvailableModuleFeatures",
3088 ModuleFeatures, OS);
3089 SubtargetFeatureInfo::emitComputeAvailableFeatures(
3090 Target.getName(), "InstructionSelector",
3091 "computeAvailableFunctionFeatures", FunctionFeatures, OS,
3092 "const MachineFunction *MF");
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003093
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003094 // Emit a table containing the LLT objects needed by the matcher and an enum
3095 // for the matcher to reference them with.
Daniel Sanders032e7f22017-08-17 13:18:35 +00003096 std::vector<LLTCodeGen> TypeObjects;
3097 for (const auto &Ty : LLTOperandMatcher::KnownTypes)
3098 TypeObjects.push_back(Ty);
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003099 std::sort(TypeObjects.begin(), TypeObjects.end());
Daniel Sanders49980702017-08-23 10:09:25 +00003100 OS << "// LLT Objects.\n"
3101 << "enum {\n";
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003102 for (const auto &TypeObject : TypeObjects) {
3103 OS << " ";
3104 TypeObject.emitCxxEnumValue(OS);
3105 OS << ",\n";
3106 }
3107 OS << "};\n"
3108 << "const static LLT TypeObjects[] = {\n";
3109 for (const auto &TypeObject : TypeObjects) {
3110 OS << " ";
3111 TypeObject.emitCxxConstructorCall(OS);
3112 OS << ",\n";
3113 }
3114 OS << "};\n\n";
3115
3116 // Emit a table containing the PredicateBitsets objects needed by the matcher
3117 // and an enum for the matcher to reference them with.
3118 std::vector<std::vector<Record *>> FeatureBitsets;
3119 for (auto &Rule : Rules)
3120 FeatureBitsets.push_back(Rule.getRequiredFeatures());
3121 std::sort(
3122 FeatureBitsets.begin(), FeatureBitsets.end(),
3123 [&](const std::vector<Record *> &A, const std::vector<Record *> &B) {
3124 if (A.size() < B.size())
3125 return true;
3126 if (A.size() > B.size())
3127 return false;
3128 for (const auto &Pair : zip(A, B)) {
3129 if (std::get<0>(Pair)->getName() < std::get<1>(Pair)->getName())
3130 return true;
3131 if (std::get<0>(Pair)->getName() > std::get<1>(Pair)->getName())
3132 return false;
3133 }
3134 return false;
3135 });
3136 FeatureBitsets.erase(
3137 std::unique(FeatureBitsets.begin(), FeatureBitsets.end()),
3138 FeatureBitsets.end());
Daniel Sanders49980702017-08-23 10:09:25 +00003139 OS << "// Feature bitsets.\n"
3140 << "enum {\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003141 << " GIFBS_Invalid,\n";
3142 for (const auto &FeatureBitset : FeatureBitsets) {
3143 if (FeatureBitset.empty())
3144 continue;
3145 OS << " " << getNameForFeatureBitset(FeatureBitset) << ",\n";
3146 }
3147 OS << "};\n"
3148 << "const static PredicateBitset FeatureBitsets[] {\n"
3149 << " {}, // GIFBS_Invalid\n";
3150 for (const auto &FeatureBitset : FeatureBitsets) {
3151 if (FeatureBitset.empty())
3152 continue;
3153 OS << " {";
3154 for (const auto &Feature : FeatureBitset) {
3155 const auto &I = SubtargetFeatures.find(Feature);
3156 assert(I != SubtargetFeatures.end() && "Didn't import predicate?");
3157 OS << I->second.getEnumBitName() << ", ";
3158 }
3159 OS << "},\n";
3160 }
3161 OS << "};\n\n";
3162
3163 // Emit complex predicate table and an enum to reference them with.
Daniel Sanders49980702017-08-23 10:09:25 +00003164 OS << "// ComplexPattern predicates.\n"
3165 << "enum {\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003166 << " GICP_Invalid,\n";
3167 for (const auto &Record : ComplexPredicates)
3168 OS << " GICP_" << Record->getName() << ",\n";
3169 OS << "};\n"
3170 << "// See constructor for table contents\n\n";
3171
Daniel Sanders11300ce2017-10-13 21:28:03 +00003172 emitImmPredicates(OS, "I64", "int64_t", [](const Record *R) {
Daniel Sanders649c5852017-10-13 20:42:18 +00003173 bool Unset;
3174 return !R->getValueAsBitOrUnset("IsAPFloat", Unset) &&
3175 !R->getValueAsBit("IsAPInt");
3176 });
Daniel Sanders11300ce2017-10-13 21:28:03 +00003177 emitImmPredicates(OS, "APFloat", "const APFloat &", [](const Record *R) {
3178 bool Unset;
3179 return R->getValueAsBitOrUnset("IsAPFloat", Unset);
3180 });
3181 emitImmPredicates(OS, "APInt", "const APInt &", [](const Record *R) {
3182 return R->getValueAsBit("IsAPInt");
3183 });
Daniel Sandersea8711b2017-10-16 03:36:29 +00003184 OS << "\n";
3185
3186 OS << Target.getName() << "InstructionSelector::ComplexMatcherMemFn\n"
3187 << Target.getName() << "InstructionSelector::ComplexPredicateFns[] = {\n"
3188 << " nullptr, // GICP_Invalid\n";
3189 for (const auto &Record : ComplexPredicates)
3190 OS << " &" << Target.getName()
3191 << "InstructionSelector::" << Record->getValueAsString("MatcherFn")
3192 << ", // " << Record->getName() << "\n";
3193 OS << "};\n\n";
Daniel Sanders2c269f62017-08-24 09:11:20 +00003194
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003195 OS << "bool " << Target.getName()
Daniel Sanders8a4bae92017-03-14 21:32:08 +00003196 << "InstructionSelector::selectImpl(MachineInstr &I) const {\n"
3197 << " MachineFunction &MF = *I.getParent()->getParent();\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003198 << " MachineRegisterInfo &MRI = MF.getRegInfo();\n"
Daniel Sanders32291982017-06-28 13:50:04 +00003199 << " // FIXME: This should be computed on a per-function basis rather "
3200 "than per-insn.\n"
3201 << " AvailableFunctionFeatures = computeAvailableFunctionFeatures(&STI, "
3202 "&MF);\n"
Daniel Sandersa6cfce62017-07-05 14:50:18 +00003203 << " const PredicateBitset AvailableFeatures = getAvailableFeatures();\n"
3204 << " NewMIVector OutMIs;\n"
3205 << " State.MIs.clear();\n"
3206 << " State.MIs.push_back(&I);\n\n";
Daniel Sanders8a4bae92017-03-14 21:32:08 +00003207
Daniel Sanders8e82af22017-07-27 11:03:45 +00003208 MatchTable Table(0);
Daniel Sandersb96f40d2017-03-20 15:20:42 +00003209 for (auto &Rule : Rules) {
Daniel Sanders8e82af22017-07-27 11:03:45 +00003210 Rule.emit(Table);
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003211 ++NumPatternEmitted;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003212 }
Daniel Sanders8e82af22017-07-27 11:03:45 +00003213 Table << MatchTable::Opcode("GIM_Reject") << MatchTable::LineBreak;
3214 Table.emitDeclaration(OS);
3215 OS << " if (executeMatchTable(*this, OutMIs, State, MatcherInfo, ";
3216 Table.emitUse(OS);
3217 OS << ", TII, MRI, TRI, RBI, AvailableFeatures)) {\n"
3218 << " return true;\n"
3219 << " }\n\n";
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003220
Daniel Sanders8a4bae92017-03-14 21:32:08 +00003221 OS << " return false;\n"
3222 << "}\n"
3223 << "#endif // ifdef GET_GLOBALISEL_IMPL\n";
Daniel Sanderse9fdba32017-04-29 17:30:09 +00003224
3225 OS << "#ifdef GET_GLOBALISEL_PREDICATES_DECL\n"
3226 << "PredicateBitset AvailableModuleFeatures;\n"
3227 << "mutable PredicateBitset AvailableFunctionFeatures;\n"
3228 << "PredicateBitset getAvailableFeatures() const {\n"
3229 << " return AvailableModuleFeatures | AvailableFunctionFeatures;\n"
3230 << "}\n"
3231 << "PredicateBitset\n"
3232 << "computeAvailableModuleFeatures(const " << Target.getName()
3233 << "Subtarget *Subtarget) const;\n"
3234 << "PredicateBitset\n"
3235 << "computeAvailableFunctionFeatures(const " << Target.getName()
3236 << "Subtarget *Subtarget,\n"
3237 << " const MachineFunction *MF) const;\n"
3238 << "#endif // ifdef GET_GLOBALISEL_PREDICATES_DECL\n";
3239
3240 OS << "#ifdef GET_GLOBALISEL_PREDICATES_INIT\n"
3241 << "AvailableModuleFeatures(computeAvailableModuleFeatures(&STI)),\n"
3242 << "AvailableFunctionFeatures()\n"
3243 << "#endif // ifdef GET_GLOBALISEL_PREDICATES_INIT\n";
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003244}
3245
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003246void GlobalISelEmitter::declareSubtargetFeature(Record *Predicate) {
3247 if (SubtargetFeatures.count(Predicate) == 0)
3248 SubtargetFeatures.emplace(
3249 Predicate, SubtargetFeatureInfo(Predicate, SubtargetFeatures.size()));
3250}
3251
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003252} // end anonymous namespace
3253
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003254//===----------------------------------------------------------------------===//
3255
3256namespace llvm {
3257void EmitGlobalISel(RecordKeeper &RK, raw_ostream &OS) {
3258 GlobalISelEmitter(RK).run(OS);
3259}
3260} // End llvm namespace