blob: d04d232744aba5a8744acbed1eed141f8c5bc07b [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 matcher for the instruction that this operand is copied from.
1457 /// This provides the facility for looking up an a operand by it's name so
1458 /// that it can be used as a source for the instruction being built.
1459 const InstructionMatcher &Matched;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001460 /// The name of the operand.
1461 const StringRef SymbolicName;
1462
1463public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001464 CopyRenderer(unsigned NewInsnID, const InstructionMatcher &Matched,
1465 StringRef SymbolicName)
1466 : OperandRenderer(OR_Copy), NewInsnID(NewInsnID), Matched(Matched),
Daniel Sanders05540042017-08-08 10:44:31 +00001467 SymbolicName(SymbolicName) {
1468 assert(!SymbolicName.empty() && "Cannot copy from an unspecified source");
1469 }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001470
1471 static bool classof(const OperandRenderer *R) {
1472 return R->getKind() == OR_Copy;
1473 }
1474
1475 const StringRef getSymbolicName() const { return SymbolicName; }
1476
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001477 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001478 const OperandMatcher &Operand = Rule.getOperandMatcher(SymbolicName);
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001479 unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001480 Table << MatchTable::Opcode("GIR_Copy") << MatchTable::Comment("NewInsnID")
1481 << MatchTable::IntValue(NewInsnID) << MatchTable::Comment("OldInsnID")
1482 << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
1483 << MatchTable::IntValue(Operand.getOperandIndex())
1484 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001485 }
1486};
1487
Daniel Sandersd66e0902017-10-23 18:19:24 +00001488/// A CopyOrAddZeroRegRenderer emits code to copy a single operand from an
1489/// existing instruction to the one being built. If the operand turns out to be
1490/// a 'G_CONSTANT 0' then it replaces the operand with a zero register.
1491class CopyOrAddZeroRegRenderer : public OperandRenderer {
1492protected:
1493 unsigned NewInsnID;
1494 /// The name of the operand.
1495 const StringRef SymbolicName;
1496 const Record *ZeroRegisterDef;
1497
1498public:
1499 CopyOrAddZeroRegRenderer(unsigned NewInsnID,
1500 const InstructionMatcher &Matched,
1501 StringRef SymbolicName, Record *ZeroRegisterDef)
1502 : OperandRenderer(OR_CopyOrAddZeroReg), NewInsnID(NewInsnID),
1503 SymbolicName(SymbolicName), ZeroRegisterDef(ZeroRegisterDef) {
1504 assert(!SymbolicName.empty() && "Cannot copy from an unspecified source");
1505 }
1506
1507 static bool classof(const OperandRenderer *R) {
1508 return R->getKind() == OR_CopyOrAddZeroReg;
1509 }
1510
1511 const StringRef getSymbolicName() const { return SymbolicName; }
1512
1513 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
1514 const OperandMatcher &Operand = Rule.getOperandMatcher(SymbolicName);
1515 unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
1516 Table << MatchTable::Opcode("GIR_CopyOrAddZeroReg")
1517 << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
1518 << MatchTable::Comment("OldInsnID")
1519 << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
1520 << MatchTable::IntValue(Operand.getOperandIndex())
1521 << MatchTable::NamedValue(
1522 (ZeroRegisterDef->getValue("Namespace")
1523 ? ZeroRegisterDef->getValueAsString("Namespace")
1524 : ""),
1525 ZeroRegisterDef->getName())
1526 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
1527 }
1528};
1529
Daniel Sanders05540042017-08-08 10:44:31 +00001530/// A CopyConstantAsImmRenderer emits code to render a G_CONSTANT instruction to
1531/// an extended immediate operand.
1532class CopyConstantAsImmRenderer : public OperandRenderer {
1533protected:
1534 unsigned NewInsnID;
1535 /// The name of the operand.
1536 const std::string SymbolicName;
1537 bool Signed;
1538
1539public:
1540 CopyConstantAsImmRenderer(unsigned NewInsnID, StringRef SymbolicName)
1541 : OperandRenderer(OR_CopyConstantAsImm), NewInsnID(NewInsnID),
1542 SymbolicName(SymbolicName), Signed(true) {}
1543
1544 static bool classof(const OperandRenderer *R) {
1545 return R->getKind() == OR_CopyConstantAsImm;
1546 }
1547
1548 const StringRef getSymbolicName() const { return SymbolicName; }
1549
1550 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
1551 const InstructionMatcher &InsnMatcher = Rule.getInstructionMatcher(SymbolicName);
1552 unsigned OldInsnVarID = Rule.getInsnVarID(InsnMatcher);
1553 Table << MatchTable::Opcode(Signed ? "GIR_CopyConstantAsSImm"
1554 : "GIR_CopyConstantAsUImm")
1555 << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
1556 << MatchTable::Comment("OldInsnID")
1557 << MatchTable::IntValue(OldInsnVarID)
1558 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
1559 }
1560};
1561
Daniel Sanders11300ce2017-10-13 21:28:03 +00001562/// A CopyFConstantAsFPImmRenderer emits code to render a G_FCONSTANT
1563/// instruction to an extended immediate operand.
1564class CopyFConstantAsFPImmRenderer : public OperandRenderer {
1565protected:
1566 unsigned NewInsnID;
1567 /// The name of the operand.
1568 const std::string SymbolicName;
1569
1570public:
1571 CopyFConstantAsFPImmRenderer(unsigned NewInsnID, StringRef SymbolicName)
1572 : OperandRenderer(OR_CopyFConstantAsFPImm), NewInsnID(NewInsnID),
1573 SymbolicName(SymbolicName) {}
1574
1575 static bool classof(const OperandRenderer *R) {
1576 return R->getKind() == OR_CopyFConstantAsFPImm;
1577 }
1578
1579 const StringRef getSymbolicName() const { return SymbolicName; }
1580
1581 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
1582 const InstructionMatcher &InsnMatcher = Rule.getInstructionMatcher(SymbolicName);
1583 unsigned OldInsnVarID = Rule.getInsnVarID(InsnMatcher);
1584 Table << MatchTable::Opcode("GIR_CopyFConstantAsFPImm")
1585 << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
1586 << MatchTable::Comment("OldInsnID")
1587 << MatchTable::IntValue(OldInsnVarID)
1588 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
1589 }
1590};
1591
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00001592/// A CopySubRegRenderer emits code to copy a single register operand from an
1593/// existing instruction to the one being built and indicate that only a
1594/// subregister should be copied.
1595class CopySubRegRenderer : public OperandRenderer {
1596protected:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001597 unsigned NewInsnID;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00001598 /// The matcher for the instruction that this operand is copied from.
1599 /// This provides the facility for looking up an a operand by it's name so
1600 /// that it can be used as a source for the instruction being built.
1601 const InstructionMatcher &Matched;
1602 /// The name of the operand.
1603 const StringRef SymbolicName;
1604 /// The subregister to extract.
1605 const CodeGenSubRegIndex *SubReg;
1606
1607public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001608 CopySubRegRenderer(unsigned NewInsnID, const InstructionMatcher &Matched,
1609 StringRef SymbolicName, const CodeGenSubRegIndex *SubReg)
1610 : OperandRenderer(OR_CopySubReg), NewInsnID(NewInsnID), Matched(Matched),
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00001611 SymbolicName(SymbolicName), SubReg(SubReg) {}
1612
1613 static bool classof(const OperandRenderer *R) {
1614 return R->getKind() == OR_CopySubReg;
1615 }
1616
1617 const StringRef getSymbolicName() const { return SymbolicName; }
1618
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001619 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001620 const OperandMatcher &Operand = Rule.getOperandMatcher(SymbolicName);
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001621 unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001622 Table << MatchTable::Opcode("GIR_CopySubReg")
1623 << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
1624 << MatchTable::Comment("OldInsnID")
1625 << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
1626 << MatchTable::IntValue(Operand.getOperandIndex())
1627 << MatchTable::Comment("SubRegIdx")
1628 << MatchTable::IntValue(SubReg->EnumValue)
1629 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00001630 }
1631};
1632
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001633/// Adds a specific physical register to the instruction being built.
1634/// This is typically useful for WZR/XZR on AArch64.
1635class AddRegisterRenderer : public OperandRenderer {
1636protected:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001637 unsigned InsnID;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001638 const Record *RegisterDef;
1639
1640public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001641 AddRegisterRenderer(unsigned InsnID, const Record *RegisterDef)
1642 : OperandRenderer(OR_Register), InsnID(InsnID), RegisterDef(RegisterDef) {
1643 }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001644
1645 static bool classof(const OperandRenderer *R) {
1646 return R->getKind() == OR_Register;
1647 }
1648
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001649 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
1650 Table << MatchTable::Opcode("GIR_AddRegister")
1651 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1652 << MatchTable::NamedValue(
1653 (RegisterDef->getValue("Namespace")
1654 ? RegisterDef->getValueAsString("Namespace")
1655 : ""),
1656 RegisterDef->getName())
1657 << MatchTable::LineBreak;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001658 }
1659};
1660
Daniel Sanders0ed28822017-04-12 08:23:08 +00001661/// Adds a specific immediate to the instruction being built.
1662class ImmRenderer : public OperandRenderer {
1663protected:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001664 unsigned InsnID;
Daniel Sanders0ed28822017-04-12 08:23:08 +00001665 int64_t Imm;
1666
1667public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001668 ImmRenderer(unsigned InsnID, int64_t Imm)
1669 : OperandRenderer(OR_Imm), InsnID(InsnID), Imm(Imm) {}
Daniel Sanders0ed28822017-04-12 08:23:08 +00001670
1671 static bool classof(const OperandRenderer *R) {
1672 return R->getKind() == OR_Imm;
1673 }
1674
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001675 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
1676 Table << MatchTable::Opcode("GIR_AddImm") << MatchTable::Comment("InsnID")
1677 << MatchTable::IntValue(InsnID) << MatchTable::Comment("Imm")
1678 << MatchTable::IntValue(Imm) << MatchTable::LineBreak;
Daniel Sanders0ed28822017-04-12 08:23:08 +00001679 }
1680};
1681
Daniel Sanders2deea182017-04-22 15:11:04 +00001682/// Adds operands by calling a renderer function supplied by the ComplexPattern
1683/// matcher function.
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001684class RenderComplexPatternOperand : public OperandRenderer {
1685private:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001686 unsigned InsnID;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001687 const Record &TheDef;
Daniel Sanders2deea182017-04-22 15:11:04 +00001688 /// The name of the operand.
1689 const StringRef SymbolicName;
1690 /// The renderer number. This must be unique within a rule since it's used to
1691 /// identify a temporary variable to hold the renderer function.
1692 unsigned RendererID;
Daniel Sandersdf39cba2017-10-15 18:22:54 +00001693 /// When provided, this is the suboperand of the ComplexPattern operand to
1694 /// render. Otherwise all the suboperands will be rendered.
1695 Optional<unsigned> SubOperand;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001696
1697 unsigned getNumOperands() const {
1698 return TheDef.getValueAsDag("Operands")->getNumArgs();
1699 }
1700
1701public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001702 RenderComplexPatternOperand(unsigned InsnID, const Record &TheDef,
Daniel Sandersdf39cba2017-10-15 18:22:54 +00001703 StringRef SymbolicName, unsigned RendererID,
1704 Optional<unsigned> SubOperand = None)
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001705 : OperandRenderer(OR_ComplexPattern), InsnID(InsnID), TheDef(TheDef),
Daniel Sandersdf39cba2017-10-15 18:22:54 +00001706 SymbolicName(SymbolicName), RendererID(RendererID),
1707 SubOperand(SubOperand) {}
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001708
1709 static bool classof(const OperandRenderer *R) {
1710 return R->getKind() == OR_ComplexPattern;
1711 }
1712
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001713 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sandersdf39cba2017-10-15 18:22:54 +00001714 Table << MatchTable::Opcode(SubOperand.hasValue() ? "GIR_ComplexSubOperandRenderer"
1715 : "GIR_ComplexRenderer")
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001716 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1717 << MatchTable::Comment("RendererID")
Daniel Sandersdf39cba2017-10-15 18:22:54 +00001718 << MatchTable::IntValue(RendererID);
1719 if (SubOperand.hasValue())
1720 Table << MatchTable::Comment("SubOperand")
1721 << MatchTable::IntValue(SubOperand.getValue());
1722 Table << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001723 }
1724};
1725
Ahmed Bougacha56ca3a92017-02-04 00:47:10 +00001726/// An action taken when all Matcher predicates succeeded for a parent rule.
1727///
1728/// Typical actions include:
1729/// * Changing the opcode of an instruction.
1730/// * Adding an operand to an instruction.
Daniel Sanders43c882c2017-02-01 10:53:10 +00001731class MatchAction {
1732public:
1733 virtual ~MatchAction() {}
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001734
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001735 /// Emit the MatchTable opcodes to implement the action.
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001736 ///
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001737 /// \param RecycleInsnID If given, it's an instruction to recycle. The
1738 /// requirements on the instruction vary from action to
1739 /// action.
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001740 virtual void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule,
1741 unsigned RecycleInsnID) const = 0;
Daniel Sanders43c882c2017-02-01 10:53:10 +00001742};
1743
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +00001744/// Generates a comment describing the matched rule being acted upon.
1745class DebugCommentAction : public MatchAction {
1746private:
1747 const PatternToMatch &P;
1748
1749public:
1750 DebugCommentAction(const PatternToMatch &P) : P(P) {}
1751
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001752 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule,
1753 unsigned RecycleInsnID) const override {
1754 Table << MatchTable::Comment(llvm::to_string(*P.getSrcPattern()) + " => " +
1755 llvm::to_string(*P.getDstPattern()))
1756 << MatchTable::LineBreak;
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +00001757 }
1758};
1759
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001760/// Generates code to build an instruction or mutate an existing instruction
1761/// into the desired instruction when this is possible.
1762class BuildMIAction : public MatchAction {
Daniel Sanders43c882c2017-02-01 10:53:10 +00001763private:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001764 unsigned InsnID;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001765 const CodeGenInstruction *I;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001766 const InstructionMatcher &Matched;
1767 std::vector<std::unique_ptr<OperandRenderer>> OperandRenderers;
1768
1769 /// True if the instruction can be built solely by mutating the opcode.
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001770 bool canMutate(RuleMatcher &Rule) const {
Daniel Sanderse9fdba32017-04-29 17:30:09 +00001771 if (OperandRenderers.size() != Matched.getNumOperands())
1772 return false;
1773
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001774 for (const auto &Renderer : enumerate(OperandRenderers)) {
Zachary Turner309a0882017-03-13 16:24:10 +00001775 if (const auto *Copy = dyn_cast<CopyRenderer>(&*Renderer.value())) {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001776 const OperandMatcher &OM = Rule.getOperandMatcher(Copy->getSymbolicName());
Daniel Sanders3016d3c2017-04-22 14:31:28 +00001777 if (&Matched != &OM.getInstructionMatcher() ||
1778 OM.getOperandIndex() != Renderer.index())
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001779 return false;
1780 } else
1781 return false;
1782 }
1783
1784 return true;
1785 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001786
Daniel Sanders43c882c2017-02-01 10:53:10 +00001787public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001788 BuildMIAction(unsigned InsnID, const CodeGenInstruction *I,
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00001789 const InstructionMatcher &Matched)
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001790 : InsnID(InsnID), I(I), Matched(Matched) {}
Daniel Sanders43c882c2017-02-01 10:53:10 +00001791
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001792 template <class Kind, class... Args>
1793 Kind &addRenderer(Args&&... args) {
1794 OperandRenderers.emplace_back(
1795 llvm::make_unique<Kind>(std::forward<Args>(args)...));
1796 return *static_cast<Kind *>(OperandRenderers.back().get());
1797 }
1798
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001799 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule,
1800 unsigned RecycleInsnID) const override {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001801 if (canMutate(Rule)) {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001802 Table << MatchTable::Opcode("GIR_MutateOpcode")
1803 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1804 << MatchTable::Comment("RecycleInsnID")
1805 << MatchTable::IntValue(RecycleInsnID)
1806 << MatchTable::Comment("Opcode")
1807 << MatchTable::NamedValue(I->Namespace, I->TheDef->getName())
1808 << MatchTable::LineBreak;
Tim Northover4340d642017-03-20 21:58:23 +00001809
1810 if (!I->ImplicitDefs.empty() || !I->ImplicitUses.empty()) {
Tim Northover4340d642017-03-20 21:58:23 +00001811 for (auto Def : I->ImplicitDefs) {
Diana Picus8abcbbb2017-05-02 09:40:49 +00001812 auto Namespace = Def->getValue("Namespace")
1813 ? Def->getValueAsString("Namespace")
1814 : "";
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001815 Table << MatchTable::Opcode("GIR_AddImplicitDef")
1816 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1817 << MatchTable::NamedValue(Namespace, Def->getName())
1818 << MatchTable::LineBreak;
Tim Northover4340d642017-03-20 21:58:23 +00001819 }
1820 for (auto Use : I->ImplicitUses) {
Diana Picus8abcbbb2017-05-02 09:40:49 +00001821 auto Namespace = Use->getValue("Namespace")
1822 ? Use->getValueAsString("Namespace")
1823 : "";
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001824 Table << MatchTable::Opcode("GIR_AddImplicitUse")
1825 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1826 << MatchTable::NamedValue(Namespace, Use->getName())
1827 << MatchTable::LineBreak;
Tim Northover4340d642017-03-20 21:58:23 +00001828 }
1829 }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001830 return;
1831 }
1832
1833 // TODO: Simple permutation looks like it could be almost as common as
1834 // mutation due to commutative operations.
1835
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001836 Table << MatchTable::Opcode("GIR_BuildMI") << MatchTable::Comment("InsnID")
1837 << MatchTable::IntValue(InsnID) << MatchTable::Comment("Opcode")
1838 << MatchTable::NamedValue(I->Namespace, I->TheDef->getName())
1839 << MatchTable::LineBreak;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001840 for (const auto &Renderer : OperandRenderers)
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001841 Renderer->emitRenderOpcodes(Table, Rule);
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001842
Florian Hahn3bc3ec62017-08-03 14:48:22 +00001843 if (I->mayLoad || I->mayStore) {
1844 Table << MatchTable::Opcode("GIR_MergeMemOperands")
1845 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1846 << MatchTable::Comment("MergeInsnID's");
1847 // Emit the ID's for all the instructions that are matched by this rule.
1848 // TODO: Limit this to matched instructions that mayLoad/mayStore or have
1849 // some other means of having a memoperand. Also limit this to
1850 // emitted instructions that expect to have a memoperand too. For
1851 // example, (G_SEXT (G_LOAD x)) that results in separate load and
1852 // sign-extend instructions shouldn't put the memoperand on the
1853 // sign-extend since it has no effect there.
1854 std::vector<unsigned> MergeInsnIDs;
1855 for (const auto &IDMatcherPair : Rule.defined_insn_vars())
1856 MergeInsnIDs.push_back(IDMatcherPair.second);
1857 std::sort(MergeInsnIDs.begin(), MergeInsnIDs.end());
1858 for (const auto &MergeInsnID : MergeInsnIDs)
1859 Table << MatchTable::IntValue(MergeInsnID);
Daniel Sanders05540042017-08-08 10:44:31 +00001860 Table << MatchTable::NamedValue("GIU_MergeMemOperands_EndOfList")
1861 << MatchTable::LineBreak;
Florian Hahn3bc3ec62017-08-03 14:48:22 +00001862 }
1863
1864 Table << MatchTable::Opcode("GIR_EraseFromParent")
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001865 << MatchTable::Comment("InsnID")
1866 << MatchTable::IntValue(RecycleInsnID) << MatchTable::LineBreak;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00001867 }
1868};
1869
1870/// Generates code to constrain the operands of an output instruction to the
1871/// register classes specified by the definition of that instruction.
1872class ConstrainOperandsToDefinitionAction : public MatchAction {
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001873 unsigned InsnID;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00001874
1875public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001876 ConstrainOperandsToDefinitionAction(unsigned InsnID) : InsnID(InsnID) {}
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00001877
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001878 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule,
1879 unsigned RecycleInsnID) const override {
1880 Table << MatchTable::Opcode("GIR_ConstrainSelectedInstOperands")
1881 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1882 << MatchTable::LineBreak;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00001883 }
1884};
1885
1886/// Generates code to constrain the specified operand of an output instruction
1887/// to the specified register class.
1888class ConstrainOperandToRegClassAction : public MatchAction {
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001889 unsigned InsnID;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00001890 unsigned OpIdx;
1891 const CodeGenRegisterClass &RC;
1892
1893public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001894 ConstrainOperandToRegClassAction(unsigned InsnID, unsigned OpIdx,
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00001895 const CodeGenRegisterClass &RC)
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001896 : InsnID(InsnID), OpIdx(OpIdx), RC(RC) {}
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00001897
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001898 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule,
1899 unsigned RecycleInsnID) const override {
1900 Table << MatchTable::Opcode("GIR_ConstrainOperandRC")
1901 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1902 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1903 << MatchTable::Comment("RC " + RC.getName())
1904 << MatchTable::IntValue(RC.EnumValue) << MatchTable::LineBreak;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001905 }
1906};
1907
Daniel Sanders05540042017-08-08 10:44:31 +00001908InstructionMatcher &RuleMatcher::addInstructionMatcher(StringRef SymbolicName) {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001909 Matchers.emplace_back(new InstructionMatcher(*this, SymbolicName));
Daniel Sandersbdfebb82017-03-15 20:18:38 +00001910 return *Matchers.back();
1911}
Ahmed Bougacha56ca3a92017-02-04 00:47:10 +00001912
Daniel Sanderse7b0d662017-04-21 15:59:56 +00001913void RuleMatcher::addRequiredFeature(Record *Feature) {
1914 RequiredFeatures.push_back(Feature);
1915}
1916
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001917const std::vector<Record *> &RuleMatcher::getRequiredFeatures() const {
1918 return RequiredFeatures;
1919}
1920
Daniel Sandersbdfebb82017-03-15 20:18:38 +00001921template <class Kind, class... Args>
1922Kind &RuleMatcher::addAction(Args &&... args) {
1923 Actions.emplace_back(llvm::make_unique<Kind>(std::forward<Args>(args)...));
1924 return *static_cast<Kind *>(Actions.back().get());
1925}
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001926
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001927unsigned
1928RuleMatcher::implicitlyDefineInsnVar(const InstructionMatcher &Matcher) {
1929 unsigned NewInsnVarID = NextInsnVarID++;
1930 InsnVariableIDs[&Matcher] = NewInsnVarID;
1931 return NewInsnVarID;
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001932}
1933
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001934unsigned RuleMatcher::defineInsnVar(MatchTable &Table,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001935 const InstructionMatcher &Matcher,
1936 unsigned InsnID, unsigned OpIdx) {
1937 unsigned NewInsnVarID = implicitlyDefineInsnVar(Matcher);
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001938 Table << MatchTable::Opcode("GIM_RecordInsn")
1939 << MatchTable::Comment("DefineMI") << MatchTable::IntValue(NewInsnVarID)
1940 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnID)
1941 << MatchTable::Comment("OpIdx") << MatchTable::IntValue(OpIdx)
1942 << MatchTable::Comment("MIs[" + llvm::to_string(NewInsnVarID) + "]")
1943 << MatchTable::LineBreak;
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001944 return NewInsnVarID;
1945}
1946
1947unsigned RuleMatcher::getInsnVarID(const InstructionMatcher &InsnMatcher) const {
1948 const auto &I = InsnVariableIDs.find(&InsnMatcher);
1949 if (I != InsnVariableIDs.end())
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001950 return I->second;
1951 llvm_unreachable("Matched Insn was not captured in a local variable");
1952}
1953
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001954void RuleMatcher::defineOperand(StringRef SymbolicName, OperandMatcher &OM) {
1955 if (DefinedOperands.find(SymbolicName) == DefinedOperands.end()) {
1956 DefinedOperands[SymbolicName] = &OM;
1957 return;
1958 }
1959
1960 // If the operand is already defined, then we must ensure both references in
1961 // the matcher have the exact same node.
1962 OM.addPredicate<SameOperandMatcher>(OM.getSymbolicName());
1963}
1964
Daniel Sanders05540042017-08-08 10:44:31 +00001965const InstructionMatcher &
1966RuleMatcher::getInstructionMatcher(StringRef SymbolicName) const {
1967 for (const auto &I : InsnVariableIDs)
1968 if (I.first->getSymbolicName() == SymbolicName)
1969 return *I.first;
1970 llvm_unreachable(
1971 ("Failed to lookup instruction " + SymbolicName).str().c_str());
1972}
1973
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001974const OperandMatcher &
1975RuleMatcher::getOperandMatcher(StringRef Name) const {
1976 const auto &I = DefinedOperands.find(Name);
1977
1978 if (I == DefinedOperands.end())
1979 PrintFatalError(SrcLoc, "Operand " + Name + " was not declared in matcher");
1980
1981 return *I->second;
1982}
1983
Daniel Sanders9d662d22017-07-06 10:06:12 +00001984/// Emit MatchTable opcodes to check the shape of the match and capture
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001985/// instructions into local variables.
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001986void RuleMatcher::emitCaptureOpcodes(MatchTable &Table) {
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001987 assert(Matchers.size() == 1 && "Cannot handle multi-root matchers yet");
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001988 unsigned InsnVarID = implicitlyDefineInsnVar(*Matchers.front());
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001989 Matchers.front()->emitCaptureOpcodes(Table, *this, InsnVarID);
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001990}
1991
Daniel Sanders8e82af22017-07-27 11:03:45 +00001992void RuleMatcher::emit(MatchTable &Table) {
Daniel Sandersbdfebb82017-03-15 20:18:38 +00001993 if (Matchers.empty())
1994 llvm_unreachable("Unexpected empty matcher!");
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001995
Daniel Sandersbdfebb82017-03-15 20:18:38 +00001996 // The representation supports rules that require multiple roots such as:
1997 // %ptr(p0) = ...
1998 // %elt0(s32) = G_LOAD %ptr
1999 // %1(p0) = G_ADD %ptr, 4
2000 // %elt1(s32) = G_LOAD p0 %1
2001 // which could be usefully folded into:
2002 // %ptr(p0) = ...
2003 // %elt0(s32), %elt1(s32) = TGT_LOAD_PAIR %ptr
2004 // on some targets but we don't need to make use of that yet.
2005 assert(Matchers.size() == 1 && "Cannot handle multi-root matchers yet");
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002006
Daniel Sanders8e82af22017-07-27 11:03:45 +00002007 unsigned LabelID = Table.allocateLabelID();
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002008 Table << MatchTable::Opcode("GIM_Try", +1)
Daniel Sanders8e82af22017-07-27 11:03:45 +00002009 << MatchTable::Comment("On fail goto") << MatchTable::JumpTarget(LabelID)
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002010 << MatchTable::LineBreak;
2011
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002012 if (!RequiredFeatures.empty()) {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002013 Table << MatchTable::Opcode("GIM_CheckFeatures")
2014 << MatchTable::NamedValue(getNameForFeatureBitset(RequiredFeatures))
2015 << MatchTable::LineBreak;
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002016 }
Daniel Sandersb96f40d2017-03-20 15:20:42 +00002017
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002018 emitCaptureOpcodes(Table);
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002019
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002020 Matchers.front()->emitPredicateOpcodes(Table, *this,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002021 getInsnVarID(*Matchers.front()));
2022
Daniel Sandersbee57392017-04-04 13:25:23 +00002023 // We must also check if it's safe to fold the matched instructions.
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002024 if (InsnVariableIDs.size() >= 2) {
Galina Kistanova1754fee2017-05-25 01:51:53 +00002025 // Invert the map to create stable ordering (by var names)
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002026 SmallVector<unsigned, 2> InsnIDs;
2027 for (const auto &Pair : InsnVariableIDs) {
Daniel Sandersbee57392017-04-04 13:25:23 +00002028 // Skip the root node since it isn't moving anywhere. Everything else is
2029 // sinking to meet it.
2030 if (Pair.first == Matchers.front().get())
2031 continue;
2032
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002033 InsnIDs.push_back(Pair.second);
Galina Kistanova1754fee2017-05-25 01:51:53 +00002034 }
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002035 std::sort(InsnIDs.begin(), InsnIDs.end());
Galina Kistanova1754fee2017-05-25 01:51:53 +00002036
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002037 for (const auto &InsnID : InsnIDs) {
Daniel Sandersbee57392017-04-04 13:25:23 +00002038 // Reject the difficult cases until we have a more accurate check.
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002039 Table << MatchTable::Opcode("GIM_CheckIsSafeToFold")
2040 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2041 << MatchTable::LineBreak;
Daniel Sandersbee57392017-04-04 13:25:23 +00002042
2043 // FIXME: Emit checks to determine it's _actually_ safe to fold and/or
2044 // account for unsafe cases.
2045 //
2046 // Example:
2047 // MI1--> %0 = ...
2048 // %1 = ... %0
2049 // MI0--> %2 = ... %0
2050 // It's not safe to erase MI1. We currently handle this by not
2051 // erasing %0 (even when it's dead).
2052 //
2053 // Example:
2054 // MI1--> %0 = load volatile @a
2055 // %1 = load volatile @a
2056 // MI0--> %2 = ... %0
2057 // It's not safe to sink %0's def past %1. We currently handle
2058 // this by rejecting all loads.
2059 //
2060 // Example:
2061 // MI1--> %0 = load @a
2062 // %1 = store @a
2063 // MI0--> %2 = ... %0
2064 // It's not safe to sink %0's def past %1. We currently handle
2065 // this by rejecting all loads.
2066 //
2067 // Example:
2068 // G_CONDBR %cond, @BB1
2069 // BB0:
2070 // MI1--> %0 = load @a
2071 // G_BR @BB1
2072 // BB1:
2073 // MI0--> %2 = ... %0
2074 // It's not always safe to sink %0 across control flow. In this
2075 // case it may introduce a memory fault. We currentl handle this
2076 // by rejecting all loads.
2077 }
2078 }
2079
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002080 for (const auto &MA : Actions)
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002081 MA->emitActionOpcodes(Table, *this, 0);
2082 Table << MatchTable::Opcode("GIR_Done", -1) << MatchTable::LineBreak
Daniel Sanders8e82af22017-07-27 11:03:45 +00002083 << MatchTable::Label(LabelID);
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002084}
Daniel Sanders43c882c2017-02-01 10:53:10 +00002085
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002086bool RuleMatcher::isHigherPriorityThan(const RuleMatcher &B) const {
2087 // Rules involving more match roots have higher priority.
2088 if (Matchers.size() > B.Matchers.size())
2089 return true;
2090 if (Matchers.size() < B.Matchers.size())
Daniel Sanders759ff412017-02-24 13:58:11 +00002091 return false;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002092
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002093 for (const auto &Matcher : zip(Matchers, B.Matchers)) {
2094 if (std::get<0>(Matcher)->isHigherPriorityThan(*std::get<1>(Matcher)))
2095 return true;
2096 if (std::get<1>(Matcher)->isHigherPriorityThan(*std::get<0>(Matcher)))
2097 return false;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002098 }
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002099
2100 return false;
Simon Pilgrima7d1da82017-03-15 22:50:47 +00002101}
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002102
Daniel Sanders2deea182017-04-22 15:11:04 +00002103unsigned RuleMatcher::countRendererFns() const {
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002104 return std::accumulate(
2105 Matchers.begin(), Matchers.end(), 0,
2106 [](unsigned A, const std::unique_ptr<InstructionMatcher> &Matcher) {
Daniel Sanders2deea182017-04-22 15:11:04 +00002107 return A + Matcher->countRendererFns();
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002108 });
2109}
2110
Daniel Sanders05540042017-08-08 10:44:31 +00002111bool OperandPredicateMatcher::isHigherPriorityThan(
2112 const OperandPredicateMatcher &B) const {
2113 // Generally speaking, an instruction is more important than an Int or a
2114 // LiteralInt because it can cover more nodes but theres an exception to
2115 // this. G_CONSTANT's are less important than either of those two because they
2116 // are more permissive.
Daniel Sandersedd07842017-08-17 09:26:14 +00002117
2118 const InstructionOperandMatcher *AOM =
2119 dyn_cast<InstructionOperandMatcher>(this);
2120 const InstructionOperandMatcher *BOM =
2121 dyn_cast<InstructionOperandMatcher>(&B);
2122 bool AIsConstantInsn = AOM && AOM->getInsnMatcher().isConstantInstruction();
2123 bool BIsConstantInsn = BOM && BOM->getInsnMatcher().isConstantInstruction();
2124
2125 if (AOM && BOM) {
2126 // The relative priorities between a G_CONSTANT and any other instruction
2127 // don't actually matter but this code is needed to ensure a strict weak
2128 // ordering. This is particularly important on Windows where the rules will
2129 // be incorrectly sorted without it.
2130 if (AIsConstantInsn != BIsConstantInsn)
2131 return AIsConstantInsn < BIsConstantInsn;
2132 return false;
Daniel Sanders05540042017-08-08 10:44:31 +00002133 }
Daniel Sandersedd07842017-08-17 09:26:14 +00002134
2135 if (AOM && AIsConstantInsn && (B.Kind == OPM_Int || B.Kind == OPM_LiteralInt))
2136 return false;
2137 if (BOM && BIsConstantInsn && (Kind == OPM_Int || Kind == OPM_LiteralInt))
2138 return true;
Daniel Sanders05540042017-08-08 10:44:31 +00002139
2140 return Kind < B.Kind;
Daniel Sanders75b84fc2017-08-08 13:21:26 +00002141}
Daniel Sanders05540042017-08-08 10:44:31 +00002142
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002143void SameOperandMatcher::emitPredicateOpcodes(MatchTable &Table,
2144 RuleMatcher &Rule,
2145 unsigned InsnVarID,
2146 unsigned OpIdx) const {
Daniel Sanders1e4569f2017-10-20 20:55:29 +00002147 const OperandMatcher &OtherOM = Rule.getOperandMatcher(MatchingName);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002148 unsigned OtherInsnVarID = Rule.getInsnVarID(OtherOM.getInstructionMatcher());
2149
2150 Table << MatchTable::Opcode("GIM_CheckIsSameOperand")
2151 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
2152 << MatchTable::Comment("OpIdx") << MatchTable::IntValue(OpIdx)
2153 << MatchTable::Comment("OtherMI")
2154 << MatchTable::IntValue(OtherInsnVarID)
2155 << MatchTable::Comment("OtherOpIdx")
2156 << MatchTable::IntValue(OtherOM.getOperandIndex())
2157 << MatchTable::LineBreak;
2158}
2159
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002160//===- GlobalISelEmitter class --------------------------------------------===//
2161
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002162class GlobalISelEmitter {
2163public:
2164 explicit GlobalISelEmitter(RecordKeeper &RK);
2165 void run(raw_ostream &OS);
2166
2167private:
2168 const RecordKeeper &RK;
2169 const CodeGenDAGPatterns CGP;
2170 const CodeGenTarget &Target;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002171 CodeGenRegBank CGRegs;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002172
Daniel Sanders39690bd2017-10-15 02:41:12 +00002173 /// Keep track of the equivalence between SDNodes and Instruction by mapping
2174 /// SDNodes to the GINodeEquiv mapping. We need to map to the GINodeEquiv to
2175 /// check for attributes on the relation such as CheckMMOIsNonAtomic.
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002176 /// This is defined using 'GINodeEquiv' in the target description.
Daniel Sanders39690bd2017-10-15 02:41:12 +00002177 DenseMap<Record *, Record *> NodeEquivs;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002178
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002179 /// Keep track of the equivalence between ComplexPattern's and
2180 /// GIComplexOperandMatcher. Map entries are specified by subclassing
2181 /// GIComplexPatternEquiv.
2182 DenseMap<const Record *, const Record *> ComplexPatternEquivs;
2183
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002184 // Map of predicates to their subtarget features.
Daniel Sanderse9fdba32017-04-29 17:30:09 +00002185 SubtargetFeatureInfoMap SubtargetFeatures;
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002186
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002187 void gatherNodeEquivs();
Daniel Sanders39690bd2017-10-15 02:41:12 +00002188 Record *findNodeEquiv(Record *N) const;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002189
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002190 Error importRulePredicates(RuleMatcher &M, ArrayRef<Predicate> Predicates);
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002191 Expected<InstructionMatcher &> createAndImportSelDAGMatcher(
2192 RuleMatcher &Rule, InstructionMatcher &InsnMatcher,
2193 const TreePatternNode *Src, unsigned &TempOpIdx) const;
2194 Error importComplexPatternOperandMatcher(OperandMatcher &OM, Record *R,
2195 unsigned &TempOpIdx) const;
2196 Error importChildMatcher(RuleMatcher &Rule, InstructionMatcher &InsnMatcher,
Daniel Sandersa71f4542017-10-16 00:56:30 +00002197 const TreePatternNode *SrcChild,
2198 bool OperandIsAPointer, unsigned OpIdx,
Daniel Sandersc270c502017-03-30 09:36:33 +00002199 unsigned &TempOpIdx) const;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002200 Expected<BuildMIAction &>
2201 createAndImportInstructionRenderer(RuleMatcher &M, const TreePatternNode *Dst,
2202 const InstructionMatcher &InsnMatcher);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002203 Error importExplicitUseRenderer(RuleMatcher &Rule,
2204 BuildMIAction &DstMIBuilder,
Daniel Sandersc270c502017-03-30 09:36:33 +00002205 TreePatternNode *DstChild,
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002206 const InstructionMatcher &InsnMatcher) const;
Diana Picus382602f2017-05-17 08:57:28 +00002207 Error importDefaultOperandRenderers(BuildMIAction &DstMIBuilder,
2208 DagInit *DefaultOps) const;
Daniel Sandersc270c502017-03-30 09:36:33 +00002209 Error
Daniel Sandersffc7d582017-03-29 15:37:18 +00002210 importImplicitDefRenderers(BuildMIAction &DstMIBuilder,
2211 const std::vector<Record *> &ImplicitDefs) const;
2212
Daniel Sanders11300ce2017-10-13 21:28:03 +00002213 void emitImmPredicates(raw_ostream &OS, StringRef TypeIdentifier,
2214 StringRef Type,
Daniel Sanders649c5852017-10-13 20:42:18 +00002215 std::function<bool(const Record *R)> Filter);
2216
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002217 /// Analyze pattern \p P, returning a matcher for it if possible.
2218 /// Otherwise, return an Error explaining why we don't support it.
2219 Expected<RuleMatcher> runOnPattern(const PatternToMatch &P);
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002220
2221 void declareSubtargetFeature(Record *Predicate);
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002222};
2223
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002224void GlobalISelEmitter::gatherNodeEquivs() {
2225 assert(NodeEquivs.empty());
2226 for (Record *Equiv : RK.getAllDerivedDefinitions("GINodeEquiv"))
Daniel Sanders39690bd2017-10-15 02:41:12 +00002227 NodeEquivs[Equiv->getValueAsDef("Node")] = Equiv;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002228
2229 assert(ComplexPatternEquivs.empty());
2230 for (Record *Equiv : RK.getAllDerivedDefinitions("GIComplexPatternEquiv")) {
2231 Record *SelDAGEquiv = Equiv->getValueAsDef("SelDAGEquivalent");
2232 if (!SelDAGEquiv)
2233 continue;
2234 ComplexPatternEquivs[SelDAGEquiv] = Equiv;
2235 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002236}
2237
Daniel Sanders39690bd2017-10-15 02:41:12 +00002238Record *GlobalISelEmitter::findNodeEquiv(Record *N) const {
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002239 return NodeEquivs.lookup(N);
2240}
2241
2242GlobalISelEmitter::GlobalISelEmitter(RecordKeeper &RK)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002243 : RK(RK), CGP(RK), Target(CGP.getTargetInfo()),
2244 CGRegs(RK, Target.getHwModes()) {}
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002245
2246//===- Emitter ------------------------------------------------------------===//
2247
Daniel Sandersc270c502017-03-30 09:36:33 +00002248Error
Daniel Sandersffc7d582017-03-29 15:37:18 +00002249GlobalISelEmitter::importRulePredicates(RuleMatcher &M,
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002250 ArrayRef<Predicate> Predicates) {
2251 for (const Predicate &P : Predicates) {
2252 if (!P.Def)
2253 continue;
2254 declareSubtargetFeature(P.Def);
2255 M.addRequiredFeature(P.Def);
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002256 }
2257
Daniel Sandersc270c502017-03-30 09:36:33 +00002258 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00002259}
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002260
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002261Expected<InstructionMatcher &> GlobalISelEmitter::createAndImportSelDAGMatcher(
2262 RuleMatcher &Rule, InstructionMatcher &InsnMatcher,
2263 const TreePatternNode *Src, unsigned &TempOpIdx) const {
Daniel Sanders39690bd2017-10-15 02:41:12 +00002264 Record *SrcGIEquivOrNull = nullptr;
Daniel Sanders85ffd362017-07-06 08:12:20 +00002265 const CodeGenInstruction *SrcGIOrNull = nullptr;
2266
Daniel Sandersffc7d582017-03-29 15:37:18 +00002267 // Start with the defined operands (i.e., the results of the root operator).
2268 if (Src->getExtTypes().size() > 1)
2269 return failedImport("Src pattern has multiple results");
2270
Daniel Sanders452c8ae2017-05-23 19:33:16 +00002271 if (Src->isLeaf()) {
2272 Init *SrcInit = Src->getLeafValue();
Daniel Sanders3334cc02017-05-23 20:02:48 +00002273 if (isa<IntInit>(SrcInit)) {
Daniel Sanders452c8ae2017-05-23 19:33:16 +00002274 InsnMatcher.addPredicate<InstructionOpcodeMatcher>(
2275 &Target.getInstruction(RK.getDef("G_CONSTANT")));
2276 } else
Daniel Sanders32291982017-06-28 13:50:04 +00002277 return failedImport(
2278 "Unable to deduce gMIR opcode to handle Src (which is a leaf)");
Daniel Sanders452c8ae2017-05-23 19:33:16 +00002279 } else {
Daniel Sanders39690bd2017-10-15 02:41:12 +00002280 SrcGIEquivOrNull = findNodeEquiv(Src->getOperator());
2281 if (!SrcGIEquivOrNull)
Daniel Sanders452c8ae2017-05-23 19:33:16 +00002282 return failedImport("Pattern operator lacks an equivalent Instruction" +
2283 explainOperator(Src->getOperator()));
Daniel Sanders39690bd2017-10-15 02:41:12 +00002284 SrcGIOrNull = &Target.getInstruction(SrcGIEquivOrNull->getValueAsDef("I"));
Daniel Sandersffc7d582017-03-29 15:37:18 +00002285
Daniel Sanders452c8ae2017-05-23 19:33:16 +00002286 // The operators look good: match the opcode
Daniel Sanders39690bd2017-10-15 02:41:12 +00002287 InsnMatcher.addPredicate<InstructionOpcodeMatcher>(SrcGIOrNull);
Daniel Sanders452c8ae2017-05-23 19:33:16 +00002288 }
Daniel Sandersffc7d582017-03-29 15:37:18 +00002289
2290 unsigned OpIdx = 0;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002291 for (const TypeSetByHwMode &VTy : Src->getExtTypes()) {
Daniel Sandersffc7d582017-03-29 15:37:18 +00002292 // Results don't have a name unless they are the root node. The caller will
2293 // set the name if appropriate.
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002294 OperandMatcher &OM = InsnMatcher.addOperand(OpIdx++, "", TempOpIdx);
Daniel Sandersa71f4542017-10-16 00:56:30 +00002295 if (auto Error = OM.addTypeCheckPredicate(VTy, false /* OperandIsAPointer */))
2296 return failedImport(toString(std::move(Error)) +
2297 " for result of Src pattern operator");
Daniel Sandersffc7d582017-03-29 15:37:18 +00002298 }
2299
Daniel Sanders2c269f62017-08-24 09:11:20 +00002300 for (const auto &Predicate : Src->getPredicateFns()) {
2301 if (Predicate.isAlwaysTrue())
2302 continue;
2303
2304 if (Predicate.isImmediatePattern()) {
2305 InsnMatcher.addPredicate<InstructionImmPredicateMatcher>(Predicate);
2306 continue;
2307 }
2308
Daniel Sandersa71f4542017-10-16 00:56:30 +00002309 // No check required. A G_LOAD is an unindexed load.
2310 if (Predicate.isLoad() && Predicate.isUnindexed())
2311 continue;
2312
2313 // No check required. G_LOAD by itself is a non-extending load.
2314 if (Predicate.isNonExtLoad())
2315 continue;
2316
2317 if (Predicate.isLoad() && Predicate.getMemoryVT() != nullptr) {
2318 Optional<LLTCodeGen> MemTyOrNone =
2319 MVTToLLT(getValueType(Predicate.getMemoryVT()));
2320
2321 if (!MemTyOrNone)
2322 return failedImport("MemVT could not be converted to LLT");
2323
2324 InsnMatcher.getOperand(0).addPredicate<LLTOperandMatcher>(MemTyOrNone.getValue());
2325 continue;
2326 }
2327
Daniel Sandersd66e0902017-10-23 18:19:24 +00002328 // No check required. A G_STORE is an unindexed store.
2329 if (Predicate.isStore() && Predicate.isUnindexed())
2330 continue;
2331
2332 // No check required. G_STORE by itself is a non-extending store.
2333 if (Predicate.isNonTruncStore())
2334 continue;
2335
2336 if (Predicate.isStore() && Predicate.getMemoryVT() != nullptr) {
2337 Optional<LLTCodeGen> MemTyOrNone =
2338 MVTToLLT(getValueType(Predicate.getMemoryVT()));
2339
2340 if (!MemTyOrNone)
2341 return failedImport("MemVT could not be converted to LLT");
2342
2343 InsnMatcher.getOperand(0).addPredicate<LLTOperandMatcher>(MemTyOrNone.getValue());
2344 continue;
2345 }
2346
Daniel Sanders2c269f62017-08-24 09:11:20 +00002347 return failedImport("Src pattern child has predicate (" +
2348 explainPredicates(Src) + ")");
2349 }
Daniel Sanders39690bd2017-10-15 02:41:12 +00002350 if (SrcGIEquivOrNull && SrcGIEquivOrNull->getValueAsBit("CheckMMOIsNonAtomic"))
2351 InsnMatcher.addPredicate<NonAtomicMMOPredicateMatcher>();
Daniel Sanders2c269f62017-08-24 09:11:20 +00002352
Daniel Sanders452c8ae2017-05-23 19:33:16 +00002353 if (Src->isLeaf()) {
2354 Init *SrcInit = Src->getLeafValue();
2355 if (IntInit *SrcIntInit = dyn_cast<IntInit>(SrcInit)) {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002356 OperandMatcher &OM =
2357 InsnMatcher.addOperand(OpIdx++, Src->getName(), TempOpIdx);
Daniel Sanders452c8ae2017-05-23 19:33:16 +00002358 OM.addPredicate<LiteralIntOperandMatcher>(SrcIntInit->getValue());
2359 } else
Daniel Sanders32291982017-06-28 13:50:04 +00002360 return failedImport(
2361 "Unable to deduce gMIR opcode to handle Src (which is a leaf)");
Daniel Sanders452c8ae2017-05-23 19:33:16 +00002362 } else {
Daniel Sanders85ffd362017-07-06 08:12:20 +00002363 assert(SrcGIOrNull &&
2364 "Expected to have already found an equivalent Instruction");
Daniel Sanders11300ce2017-10-13 21:28:03 +00002365 if (SrcGIOrNull->TheDef->getName() == "G_CONSTANT" ||
2366 SrcGIOrNull->TheDef->getName() == "G_FCONSTANT") {
2367 // imm/fpimm still have operands but we don't need to do anything with it
Daniel Sanders05540042017-08-08 10:44:31 +00002368 // here since we don't support ImmLeaf predicates yet. However, we still
2369 // need to note the hidden operand to get GIM_CheckNumOperands correct.
2370 InsnMatcher.addOperand(OpIdx++, "", TempOpIdx);
2371 return InsnMatcher;
2372 }
2373
Daniel Sanders452c8ae2017-05-23 19:33:16 +00002374 // Match the used operands (i.e. the children of the operator).
2375 for (unsigned i = 0, e = Src->getNumChildren(); i != e; ++i) {
Daniel Sanders85ffd362017-07-06 08:12:20 +00002376 TreePatternNode *SrcChild = Src->getChild(i);
2377
Daniel Sandersa71f4542017-10-16 00:56:30 +00002378 // SelectionDAG allows pointers to be represented with iN since it doesn't
2379 // distinguish between pointers and integers but they are different types in GlobalISel.
2380 // Coerce integers to pointers to address space 0 if the context indicates a pointer.
2381 // TODO: Find a better way to do this, SDTCisPtrTy?
2382 bool OperandIsAPointer =
Daniel Sandersd66e0902017-10-23 18:19:24 +00002383 (SrcGIOrNull->TheDef->getName() == "G_LOAD" && i == 0) ||
2384 (SrcGIOrNull->TheDef->getName() == "G_STORE" && i == 1);
Daniel Sandersa71f4542017-10-16 00:56:30 +00002385
Daniel Sanders28887fe2017-09-19 12:56:36 +00002386 // For G_INTRINSIC/G_INTRINSIC_W_SIDE_EFFECTS, the operand immediately
2387 // following the defs is an intrinsic ID.
2388 if ((SrcGIOrNull->TheDef->getName() == "G_INTRINSIC" ||
2389 SrcGIOrNull->TheDef->getName() == "G_INTRINSIC_W_SIDE_EFFECTS") &&
2390 i == 0) {
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00002391 if (const CodeGenIntrinsic *II = Src->getIntrinsicInfo(CGP)) {
Daniel Sanders85ffd362017-07-06 08:12:20 +00002392 OperandMatcher &OM =
2393 InsnMatcher.addOperand(OpIdx++, SrcChild->getName(), TempOpIdx);
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00002394 OM.addPredicate<IntrinsicIDOperandMatcher>(II);
Daniel Sanders85ffd362017-07-06 08:12:20 +00002395 continue;
2396 }
2397
2398 return failedImport("Expected IntInit containing instrinsic ID)");
2399 }
2400
Daniel Sandersa71f4542017-10-16 00:56:30 +00002401 if (auto Error =
2402 importChildMatcher(Rule, InsnMatcher, SrcChild, OperandIsAPointer,
2403 OpIdx++, TempOpIdx))
Daniel Sanders452c8ae2017-05-23 19:33:16 +00002404 return std::move(Error);
2405 }
Daniel Sandersffc7d582017-03-29 15:37:18 +00002406 }
2407
2408 return InsnMatcher;
2409}
2410
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002411Error GlobalISelEmitter::importComplexPatternOperandMatcher(
2412 OperandMatcher &OM, Record *R, unsigned &TempOpIdx) const {
2413 const auto &ComplexPattern = ComplexPatternEquivs.find(R);
2414 if (ComplexPattern == ComplexPatternEquivs.end())
2415 return failedImport("SelectionDAG ComplexPattern (" + R->getName() +
2416 ") not mapped to GlobalISel");
2417
2418 OM.addPredicate<ComplexPatternOperandMatcher>(OM, *ComplexPattern->second);
2419 TempOpIdx++;
2420 return Error::success();
2421}
2422
2423Error GlobalISelEmitter::importChildMatcher(RuleMatcher &Rule,
2424 InstructionMatcher &InsnMatcher,
Daniel Sanders452c8ae2017-05-23 19:33:16 +00002425 const TreePatternNode *SrcChild,
Daniel Sandersa71f4542017-10-16 00:56:30 +00002426 bool OperandIsAPointer,
Daniel Sandersc270c502017-03-30 09:36:33 +00002427 unsigned OpIdx,
2428 unsigned &TempOpIdx) const {
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002429 OperandMatcher &OM =
2430 InsnMatcher.addOperand(OpIdx, SrcChild->getName(), TempOpIdx);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002431 if (OM.isSameAsAnotherOperand())
2432 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00002433
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002434 ArrayRef<TypeSetByHwMode> ChildTypes = SrcChild->getExtTypes();
Daniel Sandersffc7d582017-03-29 15:37:18 +00002435 if (ChildTypes.size() != 1)
2436 return failedImport("Src pattern child has multiple results");
2437
2438 // Check MBB's before the type check since they are not a known type.
2439 if (!SrcChild->isLeaf()) {
2440 if (SrcChild->getOperator()->isSubClassOf("SDNode")) {
2441 auto &ChildSDNI = CGP.getSDNodeInfo(SrcChild->getOperator());
2442 if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") {
2443 OM.addPredicate<MBBOperandMatcher>();
Daniel Sandersc270c502017-03-30 09:36:33 +00002444 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00002445 }
2446 }
Daniel Sandersffc7d582017-03-29 15:37:18 +00002447 }
2448
Daniel Sandersa71f4542017-10-16 00:56:30 +00002449 if (auto Error =
2450 OM.addTypeCheckPredicate(ChildTypes.front(), OperandIsAPointer))
2451 return failedImport(toString(std::move(Error)) + " for Src operand (" +
2452 to_string(*SrcChild) + ")");
Daniel Sandersffc7d582017-03-29 15:37:18 +00002453
Daniel Sandersbee57392017-04-04 13:25:23 +00002454 // Check for nested instructions.
2455 if (!SrcChild->isLeaf()) {
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002456 if (SrcChild->getOperator()->isSubClassOf("ComplexPattern")) {
2457 // When a ComplexPattern is used as an operator, it should do the same
2458 // thing as when used as a leaf. However, the children of the operator
2459 // name the sub-operands that make up the complex operand and we must
2460 // prepare to reference them in the renderer too.
2461 unsigned RendererID = TempOpIdx;
2462 if (auto Error = importComplexPatternOperandMatcher(
2463 OM, SrcChild->getOperator(), TempOpIdx))
2464 return Error;
2465
2466 for (unsigned i = 0, e = SrcChild->getNumChildren(); i != e; ++i) {
2467 auto *SubOperand = SrcChild->getChild(i);
2468 if (!SubOperand->getName().empty())
2469 Rule.defineComplexSubOperand(SubOperand->getName(),
2470 SrcChild->getOperator(), RendererID, i);
2471 }
2472
2473 return Error::success();
2474 }
2475
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002476 auto MaybeInsnOperand = OM.addPredicate<InstructionOperandMatcher>(
2477 InsnMatcher.getRuleMatcher(), SrcChild->getName());
2478 if (!MaybeInsnOperand.hasValue()) {
2479 // This isn't strictly true. If the user were to provide exactly the same
2480 // matchers as the original operand then we could allow it. However, it's
2481 // simpler to not permit the redundant specification.
2482 return failedImport("Nested instruction cannot be the same as another operand");
2483 }
2484
Daniel Sandersbee57392017-04-04 13:25:23 +00002485 // Map the node to a gMIR instruction.
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002486 InstructionOperandMatcher &InsnOperand = **MaybeInsnOperand;
Daniel Sanders57938df2017-07-11 10:40:18 +00002487 auto InsnMatcherOrError = createAndImportSelDAGMatcher(
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002488 Rule, InsnOperand.getInsnMatcher(), SrcChild, TempOpIdx);
Daniel Sandersbee57392017-04-04 13:25:23 +00002489 if (auto Error = InsnMatcherOrError.takeError())
2490 return Error;
2491
2492 return Error::success();
2493 }
2494
Daniel Sandersffc7d582017-03-29 15:37:18 +00002495 // Check for constant immediates.
2496 if (auto *ChildInt = dyn_cast<IntInit>(SrcChild->getLeafValue())) {
Daniel Sanders452c8ae2017-05-23 19:33:16 +00002497 OM.addPredicate<ConstantIntOperandMatcher>(ChildInt->getValue());
Daniel Sandersc270c502017-03-30 09:36:33 +00002498 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00002499 }
2500
2501 // Check for def's like register classes or ComplexPattern's.
2502 if (auto *ChildDefInit = dyn_cast<DefInit>(SrcChild->getLeafValue())) {
2503 auto *ChildRec = ChildDefInit->getDef();
2504
2505 // Check for register classes.
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002506 if (ChildRec->isSubClassOf("RegisterClass") ||
2507 ChildRec->isSubClassOf("RegisterOperand")) {
Daniel Sandersffc7d582017-03-29 15:37:18 +00002508 OM.addPredicate<RegisterBankOperandMatcher>(
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002509 Target.getRegisterClass(getInitValueAsRegClass(ChildDefInit)));
Daniel Sanders658541f2017-04-22 15:53:21 +00002510 return Error::success();
2511 }
2512
Daniel Sanders4d4e7652017-10-09 18:14:53 +00002513 // Check for ValueType.
2514 if (ChildRec->isSubClassOf("ValueType")) {
2515 // We already added a type check as standard practice so this doesn't need
2516 // to do anything.
2517 return Error::success();
2518 }
2519
Daniel Sandersffc7d582017-03-29 15:37:18 +00002520 // Check for ComplexPattern's.
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002521 if (ChildRec->isSubClassOf("ComplexPattern"))
2522 return importComplexPatternOperandMatcher(OM, ChildRec, TempOpIdx);
Daniel Sandersffc7d582017-03-29 15:37:18 +00002523
Daniel Sandersd0656a32017-04-13 09:45:37 +00002524 if (ChildRec->isSubClassOf("ImmLeaf")) {
2525 return failedImport(
2526 "Src pattern child def is an unsupported tablegen class (ImmLeaf)");
2527 }
2528
Daniel Sandersffc7d582017-03-29 15:37:18 +00002529 return failedImport(
2530 "Src pattern child def is an unsupported tablegen class");
2531 }
2532
2533 return failedImport("Src pattern child is an unsupported kind");
2534}
2535
Daniel Sandersc270c502017-03-30 09:36:33 +00002536Error GlobalISelEmitter::importExplicitUseRenderer(
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002537 RuleMatcher &Rule, BuildMIAction &DstMIBuilder, TreePatternNode *DstChild,
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002538 const InstructionMatcher &InsnMatcher) const {
Daniel Sanders2c269f62017-08-24 09:11:20 +00002539 if (DstChild->getTransformFn() != nullptr) {
2540 return failedImport("Dst pattern child has transform fn " +
2541 DstChild->getTransformFn()->getName());
2542 }
2543
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002544 const auto &SubOperand = Rule.getComplexSubOperand(DstChild->getName());
2545 if (SubOperand.hasValue()) {
2546 DstMIBuilder.addRenderer<RenderComplexPatternOperand>(
2547 0, *std::get<0>(*SubOperand), DstChild->getName(),
2548 std::get<1>(*SubOperand), std::get<2>(*SubOperand));
2549 return Error::success();
2550 }
2551
Daniel Sandersffc7d582017-03-29 15:37:18 +00002552 if (!DstChild->isLeaf()) {
Daniel Sanders05540042017-08-08 10:44:31 +00002553 // We accept 'bb' here. It's an operator because BasicBlockSDNode isn't
2554 // inline, but in MI it's just another operand.
Daniel Sandersffc7d582017-03-29 15:37:18 +00002555 if (DstChild->getOperator()->isSubClassOf("SDNode")) {
2556 auto &ChildSDNI = CGP.getSDNodeInfo(DstChild->getOperator());
2557 if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") {
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002558 DstMIBuilder.addRenderer<CopyRenderer>(0, InsnMatcher,
Daniel Sandersffc7d582017-03-29 15:37:18 +00002559 DstChild->getName());
Daniel Sandersc270c502017-03-30 09:36:33 +00002560 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00002561 }
2562 }
Daniel Sanders05540042017-08-08 10:44:31 +00002563
2564 // Similarly, imm is an operator in TreePatternNode's view but must be
2565 // rendered as operands.
2566 // FIXME: The target should be able to choose sign-extended when appropriate
2567 // (e.g. on Mips).
2568 if (DstChild->getOperator()->getName() == "imm") {
2569 DstMIBuilder.addRenderer<CopyConstantAsImmRenderer>(0,
2570 DstChild->getName());
2571 return Error::success();
Daniel Sanders11300ce2017-10-13 21:28:03 +00002572 } else if (DstChild->getOperator()->getName() == "fpimm") {
2573 DstMIBuilder.addRenderer<CopyFConstantAsFPImmRenderer>(
2574 0, DstChild->getName());
2575 return Error::success();
Daniel Sanders05540042017-08-08 10:44:31 +00002576 }
2577
Daniel Sanders2c269f62017-08-24 09:11:20 +00002578 return failedImport("Dst pattern child isn't a leaf node or an MBB" + llvm::to_string(*DstChild));
Daniel Sandersffc7d582017-03-29 15:37:18 +00002579 }
2580
2581 // Otherwise, we're looking for a bog-standard RegisterClass operand.
Daniel Sandersffc7d582017-03-29 15:37:18 +00002582 if (auto *ChildDefInit = dyn_cast<DefInit>(DstChild->getLeafValue())) {
2583 auto *ChildRec = ChildDefInit->getDef();
2584
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002585 ArrayRef<TypeSetByHwMode> ChildTypes = DstChild->getExtTypes();
Daniel Sandersffc7d582017-03-29 15:37:18 +00002586 if (ChildTypes.size() != 1)
2587 return failedImport("Dst pattern child has multiple results");
2588
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002589 Optional<LLTCodeGen> OpTyOrNone = None;
2590 if (ChildTypes.front().isMachineValueType())
2591 OpTyOrNone = MVTToLLT(ChildTypes.front().getMachineValueType().SimpleTy);
Daniel Sandersffc7d582017-03-29 15:37:18 +00002592 if (!OpTyOrNone)
2593 return failedImport("Dst operand has an unsupported type");
2594
2595 if (ChildRec->isSubClassOf("Register")) {
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002596 DstMIBuilder.addRenderer<AddRegisterRenderer>(0, ChildRec);
Daniel Sandersc270c502017-03-30 09:36:33 +00002597 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00002598 }
2599
Daniel Sanders658541f2017-04-22 15:53:21 +00002600 if (ChildRec->isSubClassOf("RegisterClass") ||
Daniel Sanders4d4e7652017-10-09 18:14:53 +00002601 ChildRec->isSubClassOf("RegisterOperand") ||
2602 ChildRec->isSubClassOf("ValueType")) {
Daniel Sandersd66e0902017-10-23 18:19:24 +00002603 if (ChildRec->isSubClassOf("RegisterOperand") &&
2604 !ChildRec->isValueUnset("GIZeroRegister")) {
2605 DstMIBuilder.addRenderer<CopyOrAddZeroRegRenderer>(
2606 0, InsnMatcher, DstChild->getName(),
2607 ChildRec->getValueAsDef("GIZeroRegister"));
2608 return Error::success();
2609 }
2610
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002611 DstMIBuilder.addRenderer<CopyRenderer>(0, InsnMatcher,
2612 DstChild->getName());
Daniel Sandersc270c502017-03-30 09:36:33 +00002613 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00002614 }
2615
2616 if (ChildRec->isSubClassOf("ComplexPattern")) {
2617 const auto &ComplexPattern = ComplexPatternEquivs.find(ChildRec);
2618 if (ComplexPattern == ComplexPatternEquivs.end())
2619 return failedImport(
2620 "SelectionDAG ComplexPattern not mapped to GlobalISel");
2621
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002622 const OperandMatcher &OM = Rule.getOperandMatcher(DstChild->getName());
Daniel Sandersffc7d582017-03-29 15:37:18 +00002623 DstMIBuilder.addRenderer<RenderComplexPatternOperand>(
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002624 0, *ComplexPattern->second, DstChild->getName(),
Daniel Sanders2deea182017-04-22 15:11:04 +00002625 OM.getAllocatedTemporariesBaseID());
Daniel Sandersc270c502017-03-30 09:36:33 +00002626 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00002627 }
2628
Daniel Sandersd0656a32017-04-13 09:45:37 +00002629 if (ChildRec->isSubClassOf("SDNodeXForm"))
2630 return failedImport("Dst pattern child def is an unsupported tablegen "
2631 "class (SDNodeXForm)");
2632
Daniel Sandersffc7d582017-03-29 15:37:18 +00002633 return failedImport(
2634 "Dst pattern child def is an unsupported tablegen class");
2635 }
2636
2637 return failedImport("Dst pattern child is an unsupported kind");
2638}
2639
Daniel Sandersc270c502017-03-30 09:36:33 +00002640Expected<BuildMIAction &> GlobalISelEmitter::createAndImportInstructionRenderer(
Daniel Sandersffc7d582017-03-29 15:37:18 +00002641 RuleMatcher &M, const TreePatternNode *Dst,
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002642 const InstructionMatcher &InsnMatcher) {
Daniel Sandersffc7d582017-03-29 15:37:18 +00002643 Record *DstOp = Dst->getOperator();
Daniel Sandersd0656a32017-04-13 09:45:37 +00002644 if (!DstOp->isSubClassOf("Instruction")) {
2645 if (DstOp->isSubClassOf("ValueType"))
2646 return failedImport(
2647 "Pattern operator isn't an instruction (it's a ValueType)");
Daniel Sandersffc7d582017-03-29 15:37:18 +00002648 return failedImport("Pattern operator isn't an instruction");
Daniel Sandersd0656a32017-04-13 09:45:37 +00002649 }
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002650 CodeGenInstruction *DstI = &Target.getInstruction(DstOp);
Daniel Sandersffc7d582017-03-29 15:37:18 +00002651
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002652 unsigned DstINumUses = DstI->Operands.size() - DstI->Operands.NumDefs;
2653 unsigned ExpectedDstINumUses = Dst->getNumChildren();
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002654 bool IsExtractSubReg = false;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002655
2656 // COPY_TO_REGCLASS is just a copy with a ConstrainOperandToRegClassAction
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002657 // attached. Similarly for EXTRACT_SUBREG except that's a subregister copy.
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002658 if (DstI->TheDef->getName() == "COPY_TO_REGCLASS") {
2659 DstI = &Target.getInstruction(RK.getDef("COPY"));
2660 DstINumUses--; // Ignore the class constraint.
2661 ExpectedDstINumUses--;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002662 } else if (DstI->TheDef->getName() == "EXTRACT_SUBREG") {
2663 DstI = &Target.getInstruction(RK.getDef("COPY"));
2664 IsExtractSubReg = true;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002665 }
2666
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002667 auto &DstMIBuilder = M.addAction<BuildMIAction>(0, DstI, InsnMatcher);
Daniel Sandersffc7d582017-03-29 15:37:18 +00002668
2669 // Render the explicit defs.
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002670 for (unsigned I = 0; I < DstI->Operands.NumDefs; ++I) {
2671 const CGIOperandList::OperandInfo &DstIOperand = DstI->Operands[I];
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002672 DstMIBuilder.addRenderer<CopyRenderer>(0, InsnMatcher, DstIOperand.Name);
Daniel Sandersffc7d582017-03-29 15:37:18 +00002673 }
2674
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002675 // EXTRACT_SUBREG needs to use a subregister COPY.
2676 if (IsExtractSubReg) {
2677 if (!Dst->getChild(0)->isLeaf())
2678 return failedImport("EXTRACT_SUBREG child #1 is not a leaf");
2679
Daniel Sanders32291982017-06-28 13:50:04 +00002680 if (DefInit *SubRegInit =
2681 dyn_cast<DefInit>(Dst->getChild(1)->getLeafValue())) {
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002682 CodeGenRegisterClass *RC = CGRegs.getRegClass(
2683 getInitValueAsRegClass(Dst->getChild(0)->getLeafValue()));
2684 CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef());
2685
2686 const auto &SrcRCDstRCPair =
2687 RC->getMatchingSubClassWithSubRegs(CGRegs, SubIdx);
2688 if (SrcRCDstRCPair.hasValue()) {
2689 assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
2690 if (SrcRCDstRCPair->first != RC)
2691 return failedImport("EXTRACT_SUBREG requires an additional COPY");
2692 }
2693
2694 DstMIBuilder.addRenderer<CopySubRegRenderer>(
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002695 0, InsnMatcher, Dst->getChild(0)->getName(), SubIdx);
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002696 return DstMIBuilder;
2697 }
2698
2699 return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
2700 }
2701
Daniel Sandersffc7d582017-03-29 15:37:18 +00002702 // Render the explicit uses.
Daniel Sanders0ed28822017-04-12 08:23:08 +00002703 unsigned Child = 0;
Diana Picus382602f2017-05-17 08:57:28 +00002704 unsigned NumDefaultOps = 0;
Daniel Sanders0ed28822017-04-12 08:23:08 +00002705 for (unsigned I = 0; I != DstINumUses; ++I) {
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002706 const CGIOperandList::OperandInfo &DstIOperand =
2707 DstI->Operands[DstI->Operands.NumDefs + I];
Daniel Sanders0ed28822017-04-12 08:23:08 +00002708
Diana Picus382602f2017-05-17 08:57:28 +00002709 // If the operand has default values, introduce them now.
2710 // FIXME: Until we have a decent test case that dictates we should do
2711 // otherwise, we're going to assume that operands with default values cannot
2712 // be specified in the patterns. Therefore, adding them will not cause us to
2713 // end up with too many rendered operands.
2714 if (DstIOperand.Rec->isSubClassOf("OperandWithDefaultOps")) {
Daniel Sanders0ed28822017-04-12 08:23:08 +00002715 DagInit *DefaultOps = DstIOperand.Rec->getValueAsDag("DefaultOps");
Diana Picus382602f2017-05-17 08:57:28 +00002716 if (auto Error = importDefaultOperandRenderers(DstMIBuilder, DefaultOps))
2717 return std::move(Error);
2718 ++NumDefaultOps;
Daniel Sanders0ed28822017-04-12 08:23:08 +00002719 continue;
2720 }
2721
2722 if (auto Error = importExplicitUseRenderer(
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002723 M, DstMIBuilder, Dst->getChild(Child), InsnMatcher))
Daniel Sandersffc7d582017-03-29 15:37:18 +00002724 return std::move(Error);
Daniel Sanders0ed28822017-04-12 08:23:08 +00002725 ++Child;
Daniel Sandersffc7d582017-03-29 15:37:18 +00002726 }
2727
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002728 if (NumDefaultOps + ExpectedDstINumUses != DstINumUses)
Diana Picuseb2057c2017-05-17 09:25:08 +00002729 return failedImport("Expected " + llvm::to_string(DstINumUses) +
Diana Picus382602f2017-05-17 08:57:28 +00002730 " used operands but found " +
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002731 llvm::to_string(ExpectedDstINumUses) +
Diana Picuseb2057c2017-05-17 09:25:08 +00002732 " explicit ones and " + llvm::to_string(NumDefaultOps) +
Diana Picus382602f2017-05-17 08:57:28 +00002733 " default ones");
2734
Daniel Sandersffc7d582017-03-29 15:37:18 +00002735 return DstMIBuilder;
2736}
2737
Diana Picus382602f2017-05-17 08:57:28 +00002738Error GlobalISelEmitter::importDefaultOperandRenderers(
2739 BuildMIAction &DstMIBuilder, DagInit *DefaultOps) const {
Craig Topper481ff702017-05-29 21:49:34 +00002740 for (const auto *DefaultOp : DefaultOps->getArgs()) {
Diana Picus382602f2017-05-17 08:57:28 +00002741 // Look through ValueType operators.
2742 if (const DagInit *DefaultDagOp = dyn_cast<DagInit>(DefaultOp)) {
2743 if (const DefInit *DefaultDagOperator =
2744 dyn_cast<DefInit>(DefaultDagOp->getOperator())) {
2745 if (DefaultDagOperator->getDef()->isSubClassOf("ValueType"))
2746 DefaultOp = DefaultDagOp->getArg(0);
2747 }
2748 }
2749
2750 if (const DefInit *DefaultDefOp = dyn_cast<DefInit>(DefaultOp)) {
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002751 DstMIBuilder.addRenderer<AddRegisterRenderer>(0, DefaultDefOp->getDef());
Diana Picus382602f2017-05-17 08:57:28 +00002752 continue;
2753 }
2754
2755 if (const IntInit *DefaultIntOp = dyn_cast<IntInit>(DefaultOp)) {
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002756 DstMIBuilder.addRenderer<ImmRenderer>(0, DefaultIntOp->getValue());
Diana Picus382602f2017-05-17 08:57:28 +00002757 continue;
2758 }
2759
2760 return failedImport("Could not add default op");
2761 }
2762
2763 return Error::success();
2764}
2765
Daniel Sandersc270c502017-03-30 09:36:33 +00002766Error GlobalISelEmitter::importImplicitDefRenderers(
Daniel Sandersffc7d582017-03-29 15:37:18 +00002767 BuildMIAction &DstMIBuilder,
2768 const std::vector<Record *> &ImplicitDefs) const {
2769 if (!ImplicitDefs.empty())
2770 return failedImport("Pattern defines a physical register");
Daniel Sandersc270c502017-03-30 09:36:33 +00002771 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00002772}
2773
2774Expected<RuleMatcher> GlobalISelEmitter::runOnPattern(const PatternToMatch &P) {
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002775 // Keep track of the matchers and actions to emit.
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002776 RuleMatcher M(P.getSrcRecord()->getLoc());
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +00002777 M.addAction<DebugCommentAction>(P);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002778
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002779 if (auto Error = importRulePredicates(M, P.getPredicates()))
Daniel Sandersffc7d582017-03-29 15:37:18 +00002780 return std::move(Error);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002781
2782 // Next, analyze the pattern operators.
2783 TreePatternNode *Src = P.getSrcPattern();
2784 TreePatternNode *Dst = P.getDstPattern();
2785
2786 // If the root of either pattern isn't a simple operator, ignore it.
Daniel Sandersd0656a32017-04-13 09:45:37 +00002787 if (auto Err = isTrivialOperatorNode(Dst))
2788 return failedImport("Dst pattern root isn't a trivial operator (" +
2789 toString(std::move(Err)) + ")");
2790 if (auto Err = isTrivialOperatorNode(Src))
2791 return failedImport("Src pattern root isn't a trivial operator (" +
2792 toString(std::move(Err)) + ")");
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002793
Daniel Sandersedd07842017-08-17 09:26:14 +00002794 InstructionMatcher &InsnMatcherTemp = M.addInstructionMatcher(Src->getName());
2795 unsigned TempOpIdx = 0;
2796 auto InsnMatcherOrError =
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002797 createAndImportSelDAGMatcher(M, InsnMatcherTemp, Src, TempOpIdx);
Daniel Sandersedd07842017-08-17 09:26:14 +00002798 if (auto Error = InsnMatcherOrError.takeError())
2799 return std::move(Error);
2800 InstructionMatcher &InsnMatcher = InsnMatcherOrError.get();
2801
2802 if (Dst->isLeaf()) {
2803 Record *RCDef = getInitValueAsRegClass(Dst->getLeafValue());
2804
2805 const CodeGenRegisterClass &RC = Target.getRegisterClass(RCDef);
2806 if (RCDef) {
2807 // We need to replace the def and all its uses with the specified
2808 // operand. However, we must also insert COPY's wherever needed.
2809 // For now, emit a copy and let the register allocator clean up.
2810 auto &DstI = Target.getInstruction(RK.getDef("COPY"));
2811 const auto &DstIOperand = DstI.Operands[0];
2812
2813 OperandMatcher &OM0 = InsnMatcher.getOperand(0);
2814 OM0.setSymbolicName(DstIOperand.Name);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002815 M.defineOperand(OM0.getSymbolicName(), OM0);
Daniel Sandersedd07842017-08-17 09:26:14 +00002816 OM0.addPredicate<RegisterBankOperandMatcher>(RC);
2817
2818 auto &DstMIBuilder = M.addAction<BuildMIAction>(0, &DstI, InsnMatcher);
2819 DstMIBuilder.addRenderer<CopyRenderer>(0, InsnMatcher, DstIOperand.Name);
2820 DstMIBuilder.addRenderer<CopyRenderer>(0, InsnMatcher, Dst->getName());
2821 M.addAction<ConstrainOperandToRegClassAction>(0, 0, RC);
2822
2823 // We're done with this pattern! It's eligible for GISel emission; return
2824 // it.
2825 ++NumPatternImported;
2826 return std::move(M);
2827 }
2828
Daniel Sanders452c8ae2017-05-23 19:33:16 +00002829 return failedImport("Dst pattern root isn't a known leaf");
Daniel Sandersedd07842017-08-17 09:26:14 +00002830 }
Daniel Sanders452c8ae2017-05-23 19:33:16 +00002831
Daniel Sandersbee57392017-04-04 13:25:23 +00002832 // Start with the defined operands (i.e., the results of the root operator).
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002833 Record *DstOp = Dst->getOperator();
2834 if (!DstOp->isSubClassOf("Instruction"))
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002835 return failedImport("Pattern operator isn't an instruction");
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002836
2837 auto &DstI = Target.getInstruction(DstOp);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002838 if (DstI.Operands.NumDefs != Src->getExtTypes().size())
Daniel Sandersd0656a32017-04-13 09:45:37 +00002839 return failedImport("Src pattern results and dst MI defs are different (" +
2840 to_string(Src->getExtTypes().size()) + " def(s) vs " +
2841 to_string(DstI.Operands.NumDefs) + " def(s))");
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002842
Daniel Sandersffc7d582017-03-29 15:37:18 +00002843 // The root of the match also has constraints on the register bank so that it
2844 // matches the result instruction.
2845 unsigned OpIdx = 0;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002846 for (const TypeSetByHwMode &VTy : Src->getExtTypes()) {
2847 (void)VTy;
Daniel Sandersffc7d582017-03-29 15:37:18 +00002848
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002849 const auto &DstIOperand = DstI.Operands[OpIdx];
2850 Record *DstIOpRec = DstIOperand.Rec;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002851 if (DstI.TheDef->getName() == "COPY_TO_REGCLASS") {
2852 DstIOpRec = getInitValueAsRegClass(Dst->getChild(1)->getLeafValue());
2853
2854 if (DstIOpRec == nullptr)
2855 return failedImport(
2856 "COPY_TO_REGCLASS operand #1 isn't a register class");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002857 } else if (DstI.TheDef->getName() == "EXTRACT_SUBREG") {
2858 if (!Dst->getChild(0)->isLeaf())
2859 return failedImport("EXTRACT_SUBREG operand #0 isn't a leaf");
2860
Daniel Sanders32291982017-06-28 13:50:04 +00002861 // We can assume that a subregister is in the same bank as it's super
2862 // register.
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002863 DstIOpRec = getInitValueAsRegClass(Dst->getChild(0)->getLeafValue());
2864
2865 if (DstIOpRec == nullptr)
2866 return failedImport(
2867 "EXTRACT_SUBREG operand #0 isn't a register class");
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002868 } else if (DstIOpRec->isSubClassOf("RegisterOperand"))
Daniel Sanders658541f2017-04-22 15:53:21 +00002869 DstIOpRec = DstIOpRec->getValueAsDef("RegClass");
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002870 else if (!DstIOpRec->isSubClassOf("RegisterClass"))
Daniel Sanders32291982017-06-28 13:50:04 +00002871 return failedImport("Dst MI def isn't a register class" +
2872 to_string(*Dst));
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002873
Daniel Sandersffc7d582017-03-29 15:37:18 +00002874 OperandMatcher &OM = InsnMatcher.getOperand(OpIdx);
2875 OM.setSymbolicName(DstIOperand.Name);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002876 M.defineOperand(OM.getSymbolicName(), OM);
Daniel Sandersdc662ff2017-01-26 11:10:14 +00002877 OM.addPredicate<RegisterBankOperandMatcher>(
2878 Target.getRegisterClass(DstIOpRec));
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002879 ++OpIdx;
2880 }
2881
Daniel Sandersc270c502017-03-30 09:36:33 +00002882 auto DstMIBuilderOrError =
2883 createAndImportInstructionRenderer(M, Dst, InsnMatcher);
Daniel Sandersffc7d582017-03-29 15:37:18 +00002884 if (auto Error = DstMIBuilderOrError.takeError())
2885 return std::move(Error);
2886 BuildMIAction &DstMIBuilder = DstMIBuilderOrError.get();
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002887
Daniel Sandersffc7d582017-03-29 15:37:18 +00002888 // Render the implicit defs.
2889 // These are only added to the root of the result.
Daniel Sandersc270c502017-03-30 09:36:33 +00002890 if (auto Error = importImplicitDefRenderers(DstMIBuilder, P.getDstRegs()))
Daniel Sandersffc7d582017-03-29 15:37:18 +00002891 return std::move(Error);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002892
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002893 // Constrain the registers to classes. This is normally derived from the
2894 // emitted instruction but a few instructions require special handling.
2895 if (DstI.TheDef->getName() == "COPY_TO_REGCLASS") {
2896 // COPY_TO_REGCLASS does not provide operand constraints itself but the
2897 // result is constrained to the class given by the second child.
2898 Record *DstIOpRec =
2899 getInitValueAsRegClass(Dst->getChild(1)->getLeafValue());
2900
2901 if (DstIOpRec == nullptr)
2902 return failedImport("COPY_TO_REGCLASS operand #1 isn't a register class");
2903
2904 M.addAction<ConstrainOperandToRegClassAction>(
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002905 0, 0, Target.getRegisterClass(DstIOpRec));
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002906
2907 // We're done with this pattern! It's eligible for GISel emission; return
2908 // it.
2909 ++NumPatternImported;
2910 return std::move(M);
2911 }
2912
2913 if (DstI.TheDef->getName() == "EXTRACT_SUBREG") {
2914 // EXTRACT_SUBREG selects into a subregister COPY but unlike most
2915 // instructions, the result register class is controlled by the
2916 // subregisters of the operand. As a result, we must constrain the result
2917 // class rather than check that it's already the right one.
2918 if (!Dst->getChild(0)->isLeaf())
2919 return failedImport("EXTRACT_SUBREG child #1 is not a leaf");
2920
Daniel Sanders320390b2017-06-28 15:16:03 +00002921 DefInit *SubRegInit = dyn_cast<DefInit>(Dst->getChild(1)->getLeafValue());
2922 if (!SubRegInit)
2923 return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002924
Daniel Sanders320390b2017-06-28 15:16:03 +00002925 // Constrain the result to the same register bank as the operand.
2926 Record *DstIOpRec =
2927 getInitValueAsRegClass(Dst->getChild(0)->getLeafValue());
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002928
Daniel Sanders320390b2017-06-28 15:16:03 +00002929 if (DstIOpRec == nullptr)
2930 return failedImport("EXTRACT_SUBREG operand #1 isn't a register class");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002931
Daniel Sanders320390b2017-06-28 15:16:03 +00002932 CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef());
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002933 CodeGenRegisterClass *SrcRC = CGRegs.getRegClass(DstIOpRec);
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002934
Daniel Sanders320390b2017-06-28 15:16:03 +00002935 // It would be nice to leave this constraint implicit but we're required
2936 // to pick a register class so constrain the result to a register class
2937 // that can hold the correct MVT.
2938 //
2939 // FIXME: This may introduce an extra copy if the chosen class doesn't
2940 // actually contain the subregisters.
2941 assert(Src->getExtTypes().size() == 1 &&
2942 "Expected Src of EXTRACT_SUBREG to have one result type");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002943
Daniel Sanders320390b2017-06-28 15:16:03 +00002944 const auto &SrcRCDstRCPair =
2945 SrcRC->getMatchingSubClassWithSubRegs(CGRegs, SubIdx);
2946 assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002947 M.addAction<ConstrainOperandToRegClassAction>(0, 0, *SrcRCDstRCPair->second);
2948 M.addAction<ConstrainOperandToRegClassAction>(0, 1, *SrcRCDstRCPair->first);
2949
2950 // We're done with this pattern! It's eligible for GISel emission; return
2951 // it.
2952 ++NumPatternImported;
2953 return std::move(M);
2954 }
2955
2956 M.addAction<ConstrainOperandsToDefinitionAction>(0);
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002957
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002958 // We're done with this pattern! It's eligible for GISel emission; return it.
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00002959 ++NumPatternImported;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002960 return std::move(M);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002961}
2962
Daniel Sanders649c5852017-10-13 20:42:18 +00002963// Emit imm predicate table and an enum to reference them with.
2964// The 'Predicate_' part of the name is redundant but eliminating it is more
2965// trouble than it's worth.
2966void GlobalISelEmitter::emitImmPredicates(
Daniel Sanders11300ce2017-10-13 21:28:03 +00002967 raw_ostream &OS, StringRef TypeIdentifier, StringRef Type,
2968 std::function<bool(const Record *R)> Filter) {
Daniel Sanders649c5852017-10-13 20:42:18 +00002969 std::vector<const Record *> MatchedRecords;
2970 const auto &Defs = RK.getAllDerivedDefinitions("PatFrag");
2971 std::copy_if(Defs.begin(), Defs.end(), std::back_inserter(MatchedRecords),
2972 [&](Record *Record) {
2973 return !Record->getValueAsString("ImmediateCode").empty() &&
2974 Filter(Record);
2975 });
2976
Daniel Sanders11300ce2017-10-13 21:28:03 +00002977 if (!MatchedRecords.empty()) {
2978 OS << "// PatFrag predicates.\n"
2979 << "enum {\n";
Daniel Sanders2fed4ff2017-10-13 21:51:20 +00002980 std::string EnumeratorSeparator =
Daniel Sanders11300ce2017-10-13 21:28:03 +00002981 (" = GIPFP_" + TypeIdentifier + "_Invalid + 1,\n").str();
2982 for (const auto *Record : MatchedRecords) {
2983 OS << " GIPFP_" << TypeIdentifier << "_Predicate_" << Record->getName()
2984 << EnumeratorSeparator;
2985 EnumeratorSeparator = ",\n";
2986 }
2987 OS << "};\n";
Daniel Sanders649c5852017-10-13 20:42:18 +00002988 }
Daniel Sanders11300ce2017-10-13 21:28:03 +00002989
Daniel Sanders649c5852017-10-13 20:42:18 +00002990 for (const auto *Record : MatchedRecords)
Daniel Sanders11300ce2017-10-13 21:28:03 +00002991 OS << "static bool Predicate_" << Record->getName() << "(" << Type
2992 << " Imm) {" << Record->getValueAsString("ImmediateCode") << "}\n";
2993
2994 OS << "static InstructionSelector::" << TypeIdentifier
2995 << "ImmediatePredicateFn " << TypeIdentifier << "ImmPredicateFns[] = {\n"
Daniel Sanders649c5852017-10-13 20:42:18 +00002996 << " nullptr,\n";
2997 for (const auto *Record : MatchedRecords)
2998 OS << " Predicate_" << Record->getName() << ",\n";
2999 OS << "};\n";
3000}
3001
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003002void GlobalISelEmitter::run(raw_ostream &OS) {
3003 // Track the GINodeEquiv definitions.
3004 gatherNodeEquivs();
3005
3006 emitSourceFileHeader(("Global Instruction Selector for the " +
3007 Target.getName() + " target").str(), OS);
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00003008 std::vector<RuleMatcher> Rules;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003009 // Look through the SelectionDAG patterns we found, possibly emitting some.
3010 for (const PatternToMatch &Pat : CGP.ptms()) {
3011 ++NumPatternTotal;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003012 auto MatcherOrErr = runOnPattern(Pat);
3013
3014 // The pattern analysis can fail, indicating an unsupported pattern.
3015 // Report that if we've been asked to do so.
3016 if (auto Err = MatcherOrErr.takeError()) {
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003017 if (WarnOnSkippedPatterns) {
3018 PrintWarning(Pat.getSrcRecord()->getLoc(),
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003019 "Skipped pattern: " + toString(std::move(Err)));
3020 } else {
3021 consumeError(std::move(Err));
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003022 }
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00003023 ++NumPatternImportsSkipped;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003024 continue;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003025 }
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003026
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00003027 Rules.push_back(std::move(MatcherOrErr.get()));
3028 }
3029
Daniel Sanderseb2f5f32017-08-15 15:10:31 +00003030 std::stable_sort(Rules.begin(), Rules.end(),
3031 [&](const RuleMatcher &A, const RuleMatcher &B) {
3032 if (A.isHigherPriorityThan(B)) {
3033 assert(!B.isHigherPriorityThan(A) && "Cannot be more important "
3034 "and less important at "
3035 "the same time");
3036 return true;
3037 }
3038 return false;
3039 });
Daniel Sanders759ff412017-02-24 13:58:11 +00003040
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003041 std::vector<Record *> ComplexPredicates =
3042 RK.getAllDerivedDefinitions("GIComplexOperandMatcher");
3043 std::sort(ComplexPredicates.begin(), ComplexPredicates.end(),
3044 [](const Record *A, const Record *B) {
3045 if (A->getName() < B->getName())
3046 return true;
3047 return false;
3048 });
Daniel Sanders8a4bae92017-03-14 21:32:08 +00003049 unsigned MaxTemporaries = 0;
3050 for (const auto &Rule : Rules)
Daniel Sanders2deea182017-04-22 15:11:04 +00003051 MaxTemporaries = std::max(MaxTemporaries, Rule.countRendererFns());
Daniel Sanders8a4bae92017-03-14 21:32:08 +00003052
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003053 OS << "#ifdef GET_GLOBALISEL_PREDICATE_BITSET\n"
3054 << "const unsigned MAX_SUBTARGET_PREDICATES = " << SubtargetFeatures.size()
3055 << ";\n"
3056 << "using PredicateBitset = "
3057 "llvm::PredicateBitsetImpl<MAX_SUBTARGET_PREDICATES>;\n"
3058 << "#endif // ifdef GET_GLOBALISEL_PREDICATE_BITSET\n\n";
3059
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003060 OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n"
3061 << " mutable MatcherState State;\n"
3062 << " typedef "
Daniel Sanders1e4569f2017-10-20 20:55:29 +00003063 "ComplexRendererFns("
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003064 << Target.getName()
3065 << "InstructionSelector::*ComplexMatcherMemFn)(MachineOperand &) const;\n"
Daniel Sandersea8711b2017-10-16 03:36:29 +00003066 << " const MatcherInfoTy<PredicateBitset, ComplexMatcherMemFn> "
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003067 "MatcherInfo;\n"
Daniel Sandersea8711b2017-10-16 03:36:29 +00003068 << " static " << Target.getName()
3069 << "InstructionSelector::ComplexMatcherMemFn ComplexPredicateFns[];\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003070 << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n\n";
Daniel Sanders8a4bae92017-03-14 21:32:08 +00003071
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003072 OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n"
3073 << ", State(" << MaxTemporaries << "),\n"
Daniel Sanders11300ce2017-10-13 21:28:03 +00003074 << "MatcherInfo({TypeObjects, FeatureBitsets, I64ImmPredicateFns, "
Daniel Sandersea8711b2017-10-16 03:36:29 +00003075 "APIntImmPredicateFns, APFloatImmPredicateFns, ComplexPredicateFns})\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003076 << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n\n";
Daniel Sanders8a4bae92017-03-14 21:32:08 +00003077
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003078 OS << "#ifdef GET_GLOBALISEL_IMPL\n";
3079 SubtargetFeatureInfo::emitSubtargetFeatureBitEnumeration(SubtargetFeatures,
3080 OS);
Daniel Sanderse9fdba32017-04-29 17:30:09 +00003081
3082 // Separate subtarget features by how often they must be recomputed.
3083 SubtargetFeatureInfoMap ModuleFeatures;
3084 std::copy_if(SubtargetFeatures.begin(), SubtargetFeatures.end(),
3085 std::inserter(ModuleFeatures, ModuleFeatures.end()),
3086 [](const SubtargetFeatureInfoMap::value_type &X) {
3087 return !X.second.mustRecomputePerFunction();
3088 });
3089 SubtargetFeatureInfoMap FunctionFeatures;
3090 std::copy_if(SubtargetFeatures.begin(), SubtargetFeatures.end(),
3091 std::inserter(FunctionFeatures, FunctionFeatures.end()),
3092 [](const SubtargetFeatureInfoMap::value_type &X) {
3093 return X.second.mustRecomputePerFunction();
3094 });
3095
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003096 SubtargetFeatureInfo::emitComputeAvailableFeatures(
Daniel Sanderse9fdba32017-04-29 17:30:09 +00003097 Target.getName(), "InstructionSelector", "computeAvailableModuleFeatures",
3098 ModuleFeatures, OS);
3099 SubtargetFeatureInfo::emitComputeAvailableFeatures(
3100 Target.getName(), "InstructionSelector",
3101 "computeAvailableFunctionFeatures", FunctionFeatures, OS,
3102 "const MachineFunction *MF");
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003103
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003104 // Emit a table containing the LLT objects needed by the matcher and an enum
3105 // for the matcher to reference them with.
Daniel Sanders032e7f22017-08-17 13:18:35 +00003106 std::vector<LLTCodeGen> TypeObjects;
3107 for (const auto &Ty : LLTOperandMatcher::KnownTypes)
3108 TypeObjects.push_back(Ty);
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003109 std::sort(TypeObjects.begin(), TypeObjects.end());
Daniel Sanders49980702017-08-23 10:09:25 +00003110 OS << "// LLT Objects.\n"
3111 << "enum {\n";
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003112 for (const auto &TypeObject : TypeObjects) {
3113 OS << " ";
3114 TypeObject.emitCxxEnumValue(OS);
3115 OS << ",\n";
3116 }
3117 OS << "};\n"
3118 << "const static LLT TypeObjects[] = {\n";
3119 for (const auto &TypeObject : TypeObjects) {
3120 OS << " ";
3121 TypeObject.emitCxxConstructorCall(OS);
3122 OS << ",\n";
3123 }
3124 OS << "};\n\n";
3125
3126 // Emit a table containing the PredicateBitsets objects needed by the matcher
3127 // and an enum for the matcher to reference them with.
3128 std::vector<std::vector<Record *>> FeatureBitsets;
3129 for (auto &Rule : Rules)
3130 FeatureBitsets.push_back(Rule.getRequiredFeatures());
3131 std::sort(
3132 FeatureBitsets.begin(), FeatureBitsets.end(),
3133 [&](const std::vector<Record *> &A, const std::vector<Record *> &B) {
3134 if (A.size() < B.size())
3135 return true;
3136 if (A.size() > B.size())
3137 return false;
3138 for (const auto &Pair : zip(A, B)) {
3139 if (std::get<0>(Pair)->getName() < std::get<1>(Pair)->getName())
3140 return true;
3141 if (std::get<0>(Pair)->getName() > std::get<1>(Pair)->getName())
3142 return false;
3143 }
3144 return false;
3145 });
3146 FeatureBitsets.erase(
3147 std::unique(FeatureBitsets.begin(), FeatureBitsets.end()),
3148 FeatureBitsets.end());
Daniel Sanders49980702017-08-23 10:09:25 +00003149 OS << "// Feature bitsets.\n"
3150 << "enum {\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003151 << " GIFBS_Invalid,\n";
3152 for (const auto &FeatureBitset : FeatureBitsets) {
3153 if (FeatureBitset.empty())
3154 continue;
3155 OS << " " << getNameForFeatureBitset(FeatureBitset) << ",\n";
3156 }
3157 OS << "};\n"
3158 << "const static PredicateBitset FeatureBitsets[] {\n"
3159 << " {}, // GIFBS_Invalid\n";
3160 for (const auto &FeatureBitset : FeatureBitsets) {
3161 if (FeatureBitset.empty())
3162 continue;
3163 OS << " {";
3164 for (const auto &Feature : FeatureBitset) {
3165 const auto &I = SubtargetFeatures.find(Feature);
3166 assert(I != SubtargetFeatures.end() && "Didn't import predicate?");
3167 OS << I->second.getEnumBitName() << ", ";
3168 }
3169 OS << "},\n";
3170 }
3171 OS << "};\n\n";
3172
3173 // Emit complex predicate table and an enum to reference them with.
Daniel Sanders49980702017-08-23 10:09:25 +00003174 OS << "// ComplexPattern predicates.\n"
3175 << "enum {\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003176 << " GICP_Invalid,\n";
3177 for (const auto &Record : ComplexPredicates)
3178 OS << " GICP_" << Record->getName() << ",\n";
3179 OS << "};\n"
3180 << "// See constructor for table contents\n\n";
3181
Daniel Sanders11300ce2017-10-13 21:28:03 +00003182 emitImmPredicates(OS, "I64", "int64_t", [](const Record *R) {
Daniel Sanders649c5852017-10-13 20:42:18 +00003183 bool Unset;
3184 return !R->getValueAsBitOrUnset("IsAPFloat", Unset) &&
3185 !R->getValueAsBit("IsAPInt");
3186 });
Daniel Sanders11300ce2017-10-13 21:28:03 +00003187 emitImmPredicates(OS, "APFloat", "const APFloat &", [](const Record *R) {
3188 bool Unset;
3189 return R->getValueAsBitOrUnset("IsAPFloat", Unset);
3190 });
3191 emitImmPredicates(OS, "APInt", "const APInt &", [](const Record *R) {
3192 return R->getValueAsBit("IsAPInt");
3193 });
Daniel Sandersea8711b2017-10-16 03:36:29 +00003194 OS << "\n";
3195
3196 OS << Target.getName() << "InstructionSelector::ComplexMatcherMemFn\n"
3197 << Target.getName() << "InstructionSelector::ComplexPredicateFns[] = {\n"
3198 << " nullptr, // GICP_Invalid\n";
3199 for (const auto &Record : ComplexPredicates)
3200 OS << " &" << Target.getName()
3201 << "InstructionSelector::" << Record->getValueAsString("MatcherFn")
3202 << ", // " << Record->getName() << "\n";
3203 OS << "};\n\n";
Daniel Sanders2c269f62017-08-24 09:11:20 +00003204
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003205 OS << "bool " << Target.getName()
Daniel Sanders8a4bae92017-03-14 21:32:08 +00003206 << "InstructionSelector::selectImpl(MachineInstr &I) const {\n"
3207 << " MachineFunction &MF = *I.getParent()->getParent();\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003208 << " MachineRegisterInfo &MRI = MF.getRegInfo();\n"
Daniel Sanders32291982017-06-28 13:50:04 +00003209 << " // FIXME: This should be computed on a per-function basis rather "
3210 "than per-insn.\n"
3211 << " AvailableFunctionFeatures = computeAvailableFunctionFeatures(&STI, "
3212 "&MF);\n"
Daniel Sandersa6cfce62017-07-05 14:50:18 +00003213 << " const PredicateBitset AvailableFeatures = getAvailableFeatures();\n"
3214 << " NewMIVector OutMIs;\n"
3215 << " State.MIs.clear();\n"
3216 << " State.MIs.push_back(&I);\n\n";
Daniel Sanders8a4bae92017-03-14 21:32:08 +00003217
Daniel Sanders8e82af22017-07-27 11:03:45 +00003218 MatchTable Table(0);
Daniel Sandersb96f40d2017-03-20 15:20:42 +00003219 for (auto &Rule : Rules) {
Daniel Sanders8e82af22017-07-27 11:03:45 +00003220 Rule.emit(Table);
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003221 ++NumPatternEmitted;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003222 }
Daniel Sanders8e82af22017-07-27 11:03:45 +00003223 Table << MatchTable::Opcode("GIM_Reject") << MatchTable::LineBreak;
3224 Table.emitDeclaration(OS);
3225 OS << " if (executeMatchTable(*this, OutMIs, State, MatcherInfo, ";
3226 Table.emitUse(OS);
3227 OS << ", TII, MRI, TRI, RBI, AvailableFeatures)) {\n"
3228 << " return true;\n"
3229 << " }\n\n";
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003230
Daniel Sanders8a4bae92017-03-14 21:32:08 +00003231 OS << " return false;\n"
3232 << "}\n"
3233 << "#endif // ifdef GET_GLOBALISEL_IMPL\n";
Daniel Sanderse9fdba32017-04-29 17:30:09 +00003234
3235 OS << "#ifdef GET_GLOBALISEL_PREDICATES_DECL\n"
3236 << "PredicateBitset AvailableModuleFeatures;\n"
3237 << "mutable PredicateBitset AvailableFunctionFeatures;\n"
3238 << "PredicateBitset getAvailableFeatures() const {\n"
3239 << " return AvailableModuleFeatures | AvailableFunctionFeatures;\n"
3240 << "}\n"
3241 << "PredicateBitset\n"
3242 << "computeAvailableModuleFeatures(const " << Target.getName()
3243 << "Subtarget *Subtarget) const;\n"
3244 << "PredicateBitset\n"
3245 << "computeAvailableFunctionFeatures(const " << Target.getName()
3246 << "Subtarget *Subtarget,\n"
3247 << " const MachineFunction *MF) const;\n"
3248 << "#endif // ifdef GET_GLOBALISEL_PREDICATES_DECL\n";
3249
3250 OS << "#ifdef GET_GLOBALISEL_PREDICATES_INIT\n"
3251 << "AvailableModuleFeatures(computeAvailableModuleFeatures(&STI)),\n"
3252 << "AvailableFunctionFeatures()\n"
3253 << "#endif // ifdef GET_GLOBALISEL_PREDICATES_INIT\n";
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003254}
3255
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003256void GlobalISelEmitter::declareSubtargetFeature(Record *Predicate) {
3257 if (SubtargetFeatures.count(Predicate) == 0)
3258 SubtargetFeatures.emplace(
3259 Predicate, SubtargetFeatureInfo(Predicate, SubtargetFeatures.size()));
3260}
3261
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003262} // end anonymous namespace
3263
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003264//===----------------------------------------------------------------------===//
3265
3266namespace llvm {
3267void EmitGlobalISel(RecordKeeper &RK, raw_ostream &OS) {
3268 GlobalISelEmitter(RK).run(OS);
3269}
3270} // End llvm namespace