blob: 360671a69b87e9941a42cedfe69d7c6bae72906a [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 Sanders066ebbf2017-02-24 15:43:30 +00001756 const InstructionMatcher &Matched;
1757 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 Sanderse9fdba32017-04-29 17:30:09 +00001761 if (OperandRenderers.size() != Matched.getNumOperands())
1762 return false;
1763
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001764 for (const auto &Renderer : enumerate(OperandRenderers)) {
Zachary Turner309a0882017-03-13 16:24:10 +00001765 if (const auto *Copy = dyn_cast<CopyRenderer>(&*Renderer.value())) {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001766 const OperandMatcher &OM = Rule.getOperandMatcher(Copy->getSymbolicName());
Daniel Sanders3016d3c2017-04-22 14:31:28 +00001767 if (&Matched != &OM.getInstructionMatcher() ||
1768 OM.getOperandIndex() != Renderer.index())
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001769 return false;
1770 } else
1771 return false;
1772 }
1773
1774 return true;
1775 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001776
Daniel Sanders43c882c2017-02-01 10:53:10 +00001777public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001778 BuildMIAction(unsigned InsnID, const CodeGenInstruction *I,
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00001779 const InstructionMatcher &Matched)
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001780 : InsnID(InsnID), I(I), Matched(Matched) {}
Daniel Sanders43c882c2017-02-01 10:53:10 +00001781
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001782 template <class Kind, class... Args>
1783 Kind &addRenderer(Args&&... args) {
1784 OperandRenderers.emplace_back(
1785 llvm::make_unique<Kind>(std::forward<Args>(args)...));
1786 return *static_cast<Kind *>(OperandRenderers.back().get());
1787 }
1788
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001789 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule,
1790 unsigned RecycleInsnID) const override {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001791 if (canMutate(Rule)) {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001792 Table << MatchTable::Opcode("GIR_MutateOpcode")
1793 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1794 << MatchTable::Comment("RecycleInsnID")
1795 << MatchTable::IntValue(RecycleInsnID)
1796 << MatchTable::Comment("Opcode")
1797 << MatchTable::NamedValue(I->Namespace, I->TheDef->getName())
1798 << MatchTable::LineBreak;
Tim Northover4340d642017-03-20 21:58:23 +00001799
1800 if (!I->ImplicitDefs.empty() || !I->ImplicitUses.empty()) {
Tim Northover4340d642017-03-20 21:58:23 +00001801 for (auto Def : I->ImplicitDefs) {
Diana Picus8abcbbb2017-05-02 09:40:49 +00001802 auto Namespace = Def->getValue("Namespace")
1803 ? Def->getValueAsString("Namespace")
1804 : "";
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001805 Table << MatchTable::Opcode("GIR_AddImplicitDef")
1806 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1807 << MatchTable::NamedValue(Namespace, Def->getName())
1808 << MatchTable::LineBreak;
Tim Northover4340d642017-03-20 21:58:23 +00001809 }
1810 for (auto Use : I->ImplicitUses) {
Diana Picus8abcbbb2017-05-02 09:40:49 +00001811 auto Namespace = Use->getValue("Namespace")
1812 ? Use->getValueAsString("Namespace")
1813 : "";
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001814 Table << MatchTable::Opcode("GIR_AddImplicitUse")
1815 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1816 << MatchTable::NamedValue(Namespace, Use->getName())
1817 << MatchTable::LineBreak;
Tim Northover4340d642017-03-20 21:58:23 +00001818 }
1819 }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001820 return;
1821 }
1822
1823 // TODO: Simple permutation looks like it could be almost as common as
1824 // mutation due to commutative operations.
1825
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001826 Table << MatchTable::Opcode("GIR_BuildMI") << MatchTable::Comment("InsnID")
1827 << MatchTable::IntValue(InsnID) << MatchTable::Comment("Opcode")
1828 << MatchTable::NamedValue(I->Namespace, I->TheDef->getName())
1829 << MatchTable::LineBreak;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001830 for (const auto &Renderer : OperandRenderers)
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001831 Renderer->emitRenderOpcodes(Table, Rule);
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001832
Florian Hahn3bc3ec62017-08-03 14:48:22 +00001833 if (I->mayLoad || I->mayStore) {
1834 Table << MatchTable::Opcode("GIR_MergeMemOperands")
1835 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1836 << MatchTable::Comment("MergeInsnID's");
1837 // Emit the ID's for all the instructions that are matched by this rule.
1838 // TODO: Limit this to matched instructions that mayLoad/mayStore or have
1839 // some other means of having a memoperand. Also limit this to
1840 // emitted instructions that expect to have a memoperand too. For
1841 // example, (G_SEXT (G_LOAD x)) that results in separate load and
1842 // sign-extend instructions shouldn't put the memoperand on the
1843 // sign-extend since it has no effect there.
1844 std::vector<unsigned> MergeInsnIDs;
1845 for (const auto &IDMatcherPair : Rule.defined_insn_vars())
1846 MergeInsnIDs.push_back(IDMatcherPair.second);
1847 std::sort(MergeInsnIDs.begin(), MergeInsnIDs.end());
1848 for (const auto &MergeInsnID : MergeInsnIDs)
1849 Table << MatchTable::IntValue(MergeInsnID);
Daniel Sanders05540042017-08-08 10:44:31 +00001850 Table << MatchTable::NamedValue("GIU_MergeMemOperands_EndOfList")
1851 << MatchTable::LineBreak;
Florian Hahn3bc3ec62017-08-03 14:48:22 +00001852 }
1853
1854 Table << MatchTable::Opcode("GIR_EraseFromParent")
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001855 << MatchTable::Comment("InsnID")
1856 << MatchTable::IntValue(RecycleInsnID) << MatchTable::LineBreak;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00001857 }
1858};
1859
1860/// Generates code to constrain the operands of an output instruction to the
1861/// register classes specified by the definition of that instruction.
1862class ConstrainOperandsToDefinitionAction : public MatchAction {
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001863 unsigned InsnID;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00001864
1865public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001866 ConstrainOperandsToDefinitionAction(unsigned InsnID) : InsnID(InsnID) {}
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00001867
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001868 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule,
1869 unsigned RecycleInsnID) const override {
1870 Table << MatchTable::Opcode("GIR_ConstrainSelectedInstOperands")
1871 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1872 << MatchTable::LineBreak;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00001873 }
1874};
1875
1876/// Generates code to constrain the specified operand of an output instruction
1877/// to the specified register class.
1878class ConstrainOperandToRegClassAction : public MatchAction {
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001879 unsigned InsnID;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00001880 unsigned OpIdx;
1881 const CodeGenRegisterClass &RC;
1882
1883public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001884 ConstrainOperandToRegClassAction(unsigned InsnID, unsigned OpIdx,
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00001885 const CodeGenRegisterClass &RC)
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001886 : InsnID(InsnID), OpIdx(OpIdx), RC(RC) {}
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00001887
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001888 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule,
1889 unsigned RecycleInsnID) const override {
1890 Table << MatchTable::Opcode("GIR_ConstrainOperandRC")
1891 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1892 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1893 << MatchTable::Comment("RC " + RC.getName())
1894 << MatchTable::IntValue(RC.EnumValue) << MatchTable::LineBreak;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001895 }
1896};
1897
Daniel Sanders05540042017-08-08 10:44:31 +00001898InstructionMatcher &RuleMatcher::addInstructionMatcher(StringRef SymbolicName) {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001899 Matchers.emplace_back(new InstructionMatcher(*this, SymbolicName));
Daniel Sandersbdfebb82017-03-15 20:18:38 +00001900 return *Matchers.back();
1901}
Ahmed Bougacha56ca3a92017-02-04 00:47:10 +00001902
Daniel Sanderse7b0d662017-04-21 15:59:56 +00001903void RuleMatcher::addRequiredFeature(Record *Feature) {
1904 RequiredFeatures.push_back(Feature);
1905}
1906
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001907const std::vector<Record *> &RuleMatcher::getRequiredFeatures() const {
1908 return RequiredFeatures;
1909}
1910
Daniel Sandersbdfebb82017-03-15 20:18:38 +00001911template <class Kind, class... Args>
1912Kind &RuleMatcher::addAction(Args &&... args) {
1913 Actions.emplace_back(llvm::make_unique<Kind>(std::forward<Args>(args)...));
1914 return *static_cast<Kind *>(Actions.back().get());
1915}
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001916
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001917unsigned
1918RuleMatcher::implicitlyDefineInsnVar(const InstructionMatcher &Matcher) {
1919 unsigned NewInsnVarID = NextInsnVarID++;
1920 InsnVariableIDs[&Matcher] = NewInsnVarID;
1921 return NewInsnVarID;
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001922}
1923
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001924unsigned RuleMatcher::defineInsnVar(MatchTable &Table,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001925 const InstructionMatcher &Matcher,
1926 unsigned InsnID, unsigned OpIdx) {
1927 unsigned NewInsnVarID = implicitlyDefineInsnVar(Matcher);
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001928 Table << MatchTable::Opcode("GIM_RecordInsn")
1929 << MatchTable::Comment("DefineMI") << MatchTable::IntValue(NewInsnVarID)
1930 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnID)
1931 << MatchTable::Comment("OpIdx") << MatchTable::IntValue(OpIdx)
1932 << MatchTable::Comment("MIs[" + llvm::to_string(NewInsnVarID) + "]")
1933 << MatchTable::LineBreak;
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001934 return NewInsnVarID;
1935}
1936
1937unsigned RuleMatcher::getInsnVarID(const InstructionMatcher &InsnMatcher) const {
1938 const auto &I = InsnVariableIDs.find(&InsnMatcher);
1939 if (I != InsnVariableIDs.end())
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001940 return I->second;
1941 llvm_unreachable("Matched Insn was not captured in a local variable");
1942}
1943
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001944void RuleMatcher::defineOperand(StringRef SymbolicName, OperandMatcher &OM) {
1945 if (DefinedOperands.find(SymbolicName) == DefinedOperands.end()) {
1946 DefinedOperands[SymbolicName] = &OM;
1947 return;
1948 }
1949
1950 // If the operand is already defined, then we must ensure both references in
1951 // the matcher have the exact same node.
1952 OM.addPredicate<SameOperandMatcher>(OM.getSymbolicName());
1953}
1954
Daniel Sanders05540042017-08-08 10:44:31 +00001955const InstructionMatcher &
1956RuleMatcher::getInstructionMatcher(StringRef SymbolicName) const {
1957 for (const auto &I : InsnVariableIDs)
1958 if (I.first->getSymbolicName() == SymbolicName)
1959 return *I.first;
1960 llvm_unreachable(
1961 ("Failed to lookup instruction " + SymbolicName).str().c_str());
1962}
1963
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001964const OperandMatcher &
1965RuleMatcher::getOperandMatcher(StringRef Name) const {
1966 const auto &I = DefinedOperands.find(Name);
1967
1968 if (I == DefinedOperands.end())
1969 PrintFatalError(SrcLoc, "Operand " + Name + " was not declared in matcher");
1970
1971 return *I->second;
1972}
1973
Daniel Sanders9d662d22017-07-06 10:06:12 +00001974/// Emit MatchTable opcodes to check the shape of the match and capture
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001975/// instructions into local variables.
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001976void RuleMatcher::emitCaptureOpcodes(MatchTable &Table) {
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001977 assert(Matchers.size() == 1 && "Cannot handle multi-root matchers yet");
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001978 unsigned InsnVarID = implicitlyDefineInsnVar(*Matchers.front());
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001979 Matchers.front()->emitCaptureOpcodes(Table, *this, InsnVarID);
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001980}
1981
Daniel Sanders8e82af22017-07-27 11:03:45 +00001982void RuleMatcher::emit(MatchTable &Table) {
Daniel Sandersbdfebb82017-03-15 20:18:38 +00001983 if (Matchers.empty())
1984 llvm_unreachable("Unexpected empty matcher!");
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001985
Daniel Sandersbdfebb82017-03-15 20:18:38 +00001986 // The representation supports rules that require multiple roots such as:
1987 // %ptr(p0) = ...
1988 // %elt0(s32) = G_LOAD %ptr
1989 // %1(p0) = G_ADD %ptr, 4
1990 // %elt1(s32) = G_LOAD p0 %1
1991 // which could be usefully folded into:
1992 // %ptr(p0) = ...
1993 // %elt0(s32), %elt1(s32) = TGT_LOAD_PAIR %ptr
1994 // on some targets but we don't need to make use of that yet.
1995 assert(Matchers.size() == 1 && "Cannot handle multi-root matchers yet");
Daniel Sanderse7b0d662017-04-21 15:59:56 +00001996
Daniel Sanders8e82af22017-07-27 11:03:45 +00001997 unsigned LabelID = Table.allocateLabelID();
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001998 Table << MatchTable::Opcode("GIM_Try", +1)
Daniel Sanders8e82af22017-07-27 11:03:45 +00001999 << MatchTable::Comment("On fail goto") << MatchTable::JumpTarget(LabelID)
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002000 << MatchTable::LineBreak;
2001
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002002 if (!RequiredFeatures.empty()) {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002003 Table << MatchTable::Opcode("GIM_CheckFeatures")
2004 << MatchTable::NamedValue(getNameForFeatureBitset(RequiredFeatures))
2005 << MatchTable::LineBreak;
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002006 }
Daniel Sandersb96f40d2017-03-20 15:20:42 +00002007
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002008 emitCaptureOpcodes(Table);
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002009
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002010 Matchers.front()->emitPredicateOpcodes(Table, *this,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002011 getInsnVarID(*Matchers.front()));
2012
Daniel Sandersbee57392017-04-04 13:25:23 +00002013 // We must also check if it's safe to fold the matched instructions.
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002014 if (InsnVariableIDs.size() >= 2) {
Galina Kistanova1754fee2017-05-25 01:51:53 +00002015 // Invert the map to create stable ordering (by var names)
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002016 SmallVector<unsigned, 2> InsnIDs;
2017 for (const auto &Pair : InsnVariableIDs) {
Daniel Sandersbee57392017-04-04 13:25:23 +00002018 // Skip the root node since it isn't moving anywhere. Everything else is
2019 // sinking to meet it.
2020 if (Pair.first == Matchers.front().get())
2021 continue;
2022
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002023 InsnIDs.push_back(Pair.second);
Galina Kistanova1754fee2017-05-25 01:51:53 +00002024 }
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002025 std::sort(InsnIDs.begin(), InsnIDs.end());
Galina Kistanova1754fee2017-05-25 01:51:53 +00002026
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002027 for (const auto &InsnID : InsnIDs) {
Daniel Sandersbee57392017-04-04 13:25:23 +00002028 // Reject the difficult cases until we have a more accurate check.
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002029 Table << MatchTable::Opcode("GIM_CheckIsSafeToFold")
2030 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2031 << MatchTable::LineBreak;
Daniel Sandersbee57392017-04-04 13:25:23 +00002032
2033 // FIXME: Emit checks to determine it's _actually_ safe to fold and/or
2034 // account for unsafe cases.
2035 //
2036 // Example:
2037 // MI1--> %0 = ...
2038 // %1 = ... %0
2039 // MI0--> %2 = ... %0
2040 // It's not safe to erase MI1. We currently handle this by not
2041 // erasing %0 (even when it's dead).
2042 //
2043 // Example:
2044 // MI1--> %0 = load volatile @a
2045 // %1 = load volatile @a
2046 // MI0--> %2 = ... %0
2047 // It's not safe to sink %0's def past %1. We currently handle
2048 // this by rejecting all loads.
2049 //
2050 // Example:
2051 // MI1--> %0 = load @a
2052 // %1 = store @a
2053 // MI0--> %2 = ... %0
2054 // It's not safe to sink %0's def past %1. We currently handle
2055 // this by rejecting all loads.
2056 //
2057 // Example:
2058 // G_CONDBR %cond, @BB1
2059 // BB0:
2060 // MI1--> %0 = load @a
2061 // G_BR @BB1
2062 // BB1:
2063 // MI0--> %2 = ... %0
2064 // It's not always safe to sink %0 across control flow. In this
2065 // case it may introduce a memory fault. We currentl handle this
2066 // by rejecting all loads.
2067 }
2068 }
2069
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002070 for (const auto &MA : Actions)
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002071 MA->emitActionOpcodes(Table, *this, 0);
2072 Table << MatchTable::Opcode("GIR_Done", -1) << MatchTable::LineBreak
Daniel Sanders8e82af22017-07-27 11:03:45 +00002073 << MatchTable::Label(LabelID);
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002074}
Daniel Sanders43c882c2017-02-01 10:53:10 +00002075
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002076bool RuleMatcher::isHigherPriorityThan(const RuleMatcher &B) const {
2077 // Rules involving more match roots have higher priority.
2078 if (Matchers.size() > B.Matchers.size())
2079 return true;
2080 if (Matchers.size() < B.Matchers.size())
Daniel Sanders759ff412017-02-24 13:58:11 +00002081 return false;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002082
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002083 for (const auto &Matcher : zip(Matchers, B.Matchers)) {
2084 if (std::get<0>(Matcher)->isHigherPriorityThan(*std::get<1>(Matcher)))
2085 return true;
2086 if (std::get<1>(Matcher)->isHigherPriorityThan(*std::get<0>(Matcher)))
2087 return false;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002088 }
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002089
2090 return false;
Simon Pilgrima7d1da82017-03-15 22:50:47 +00002091}
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002092
Daniel Sanders2deea182017-04-22 15:11:04 +00002093unsigned RuleMatcher::countRendererFns() const {
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002094 return std::accumulate(
2095 Matchers.begin(), Matchers.end(), 0,
2096 [](unsigned A, const std::unique_ptr<InstructionMatcher> &Matcher) {
Daniel Sanders2deea182017-04-22 15:11:04 +00002097 return A + Matcher->countRendererFns();
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002098 });
2099}
2100
Daniel Sanders05540042017-08-08 10:44:31 +00002101bool OperandPredicateMatcher::isHigherPriorityThan(
2102 const OperandPredicateMatcher &B) const {
2103 // Generally speaking, an instruction is more important than an Int or a
2104 // LiteralInt because it can cover more nodes but theres an exception to
2105 // this. G_CONSTANT's are less important than either of those two because they
2106 // are more permissive.
Daniel Sandersedd07842017-08-17 09:26:14 +00002107
2108 const InstructionOperandMatcher *AOM =
2109 dyn_cast<InstructionOperandMatcher>(this);
2110 const InstructionOperandMatcher *BOM =
2111 dyn_cast<InstructionOperandMatcher>(&B);
2112 bool AIsConstantInsn = AOM && AOM->getInsnMatcher().isConstantInstruction();
2113 bool BIsConstantInsn = BOM && BOM->getInsnMatcher().isConstantInstruction();
2114
2115 if (AOM && BOM) {
2116 // The relative priorities between a G_CONSTANT and any other instruction
2117 // don't actually matter but this code is needed to ensure a strict weak
2118 // ordering. This is particularly important on Windows where the rules will
2119 // be incorrectly sorted without it.
2120 if (AIsConstantInsn != BIsConstantInsn)
2121 return AIsConstantInsn < BIsConstantInsn;
2122 return false;
Daniel Sanders05540042017-08-08 10:44:31 +00002123 }
Daniel Sandersedd07842017-08-17 09:26:14 +00002124
2125 if (AOM && AIsConstantInsn && (B.Kind == OPM_Int || B.Kind == OPM_LiteralInt))
2126 return false;
2127 if (BOM && BIsConstantInsn && (Kind == OPM_Int || Kind == OPM_LiteralInt))
2128 return true;
Daniel Sanders05540042017-08-08 10:44:31 +00002129
2130 return Kind < B.Kind;
Daniel Sanders75b84fc2017-08-08 13:21:26 +00002131}
Daniel Sanders05540042017-08-08 10:44:31 +00002132
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002133void SameOperandMatcher::emitPredicateOpcodes(MatchTable &Table,
2134 RuleMatcher &Rule,
2135 unsigned InsnVarID,
2136 unsigned OpIdx) const {
Daniel Sanders1e4569f2017-10-20 20:55:29 +00002137 const OperandMatcher &OtherOM = Rule.getOperandMatcher(MatchingName);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002138 unsigned OtherInsnVarID = Rule.getInsnVarID(OtherOM.getInstructionMatcher());
2139
2140 Table << MatchTable::Opcode("GIM_CheckIsSameOperand")
2141 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
2142 << MatchTable::Comment("OpIdx") << MatchTable::IntValue(OpIdx)
2143 << MatchTable::Comment("OtherMI")
2144 << MatchTable::IntValue(OtherInsnVarID)
2145 << MatchTable::Comment("OtherOpIdx")
2146 << MatchTable::IntValue(OtherOM.getOperandIndex())
2147 << MatchTable::LineBreak;
2148}
2149
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002150//===- GlobalISelEmitter class --------------------------------------------===//
2151
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002152class GlobalISelEmitter {
2153public:
2154 explicit GlobalISelEmitter(RecordKeeper &RK);
2155 void run(raw_ostream &OS);
2156
2157private:
2158 const RecordKeeper &RK;
2159 const CodeGenDAGPatterns CGP;
2160 const CodeGenTarget &Target;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002161 CodeGenRegBank CGRegs;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002162
Daniel Sanders39690bd2017-10-15 02:41:12 +00002163 /// Keep track of the equivalence between SDNodes and Instruction by mapping
2164 /// SDNodes to the GINodeEquiv mapping. We need to map to the GINodeEquiv to
2165 /// check for attributes on the relation such as CheckMMOIsNonAtomic.
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002166 /// This is defined using 'GINodeEquiv' in the target description.
Daniel Sanders39690bd2017-10-15 02:41:12 +00002167 DenseMap<Record *, Record *> NodeEquivs;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002168
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002169 /// Keep track of the equivalence between ComplexPattern's and
2170 /// GIComplexOperandMatcher. Map entries are specified by subclassing
2171 /// GIComplexPatternEquiv.
2172 DenseMap<const Record *, const Record *> ComplexPatternEquivs;
2173
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002174 // Map of predicates to their subtarget features.
Daniel Sanderse9fdba32017-04-29 17:30:09 +00002175 SubtargetFeatureInfoMap SubtargetFeatures;
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002176
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002177 void gatherNodeEquivs();
Daniel Sanders39690bd2017-10-15 02:41:12 +00002178 Record *findNodeEquiv(Record *N) const;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002179
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002180 Error importRulePredicates(RuleMatcher &M, ArrayRef<Predicate> Predicates);
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002181 Expected<InstructionMatcher &> createAndImportSelDAGMatcher(
2182 RuleMatcher &Rule, InstructionMatcher &InsnMatcher,
2183 const TreePatternNode *Src, unsigned &TempOpIdx) const;
2184 Error importComplexPatternOperandMatcher(OperandMatcher &OM, Record *R,
2185 unsigned &TempOpIdx) const;
2186 Error importChildMatcher(RuleMatcher &Rule, InstructionMatcher &InsnMatcher,
Daniel Sandersa71f4542017-10-16 00:56:30 +00002187 const TreePatternNode *SrcChild,
2188 bool OperandIsAPointer, unsigned OpIdx,
Daniel Sandersc270c502017-03-30 09:36:33 +00002189 unsigned &TempOpIdx) const;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002190 Expected<BuildMIAction &>
2191 createAndImportInstructionRenderer(RuleMatcher &M, const TreePatternNode *Dst,
2192 const InstructionMatcher &InsnMatcher);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002193 Error importExplicitUseRenderer(RuleMatcher &Rule,
2194 BuildMIAction &DstMIBuilder,
Daniel Sandersc270c502017-03-30 09:36:33 +00002195 TreePatternNode *DstChild,
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002196 const InstructionMatcher &InsnMatcher) const;
Diana Picus382602f2017-05-17 08:57:28 +00002197 Error importDefaultOperandRenderers(BuildMIAction &DstMIBuilder,
2198 DagInit *DefaultOps) const;
Daniel Sandersc270c502017-03-30 09:36:33 +00002199 Error
Daniel Sandersffc7d582017-03-29 15:37:18 +00002200 importImplicitDefRenderers(BuildMIAction &DstMIBuilder,
2201 const std::vector<Record *> &ImplicitDefs) const;
2202
Daniel Sanders11300ce2017-10-13 21:28:03 +00002203 void emitImmPredicates(raw_ostream &OS, StringRef TypeIdentifier,
2204 StringRef Type,
Daniel Sanders649c5852017-10-13 20:42:18 +00002205 std::function<bool(const Record *R)> Filter);
2206
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002207 /// Analyze pattern \p P, returning a matcher for it if possible.
2208 /// Otherwise, return an Error explaining why we don't support it.
2209 Expected<RuleMatcher> runOnPattern(const PatternToMatch &P);
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002210
2211 void declareSubtargetFeature(Record *Predicate);
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002212};
2213
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002214void GlobalISelEmitter::gatherNodeEquivs() {
2215 assert(NodeEquivs.empty());
2216 for (Record *Equiv : RK.getAllDerivedDefinitions("GINodeEquiv"))
Daniel Sanders39690bd2017-10-15 02:41:12 +00002217 NodeEquivs[Equiv->getValueAsDef("Node")] = Equiv;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002218
2219 assert(ComplexPatternEquivs.empty());
2220 for (Record *Equiv : RK.getAllDerivedDefinitions("GIComplexPatternEquiv")) {
2221 Record *SelDAGEquiv = Equiv->getValueAsDef("SelDAGEquivalent");
2222 if (!SelDAGEquiv)
2223 continue;
2224 ComplexPatternEquivs[SelDAGEquiv] = Equiv;
2225 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002226}
2227
Daniel Sanders39690bd2017-10-15 02:41:12 +00002228Record *GlobalISelEmitter::findNodeEquiv(Record *N) const {
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002229 return NodeEquivs.lookup(N);
2230}
2231
2232GlobalISelEmitter::GlobalISelEmitter(RecordKeeper &RK)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002233 : RK(RK), CGP(RK), Target(CGP.getTargetInfo()),
2234 CGRegs(RK, Target.getHwModes()) {}
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002235
2236//===- Emitter ------------------------------------------------------------===//
2237
Daniel Sandersc270c502017-03-30 09:36:33 +00002238Error
Daniel Sandersffc7d582017-03-29 15:37:18 +00002239GlobalISelEmitter::importRulePredicates(RuleMatcher &M,
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002240 ArrayRef<Predicate> Predicates) {
2241 for (const Predicate &P : Predicates) {
2242 if (!P.Def)
2243 continue;
2244 declareSubtargetFeature(P.Def);
2245 M.addRequiredFeature(P.Def);
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002246 }
2247
Daniel Sandersc270c502017-03-30 09:36:33 +00002248 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00002249}
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002250
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002251Expected<InstructionMatcher &> GlobalISelEmitter::createAndImportSelDAGMatcher(
2252 RuleMatcher &Rule, InstructionMatcher &InsnMatcher,
2253 const TreePatternNode *Src, unsigned &TempOpIdx) const {
Daniel Sanders39690bd2017-10-15 02:41:12 +00002254 Record *SrcGIEquivOrNull = nullptr;
Daniel Sanders85ffd362017-07-06 08:12:20 +00002255 const CodeGenInstruction *SrcGIOrNull = nullptr;
2256
Daniel Sandersffc7d582017-03-29 15:37:18 +00002257 // Start with the defined operands (i.e., the results of the root operator).
2258 if (Src->getExtTypes().size() > 1)
2259 return failedImport("Src pattern has multiple results");
2260
Daniel Sanders452c8ae2017-05-23 19:33:16 +00002261 if (Src->isLeaf()) {
2262 Init *SrcInit = Src->getLeafValue();
Daniel Sanders3334cc02017-05-23 20:02:48 +00002263 if (isa<IntInit>(SrcInit)) {
Daniel Sanders452c8ae2017-05-23 19:33:16 +00002264 InsnMatcher.addPredicate<InstructionOpcodeMatcher>(
2265 &Target.getInstruction(RK.getDef("G_CONSTANT")));
2266 } else
Daniel Sanders32291982017-06-28 13:50:04 +00002267 return failedImport(
2268 "Unable to deduce gMIR opcode to handle Src (which is a leaf)");
Daniel Sanders452c8ae2017-05-23 19:33:16 +00002269 } else {
Daniel Sanders39690bd2017-10-15 02:41:12 +00002270 SrcGIEquivOrNull = findNodeEquiv(Src->getOperator());
2271 if (!SrcGIEquivOrNull)
Daniel Sanders452c8ae2017-05-23 19:33:16 +00002272 return failedImport("Pattern operator lacks an equivalent Instruction" +
2273 explainOperator(Src->getOperator()));
Daniel Sanders39690bd2017-10-15 02:41:12 +00002274 SrcGIOrNull = &Target.getInstruction(SrcGIEquivOrNull->getValueAsDef("I"));
Daniel Sandersffc7d582017-03-29 15:37:18 +00002275
Daniel Sanders452c8ae2017-05-23 19:33:16 +00002276 // The operators look good: match the opcode
Daniel Sanders39690bd2017-10-15 02:41:12 +00002277 InsnMatcher.addPredicate<InstructionOpcodeMatcher>(SrcGIOrNull);
Daniel Sanders452c8ae2017-05-23 19:33:16 +00002278 }
Daniel Sandersffc7d582017-03-29 15:37:18 +00002279
2280 unsigned OpIdx = 0;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002281 for (const TypeSetByHwMode &VTy : Src->getExtTypes()) {
Daniel Sandersffc7d582017-03-29 15:37:18 +00002282 // Results don't have a name unless they are the root node. The caller will
2283 // set the name if appropriate.
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002284 OperandMatcher &OM = InsnMatcher.addOperand(OpIdx++, "", TempOpIdx);
Daniel Sandersa71f4542017-10-16 00:56:30 +00002285 if (auto Error = OM.addTypeCheckPredicate(VTy, false /* OperandIsAPointer */))
2286 return failedImport(toString(std::move(Error)) +
2287 " for result of Src pattern operator");
Daniel Sandersffc7d582017-03-29 15:37:18 +00002288 }
2289
Daniel Sanders2c269f62017-08-24 09:11:20 +00002290 for (const auto &Predicate : Src->getPredicateFns()) {
2291 if (Predicate.isAlwaysTrue())
2292 continue;
2293
2294 if (Predicate.isImmediatePattern()) {
2295 InsnMatcher.addPredicate<InstructionImmPredicateMatcher>(Predicate);
2296 continue;
2297 }
2298
Daniel Sandersa71f4542017-10-16 00:56:30 +00002299 // No check required. A G_LOAD is an unindexed load.
2300 if (Predicate.isLoad() && Predicate.isUnindexed())
2301 continue;
2302
2303 // No check required. G_LOAD by itself is a non-extending load.
2304 if (Predicate.isNonExtLoad())
2305 continue;
2306
2307 if (Predicate.isLoad() && Predicate.getMemoryVT() != nullptr) {
2308 Optional<LLTCodeGen> MemTyOrNone =
2309 MVTToLLT(getValueType(Predicate.getMemoryVT()));
2310
2311 if (!MemTyOrNone)
2312 return failedImport("MemVT could not be converted to LLT");
2313
2314 InsnMatcher.getOperand(0).addPredicate<LLTOperandMatcher>(MemTyOrNone.getValue());
2315 continue;
2316 }
2317
Daniel Sandersd66e0902017-10-23 18:19:24 +00002318 // No check required. A G_STORE is an unindexed store.
2319 if (Predicate.isStore() && Predicate.isUnindexed())
2320 continue;
2321
2322 // No check required. G_STORE by itself is a non-extending store.
2323 if (Predicate.isNonTruncStore())
2324 continue;
2325
2326 if (Predicate.isStore() && Predicate.getMemoryVT() != nullptr) {
2327 Optional<LLTCodeGen> MemTyOrNone =
2328 MVTToLLT(getValueType(Predicate.getMemoryVT()));
2329
2330 if (!MemTyOrNone)
2331 return failedImport("MemVT could not be converted to LLT");
2332
2333 InsnMatcher.getOperand(0).addPredicate<LLTOperandMatcher>(MemTyOrNone.getValue());
2334 continue;
2335 }
2336
Daniel Sanders2c269f62017-08-24 09:11:20 +00002337 return failedImport("Src pattern child has predicate (" +
2338 explainPredicates(Src) + ")");
2339 }
Daniel Sanders39690bd2017-10-15 02:41:12 +00002340 if (SrcGIEquivOrNull && SrcGIEquivOrNull->getValueAsBit("CheckMMOIsNonAtomic"))
2341 InsnMatcher.addPredicate<NonAtomicMMOPredicateMatcher>();
Daniel Sanders2c269f62017-08-24 09:11:20 +00002342
Daniel Sanders452c8ae2017-05-23 19:33:16 +00002343 if (Src->isLeaf()) {
2344 Init *SrcInit = Src->getLeafValue();
2345 if (IntInit *SrcIntInit = dyn_cast<IntInit>(SrcInit)) {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002346 OperandMatcher &OM =
2347 InsnMatcher.addOperand(OpIdx++, Src->getName(), TempOpIdx);
Daniel Sanders452c8ae2017-05-23 19:33:16 +00002348 OM.addPredicate<LiteralIntOperandMatcher>(SrcIntInit->getValue());
2349 } else
Daniel Sanders32291982017-06-28 13:50:04 +00002350 return failedImport(
2351 "Unable to deduce gMIR opcode to handle Src (which is a leaf)");
Daniel Sanders452c8ae2017-05-23 19:33:16 +00002352 } else {
Daniel Sanders85ffd362017-07-06 08:12:20 +00002353 assert(SrcGIOrNull &&
2354 "Expected to have already found an equivalent Instruction");
Daniel Sanders11300ce2017-10-13 21:28:03 +00002355 if (SrcGIOrNull->TheDef->getName() == "G_CONSTANT" ||
2356 SrcGIOrNull->TheDef->getName() == "G_FCONSTANT") {
2357 // imm/fpimm still have operands but we don't need to do anything with it
Daniel Sanders05540042017-08-08 10:44:31 +00002358 // here since we don't support ImmLeaf predicates yet. However, we still
2359 // need to note the hidden operand to get GIM_CheckNumOperands correct.
2360 InsnMatcher.addOperand(OpIdx++, "", TempOpIdx);
2361 return InsnMatcher;
2362 }
2363
Daniel Sanders452c8ae2017-05-23 19:33:16 +00002364 // Match the used operands (i.e. the children of the operator).
2365 for (unsigned i = 0, e = Src->getNumChildren(); i != e; ++i) {
Daniel Sanders85ffd362017-07-06 08:12:20 +00002366 TreePatternNode *SrcChild = Src->getChild(i);
2367
Daniel Sandersa71f4542017-10-16 00:56:30 +00002368 // SelectionDAG allows pointers to be represented with iN since it doesn't
2369 // distinguish between pointers and integers but they are different types in GlobalISel.
2370 // Coerce integers to pointers to address space 0 if the context indicates a pointer.
2371 // TODO: Find a better way to do this, SDTCisPtrTy?
2372 bool OperandIsAPointer =
Daniel Sandersd66e0902017-10-23 18:19:24 +00002373 (SrcGIOrNull->TheDef->getName() == "G_LOAD" && i == 0) ||
2374 (SrcGIOrNull->TheDef->getName() == "G_STORE" && i == 1);
Daniel Sandersa71f4542017-10-16 00:56:30 +00002375
Daniel Sanders28887fe2017-09-19 12:56:36 +00002376 // For G_INTRINSIC/G_INTRINSIC_W_SIDE_EFFECTS, the operand immediately
2377 // following the defs is an intrinsic ID.
2378 if ((SrcGIOrNull->TheDef->getName() == "G_INTRINSIC" ||
2379 SrcGIOrNull->TheDef->getName() == "G_INTRINSIC_W_SIDE_EFFECTS") &&
2380 i == 0) {
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00002381 if (const CodeGenIntrinsic *II = Src->getIntrinsicInfo(CGP)) {
Daniel Sanders85ffd362017-07-06 08:12:20 +00002382 OperandMatcher &OM =
2383 InsnMatcher.addOperand(OpIdx++, SrcChild->getName(), TempOpIdx);
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00002384 OM.addPredicate<IntrinsicIDOperandMatcher>(II);
Daniel Sanders85ffd362017-07-06 08:12:20 +00002385 continue;
2386 }
2387
2388 return failedImport("Expected IntInit containing instrinsic ID)");
2389 }
2390
Daniel Sandersa71f4542017-10-16 00:56:30 +00002391 if (auto Error =
2392 importChildMatcher(Rule, InsnMatcher, SrcChild, OperandIsAPointer,
2393 OpIdx++, TempOpIdx))
Daniel Sanders452c8ae2017-05-23 19:33:16 +00002394 return std::move(Error);
2395 }
Daniel Sandersffc7d582017-03-29 15:37:18 +00002396 }
2397
2398 return InsnMatcher;
2399}
2400
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002401Error GlobalISelEmitter::importComplexPatternOperandMatcher(
2402 OperandMatcher &OM, Record *R, unsigned &TempOpIdx) const {
2403 const auto &ComplexPattern = ComplexPatternEquivs.find(R);
2404 if (ComplexPattern == ComplexPatternEquivs.end())
2405 return failedImport("SelectionDAG ComplexPattern (" + R->getName() +
2406 ") not mapped to GlobalISel");
2407
2408 OM.addPredicate<ComplexPatternOperandMatcher>(OM, *ComplexPattern->second);
2409 TempOpIdx++;
2410 return Error::success();
2411}
2412
2413Error GlobalISelEmitter::importChildMatcher(RuleMatcher &Rule,
2414 InstructionMatcher &InsnMatcher,
Daniel Sanders452c8ae2017-05-23 19:33:16 +00002415 const TreePatternNode *SrcChild,
Daniel Sandersa71f4542017-10-16 00:56:30 +00002416 bool OperandIsAPointer,
Daniel Sandersc270c502017-03-30 09:36:33 +00002417 unsigned OpIdx,
2418 unsigned &TempOpIdx) const {
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002419 OperandMatcher &OM =
2420 InsnMatcher.addOperand(OpIdx, SrcChild->getName(), TempOpIdx);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002421 if (OM.isSameAsAnotherOperand())
2422 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00002423
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002424 ArrayRef<TypeSetByHwMode> ChildTypes = SrcChild->getExtTypes();
Daniel Sandersffc7d582017-03-29 15:37:18 +00002425 if (ChildTypes.size() != 1)
2426 return failedImport("Src pattern child has multiple results");
2427
2428 // Check MBB's before the type check since they are not a known type.
2429 if (!SrcChild->isLeaf()) {
2430 if (SrcChild->getOperator()->isSubClassOf("SDNode")) {
2431 auto &ChildSDNI = CGP.getSDNodeInfo(SrcChild->getOperator());
2432 if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") {
2433 OM.addPredicate<MBBOperandMatcher>();
Daniel Sandersc270c502017-03-30 09:36:33 +00002434 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00002435 }
2436 }
Daniel Sandersffc7d582017-03-29 15:37:18 +00002437 }
2438
Daniel Sandersa71f4542017-10-16 00:56:30 +00002439 if (auto Error =
2440 OM.addTypeCheckPredicate(ChildTypes.front(), OperandIsAPointer))
2441 return failedImport(toString(std::move(Error)) + " for Src operand (" +
2442 to_string(*SrcChild) + ")");
Daniel Sandersffc7d582017-03-29 15:37:18 +00002443
Daniel Sandersbee57392017-04-04 13:25:23 +00002444 // Check for nested instructions.
2445 if (!SrcChild->isLeaf()) {
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002446 if (SrcChild->getOperator()->isSubClassOf("ComplexPattern")) {
2447 // When a ComplexPattern is used as an operator, it should do the same
2448 // thing as when used as a leaf. However, the children of the operator
2449 // name the sub-operands that make up the complex operand and we must
2450 // prepare to reference them in the renderer too.
2451 unsigned RendererID = TempOpIdx;
2452 if (auto Error = importComplexPatternOperandMatcher(
2453 OM, SrcChild->getOperator(), TempOpIdx))
2454 return Error;
2455
2456 for (unsigned i = 0, e = SrcChild->getNumChildren(); i != e; ++i) {
2457 auto *SubOperand = SrcChild->getChild(i);
2458 if (!SubOperand->getName().empty())
2459 Rule.defineComplexSubOperand(SubOperand->getName(),
2460 SrcChild->getOperator(), RendererID, i);
2461 }
2462
2463 return Error::success();
2464 }
2465
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002466 auto MaybeInsnOperand = OM.addPredicate<InstructionOperandMatcher>(
2467 InsnMatcher.getRuleMatcher(), SrcChild->getName());
2468 if (!MaybeInsnOperand.hasValue()) {
2469 // This isn't strictly true. If the user were to provide exactly the same
2470 // matchers as the original operand then we could allow it. However, it's
2471 // simpler to not permit the redundant specification.
2472 return failedImport("Nested instruction cannot be the same as another operand");
2473 }
2474
Daniel Sandersbee57392017-04-04 13:25:23 +00002475 // Map the node to a gMIR instruction.
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002476 InstructionOperandMatcher &InsnOperand = **MaybeInsnOperand;
Daniel Sanders57938df2017-07-11 10:40:18 +00002477 auto InsnMatcherOrError = createAndImportSelDAGMatcher(
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002478 Rule, InsnOperand.getInsnMatcher(), SrcChild, TempOpIdx);
Daniel Sandersbee57392017-04-04 13:25:23 +00002479 if (auto Error = InsnMatcherOrError.takeError())
2480 return Error;
2481
2482 return Error::success();
2483 }
2484
Daniel Sandersffc7d582017-03-29 15:37:18 +00002485 // Check for constant immediates.
2486 if (auto *ChildInt = dyn_cast<IntInit>(SrcChild->getLeafValue())) {
Daniel Sanders452c8ae2017-05-23 19:33:16 +00002487 OM.addPredicate<ConstantIntOperandMatcher>(ChildInt->getValue());
Daniel Sandersc270c502017-03-30 09:36:33 +00002488 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00002489 }
2490
2491 // Check for def's like register classes or ComplexPattern's.
2492 if (auto *ChildDefInit = dyn_cast<DefInit>(SrcChild->getLeafValue())) {
2493 auto *ChildRec = ChildDefInit->getDef();
2494
2495 // Check for register classes.
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002496 if (ChildRec->isSubClassOf("RegisterClass") ||
2497 ChildRec->isSubClassOf("RegisterOperand")) {
Daniel Sandersffc7d582017-03-29 15:37:18 +00002498 OM.addPredicate<RegisterBankOperandMatcher>(
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002499 Target.getRegisterClass(getInitValueAsRegClass(ChildDefInit)));
Daniel Sanders658541f2017-04-22 15:53:21 +00002500 return Error::success();
2501 }
2502
Daniel Sanders4d4e7652017-10-09 18:14:53 +00002503 // Check for ValueType.
2504 if (ChildRec->isSubClassOf("ValueType")) {
2505 // We already added a type check as standard practice so this doesn't need
2506 // to do anything.
2507 return Error::success();
2508 }
2509
Daniel Sandersffc7d582017-03-29 15:37:18 +00002510 // Check for ComplexPattern's.
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002511 if (ChildRec->isSubClassOf("ComplexPattern"))
2512 return importComplexPatternOperandMatcher(OM, ChildRec, TempOpIdx);
Daniel Sandersffc7d582017-03-29 15:37:18 +00002513
Daniel Sandersd0656a32017-04-13 09:45:37 +00002514 if (ChildRec->isSubClassOf("ImmLeaf")) {
2515 return failedImport(
2516 "Src pattern child def is an unsupported tablegen class (ImmLeaf)");
2517 }
2518
Daniel Sandersffc7d582017-03-29 15:37:18 +00002519 return failedImport(
2520 "Src pattern child def is an unsupported tablegen class");
2521 }
2522
2523 return failedImport("Src pattern child is an unsupported kind");
2524}
2525
Daniel Sandersc270c502017-03-30 09:36:33 +00002526Error GlobalISelEmitter::importExplicitUseRenderer(
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002527 RuleMatcher &Rule, BuildMIAction &DstMIBuilder, TreePatternNode *DstChild,
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002528 const InstructionMatcher &InsnMatcher) const {
Daniel Sanders2c269f62017-08-24 09:11:20 +00002529 if (DstChild->getTransformFn() != nullptr) {
2530 return failedImport("Dst pattern child has transform fn " +
2531 DstChild->getTransformFn()->getName());
2532 }
2533
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002534 const auto &SubOperand = Rule.getComplexSubOperand(DstChild->getName());
2535 if (SubOperand.hasValue()) {
2536 DstMIBuilder.addRenderer<RenderComplexPatternOperand>(
2537 0, *std::get<0>(*SubOperand), DstChild->getName(),
2538 std::get<1>(*SubOperand), std::get<2>(*SubOperand));
2539 return Error::success();
2540 }
2541
Daniel Sandersffc7d582017-03-29 15:37:18 +00002542 if (!DstChild->isLeaf()) {
Daniel Sanders05540042017-08-08 10:44:31 +00002543 // We accept 'bb' here. It's an operator because BasicBlockSDNode isn't
2544 // inline, but in MI it's just another operand.
Daniel Sandersffc7d582017-03-29 15:37:18 +00002545 if (DstChild->getOperator()->isSubClassOf("SDNode")) {
2546 auto &ChildSDNI = CGP.getSDNodeInfo(DstChild->getOperator());
2547 if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") {
Daniel Sandersbd83ad42017-10-24 01:48:34 +00002548 DstMIBuilder.addRenderer<CopyRenderer>(0, DstChild->getName());
Daniel Sandersc270c502017-03-30 09:36:33 +00002549 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00002550 }
2551 }
Daniel Sanders05540042017-08-08 10:44:31 +00002552
2553 // Similarly, imm is an operator in TreePatternNode's view but must be
2554 // rendered as operands.
2555 // FIXME: The target should be able to choose sign-extended when appropriate
2556 // (e.g. on Mips).
2557 if (DstChild->getOperator()->getName() == "imm") {
2558 DstMIBuilder.addRenderer<CopyConstantAsImmRenderer>(0,
2559 DstChild->getName());
2560 return Error::success();
Daniel Sanders11300ce2017-10-13 21:28:03 +00002561 } else if (DstChild->getOperator()->getName() == "fpimm") {
2562 DstMIBuilder.addRenderer<CopyFConstantAsFPImmRenderer>(
2563 0, DstChild->getName());
2564 return Error::success();
Daniel Sanders05540042017-08-08 10:44:31 +00002565 }
2566
Daniel Sanders2c269f62017-08-24 09:11:20 +00002567 return failedImport("Dst pattern child isn't a leaf node or an MBB" + llvm::to_string(*DstChild));
Daniel Sandersffc7d582017-03-29 15:37:18 +00002568 }
2569
2570 // Otherwise, we're looking for a bog-standard RegisterClass operand.
Daniel Sandersffc7d582017-03-29 15:37:18 +00002571 if (auto *ChildDefInit = dyn_cast<DefInit>(DstChild->getLeafValue())) {
2572 auto *ChildRec = ChildDefInit->getDef();
2573
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002574 ArrayRef<TypeSetByHwMode> ChildTypes = DstChild->getExtTypes();
Daniel Sandersffc7d582017-03-29 15:37:18 +00002575 if (ChildTypes.size() != 1)
2576 return failedImport("Dst pattern child has multiple results");
2577
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002578 Optional<LLTCodeGen> OpTyOrNone = None;
2579 if (ChildTypes.front().isMachineValueType())
2580 OpTyOrNone = MVTToLLT(ChildTypes.front().getMachineValueType().SimpleTy);
Daniel Sandersffc7d582017-03-29 15:37:18 +00002581 if (!OpTyOrNone)
2582 return failedImport("Dst operand has an unsupported type");
2583
2584 if (ChildRec->isSubClassOf("Register")) {
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002585 DstMIBuilder.addRenderer<AddRegisterRenderer>(0, ChildRec);
Daniel Sandersc270c502017-03-30 09:36:33 +00002586 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00002587 }
2588
Daniel Sanders658541f2017-04-22 15:53:21 +00002589 if (ChildRec->isSubClassOf("RegisterClass") ||
Daniel Sanders4d4e7652017-10-09 18:14:53 +00002590 ChildRec->isSubClassOf("RegisterOperand") ||
2591 ChildRec->isSubClassOf("ValueType")) {
Daniel Sandersd66e0902017-10-23 18:19:24 +00002592 if (ChildRec->isSubClassOf("RegisterOperand") &&
2593 !ChildRec->isValueUnset("GIZeroRegister")) {
2594 DstMIBuilder.addRenderer<CopyOrAddZeroRegRenderer>(
Daniel Sandersbd83ad42017-10-24 01:48:34 +00002595 0, DstChild->getName(), ChildRec->getValueAsDef("GIZeroRegister"));
Daniel Sandersd66e0902017-10-23 18:19:24 +00002596 return Error::success();
2597 }
2598
Daniel Sandersbd83ad42017-10-24 01:48:34 +00002599 DstMIBuilder.addRenderer<CopyRenderer>(0, DstChild->getName());
Daniel Sandersc270c502017-03-30 09:36:33 +00002600 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00002601 }
2602
2603 if (ChildRec->isSubClassOf("ComplexPattern")) {
2604 const auto &ComplexPattern = ComplexPatternEquivs.find(ChildRec);
2605 if (ComplexPattern == ComplexPatternEquivs.end())
2606 return failedImport(
2607 "SelectionDAG ComplexPattern not mapped to GlobalISel");
2608
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002609 const OperandMatcher &OM = Rule.getOperandMatcher(DstChild->getName());
Daniel Sandersffc7d582017-03-29 15:37:18 +00002610 DstMIBuilder.addRenderer<RenderComplexPatternOperand>(
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002611 0, *ComplexPattern->second, DstChild->getName(),
Daniel Sanders2deea182017-04-22 15:11:04 +00002612 OM.getAllocatedTemporariesBaseID());
Daniel Sandersc270c502017-03-30 09:36:33 +00002613 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00002614 }
2615
Daniel Sandersd0656a32017-04-13 09:45:37 +00002616 if (ChildRec->isSubClassOf("SDNodeXForm"))
2617 return failedImport("Dst pattern child def is an unsupported tablegen "
2618 "class (SDNodeXForm)");
2619
Daniel Sandersffc7d582017-03-29 15:37:18 +00002620 return failedImport(
2621 "Dst pattern child def is an unsupported tablegen class");
2622 }
2623
2624 return failedImport("Dst pattern child is an unsupported kind");
2625}
2626
Daniel Sandersc270c502017-03-30 09:36:33 +00002627Expected<BuildMIAction &> GlobalISelEmitter::createAndImportInstructionRenderer(
Daniel Sandersffc7d582017-03-29 15:37:18 +00002628 RuleMatcher &M, const TreePatternNode *Dst,
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002629 const InstructionMatcher &InsnMatcher) {
Daniel Sandersffc7d582017-03-29 15:37:18 +00002630 Record *DstOp = Dst->getOperator();
Daniel Sandersd0656a32017-04-13 09:45:37 +00002631 if (!DstOp->isSubClassOf("Instruction")) {
2632 if (DstOp->isSubClassOf("ValueType"))
2633 return failedImport(
2634 "Pattern operator isn't an instruction (it's a ValueType)");
Daniel Sandersffc7d582017-03-29 15:37:18 +00002635 return failedImport("Pattern operator isn't an instruction");
Daniel Sandersd0656a32017-04-13 09:45:37 +00002636 }
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002637 CodeGenInstruction *DstI = &Target.getInstruction(DstOp);
Daniel Sandersffc7d582017-03-29 15:37:18 +00002638
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002639 unsigned DstINumUses = DstI->Operands.size() - DstI->Operands.NumDefs;
2640 unsigned ExpectedDstINumUses = Dst->getNumChildren();
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002641 bool IsExtractSubReg = false;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002642
2643 // COPY_TO_REGCLASS is just a copy with a ConstrainOperandToRegClassAction
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002644 // attached. Similarly for EXTRACT_SUBREG except that's a subregister copy.
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002645 if (DstI->TheDef->getName() == "COPY_TO_REGCLASS") {
2646 DstI = &Target.getInstruction(RK.getDef("COPY"));
2647 DstINumUses--; // Ignore the class constraint.
2648 ExpectedDstINumUses--;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002649 } else if (DstI->TheDef->getName() == "EXTRACT_SUBREG") {
2650 DstI = &Target.getInstruction(RK.getDef("COPY"));
2651 IsExtractSubReg = true;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002652 }
2653
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002654 auto &DstMIBuilder = M.addAction<BuildMIAction>(0, DstI, InsnMatcher);
Daniel Sandersffc7d582017-03-29 15:37:18 +00002655
2656 // Render the explicit defs.
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002657 for (unsigned I = 0; I < DstI->Operands.NumDefs; ++I) {
2658 const CGIOperandList::OperandInfo &DstIOperand = DstI->Operands[I];
Daniel Sandersbd83ad42017-10-24 01:48:34 +00002659 DstMIBuilder.addRenderer<CopyRenderer>(0, DstIOperand.Name);
Daniel Sandersffc7d582017-03-29 15:37:18 +00002660 }
2661
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002662 // EXTRACT_SUBREG needs to use a subregister COPY.
2663 if (IsExtractSubReg) {
2664 if (!Dst->getChild(0)->isLeaf())
2665 return failedImport("EXTRACT_SUBREG child #1 is not a leaf");
2666
Daniel Sanders32291982017-06-28 13:50:04 +00002667 if (DefInit *SubRegInit =
2668 dyn_cast<DefInit>(Dst->getChild(1)->getLeafValue())) {
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002669 CodeGenRegisterClass *RC = CGRegs.getRegClass(
2670 getInitValueAsRegClass(Dst->getChild(0)->getLeafValue()));
2671 CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef());
2672
2673 const auto &SrcRCDstRCPair =
2674 RC->getMatchingSubClassWithSubRegs(CGRegs, SubIdx);
2675 if (SrcRCDstRCPair.hasValue()) {
2676 assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
2677 if (SrcRCDstRCPair->first != RC)
2678 return failedImport("EXTRACT_SUBREG requires an additional COPY");
2679 }
2680
2681 DstMIBuilder.addRenderer<CopySubRegRenderer>(
Daniel Sandersbd83ad42017-10-24 01:48:34 +00002682 0, Dst->getChild(0)->getName(), SubIdx);
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002683 return DstMIBuilder;
2684 }
2685
2686 return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
2687 }
2688
Daniel Sandersffc7d582017-03-29 15:37:18 +00002689 // Render the explicit uses.
Daniel Sanders0ed28822017-04-12 08:23:08 +00002690 unsigned Child = 0;
Diana Picus382602f2017-05-17 08:57:28 +00002691 unsigned NumDefaultOps = 0;
Daniel Sanders0ed28822017-04-12 08:23:08 +00002692 for (unsigned I = 0; I != DstINumUses; ++I) {
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002693 const CGIOperandList::OperandInfo &DstIOperand =
2694 DstI->Operands[DstI->Operands.NumDefs + I];
Daniel Sanders0ed28822017-04-12 08:23:08 +00002695
Diana Picus382602f2017-05-17 08:57:28 +00002696 // If the operand has default values, introduce them now.
2697 // FIXME: Until we have a decent test case that dictates we should do
2698 // otherwise, we're going to assume that operands with default values cannot
2699 // be specified in the patterns. Therefore, adding them will not cause us to
2700 // end up with too many rendered operands.
2701 if (DstIOperand.Rec->isSubClassOf("OperandWithDefaultOps")) {
Daniel Sanders0ed28822017-04-12 08:23:08 +00002702 DagInit *DefaultOps = DstIOperand.Rec->getValueAsDag("DefaultOps");
Diana Picus382602f2017-05-17 08:57:28 +00002703 if (auto Error = importDefaultOperandRenderers(DstMIBuilder, DefaultOps))
2704 return std::move(Error);
2705 ++NumDefaultOps;
Daniel Sanders0ed28822017-04-12 08:23:08 +00002706 continue;
2707 }
2708
2709 if (auto Error = importExplicitUseRenderer(
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002710 M, DstMIBuilder, Dst->getChild(Child), InsnMatcher))
Daniel Sandersffc7d582017-03-29 15:37:18 +00002711 return std::move(Error);
Daniel Sanders0ed28822017-04-12 08:23:08 +00002712 ++Child;
Daniel Sandersffc7d582017-03-29 15:37:18 +00002713 }
2714
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002715 if (NumDefaultOps + ExpectedDstINumUses != DstINumUses)
Diana Picuseb2057c2017-05-17 09:25:08 +00002716 return failedImport("Expected " + llvm::to_string(DstINumUses) +
Diana Picus382602f2017-05-17 08:57:28 +00002717 " used operands but found " +
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002718 llvm::to_string(ExpectedDstINumUses) +
Diana Picuseb2057c2017-05-17 09:25:08 +00002719 " explicit ones and " + llvm::to_string(NumDefaultOps) +
Diana Picus382602f2017-05-17 08:57:28 +00002720 " default ones");
2721
Daniel Sandersffc7d582017-03-29 15:37:18 +00002722 return DstMIBuilder;
2723}
2724
Diana Picus382602f2017-05-17 08:57:28 +00002725Error GlobalISelEmitter::importDefaultOperandRenderers(
2726 BuildMIAction &DstMIBuilder, DagInit *DefaultOps) const {
Craig Topper481ff702017-05-29 21:49:34 +00002727 for (const auto *DefaultOp : DefaultOps->getArgs()) {
Diana Picus382602f2017-05-17 08:57:28 +00002728 // Look through ValueType operators.
2729 if (const DagInit *DefaultDagOp = dyn_cast<DagInit>(DefaultOp)) {
2730 if (const DefInit *DefaultDagOperator =
2731 dyn_cast<DefInit>(DefaultDagOp->getOperator())) {
2732 if (DefaultDagOperator->getDef()->isSubClassOf("ValueType"))
2733 DefaultOp = DefaultDagOp->getArg(0);
2734 }
2735 }
2736
2737 if (const DefInit *DefaultDefOp = dyn_cast<DefInit>(DefaultOp)) {
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002738 DstMIBuilder.addRenderer<AddRegisterRenderer>(0, DefaultDefOp->getDef());
Diana Picus382602f2017-05-17 08:57:28 +00002739 continue;
2740 }
2741
2742 if (const IntInit *DefaultIntOp = dyn_cast<IntInit>(DefaultOp)) {
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002743 DstMIBuilder.addRenderer<ImmRenderer>(0, DefaultIntOp->getValue());
Diana Picus382602f2017-05-17 08:57:28 +00002744 continue;
2745 }
2746
2747 return failedImport("Could not add default op");
2748 }
2749
2750 return Error::success();
2751}
2752
Daniel Sandersc270c502017-03-30 09:36:33 +00002753Error GlobalISelEmitter::importImplicitDefRenderers(
Daniel Sandersffc7d582017-03-29 15:37:18 +00002754 BuildMIAction &DstMIBuilder,
2755 const std::vector<Record *> &ImplicitDefs) const {
2756 if (!ImplicitDefs.empty())
2757 return failedImport("Pattern defines a physical register");
Daniel Sandersc270c502017-03-30 09:36:33 +00002758 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00002759}
2760
2761Expected<RuleMatcher> GlobalISelEmitter::runOnPattern(const PatternToMatch &P) {
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002762 // Keep track of the matchers and actions to emit.
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002763 RuleMatcher M(P.getSrcRecord()->getLoc());
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +00002764 M.addAction<DebugCommentAction>(P);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002765
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002766 if (auto Error = importRulePredicates(M, P.getPredicates()))
Daniel Sandersffc7d582017-03-29 15:37:18 +00002767 return std::move(Error);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002768
2769 // Next, analyze the pattern operators.
2770 TreePatternNode *Src = P.getSrcPattern();
2771 TreePatternNode *Dst = P.getDstPattern();
2772
2773 // If the root of either pattern isn't a simple operator, ignore it.
Daniel Sandersd0656a32017-04-13 09:45:37 +00002774 if (auto Err = isTrivialOperatorNode(Dst))
2775 return failedImport("Dst pattern root isn't a trivial operator (" +
2776 toString(std::move(Err)) + ")");
2777 if (auto Err = isTrivialOperatorNode(Src))
2778 return failedImport("Src pattern root isn't a trivial operator (" +
2779 toString(std::move(Err)) + ")");
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002780
Daniel Sandersedd07842017-08-17 09:26:14 +00002781 InstructionMatcher &InsnMatcherTemp = M.addInstructionMatcher(Src->getName());
2782 unsigned TempOpIdx = 0;
2783 auto InsnMatcherOrError =
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002784 createAndImportSelDAGMatcher(M, InsnMatcherTemp, Src, TempOpIdx);
Daniel Sandersedd07842017-08-17 09:26:14 +00002785 if (auto Error = InsnMatcherOrError.takeError())
2786 return std::move(Error);
2787 InstructionMatcher &InsnMatcher = InsnMatcherOrError.get();
2788
2789 if (Dst->isLeaf()) {
2790 Record *RCDef = getInitValueAsRegClass(Dst->getLeafValue());
2791
2792 const CodeGenRegisterClass &RC = Target.getRegisterClass(RCDef);
2793 if (RCDef) {
2794 // We need to replace the def and all its uses with the specified
2795 // operand. However, we must also insert COPY's wherever needed.
2796 // For now, emit a copy and let the register allocator clean up.
2797 auto &DstI = Target.getInstruction(RK.getDef("COPY"));
2798 const auto &DstIOperand = DstI.Operands[0];
2799
2800 OperandMatcher &OM0 = InsnMatcher.getOperand(0);
2801 OM0.setSymbolicName(DstIOperand.Name);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002802 M.defineOperand(OM0.getSymbolicName(), OM0);
Daniel Sandersedd07842017-08-17 09:26:14 +00002803 OM0.addPredicate<RegisterBankOperandMatcher>(RC);
2804
2805 auto &DstMIBuilder = M.addAction<BuildMIAction>(0, &DstI, InsnMatcher);
Daniel Sandersbd83ad42017-10-24 01:48:34 +00002806 DstMIBuilder.addRenderer<CopyRenderer>(0, DstIOperand.Name);
2807 DstMIBuilder.addRenderer<CopyRenderer>(0, Dst->getName());
Daniel Sandersedd07842017-08-17 09:26:14 +00002808 M.addAction<ConstrainOperandToRegClassAction>(0, 0, RC);
2809
2810 // We're done with this pattern! It's eligible for GISel emission; return
2811 // it.
2812 ++NumPatternImported;
2813 return std::move(M);
2814 }
2815
Daniel Sanders452c8ae2017-05-23 19:33:16 +00002816 return failedImport("Dst pattern root isn't a known leaf");
Daniel Sandersedd07842017-08-17 09:26:14 +00002817 }
Daniel Sanders452c8ae2017-05-23 19:33:16 +00002818
Daniel Sandersbee57392017-04-04 13:25:23 +00002819 // Start with the defined operands (i.e., the results of the root operator).
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002820 Record *DstOp = Dst->getOperator();
2821 if (!DstOp->isSubClassOf("Instruction"))
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002822 return failedImport("Pattern operator isn't an instruction");
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002823
2824 auto &DstI = Target.getInstruction(DstOp);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002825 if (DstI.Operands.NumDefs != Src->getExtTypes().size())
Daniel Sandersd0656a32017-04-13 09:45:37 +00002826 return failedImport("Src pattern results and dst MI defs are different (" +
2827 to_string(Src->getExtTypes().size()) + " def(s) vs " +
2828 to_string(DstI.Operands.NumDefs) + " def(s))");
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002829
Daniel Sandersffc7d582017-03-29 15:37:18 +00002830 // The root of the match also has constraints on the register bank so that it
2831 // matches the result instruction.
2832 unsigned OpIdx = 0;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002833 for (const TypeSetByHwMode &VTy : Src->getExtTypes()) {
2834 (void)VTy;
Daniel Sandersffc7d582017-03-29 15:37:18 +00002835
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002836 const auto &DstIOperand = DstI.Operands[OpIdx];
2837 Record *DstIOpRec = DstIOperand.Rec;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002838 if (DstI.TheDef->getName() == "COPY_TO_REGCLASS") {
2839 DstIOpRec = getInitValueAsRegClass(Dst->getChild(1)->getLeafValue());
2840
2841 if (DstIOpRec == nullptr)
2842 return failedImport(
2843 "COPY_TO_REGCLASS operand #1 isn't a register class");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002844 } else if (DstI.TheDef->getName() == "EXTRACT_SUBREG") {
2845 if (!Dst->getChild(0)->isLeaf())
2846 return failedImport("EXTRACT_SUBREG operand #0 isn't a leaf");
2847
Daniel Sanders32291982017-06-28 13:50:04 +00002848 // We can assume that a subregister is in the same bank as it's super
2849 // register.
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002850 DstIOpRec = getInitValueAsRegClass(Dst->getChild(0)->getLeafValue());
2851
2852 if (DstIOpRec == nullptr)
2853 return failedImport(
2854 "EXTRACT_SUBREG operand #0 isn't a register class");
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002855 } else if (DstIOpRec->isSubClassOf("RegisterOperand"))
Daniel Sanders658541f2017-04-22 15:53:21 +00002856 DstIOpRec = DstIOpRec->getValueAsDef("RegClass");
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002857 else if (!DstIOpRec->isSubClassOf("RegisterClass"))
Daniel Sanders32291982017-06-28 13:50:04 +00002858 return failedImport("Dst MI def isn't a register class" +
2859 to_string(*Dst));
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002860
Daniel Sandersffc7d582017-03-29 15:37:18 +00002861 OperandMatcher &OM = InsnMatcher.getOperand(OpIdx);
2862 OM.setSymbolicName(DstIOperand.Name);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002863 M.defineOperand(OM.getSymbolicName(), OM);
Daniel Sandersdc662ff2017-01-26 11:10:14 +00002864 OM.addPredicate<RegisterBankOperandMatcher>(
2865 Target.getRegisterClass(DstIOpRec));
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002866 ++OpIdx;
2867 }
2868
Daniel Sandersc270c502017-03-30 09:36:33 +00002869 auto DstMIBuilderOrError =
2870 createAndImportInstructionRenderer(M, Dst, InsnMatcher);
Daniel Sandersffc7d582017-03-29 15:37:18 +00002871 if (auto Error = DstMIBuilderOrError.takeError())
2872 return std::move(Error);
2873 BuildMIAction &DstMIBuilder = DstMIBuilderOrError.get();
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002874
Daniel Sandersffc7d582017-03-29 15:37:18 +00002875 // Render the implicit defs.
2876 // These are only added to the root of the result.
Daniel Sandersc270c502017-03-30 09:36:33 +00002877 if (auto Error = importImplicitDefRenderers(DstMIBuilder, P.getDstRegs()))
Daniel Sandersffc7d582017-03-29 15:37:18 +00002878 return std::move(Error);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002879
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002880 // Constrain the registers to classes. This is normally derived from the
2881 // emitted instruction but a few instructions require special handling.
2882 if (DstI.TheDef->getName() == "COPY_TO_REGCLASS") {
2883 // COPY_TO_REGCLASS does not provide operand constraints itself but the
2884 // result is constrained to the class given by the second child.
2885 Record *DstIOpRec =
2886 getInitValueAsRegClass(Dst->getChild(1)->getLeafValue());
2887
2888 if (DstIOpRec == nullptr)
2889 return failedImport("COPY_TO_REGCLASS operand #1 isn't a register class");
2890
2891 M.addAction<ConstrainOperandToRegClassAction>(
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002892 0, 0, Target.getRegisterClass(DstIOpRec));
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002893
2894 // We're done with this pattern! It's eligible for GISel emission; return
2895 // it.
2896 ++NumPatternImported;
2897 return std::move(M);
2898 }
2899
2900 if (DstI.TheDef->getName() == "EXTRACT_SUBREG") {
2901 // EXTRACT_SUBREG selects into a subregister COPY but unlike most
2902 // instructions, the result register class is controlled by the
2903 // subregisters of the operand. As a result, we must constrain the result
2904 // class rather than check that it's already the right one.
2905 if (!Dst->getChild(0)->isLeaf())
2906 return failedImport("EXTRACT_SUBREG child #1 is not a leaf");
2907
Daniel Sanders320390b2017-06-28 15:16:03 +00002908 DefInit *SubRegInit = dyn_cast<DefInit>(Dst->getChild(1)->getLeafValue());
2909 if (!SubRegInit)
2910 return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002911
Daniel Sanders320390b2017-06-28 15:16:03 +00002912 // Constrain the result to the same register bank as the operand.
2913 Record *DstIOpRec =
2914 getInitValueAsRegClass(Dst->getChild(0)->getLeafValue());
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002915
Daniel Sanders320390b2017-06-28 15:16:03 +00002916 if (DstIOpRec == nullptr)
2917 return failedImport("EXTRACT_SUBREG operand #1 isn't a register class");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002918
Daniel Sanders320390b2017-06-28 15:16:03 +00002919 CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef());
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002920 CodeGenRegisterClass *SrcRC = CGRegs.getRegClass(DstIOpRec);
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002921
Daniel Sanders320390b2017-06-28 15:16:03 +00002922 // It would be nice to leave this constraint implicit but we're required
2923 // to pick a register class so constrain the result to a register class
2924 // that can hold the correct MVT.
2925 //
2926 // FIXME: This may introduce an extra copy if the chosen class doesn't
2927 // actually contain the subregisters.
2928 assert(Src->getExtTypes().size() == 1 &&
2929 "Expected Src of EXTRACT_SUBREG to have one result type");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002930
Daniel Sanders320390b2017-06-28 15:16:03 +00002931 const auto &SrcRCDstRCPair =
2932 SrcRC->getMatchingSubClassWithSubRegs(CGRegs, SubIdx);
2933 assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002934 M.addAction<ConstrainOperandToRegClassAction>(0, 0, *SrcRCDstRCPair->second);
2935 M.addAction<ConstrainOperandToRegClassAction>(0, 1, *SrcRCDstRCPair->first);
2936
2937 // We're done with this pattern! It's eligible for GISel emission; return
2938 // it.
2939 ++NumPatternImported;
2940 return std::move(M);
2941 }
2942
2943 M.addAction<ConstrainOperandsToDefinitionAction>(0);
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002944
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002945 // We're done with this pattern! It's eligible for GISel emission; return it.
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00002946 ++NumPatternImported;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002947 return std::move(M);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002948}
2949
Daniel Sanders649c5852017-10-13 20:42:18 +00002950// Emit imm predicate table and an enum to reference them with.
2951// The 'Predicate_' part of the name is redundant but eliminating it is more
2952// trouble than it's worth.
2953void GlobalISelEmitter::emitImmPredicates(
Daniel Sanders11300ce2017-10-13 21:28:03 +00002954 raw_ostream &OS, StringRef TypeIdentifier, StringRef Type,
2955 std::function<bool(const Record *R)> Filter) {
Daniel Sanders649c5852017-10-13 20:42:18 +00002956 std::vector<const Record *> MatchedRecords;
2957 const auto &Defs = RK.getAllDerivedDefinitions("PatFrag");
2958 std::copy_if(Defs.begin(), Defs.end(), std::back_inserter(MatchedRecords),
2959 [&](Record *Record) {
2960 return !Record->getValueAsString("ImmediateCode").empty() &&
2961 Filter(Record);
2962 });
2963
Daniel Sanders11300ce2017-10-13 21:28:03 +00002964 if (!MatchedRecords.empty()) {
2965 OS << "// PatFrag predicates.\n"
2966 << "enum {\n";
Daniel Sanders2fed4ff2017-10-13 21:51:20 +00002967 std::string EnumeratorSeparator =
Daniel Sanders11300ce2017-10-13 21:28:03 +00002968 (" = GIPFP_" + TypeIdentifier + "_Invalid + 1,\n").str();
2969 for (const auto *Record : MatchedRecords) {
2970 OS << " GIPFP_" << TypeIdentifier << "_Predicate_" << Record->getName()
2971 << EnumeratorSeparator;
2972 EnumeratorSeparator = ",\n";
2973 }
2974 OS << "};\n";
Daniel Sanders649c5852017-10-13 20:42:18 +00002975 }
Daniel Sanders11300ce2017-10-13 21:28:03 +00002976
Daniel Sanders649c5852017-10-13 20:42:18 +00002977 for (const auto *Record : MatchedRecords)
Daniel Sanders11300ce2017-10-13 21:28:03 +00002978 OS << "static bool Predicate_" << Record->getName() << "(" << Type
2979 << " Imm) {" << Record->getValueAsString("ImmediateCode") << "}\n";
2980
2981 OS << "static InstructionSelector::" << TypeIdentifier
2982 << "ImmediatePredicateFn " << TypeIdentifier << "ImmPredicateFns[] = {\n"
Daniel Sanders649c5852017-10-13 20:42:18 +00002983 << " nullptr,\n";
2984 for (const auto *Record : MatchedRecords)
2985 OS << " Predicate_" << Record->getName() << ",\n";
2986 OS << "};\n";
2987}
2988
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002989void GlobalISelEmitter::run(raw_ostream &OS) {
2990 // Track the GINodeEquiv definitions.
2991 gatherNodeEquivs();
2992
2993 emitSourceFileHeader(("Global Instruction Selector for the " +
2994 Target.getName() + " target").str(), OS);
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00002995 std::vector<RuleMatcher> Rules;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002996 // Look through the SelectionDAG patterns we found, possibly emitting some.
2997 for (const PatternToMatch &Pat : CGP.ptms()) {
2998 ++NumPatternTotal;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002999 auto MatcherOrErr = runOnPattern(Pat);
3000
3001 // The pattern analysis can fail, indicating an unsupported pattern.
3002 // Report that if we've been asked to do so.
3003 if (auto Err = MatcherOrErr.takeError()) {
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003004 if (WarnOnSkippedPatterns) {
3005 PrintWarning(Pat.getSrcRecord()->getLoc(),
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003006 "Skipped pattern: " + toString(std::move(Err)));
3007 } else {
3008 consumeError(std::move(Err));
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003009 }
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00003010 ++NumPatternImportsSkipped;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003011 continue;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003012 }
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003013
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00003014 Rules.push_back(std::move(MatcherOrErr.get()));
3015 }
3016
Daniel Sanderseb2f5f32017-08-15 15:10:31 +00003017 std::stable_sort(Rules.begin(), Rules.end(),
3018 [&](const RuleMatcher &A, const RuleMatcher &B) {
3019 if (A.isHigherPriorityThan(B)) {
3020 assert(!B.isHigherPriorityThan(A) && "Cannot be more important "
3021 "and less important at "
3022 "the same time");
3023 return true;
3024 }
3025 return false;
3026 });
Daniel Sanders759ff412017-02-24 13:58:11 +00003027
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003028 std::vector<Record *> ComplexPredicates =
3029 RK.getAllDerivedDefinitions("GIComplexOperandMatcher");
3030 std::sort(ComplexPredicates.begin(), ComplexPredicates.end(),
3031 [](const Record *A, const Record *B) {
3032 if (A->getName() < B->getName())
3033 return true;
3034 return false;
3035 });
Daniel Sanders8a4bae92017-03-14 21:32:08 +00003036 unsigned MaxTemporaries = 0;
3037 for (const auto &Rule : Rules)
Daniel Sanders2deea182017-04-22 15:11:04 +00003038 MaxTemporaries = std::max(MaxTemporaries, Rule.countRendererFns());
Daniel Sanders8a4bae92017-03-14 21:32:08 +00003039
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003040 OS << "#ifdef GET_GLOBALISEL_PREDICATE_BITSET\n"
3041 << "const unsigned MAX_SUBTARGET_PREDICATES = " << SubtargetFeatures.size()
3042 << ";\n"
3043 << "using PredicateBitset = "
3044 "llvm::PredicateBitsetImpl<MAX_SUBTARGET_PREDICATES>;\n"
3045 << "#endif // ifdef GET_GLOBALISEL_PREDICATE_BITSET\n\n";
3046
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003047 OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n"
3048 << " mutable MatcherState State;\n"
3049 << " typedef "
Daniel Sanders1e4569f2017-10-20 20:55:29 +00003050 "ComplexRendererFns("
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003051 << Target.getName()
3052 << "InstructionSelector::*ComplexMatcherMemFn)(MachineOperand &) const;\n"
Daniel Sandersea8711b2017-10-16 03:36:29 +00003053 << " const MatcherInfoTy<PredicateBitset, ComplexMatcherMemFn> "
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003054 "MatcherInfo;\n"
Daniel Sandersea8711b2017-10-16 03:36:29 +00003055 << " static " << Target.getName()
3056 << "InstructionSelector::ComplexMatcherMemFn ComplexPredicateFns[];\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003057 << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n\n";
Daniel Sanders8a4bae92017-03-14 21:32:08 +00003058
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003059 OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n"
3060 << ", State(" << MaxTemporaries << "),\n"
Daniel Sanders11300ce2017-10-13 21:28:03 +00003061 << "MatcherInfo({TypeObjects, FeatureBitsets, I64ImmPredicateFns, "
Daniel Sandersea8711b2017-10-16 03:36:29 +00003062 "APIntImmPredicateFns, APFloatImmPredicateFns, ComplexPredicateFns})\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003063 << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n\n";
Daniel Sanders8a4bae92017-03-14 21:32:08 +00003064
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003065 OS << "#ifdef GET_GLOBALISEL_IMPL\n";
3066 SubtargetFeatureInfo::emitSubtargetFeatureBitEnumeration(SubtargetFeatures,
3067 OS);
Daniel Sanderse9fdba32017-04-29 17:30:09 +00003068
3069 // Separate subtarget features by how often they must be recomputed.
3070 SubtargetFeatureInfoMap ModuleFeatures;
3071 std::copy_if(SubtargetFeatures.begin(), SubtargetFeatures.end(),
3072 std::inserter(ModuleFeatures, ModuleFeatures.end()),
3073 [](const SubtargetFeatureInfoMap::value_type &X) {
3074 return !X.second.mustRecomputePerFunction();
3075 });
3076 SubtargetFeatureInfoMap FunctionFeatures;
3077 std::copy_if(SubtargetFeatures.begin(), SubtargetFeatures.end(),
3078 std::inserter(FunctionFeatures, FunctionFeatures.end()),
3079 [](const SubtargetFeatureInfoMap::value_type &X) {
3080 return X.second.mustRecomputePerFunction();
3081 });
3082
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003083 SubtargetFeatureInfo::emitComputeAvailableFeatures(
Daniel Sanderse9fdba32017-04-29 17:30:09 +00003084 Target.getName(), "InstructionSelector", "computeAvailableModuleFeatures",
3085 ModuleFeatures, OS);
3086 SubtargetFeatureInfo::emitComputeAvailableFeatures(
3087 Target.getName(), "InstructionSelector",
3088 "computeAvailableFunctionFeatures", FunctionFeatures, OS,
3089 "const MachineFunction *MF");
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003090
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003091 // Emit a table containing the LLT objects needed by the matcher and an enum
3092 // for the matcher to reference them with.
Daniel Sanders032e7f22017-08-17 13:18:35 +00003093 std::vector<LLTCodeGen> TypeObjects;
3094 for (const auto &Ty : LLTOperandMatcher::KnownTypes)
3095 TypeObjects.push_back(Ty);
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003096 std::sort(TypeObjects.begin(), TypeObjects.end());
Daniel Sanders49980702017-08-23 10:09:25 +00003097 OS << "// LLT Objects.\n"
3098 << "enum {\n";
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003099 for (const auto &TypeObject : TypeObjects) {
3100 OS << " ";
3101 TypeObject.emitCxxEnumValue(OS);
3102 OS << ",\n";
3103 }
3104 OS << "};\n"
3105 << "const static LLT TypeObjects[] = {\n";
3106 for (const auto &TypeObject : TypeObjects) {
3107 OS << " ";
3108 TypeObject.emitCxxConstructorCall(OS);
3109 OS << ",\n";
3110 }
3111 OS << "};\n\n";
3112
3113 // Emit a table containing the PredicateBitsets objects needed by the matcher
3114 // and an enum for the matcher to reference them with.
3115 std::vector<std::vector<Record *>> FeatureBitsets;
3116 for (auto &Rule : Rules)
3117 FeatureBitsets.push_back(Rule.getRequiredFeatures());
3118 std::sort(
3119 FeatureBitsets.begin(), FeatureBitsets.end(),
3120 [&](const std::vector<Record *> &A, const std::vector<Record *> &B) {
3121 if (A.size() < B.size())
3122 return true;
3123 if (A.size() > B.size())
3124 return false;
3125 for (const auto &Pair : zip(A, B)) {
3126 if (std::get<0>(Pair)->getName() < std::get<1>(Pair)->getName())
3127 return true;
3128 if (std::get<0>(Pair)->getName() > std::get<1>(Pair)->getName())
3129 return false;
3130 }
3131 return false;
3132 });
3133 FeatureBitsets.erase(
3134 std::unique(FeatureBitsets.begin(), FeatureBitsets.end()),
3135 FeatureBitsets.end());
Daniel Sanders49980702017-08-23 10:09:25 +00003136 OS << "// Feature bitsets.\n"
3137 << "enum {\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003138 << " GIFBS_Invalid,\n";
3139 for (const auto &FeatureBitset : FeatureBitsets) {
3140 if (FeatureBitset.empty())
3141 continue;
3142 OS << " " << getNameForFeatureBitset(FeatureBitset) << ",\n";
3143 }
3144 OS << "};\n"
3145 << "const static PredicateBitset FeatureBitsets[] {\n"
3146 << " {}, // GIFBS_Invalid\n";
3147 for (const auto &FeatureBitset : FeatureBitsets) {
3148 if (FeatureBitset.empty())
3149 continue;
3150 OS << " {";
3151 for (const auto &Feature : FeatureBitset) {
3152 const auto &I = SubtargetFeatures.find(Feature);
3153 assert(I != SubtargetFeatures.end() && "Didn't import predicate?");
3154 OS << I->second.getEnumBitName() << ", ";
3155 }
3156 OS << "},\n";
3157 }
3158 OS << "};\n\n";
3159
3160 // Emit complex predicate table and an enum to reference them with.
Daniel Sanders49980702017-08-23 10:09:25 +00003161 OS << "// ComplexPattern predicates.\n"
3162 << "enum {\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003163 << " GICP_Invalid,\n";
3164 for (const auto &Record : ComplexPredicates)
3165 OS << " GICP_" << Record->getName() << ",\n";
3166 OS << "};\n"
3167 << "// See constructor for table contents\n\n";
3168
Daniel Sanders11300ce2017-10-13 21:28:03 +00003169 emitImmPredicates(OS, "I64", "int64_t", [](const Record *R) {
Daniel Sanders649c5852017-10-13 20:42:18 +00003170 bool Unset;
3171 return !R->getValueAsBitOrUnset("IsAPFloat", Unset) &&
3172 !R->getValueAsBit("IsAPInt");
3173 });
Daniel Sanders11300ce2017-10-13 21:28:03 +00003174 emitImmPredicates(OS, "APFloat", "const APFloat &", [](const Record *R) {
3175 bool Unset;
3176 return R->getValueAsBitOrUnset("IsAPFloat", Unset);
3177 });
3178 emitImmPredicates(OS, "APInt", "const APInt &", [](const Record *R) {
3179 return R->getValueAsBit("IsAPInt");
3180 });
Daniel Sandersea8711b2017-10-16 03:36:29 +00003181 OS << "\n";
3182
3183 OS << Target.getName() << "InstructionSelector::ComplexMatcherMemFn\n"
3184 << Target.getName() << "InstructionSelector::ComplexPredicateFns[] = {\n"
3185 << " nullptr, // GICP_Invalid\n";
3186 for (const auto &Record : ComplexPredicates)
3187 OS << " &" << Target.getName()
3188 << "InstructionSelector::" << Record->getValueAsString("MatcherFn")
3189 << ", // " << Record->getName() << "\n";
3190 OS << "};\n\n";
Daniel Sanders2c269f62017-08-24 09:11:20 +00003191
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003192 OS << "bool " << Target.getName()
Daniel Sanders8a4bae92017-03-14 21:32:08 +00003193 << "InstructionSelector::selectImpl(MachineInstr &I) const {\n"
3194 << " MachineFunction &MF = *I.getParent()->getParent();\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003195 << " MachineRegisterInfo &MRI = MF.getRegInfo();\n"
Daniel Sanders32291982017-06-28 13:50:04 +00003196 << " // FIXME: This should be computed on a per-function basis rather "
3197 "than per-insn.\n"
3198 << " AvailableFunctionFeatures = computeAvailableFunctionFeatures(&STI, "
3199 "&MF);\n"
Daniel Sandersa6cfce62017-07-05 14:50:18 +00003200 << " const PredicateBitset AvailableFeatures = getAvailableFeatures();\n"
3201 << " NewMIVector OutMIs;\n"
3202 << " State.MIs.clear();\n"
3203 << " State.MIs.push_back(&I);\n\n";
Daniel Sanders8a4bae92017-03-14 21:32:08 +00003204
Daniel Sanders8e82af22017-07-27 11:03:45 +00003205 MatchTable Table(0);
Daniel Sandersb96f40d2017-03-20 15:20:42 +00003206 for (auto &Rule : Rules) {
Daniel Sanders8e82af22017-07-27 11:03:45 +00003207 Rule.emit(Table);
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003208 ++NumPatternEmitted;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003209 }
Daniel Sanders8e82af22017-07-27 11:03:45 +00003210 Table << MatchTable::Opcode("GIM_Reject") << MatchTable::LineBreak;
3211 Table.emitDeclaration(OS);
3212 OS << " if (executeMatchTable(*this, OutMIs, State, MatcherInfo, ";
3213 Table.emitUse(OS);
3214 OS << ", TII, MRI, TRI, RBI, AvailableFeatures)) {\n"
3215 << " return true;\n"
3216 << " }\n\n";
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003217
Daniel Sanders8a4bae92017-03-14 21:32:08 +00003218 OS << " return false;\n"
3219 << "}\n"
3220 << "#endif // ifdef GET_GLOBALISEL_IMPL\n";
Daniel Sanderse9fdba32017-04-29 17:30:09 +00003221
3222 OS << "#ifdef GET_GLOBALISEL_PREDICATES_DECL\n"
3223 << "PredicateBitset AvailableModuleFeatures;\n"
3224 << "mutable PredicateBitset AvailableFunctionFeatures;\n"
3225 << "PredicateBitset getAvailableFeatures() const {\n"
3226 << " return AvailableModuleFeatures | AvailableFunctionFeatures;\n"
3227 << "}\n"
3228 << "PredicateBitset\n"
3229 << "computeAvailableModuleFeatures(const " << Target.getName()
3230 << "Subtarget *Subtarget) const;\n"
3231 << "PredicateBitset\n"
3232 << "computeAvailableFunctionFeatures(const " << Target.getName()
3233 << "Subtarget *Subtarget,\n"
3234 << " const MachineFunction *MF) const;\n"
3235 << "#endif // ifdef GET_GLOBALISEL_PREDICATES_DECL\n";
3236
3237 OS << "#ifdef GET_GLOBALISEL_PREDICATES_INIT\n"
3238 << "AvailableModuleFeatures(computeAvailableModuleFeatures(&STI)),\n"
3239 << "AvailableFunctionFeatures()\n"
3240 << "#endif // ifdef GET_GLOBALISEL_PREDICATES_INIT\n";
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003241}
3242
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003243void GlobalISelEmitter::declareSubtargetFeature(Record *Predicate) {
3244 if (SubtargetFeatures.count(Predicate) == 0)
3245 SubtargetFeatures.emplace(
3246 Predicate, SubtargetFeatureInfo(Predicate, SubtargetFeatures.size()));
3247}
3248
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003249} // end anonymous namespace
3250
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003251//===----------------------------------------------------------------------===//
3252
3253namespace llvm {
3254void EmitGlobalISel(RecordKeeper &RK, raw_ostream &OS) {
3255 GlobalISelEmitter(RK).run(OS);
3256}
3257} // End llvm namespace