blob: 03e2f381d9cd328b1bc726a1edc40242fe34f0df [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"
Daniel Sandersf76f3152017-11-16 00:46:35 +000038#include "llvm/Support/CodeGenCoverage.h"
Ahmed Bougacha36f70352016-12-21 23:26:20 +000039#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"
David Blaikie13e77db2018-03-23 23:58:25 +000042#include "llvm/Support/MachineValueType.h"
Pavel Labath52a82e22017-02-21 09:19:41 +000043#include "llvm/Support/ScopedPrinter.h"
Ahmed Bougacha36f70352016-12-21 23:26:20 +000044#include "llvm/TableGen/Error.h"
45#include "llvm/TableGen/Record.h"
46#include "llvm/TableGen/TableGenBackend.h"
Daniel Sanders8a4bae92017-03-14 21:32:08 +000047#include <numeric>
Daniel Sandersf76f3152017-11-16 00:46:35 +000048#include <string>
Ahmed Bougacha36f70352016-12-21 23:26:20 +000049using namespace llvm;
50
51#define DEBUG_TYPE "gisel-emitter"
52
53STATISTIC(NumPatternTotal, "Total number of patterns");
Daniel Sandersb41ce2b2017-02-20 14:31:27 +000054STATISTIC(NumPatternImported, "Number of patterns imported from SelectionDAG");
55STATISTIC(NumPatternImportsSkipped, "Number of SelectionDAG imports skipped");
Daniel Sandersf76f3152017-11-16 00:46:35 +000056STATISTIC(NumPatternsTested, "Number of patterns executed according to coverage information");
Ahmed Bougacha36f70352016-12-21 23:26:20 +000057STATISTIC(NumPatternEmitted, "Number of patterns emitted");
58
Daniel Sanders0848b232017-03-27 13:15:13 +000059cl::OptionCategory GlobalISelEmitterCat("Options for -gen-global-isel");
60
Ahmed Bougacha36f70352016-12-21 23:26:20 +000061static cl::opt<bool> WarnOnSkippedPatterns(
62 "warn-on-skipped-patterns",
63 cl::desc("Explain why a pattern was skipped for inclusion "
64 "in the GlobalISel selector"),
Daniel Sanders0848b232017-03-27 13:15:13 +000065 cl::init(false), cl::cat(GlobalISelEmitterCat));
Ahmed Bougacha36f70352016-12-21 23:26:20 +000066
Daniel Sandersf76f3152017-11-16 00:46:35 +000067static cl::opt<bool> GenerateCoverage(
68 "instrument-gisel-coverage",
69 cl::desc("Generate coverage instrumentation for GlobalISel"),
70 cl::init(false), cl::cat(GlobalISelEmitterCat));
71
72static cl::opt<std::string> UseCoverageFile(
73 "gisel-coverage-file", cl::init(""),
74 cl::desc("Specify file to retrieve coverage information from"),
75 cl::cat(GlobalISelEmitterCat));
76
Quentin Colombetec76d9c2017-12-18 19:47:41 +000077static cl::opt<bool> OptimizeMatchTable(
78 "optimize-match-table",
79 cl::desc("Generate an optimized version of the match table"),
80 cl::init(true), cl::cat(GlobalISelEmitterCat));
81
Daniel Sandersbdfebb82017-03-15 20:18:38 +000082namespace {
Ahmed Bougacha36f70352016-12-21 23:26:20 +000083//===- Helper functions ---------------------------------------------------===//
84
Daniel Sanders11300ce2017-10-13 21:28:03 +000085/// Get the name of the enum value used to number the predicate function.
86std::string getEnumNameForPredicate(const TreePredicateFn &Predicate) {
Daniel Sanders8ead1292018-06-15 23:13:43 +000087 if (Predicate.hasGISelPredicateCode())
88 return "GIPFP_MI_" + Predicate.getFnName();
Simon Pilgrim6ecae9f2017-10-14 21:27:53 +000089 return "GIPFP_" + Predicate.getImmTypeIdentifier().str() + "_" +
Daniel Sanders11300ce2017-10-13 21:28:03 +000090 Predicate.getFnName();
91}
92
93/// Get the opcode used to check this predicate.
94std::string getMatchOpcodeForPredicate(const TreePredicateFn &Predicate) {
Simon Pilgrim6ecae9f2017-10-14 21:27:53 +000095 return "GIM_Check" + Predicate.getImmTypeIdentifier().str() + "ImmPredicate";
Daniel Sanders11300ce2017-10-13 21:28:03 +000096}
97
Daniel Sanders52b4ce72017-03-07 23:20:35 +000098/// This class stands in for LLT wherever we want to tablegen-erate an
99/// equivalent at compiler run-time.
100class LLTCodeGen {
101private:
102 LLT Ty;
103
104public:
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000105 LLTCodeGen() = default;
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000106 LLTCodeGen(const LLT &Ty) : Ty(Ty) {}
107
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000108 std::string getCxxEnumValue() const {
109 std::string Str;
110 raw_string_ostream OS(Str);
111
112 emitCxxEnumValue(OS);
113 return OS.str();
114 }
115
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000116 void emitCxxEnumValue(raw_ostream &OS) const {
117 if (Ty.isScalar()) {
118 OS << "GILLT_s" << Ty.getSizeInBits();
119 return;
120 }
121 if (Ty.isVector()) {
122 OS << "GILLT_v" << Ty.getNumElements() << "s" << Ty.getScalarSizeInBits();
123 return;
124 }
Daniel Sandersa71f4542017-10-16 00:56:30 +0000125 if (Ty.isPointer()) {
126 OS << "GILLT_p" << Ty.getAddressSpace();
127 if (Ty.getSizeInBits() > 0)
128 OS << "s" << Ty.getSizeInBits();
129 return;
130 }
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000131 llvm_unreachable("Unhandled LLT");
132 }
133
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000134 void emitCxxConstructorCall(raw_ostream &OS) const {
135 if (Ty.isScalar()) {
136 OS << "LLT::scalar(" << Ty.getSizeInBits() << ")";
137 return;
138 }
139 if (Ty.isVector()) {
Daniel Sanders32291982017-06-28 13:50:04 +0000140 OS << "LLT::vector(" << Ty.getNumElements() << ", "
141 << Ty.getScalarSizeInBits() << ")";
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000142 return;
143 }
Daniel Sandersa71f4542017-10-16 00:56:30 +0000144 if (Ty.isPointer() && Ty.getSizeInBits() > 0) {
145 OS << "LLT::pointer(" << Ty.getAddressSpace() << ", "
146 << Ty.getSizeInBits() << ")";
147 return;
148 }
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000149 llvm_unreachable("Unhandled LLT");
150 }
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000151
152 const LLT &get() const { return Ty; }
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000153
Mandeep Singh Grang1b0e2f22018-04-06 20:18:05 +0000154 /// This ordering is used for std::unique() and llvm::sort(). There's no
Daniel Sanders032e7f22017-08-17 13:18:35 +0000155 /// particular logic behind the order but either A < B or B < A must be
156 /// true if A != B.
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000157 bool operator<(const LLTCodeGen &Other) const {
Daniel Sanders032e7f22017-08-17 13:18:35 +0000158 if (Ty.isValid() != Other.Ty.isValid())
159 return Ty.isValid() < Other.Ty.isValid();
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000160 if (!Ty.isValid())
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000161 return false;
Daniel Sanders032e7f22017-08-17 13:18:35 +0000162
163 if (Ty.isVector() != Other.Ty.isVector())
164 return Ty.isVector() < Other.Ty.isVector();
165 if (Ty.isScalar() != Other.Ty.isScalar())
166 return Ty.isScalar() < Other.Ty.isScalar();
167 if (Ty.isPointer() != Other.Ty.isPointer())
168 return Ty.isPointer() < Other.Ty.isPointer();
169
170 if (Ty.isPointer() && Ty.getAddressSpace() != Other.Ty.getAddressSpace())
171 return Ty.getAddressSpace() < Other.Ty.getAddressSpace();
172
173 if (Ty.isVector() && Ty.getNumElements() != Other.Ty.getNumElements())
174 return Ty.getNumElements() < Other.Ty.getNumElements();
175
176 return Ty.getSizeInBits() < Other.Ty.getSizeInBits();
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000177 }
Quentin Colombet893e0f12017-12-15 23:24:39 +0000178
179 bool operator==(const LLTCodeGen &B) const { return Ty == B.Ty; }
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000180};
181
Daniel Sandersf84bc372018-05-05 20:53:24 +0000182// Track all types that are used so we can emit the corresponding enum.
183std::set<LLTCodeGen> KnownTypes;
184
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000185class InstructionMatcher;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000186/// Convert an MVT to an equivalent LLT if possible, or the invalid LLT() for
187/// MVTs that don't map cleanly to an LLT (e.g., iPTR, *any, ...).
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000188static Optional<LLTCodeGen> MVTToLLT(MVT::SimpleValueType SVT) {
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000189 MVT VT(SVT);
Daniel Sandersa71f4542017-10-16 00:56:30 +0000190
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000191 if (VT.isVector() && VT.getVectorNumElements() != 1)
Daniel Sanders32291982017-06-28 13:50:04 +0000192 return LLTCodeGen(
193 LLT::vector(VT.getVectorNumElements(), VT.getScalarSizeInBits()));
Daniel Sandersa71f4542017-10-16 00:56:30 +0000194
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000195 if (VT.isInteger() || VT.isFloatingPoint())
196 return LLTCodeGen(LLT::scalar(VT.getSizeInBits()));
197 return None;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000198}
199
Florian Hahn6b1db822018-06-14 20:32:58 +0000200static std::string explainPredicates(const TreePatternNode *N) {
Daniel Sandersd0656a32017-04-13 09:45:37 +0000201 std::string Explanation = "";
202 StringRef Separator = "";
Florian Hahn6b1db822018-06-14 20:32:58 +0000203 for (const auto &P : N->getPredicateFns()) {
Daniel Sandersd0656a32017-04-13 09:45:37 +0000204 Explanation +=
205 (Separator + P.getOrigPatFragRecord()->getRecord()->getName()).str();
Daniel Sanders76664652017-11-28 22:07:05 +0000206 Separator = ", ";
207
Daniel Sandersd0656a32017-04-13 09:45:37 +0000208 if (P.isAlwaysTrue())
209 Explanation += " always-true";
210 if (P.isImmediatePattern())
211 Explanation += " immediate";
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000212
213 if (P.isUnindexed())
214 Explanation += " unindexed";
215
216 if (P.isNonExtLoad())
217 Explanation += " non-extload";
218 if (P.isAnyExtLoad())
219 Explanation += " extload";
220 if (P.isSignExtLoad())
221 Explanation += " sextload";
222 if (P.isZeroExtLoad())
223 Explanation += " zextload";
224
225 if (P.isNonTruncStore())
226 Explanation += " non-truncstore";
227 if (P.isTruncStore())
228 Explanation += " truncstore";
229
230 if (Record *VT = P.getMemoryVT())
231 Explanation += (" MemVT=" + VT->getName()).str();
232 if (Record *VT = P.getScalarMemoryVT())
233 Explanation += (" ScalarVT(MemVT)=" + VT->getName()).str();
Daniel Sanders76664652017-11-28 22:07:05 +0000234
235 if (P.isAtomicOrderingMonotonic())
236 Explanation += " monotonic";
237 if (P.isAtomicOrderingAcquire())
238 Explanation += " acquire";
239 if (P.isAtomicOrderingRelease())
240 Explanation += " release";
241 if (P.isAtomicOrderingAcquireRelease())
242 Explanation += " acq_rel";
243 if (P.isAtomicOrderingSequentiallyConsistent())
244 Explanation += " seq_cst";
Daniel Sanders0c43b3a2017-11-30 21:05:59 +0000245 if (P.isAtomicOrderingAcquireOrStronger())
246 Explanation += " >=acquire";
247 if (P.isAtomicOrderingWeakerThanAcquire())
248 Explanation += " <acquire";
249 if (P.isAtomicOrderingReleaseOrStronger())
250 Explanation += " >=release";
251 if (P.isAtomicOrderingWeakerThanRelease())
252 Explanation += " <release";
Daniel Sandersd0656a32017-04-13 09:45:37 +0000253 }
254 return Explanation;
255}
256
Daniel Sandersd0656a32017-04-13 09:45:37 +0000257std::string explainOperator(Record *Operator) {
258 if (Operator->isSubClassOf("SDNode"))
Craig Topper2b8419a2017-05-31 19:01:11 +0000259 return (" (" + Operator->getValueAsString("Opcode") + ")").str();
Daniel Sandersd0656a32017-04-13 09:45:37 +0000260
261 if (Operator->isSubClassOf("Intrinsic"))
262 return (" (Operator is an Intrinsic, " + Operator->getName() + ")").str();
263
Daniel Sandersdf39cba2017-10-15 18:22:54 +0000264 if (Operator->isSubClassOf("ComplexPattern"))
265 return (" (Operator is an unmapped ComplexPattern, " + Operator->getName() +
266 ")")
267 .str();
268
Volkan Kelesf7f25682018-01-16 18:44:05 +0000269 if (Operator->isSubClassOf("SDNodeXForm"))
270 return (" (Operator is an unmapped SDNodeXForm, " + Operator->getName() +
271 ")")
272 .str();
273
Daniel Sandersdf39cba2017-10-15 18:22:54 +0000274 return (" (Operator " + Operator->getName() + " not understood)").str();
Daniel Sandersd0656a32017-04-13 09:45:37 +0000275}
276
277/// Helper function to let the emitter report skip reason error messages.
278static Error failedImport(const Twine &Reason) {
279 return make_error<StringError>(Reason, inconvertibleErrorCode());
280}
281
Florian Hahn6b1db822018-06-14 20:32:58 +0000282static Error isTrivialOperatorNode(const TreePatternNode *N) {
Daniel Sandersd0656a32017-04-13 09:45:37 +0000283 std::string Explanation = "";
284 std::string Separator = "";
Daniel Sanders2c269f62017-08-24 09:11:20 +0000285
286 bool HasUnsupportedPredicate = false;
Florian Hahn6b1db822018-06-14 20:32:58 +0000287 for (const auto &Predicate : N->getPredicateFns()) {
Daniel Sanders2c269f62017-08-24 09:11:20 +0000288 if (Predicate.isAlwaysTrue())
289 continue;
290
291 if (Predicate.isImmediatePattern())
292 continue;
293
Daniel Sandersf84bc372018-05-05 20:53:24 +0000294 if (Predicate.isNonExtLoad() || Predicate.isAnyExtLoad() ||
295 Predicate.isSignExtLoad() || Predicate.isZeroExtLoad())
Daniel Sandersa71f4542017-10-16 00:56:30 +0000296 continue;
Daniel Sandersd66e0902017-10-23 18:19:24 +0000297
Daniel Sanders76664652017-11-28 22:07:05 +0000298 if (Predicate.isNonTruncStore())
Daniel Sandersd66e0902017-10-23 18:19:24 +0000299 continue;
300
Daniel Sandersf84bc372018-05-05 20:53:24 +0000301 if (Predicate.isLoad() && Predicate.getMemoryVT())
302 continue;
303
Daniel Sanders76664652017-11-28 22:07:05 +0000304 if (Predicate.isLoad() || Predicate.isStore()) {
305 if (Predicate.isUnindexed())
306 continue;
307 }
308
309 if (Predicate.isAtomic() && Predicate.getMemoryVT())
310 continue;
311
312 if (Predicate.isAtomic() &&
313 (Predicate.isAtomicOrderingMonotonic() ||
314 Predicate.isAtomicOrderingAcquire() ||
315 Predicate.isAtomicOrderingRelease() ||
316 Predicate.isAtomicOrderingAcquireRelease() ||
Daniel Sanders0c43b3a2017-11-30 21:05:59 +0000317 Predicate.isAtomicOrderingSequentiallyConsistent() ||
318 Predicate.isAtomicOrderingAcquireOrStronger() ||
319 Predicate.isAtomicOrderingWeakerThanAcquire() ||
320 Predicate.isAtomicOrderingReleaseOrStronger() ||
321 Predicate.isAtomicOrderingWeakerThanRelease()))
Daniel Sandersd66e0902017-10-23 18:19:24 +0000322 continue;
323
Daniel Sanders8ead1292018-06-15 23:13:43 +0000324 if (Predicate.hasGISelPredicateCode())
325 continue;
326
Daniel Sanders2c269f62017-08-24 09:11:20 +0000327 HasUnsupportedPredicate = true;
Daniel Sandersd0656a32017-04-13 09:45:37 +0000328 Explanation = Separator + "Has a predicate (" + explainPredicates(N) + ")";
329 Separator = ", ";
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000330 Explanation += (Separator + "first-failing:" +
331 Predicate.getOrigPatFragRecord()->getRecord()->getName())
332 .str();
Daniel Sanders2c269f62017-08-24 09:11:20 +0000333 break;
Daniel Sandersd0656a32017-04-13 09:45:37 +0000334 }
335
Volkan Kelesf7f25682018-01-16 18:44:05 +0000336 if (!HasUnsupportedPredicate)
Daniel Sandersd0656a32017-04-13 09:45:37 +0000337 return Error::success();
338
339 return failedImport(Explanation);
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000340}
341
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +0000342static Record *getInitValueAsRegClass(Init *V) {
343 if (DefInit *VDefInit = dyn_cast<DefInit>(V)) {
344 if (VDefInit->getDef()->isSubClassOf("RegisterOperand"))
345 return VDefInit->getDef()->getValueAsDef("RegClass");
346 if (VDefInit->getDef()->isSubClassOf("RegisterClass"))
347 return VDefInit->getDef();
348 }
349 return nullptr;
350}
351
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000352std::string
353getNameForFeatureBitset(const std::vector<Record *> &FeatureBitset) {
354 std::string Name = "GIFBS";
355 for (const auto &Feature : FeatureBitset)
356 Name += ("_" + Feature->getName()).str();
357 return Name;
358}
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000359
360//===- MatchTable Helpers -------------------------------------------------===//
361
362class MatchTable;
363
364/// A record to be stored in a MatchTable.
365///
366/// This class represents any and all output that may be required to emit the
367/// MatchTable. Instances are most often configured to represent an opcode or
368/// value that will be emitted to the table with some formatting but it can also
369/// represent commas, comments, and other formatting instructions.
370struct MatchTableRecord {
371 enum RecordFlagsBits {
372 MTRF_None = 0x0,
373 /// Causes EmitStr to be formatted as comment when emitted.
374 MTRF_Comment = 0x1,
375 /// Causes the record value to be followed by a comma when emitted.
376 MTRF_CommaFollows = 0x2,
377 /// Causes the record value to be followed by a line break when emitted.
378 MTRF_LineBreakFollows = 0x4,
379 /// Indicates that the record defines a label and causes an additional
380 /// comment to be emitted containing the index of the label.
381 MTRF_Label = 0x8,
382 /// Causes the record to be emitted as the index of the label specified by
383 /// LabelID along with a comment indicating where that label is.
384 MTRF_JumpTarget = 0x10,
385 /// Causes the formatter to add a level of indentation before emitting the
386 /// record.
387 MTRF_Indent = 0x20,
388 /// Causes the formatter to remove a level of indentation after emitting the
389 /// record.
390 MTRF_Outdent = 0x40,
391 };
392
393 /// When MTRF_Label or MTRF_JumpTarget is used, indicates a label id to
394 /// reference or define.
395 unsigned LabelID;
396 /// The string to emit. Depending on the MTRF_* flags it may be a comment, a
397 /// value, a label name.
398 std::string EmitStr;
399
400private:
401 /// The number of MatchTable elements described by this record. Comments are 0
402 /// while values are typically 1. Values >1 may occur when we need to emit
403 /// values that exceed the size of a MatchTable element.
404 unsigned NumElements;
405
406public:
407 /// A bitfield of RecordFlagsBits flags.
408 unsigned Flags;
409
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000410 /// The actual run-time value, if known
411 int64_t RawValue;
412
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000413 MatchTableRecord(Optional<unsigned> LabelID_, StringRef EmitStr,
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000414 unsigned NumElements, unsigned Flags,
415 int64_t RawValue = std::numeric_limits<int64_t>::min())
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000416 : LabelID(LabelID_.hasValue() ? LabelID_.getValue() : ~0u),
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000417 EmitStr(EmitStr), NumElements(NumElements), Flags(Flags),
418 RawValue(RawValue) {
419
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000420 assert((!LabelID_.hasValue() || LabelID != ~0u) &&
421 "This value is reserved for non-labels");
422 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000423 MatchTableRecord(const MatchTableRecord &Other) = default;
424 MatchTableRecord(MatchTableRecord &&Other) = default;
425
426 /// Useful if a Match Table Record gets optimized out
427 void turnIntoComment() {
428 Flags |= MTRF_Comment;
429 Flags &= ~MTRF_CommaFollows;
430 NumElements = 0;
431 }
432
433 /// For Jump Table generation purposes
434 bool operator<(const MatchTableRecord &Other) const {
435 return RawValue < Other.RawValue;
436 }
437 int64_t getRawValue() const { return RawValue; }
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000438
439 void emit(raw_ostream &OS, bool LineBreakNextAfterThis,
440 const MatchTable &Table) const;
441 unsigned size() const { return NumElements; }
442};
443
Roman Tereshin2d6d3762018-05-02 20:08:14 +0000444class Matcher;
445
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000446/// Holds the contents of a generated MatchTable to enable formatting and the
447/// necessary index tracking needed to support GIM_Try.
448class MatchTable {
449 /// An unique identifier for the table. The generated table will be named
450 /// MatchTable${ID}.
451 unsigned ID;
452 /// The records that make up the table. Also includes comments describing the
453 /// values being emitted and line breaks to format it.
454 std::vector<MatchTableRecord> Contents;
455 /// The currently defined labels.
456 DenseMap<unsigned, unsigned> LabelMap;
457 /// Tracks the sum of MatchTableRecord::NumElements as the table is built.
Roman Tereshin2d6d3762018-05-02 20:08:14 +0000458 unsigned CurrentSize = 0;
Daniel Sanders8e82af22017-07-27 11:03:45 +0000459 /// A unique identifier for a MatchTable label.
Roman Tereshin2d6d3762018-05-02 20:08:14 +0000460 unsigned CurrentLabelID = 0;
Roman Tereshinbeb39312018-05-02 20:15:11 +0000461 /// Determines if the table should be instrumented for rule coverage tracking.
462 bool IsWithCoverage;
Daniel Sanders8e82af22017-07-27 11:03:45 +0000463
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000464public:
465 static MatchTableRecord LineBreak;
466 static MatchTableRecord Comment(StringRef Comment) {
467 return MatchTableRecord(None, Comment, 0, MatchTableRecord::MTRF_Comment);
468 }
469 static MatchTableRecord Opcode(StringRef Opcode, int IndentAdjust = 0) {
470 unsigned ExtraFlags = 0;
471 if (IndentAdjust > 0)
472 ExtraFlags |= MatchTableRecord::MTRF_Indent;
473 if (IndentAdjust < 0)
474 ExtraFlags |= MatchTableRecord::MTRF_Outdent;
475
476 return MatchTableRecord(None, Opcode, 1,
477 MatchTableRecord::MTRF_CommaFollows | ExtraFlags);
478 }
479 static MatchTableRecord NamedValue(StringRef NamedValue) {
480 return MatchTableRecord(None, NamedValue, 1,
481 MatchTableRecord::MTRF_CommaFollows);
482 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000483 static MatchTableRecord NamedValue(StringRef NamedValue, int64_t RawValue) {
484 return MatchTableRecord(None, NamedValue, 1,
485 MatchTableRecord::MTRF_CommaFollows, RawValue);
486 }
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000487 static MatchTableRecord NamedValue(StringRef Namespace,
488 StringRef NamedValue) {
489 return MatchTableRecord(None, (Namespace + "::" + NamedValue).str(), 1,
490 MatchTableRecord::MTRF_CommaFollows);
491 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000492 static MatchTableRecord NamedValue(StringRef Namespace, StringRef NamedValue,
493 int64_t RawValue) {
494 return MatchTableRecord(None, (Namespace + "::" + NamedValue).str(), 1,
495 MatchTableRecord::MTRF_CommaFollows, RawValue);
496 }
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000497 static MatchTableRecord IntValue(int64_t IntValue) {
498 return MatchTableRecord(None, llvm::to_string(IntValue), 1,
499 MatchTableRecord::MTRF_CommaFollows);
500 }
501 static MatchTableRecord Label(unsigned LabelID) {
502 return MatchTableRecord(LabelID, "Label " + llvm::to_string(LabelID), 0,
503 MatchTableRecord::MTRF_Label |
504 MatchTableRecord::MTRF_Comment |
505 MatchTableRecord::MTRF_LineBreakFollows);
506 }
507 static MatchTableRecord JumpTarget(unsigned LabelID) {
Daniel Sanders8e82af22017-07-27 11:03:45 +0000508 return MatchTableRecord(LabelID, "Label " + llvm::to_string(LabelID), 1,
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000509 MatchTableRecord::MTRF_JumpTarget |
510 MatchTableRecord::MTRF_Comment |
511 MatchTableRecord::MTRF_CommaFollows);
512 }
513
Roman Tereshinbeb39312018-05-02 20:15:11 +0000514 static MatchTable buildTable(ArrayRef<Matcher *> Rules, bool WithCoverage);
Roman Tereshin2d6d3762018-05-02 20:08:14 +0000515
Roman Tereshinbeb39312018-05-02 20:15:11 +0000516 MatchTable(bool WithCoverage, unsigned ID = 0)
517 : ID(ID), IsWithCoverage(WithCoverage) {}
518
519 bool isWithCoverage() const { return IsWithCoverage; }
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000520
521 void push_back(const MatchTableRecord &Value) {
522 if (Value.Flags & MatchTableRecord::MTRF_Label)
523 defineLabel(Value.LabelID);
524 Contents.push_back(Value);
525 CurrentSize += Value.size();
526 }
527
Roman Tereshin2d6d3762018-05-02 20:08:14 +0000528 unsigned allocateLabelID() { return CurrentLabelID++; }
Daniel Sanders8e82af22017-07-27 11:03:45 +0000529
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000530 void defineLabel(unsigned LabelID) {
Daniel Sanders8e82af22017-07-27 11:03:45 +0000531 LabelMap.insert(std::make_pair(LabelID, CurrentSize));
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000532 }
533
534 unsigned getLabelIndex(unsigned LabelID) const {
535 const auto I = LabelMap.find(LabelID);
536 assert(I != LabelMap.end() && "Use of undeclared label");
537 return I->second;
538 }
539
Daniel Sanders8e82af22017-07-27 11:03:45 +0000540 void emitUse(raw_ostream &OS) const { OS << "MatchTable" << ID; }
541
542 void emitDeclaration(raw_ostream &OS) const {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000543 unsigned Indentation = 4;
Daniel Sanderscbbbfe42017-07-27 12:47:31 +0000544 OS << " constexpr static int64_t MatchTable" << ID << "[] = {";
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000545 LineBreak.emit(OS, true, *this);
546 OS << std::string(Indentation, ' ');
547
548 for (auto I = Contents.begin(), E = Contents.end(); I != E;
549 ++I) {
550 bool LineBreakIsNext = false;
551 const auto &NextI = std::next(I);
552
553 if (NextI != E) {
554 if (NextI->EmitStr == "" &&
555 NextI->Flags == MatchTableRecord::MTRF_LineBreakFollows)
556 LineBreakIsNext = true;
557 }
558
559 if (I->Flags & MatchTableRecord::MTRF_Indent)
560 Indentation += 2;
561
562 I->emit(OS, LineBreakIsNext, *this);
563 if (I->Flags & MatchTableRecord::MTRF_LineBreakFollows)
564 OS << std::string(Indentation, ' ');
565
566 if (I->Flags & MatchTableRecord::MTRF_Outdent)
567 Indentation -= 2;
568 }
569 OS << "};\n";
570 }
571};
572
573MatchTableRecord MatchTable::LineBreak = {
574 None, "" /* Emit String */, 0 /* Elements */,
575 MatchTableRecord::MTRF_LineBreakFollows};
576
577void MatchTableRecord::emit(raw_ostream &OS, bool LineBreakIsNextAfterThis,
578 const MatchTable &Table) const {
579 bool UseLineComment =
580 LineBreakIsNextAfterThis | (Flags & MTRF_LineBreakFollows);
581 if (Flags & (MTRF_JumpTarget | MTRF_CommaFollows))
582 UseLineComment = false;
583
584 if (Flags & MTRF_Comment)
585 OS << (UseLineComment ? "// " : "/*");
586
587 OS << EmitStr;
588 if (Flags & MTRF_Label)
589 OS << ": @" << Table.getLabelIndex(LabelID);
590
591 if (Flags & MTRF_Comment && !UseLineComment)
592 OS << "*/";
593
594 if (Flags & MTRF_JumpTarget) {
595 if (Flags & MTRF_Comment)
596 OS << " ";
597 OS << Table.getLabelIndex(LabelID);
598 }
599
600 if (Flags & MTRF_CommaFollows) {
601 OS << ",";
602 if (!LineBreakIsNextAfterThis && !(Flags & MTRF_LineBreakFollows))
603 OS << " ";
604 }
605
606 if (Flags & MTRF_LineBreakFollows)
607 OS << "\n";
608}
609
610MatchTable &operator<<(MatchTable &Table, const MatchTableRecord &Value) {
611 Table.push_back(Value);
612 return Table;
613}
614
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000615//===- Matchers -----------------------------------------------------------===//
616
Daniel Sandersbee57392017-04-04 13:25:23 +0000617class OperandMatcher;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000618class MatchAction;
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000619class PredicateMatcher;
620class RuleMatcher;
621
622class Matcher {
623public:
624 virtual ~Matcher() = default;
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000625 virtual void optimize() {}
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000626 virtual void emit(MatchTable &Table) = 0;
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000627
628 virtual bool hasFirstCondition() const = 0;
629 virtual const PredicateMatcher &getFirstCondition() const = 0;
630 virtual std::unique_ptr<PredicateMatcher> popFirstCondition() = 0;
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000631};
632
Roman Tereshinbeb39312018-05-02 20:15:11 +0000633MatchTable MatchTable::buildTable(ArrayRef<Matcher *> Rules,
634 bool WithCoverage) {
635 MatchTable Table(WithCoverage);
Roman Tereshin2d6d3762018-05-02 20:08:14 +0000636 for (Matcher *Rule : Rules)
637 Rule->emit(Table);
638
639 return Table << MatchTable::Opcode("GIM_Reject") << MatchTable::LineBreak;
640}
641
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000642class GroupMatcher final : public Matcher {
643 /// Conditions that form a common prefix of all the matchers contained.
644 SmallVector<std::unique_ptr<PredicateMatcher>, 1> Conditions;
645
646 /// All the nested matchers, sharing a common prefix.
647 std::vector<Matcher *> Matchers;
648
649 /// An owning collection for any auxiliary matchers created while optimizing
650 /// nested matchers contained.
651 std::vector<std::unique_ptr<Matcher>> MatcherStorage;
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000652
653public:
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000654 /// Add a matcher to the collection of nested matchers if it meets the
655 /// requirements, and return true. If it doesn't, do nothing and return false.
656 ///
657 /// Expected to preserve its argument, so it could be moved out later on.
658 bool addMatcher(Matcher &Candidate);
659
660 /// Mark the matcher as fully-built and ensure any invariants expected by both
661 /// optimize() and emit(...) methods. Generally, both sequences of calls
662 /// are expected to lead to a sensible result:
663 ///
664 /// addMatcher(...)*; finalize(); optimize(); emit(...); and
665 /// addMatcher(...)*; finalize(); emit(...);
666 ///
667 /// or generally
668 ///
669 /// addMatcher(...)*; finalize(); { optimize()*; emit(...); }*
670 ///
671 /// Multiple calls to optimize() are expected to be handled gracefully, though
672 /// optimize() is not expected to be idempotent. Multiple calls to finalize()
673 /// aren't generally supported. emit(...) is expected to be non-mutating and
674 /// producing the exact same results upon repeated calls.
675 ///
676 /// addMatcher() calls after the finalize() call are not supported.
677 ///
678 /// finalize() and optimize() are both allowed to mutate the contained
679 /// matchers, so moving them out after finalize() is not supported.
680 void finalize();
Roman Tereshinfedae332018-05-23 02:04:19 +0000681 void optimize() override;
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000682 void emit(MatchTable &Table) override;
Quentin Colombet34688b92017-12-18 21:25:53 +0000683
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000684 /// Could be used to move out the matchers added previously, unless finalize()
685 /// has been already called. If any of the matchers are moved out, the group
686 /// becomes safe to destroy, but not safe to re-use for anything else.
687 iterator_range<std::vector<Matcher *>::iterator> matchers() {
688 return make_range(Matchers.begin(), Matchers.end());
Quentin Colombet34688b92017-12-18 21:25:53 +0000689 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000690 size_t size() const { return Matchers.size(); }
691 bool empty() const { return Matchers.empty(); }
692
693 std::unique_ptr<PredicateMatcher> popFirstCondition() override {
694 assert(!Conditions.empty() &&
695 "Trying to pop a condition from a condition-less group");
696 std::unique_ptr<PredicateMatcher> P = std::move(Conditions.front());
697 Conditions.erase(Conditions.begin());
698 return P;
699 }
700 const PredicateMatcher &getFirstCondition() const override {
701 assert(!Conditions.empty() &&
702 "Trying to get a condition from a condition-less group");
703 return *Conditions.front();
704 }
705 bool hasFirstCondition() const override { return !Conditions.empty(); }
706
707private:
708 /// See if a candidate matcher could be added to this group solely by
709 /// analyzing its first condition.
710 bool candidateConditionMatches(const PredicateMatcher &Predicate) const;
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000711};
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000712
Roman Tereshin0ee082f2018-05-22 19:37:59 +0000713class SwitchMatcher : public Matcher {
714 /// All the nested matchers, representing distinct switch-cases. The first
715 /// conditions (as Matcher::getFirstCondition() reports) of all the nested
716 /// matchers must share the same type and path to a value they check, in other
717 /// words, be isIdenticalDownToValue, but have different values they check
718 /// against.
719 std::vector<Matcher *> Matchers;
720
721 /// The representative condition, with a type and a path (InsnVarID and OpIdx
722 /// in most cases) shared by all the matchers contained.
723 std::unique_ptr<PredicateMatcher> Condition = nullptr;
724
725 /// Temporary set used to check that the case values don't repeat within the
726 /// same switch.
727 std::set<MatchTableRecord> Values;
728
729 /// An owning collection for any auxiliary matchers created while optimizing
730 /// nested matchers contained.
731 std::vector<std::unique_ptr<Matcher>> MatcherStorage;
732
733public:
734 bool addMatcher(Matcher &Candidate);
735
736 void finalize();
737 void emit(MatchTable &Table) override;
738
739 iterator_range<std::vector<Matcher *>::iterator> matchers() {
740 return make_range(Matchers.begin(), Matchers.end());
741 }
742 size_t size() const { return Matchers.size(); }
743 bool empty() const { return Matchers.empty(); }
744
745 std::unique_ptr<PredicateMatcher> popFirstCondition() override {
746 // SwitchMatcher doesn't have a common first condition for its cases, as all
747 // the cases only share a kind of a value (a type and a path to it) they
748 // match, but deliberately differ in the actual value they match.
749 llvm_unreachable("Trying to pop a condition from a condition-less group");
750 }
751 const PredicateMatcher &getFirstCondition() const override {
752 llvm_unreachable("Trying to pop a condition from a condition-less group");
753 }
754 bool hasFirstCondition() const override { return false; }
755
756private:
757 /// See if the predicate type has a Switch-implementation for it.
758 static bool isSupportedPredicateType(const PredicateMatcher &Predicate);
759
760 bool candidateConditionMatches(const PredicateMatcher &Predicate) const;
761
762 /// emit()-helper
763 static void emitPredicateSpecificOpcodes(const PredicateMatcher &P,
764 MatchTable &Table);
765};
766
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000767/// Generates code to check that a match rule matches.
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000768class RuleMatcher : public Matcher {
Daniel Sanders7438b262017-10-31 23:03:18 +0000769public:
Daniel Sanders08464522018-01-29 21:09:12 +0000770 using ActionList = std::list<std::unique_ptr<MatchAction>>;
771 using action_iterator = ActionList::iterator;
Daniel Sanders7438b262017-10-31 23:03:18 +0000772
773protected:
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000774 /// A list of matchers that all need to succeed for the current rule to match.
775 /// FIXME: This currently supports a single match position but could be
776 /// extended to support multiple positions to support div/rem fusion or
777 /// load-multiple instructions.
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000778 using MatchersTy = std::vector<std::unique_ptr<InstructionMatcher>> ;
779 MatchersTy Matchers;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000780
781 /// A list of actions that need to be taken when all predicates in this rule
782 /// have succeeded.
Daniel Sanders08464522018-01-29 21:09:12 +0000783 ActionList Actions;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000784
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000785 using DefinedInsnVariablesMap = std::map<InstructionMatcher *, unsigned>;
Daniel Sandersa7b75262017-10-31 18:50:24 +0000786
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000787 /// A map of instruction matchers to the local variables
Daniel Sanders078572b2017-08-02 11:03:36 +0000788 DefinedInsnVariablesMap InsnVariableIDs;
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000789
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000790 using MutatableInsnSet = SmallPtrSet<InstructionMatcher *, 4>;
Daniel Sandersa7b75262017-10-31 18:50:24 +0000791
792 // The set of instruction matchers that have not yet been claimed for mutation
793 // by a BuildMI.
794 MutatableInsnSet MutatableInsns;
795
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000796 /// A map of named operands defined by the matchers that may be referenced by
797 /// the renderers.
798 StringMap<OperandMatcher *> DefinedOperands;
799
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000800 /// ID for the next instruction variable defined with implicitlyDefineInsnVar()
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000801 unsigned NextInsnVarID;
802
Daniel Sanders198447a2017-11-01 00:29:47 +0000803 /// ID for the next output instruction allocated with allocateOutputInsnID()
804 unsigned NextOutputInsnID;
805
Daniel Sanders9cbe7c72017-11-01 19:57:57 +0000806 /// ID for the next temporary register ID allocated with allocateTempRegID()
807 unsigned NextTempRegID;
808
Daniel Sanderse7b0d662017-04-21 15:59:56 +0000809 std::vector<Record *> RequiredFeatures;
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000810 std::vector<std::unique_ptr<PredicateMatcher>> EpilogueMatchers;
Daniel Sanderse7b0d662017-04-21 15:59:56 +0000811
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000812 ArrayRef<SMLoc> SrcLoc;
813
Daniel Sandersdf39cba2017-10-15 18:22:54 +0000814 typedef std::tuple<Record *, unsigned, unsigned>
815 DefinedComplexPatternSubOperand;
816 typedef StringMap<DefinedComplexPatternSubOperand>
817 DefinedComplexPatternSubOperandMap;
818 /// A map of Symbolic Names to ComplexPattern sub-operands.
819 DefinedComplexPatternSubOperandMap ComplexSubOperands;
820
Daniel Sandersf76f3152017-11-16 00:46:35 +0000821 uint64_t RuleID;
822 static uint64_t NextRuleID;
823
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000824public:
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000825 RuleMatcher(ArrayRef<SMLoc> SrcLoc)
Daniel Sandersa7b75262017-10-31 18:50:24 +0000826 : Matchers(), Actions(), InsnVariableIDs(), MutatableInsns(),
Daniel Sanders198447a2017-11-01 00:29:47 +0000827 DefinedOperands(), NextInsnVarID(0), NextOutputInsnID(0),
Daniel Sandersf76f3152017-11-16 00:46:35 +0000828 NextTempRegID(0), SrcLoc(SrcLoc), ComplexSubOperands(),
829 RuleID(NextRuleID++) {}
Zachary Turnerb7dbd872017-03-20 19:56:52 +0000830 RuleMatcher(RuleMatcher &&Other) = default;
831 RuleMatcher &operator=(RuleMatcher &&Other) = default;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000832
Daniel Sandersf76f3152017-11-16 00:46:35 +0000833 uint64_t getRuleID() const { return RuleID; }
834
Daniel Sanders05540042017-08-08 10:44:31 +0000835 InstructionMatcher &addInstructionMatcher(StringRef SymbolicName);
Daniel Sanderse7b0d662017-04-21 15:59:56 +0000836 void addRequiredFeature(Record *Feature);
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000837 const std::vector<Record *> &getRequiredFeatures() const;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000838
839 template <class Kind, class... Args> Kind &addAction(Args &&... args);
Daniel Sanders7438b262017-10-31 23:03:18 +0000840 template <class Kind, class... Args>
841 action_iterator insertAction(action_iterator InsertPt, Args &&... args);
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000842
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000843 /// Define an instruction without emitting any code to do so.
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000844 unsigned implicitlyDefineInsnVar(InstructionMatcher &Matcher);
845
846 unsigned getInsnVarID(InstructionMatcher &InsnMatcher) const;
Daniel Sanders078572b2017-08-02 11:03:36 +0000847 DefinedInsnVariablesMap::const_iterator defined_insn_vars_begin() const {
848 return InsnVariableIDs.begin();
849 }
850 DefinedInsnVariablesMap::const_iterator defined_insn_vars_end() const {
851 return InsnVariableIDs.end();
852 }
853 iterator_range<typename DefinedInsnVariablesMap::const_iterator>
854 defined_insn_vars() const {
855 return make_range(defined_insn_vars_begin(), defined_insn_vars_end());
856 }
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000857
Daniel Sandersa7b75262017-10-31 18:50:24 +0000858 MutatableInsnSet::const_iterator mutatable_insns_begin() const {
859 return MutatableInsns.begin();
860 }
861 MutatableInsnSet::const_iterator mutatable_insns_end() const {
862 return MutatableInsns.end();
863 }
864 iterator_range<typename MutatableInsnSet::const_iterator>
865 mutatable_insns() const {
866 return make_range(mutatable_insns_begin(), mutatable_insns_end());
867 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000868 void reserveInsnMatcherForMutation(InstructionMatcher *InsnMatcher) {
Daniel Sandersa7b75262017-10-31 18:50:24 +0000869 bool R = MutatableInsns.erase(InsnMatcher);
870 assert(R && "Reserving a mutatable insn that isn't available");
871 (void)R;
872 }
873
Daniel Sanders7438b262017-10-31 23:03:18 +0000874 action_iterator actions_begin() { return Actions.begin(); }
875 action_iterator actions_end() { return Actions.end(); }
876 iterator_range<action_iterator> actions() {
877 return make_range(actions_begin(), actions_end());
878 }
879
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000880 void defineOperand(StringRef SymbolicName, OperandMatcher &OM);
881
Daniel Sandersdf39cba2017-10-15 18:22:54 +0000882 void defineComplexSubOperand(StringRef SymbolicName, Record *ComplexPattern,
883 unsigned RendererID, unsigned SubOperandID) {
884 assert(ComplexSubOperands.count(SymbolicName) == 0 && "Already defined");
885 ComplexSubOperands[SymbolicName] =
886 std::make_tuple(ComplexPattern, RendererID, SubOperandID);
887 }
888 Optional<DefinedComplexPatternSubOperand>
889 getComplexSubOperand(StringRef SymbolicName) const {
890 const auto &I = ComplexSubOperands.find(SymbolicName);
891 if (I == ComplexSubOperands.end())
892 return None;
893 return I->second;
894 }
895
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000896 InstructionMatcher &getInstructionMatcher(StringRef SymbolicName) const;
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000897 const OperandMatcher &getOperandMatcher(StringRef Name) const;
Daniel Sanders05540042017-08-08 10:44:31 +0000898
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000899 void optimize() override;
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000900 void emit(MatchTable &Table) override;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000901
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000902 /// Compare the priority of this object and B.
903 ///
904 /// Returns true if this object is more important than B.
905 bool isHigherPriorityThan(const RuleMatcher &B) const;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000906
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000907 /// Report the maximum number of temporary operands needed by the rule
908 /// matcher.
909 unsigned countRendererFns() const;
Daniel Sanders2deea182017-04-22 15:11:04 +0000910
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000911 std::unique_ptr<PredicateMatcher> popFirstCondition() override;
912 const PredicateMatcher &getFirstCondition() const override;
Roman Tereshin9a9fa492018-05-23 21:30:16 +0000913 LLTCodeGen getFirstConditionAsRootType();
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000914 bool hasFirstCondition() const override;
915 unsigned getNumOperands() const;
Roman Tereshin19da6672018-05-22 04:31:50 +0000916 StringRef getOpcode() const;
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000917
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000918 // FIXME: Remove this as soon as possible
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000919 InstructionMatcher &insnmatchers_front() const { return *Matchers.front(); }
Daniel Sanders198447a2017-11-01 00:29:47 +0000920
921 unsigned allocateOutputInsnID() { return NextOutputInsnID++; }
Daniel Sanders9cbe7c72017-11-01 19:57:57 +0000922 unsigned allocateTempRegID() { return NextTempRegID++; }
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000923
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000924 iterator_range<MatchersTy::iterator> insnmatchers() {
925 return make_range(Matchers.begin(), Matchers.end());
926 }
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000927 bool insnmatchers_empty() const { return Matchers.empty(); }
928 void insnmatchers_pop_front() { Matchers.erase(Matchers.begin()); }
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000929};
930
Daniel Sandersf76f3152017-11-16 00:46:35 +0000931uint64_t RuleMatcher::NextRuleID = 0;
932
Daniel Sanders7438b262017-10-31 23:03:18 +0000933using action_iterator = RuleMatcher::action_iterator;
934
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000935template <class PredicateTy> class PredicateListMatcher {
936private:
Daniel Sanders2c269f62017-08-24 09:11:20 +0000937 /// Template instantiations should specialize this to return a string to use
938 /// for the comment emitted when there are no predicates.
939 std::string getNoPredicateComment() const;
940
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000941protected:
942 using PredicatesTy = std::deque<std::unique_ptr<PredicateTy>>;
943 PredicatesTy Predicates;
Roman Tereshinf0dc9fa2018-05-21 22:04:39 +0000944
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000945 /// Track if the list of predicates was manipulated by one of the optimization
946 /// methods.
947 bool Optimized = false;
948
949public:
950 /// Construct a new predicate and add it to the matcher.
951 template <class Kind, class... Args>
952 Optional<Kind *> addPredicate(Args &&... args);
953
954 typename PredicatesTy::iterator predicates_begin() {
Daniel Sanders32291982017-06-28 13:50:04 +0000955 return Predicates.begin();
956 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000957 typename PredicatesTy::iterator predicates_end() {
Daniel Sanders32291982017-06-28 13:50:04 +0000958 return Predicates.end();
959 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000960 iterator_range<typename PredicatesTy::iterator> predicates() {
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000961 return make_range(predicates_begin(), predicates_end());
962 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000963 typename PredicatesTy::size_type predicates_size() const {
Daniel Sanders32291982017-06-28 13:50:04 +0000964 return Predicates.size();
965 }
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000966 bool predicates_empty() const { return Predicates.empty(); }
967
968 std::unique_ptr<PredicateTy> predicates_pop_front() {
969 std::unique_ptr<PredicateTy> Front = std::move(Predicates.front());
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000970 Predicates.pop_front();
971 Optimized = true;
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000972 return Front;
973 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000974
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000975 void prependPredicate(std::unique_ptr<PredicateTy> &&Predicate) {
976 Predicates.push_front(std::move(Predicate));
977 }
978
979 void eraseNullPredicates() {
980 const auto NewEnd =
981 std::stable_partition(Predicates.begin(), Predicates.end(),
982 std::logical_not<std::unique_ptr<PredicateTy>>());
983 if (NewEnd != Predicates.begin()) {
984 Predicates.erase(Predicates.begin(), NewEnd);
985 Optimized = true;
986 }
987 }
988
Daniel Sanders9d662d22017-07-06 10:06:12 +0000989 /// Emit MatchTable opcodes that tests whether all the predicates are met.
Ahmed Bougachab67a3ce2017-01-26 22:07:37 +0000990 template <class... Args>
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000991 void emitPredicateListOpcodes(MatchTable &Table, Args &&... args) {
992 if (Predicates.empty() && !Optimized) {
Daniel Sanders2c269f62017-08-24 09:11:20 +0000993 Table << MatchTable::Comment(getNoPredicateComment())
994 << MatchTable::LineBreak;
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000995 return;
996 }
997
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000998 for (const auto &Predicate : predicates())
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000999 Predicate->emitPredicateOpcodes(Table, std::forward<Args>(args)...);
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001000 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001001};
1002
Quentin Colombet063d7982017-12-14 23:44:07 +00001003class PredicateMatcher {
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001004public:
Daniel Sanders759ff412017-02-24 13:58:11 +00001005 /// This enum is used for RTTI and also defines the priority that is given to
1006 /// the predicate when generating the matcher code. Kinds with higher priority
1007 /// must be tested first.
1008 ///
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001009 /// The relative priority of OPM_LLT, OPM_RegBank, and OPM_MBB do not matter
1010 /// but OPM_Int must have priority over OPM_RegBank since constant integers
1011 /// are represented by a virtual register defined by a G_CONSTANT instruction.
Quentin Colombet063d7982017-12-14 23:44:07 +00001012 ///
1013 /// Note: The relative priority between IPM_ and OPM_ does not matter, they
1014 /// are currently not compared between each other.
Daniel Sanders759ff412017-02-24 13:58:11 +00001015 enum PredicateKind {
Quentin Colombet063d7982017-12-14 23:44:07 +00001016 IPM_Opcode,
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001017 IPM_NumOperands,
Quentin Colombet063d7982017-12-14 23:44:07 +00001018 IPM_ImmPredicate,
1019 IPM_AtomicOrderingMMO,
Daniel Sandersf84bc372018-05-05 20:53:24 +00001020 IPM_MemoryLLTSize,
1021 IPM_MemoryVsLLTSize,
Daniel Sanders8ead1292018-06-15 23:13:43 +00001022 IPM_GenericPredicate,
Daniel Sanders1e4569f2017-10-20 20:55:29 +00001023 OPM_SameOperand,
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001024 OPM_ComplexPattern,
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00001025 OPM_IntrinsicID,
Daniel Sanders05540042017-08-08 10:44:31 +00001026 OPM_Instruction,
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001027 OPM_Int,
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001028 OPM_LiteralInt,
Daniel Sanders759ff412017-02-24 13:58:11 +00001029 OPM_LLT,
Daniel Sandersa71f4542017-10-16 00:56:30 +00001030 OPM_PointerToAny,
Daniel Sanders759ff412017-02-24 13:58:11 +00001031 OPM_RegBank,
1032 OPM_MBB,
1033 };
1034
1035protected:
1036 PredicateKind Kind;
Quentin Colombetaad20be2017-12-15 23:07:42 +00001037 unsigned InsnVarID;
1038 unsigned OpIdx;
Daniel Sanders759ff412017-02-24 13:58:11 +00001039
1040public:
Quentin Colombetaad20be2017-12-15 23:07:42 +00001041 PredicateMatcher(PredicateKind Kind, unsigned InsnVarID, unsigned OpIdx = ~0)
1042 : Kind(Kind), InsnVarID(InsnVarID), OpIdx(OpIdx) {}
Quentin Colombet063d7982017-12-14 23:44:07 +00001043
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001044 unsigned getInsnVarID() const { return InsnVarID; }
Quentin Colombetaad20be2017-12-15 23:07:42 +00001045 unsigned getOpIdx() const { return OpIdx; }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001046
Quentin Colombet063d7982017-12-14 23:44:07 +00001047 virtual ~PredicateMatcher() = default;
1048 /// Emit MatchTable opcodes that check the predicate for the given operand.
Quentin Colombetaad20be2017-12-15 23:07:42 +00001049 virtual void emitPredicateOpcodes(MatchTable &Table,
1050 RuleMatcher &Rule) const = 0;
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001051
Daniel Sanders759ff412017-02-24 13:58:11 +00001052 PredicateKind getKind() const { return Kind; }
Quentin Colombet893e0f12017-12-15 23:24:39 +00001053
1054 virtual bool isIdentical(const PredicateMatcher &B) const {
Quentin Colombet893e0f12017-12-15 23:24:39 +00001055 return B.getKind() == getKind() && InsnVarID == B.InsnVarID &&
1056 OpIdx == B.OpIdx;
1057 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001058
1059 virtual bool isIdenticalDownToValue(const PredicateMatcher &B) const {
1060 return hasValue() && PredicateMatcher::isIdentical(B);
1061 }
1062
1063 virtual MatchTableRecord getValue() const {
1064 assert(hasValue() && "Can not get a value of a value-less predicate!");
1065 llvm_unreachable("Not implemented yet");
1066 }
1067 virtual bool hasValue() const { return false; }
1068
1069 /// Report the maximum number of temporary operands needed by the predicate
1070 /// matcher.
1071 virtual unsigned countRendererFns() const { return 0; }
Quentin Colombet063d7982017-12-14 23:44:07 +00001072};
1073
1074/// Generates code to check a predicate of an operand.
1075///
1076/// Typical predicates include:
1077/// * Operand is a particular register.
1078/// * Operand is assigned a particular register bank.
1079/// * Operand is an MBB.
1080class OperandPredicateMatcher : public PredicateMatcher {
1081public:
Quentin Colombetaad20be2017-12-15 23:07:42 +00001082 OperandPredicateMatcher(PredicateKind Kind, unsigned InsnVarID,
1083 unsigned OpIdx)
1084 : PredicateMatcher(Kind, InsnVarID, OpIdx) {}
Quentin Colombet063d7982017-12-14 23:44:07 +00001085 virtual ~OperandPredicateMatcher() {}
Daniel Sanders759ff412017-02-24 13:58:11 +00001086
Daniel Sanders759ff412017-02-24 13:58:11 +00001087 /// Compare the priority of this object and B.
1088 ///
1089 /// Returns true if this object is more important than B.
Daniel Sanders05540042017-08-08 10:44:31 +00001090 virtual bool isHigherPriorityThan(const OperandPredicateMatcher &B) const;
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001091};
1092
Daniel Sanders2c269f62017-08-24 09:11:20 +00001093template <>
1094std::string
1095PredicateListMatcher<OperandPredicateMatcher>::getNoPredicateComment() const {
1096 return "No operand predicates";
1097}
1098
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001099/// Generates code to check that a register operand is defined by the same exact
1100/// one as another.
1101class SameOperandMatcher : public OperandPredicateMatcher {
Daniel Sanders1e4569f2017-10-20 20:55:29 +00001102 std::string MatchingName;
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001103
1104public:
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001105 SameOperandMatcher(unsigned InsnVarID, unsigned OpIdx, StringRef MatchingName)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001106 : OperandPredicateMatcher(OPM_SameOperand, InsnVarID, OpIdx),
1107 MatchingName(MatchingName) {}
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001108
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001109 static bool classof(const PredicateMatcher *P) {
Daniel Sanders1e4569f2017-10-20 20:55:29 +00001110 return P->getKind() == OPM_SameOperand;
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001111 }
1112
Quentin Colombetaad20be2017-12-15 23:07:42 +00001113 void emitPredicateOpcodes(MatchTable &Table,
1114 RuleMatcher &Rule) const override;
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001115
1116 bool isIdentical(const PredicateMatcher &B) const override {
1117 return OperandPredicateMatcher::isIdentical(B) &&
1118 MatchingName == cast<SameOperandMatcher>(&B)->MatchingName;
1119 }
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001120};
1121
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001122/// Generates code to check that an operand is a particular LLT.
1123class LLTOperandMatcher : public OperandPredicateMatcher {
1124protected:
Daniel Sanders52b4ce72017-03-07 23:20:35 +00001125 LLTCodeGen Ty;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001126
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001127public:
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001128 static std::map<LLTCodeGen, unsigned> TypeIDValues;
1129
1130 static void initTypeIDValuesMap() {
1131 TypeIDValues.clear();
1132
1133 unsigned ID = 0;
1134 for (const LLTCodeGen LLTy : KnownTypes)
1135 TypeIDValues[LLTy] = ID++;
1136 }
1137
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001138 LLTOperandMatcher(unsigned InsnVarID, unsigned OpIdx, const LLTCodeGen &Ty)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001139 : OperandPredicateMatcher(OPM_LLT, InsnVarID, OpIdx), Ty(Ty) {
Daniel Sanders032e7f22017-08-17 13:18:35 +00001140 KnownTypes.insert(Ty);
1141 }
Daniel Sanders759ff412017-02-24 13:58:11 +00001142
Quentin Colombet063d7982017-12-14 23:44:07 +00001143 static bool classof(const PredicateMatcher *P) {
Daniel Sanders759ff412017-02-24 13:58:11 +00001144 return P->getKind() == OPM_LLT;
1145 }
Quentin Colombet893e0f12017-12-15 23:24:39 +00001146 bool isIdentical(const PredicateMatcher &B) const override {
1147 return OperandPredicateMatcher::isIdentical(B) &&
1148 Ty == cast<LLTOperandMatcher>(&B)->Ty;
1149 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001150 MatchTableRecord getValue() const override {
1151 const auto VI = TypeIDValues.find(Ty);
1152 if (VI == TypeIDValues.end())
1153 return MatchTable::NamedValue(getTy().getCxxEnumValue());
1154 return MatchTable::NamedValue(getTy().getCxxEnumValue(), VI->second);
1155 }
1156 bool hasValue() const override {
1157 if (TypeIDValues.size() != KnownTypes.size())
1158 initTypeIDValuesMap();
1159 return TypeIDValues.count(Ty);
1160 }
1161
1162 LLTCodeGen getTy() const { return Ty; }
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001163
Quentin Colombetaad20be2017-12-15 23:07:42 +00001164 void emitPredicateOpcodes(MatchTable &Table,
1165 RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001166 Table << MatchTable::Opcode("GIM_CheckType") << MatchTable::Comment("MI")
1167 << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Op")
1168 << MatchTable::IntValue(OpIdx) << MatchTable::Comment("Type")
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001169 << getValue() << MatchTable::LineBreak;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001170 }
1171};
1172
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001173std::map<LLTCodeGen, unsigned> LLTOperandMatcher::TypeIDValues;
1174
Daniel Sandersa71f4542017-10-16 00:56:30 +00001175/// Generates code to check that an operand is a pointer to any address space.
1176///
1177/// In SelectionDAG, the types did not describe pointers or address spaces. As a
1178/// result, iN is used to describe a pointer of N bits to any address space and
1179/// PatFrag predicates are typically used to constrain the address space. There's
1180/// no reliable means to derive the missing type information from the pattern so
1181/// imported rules must test the components of a pointer separately.
1182///
Daniel Sandersea8711b2017-10-16 03:36:29 +00001183/// If SizeInBits is zero, then the pointer size will be obtained from the
1184/// subtarget.
Daniel Sandersa71f4542017-10-16 00:56:30 +00001185class PointerToAnyOperandMatcher : public OperandPredicateMatcher {
1186protected:
1187 unsigned SizeInBits;
1188
1189public:
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001190 PointerToAnyOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
1191 unsigned SizeInBits)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001192 : OperandPredicateMatcher(OPM_PointerToAny, InsnVarID, OpIdx),
1193 SizeInBits(SizeInBits) {}
Daniel Sandersa71f4542017-10-16 00:56:30 +00001194
1195 static bool classof(const OperandPredicateMatcher *P) {
1196 return P->getKind() == OPM_PointerToAny;
1197 }
1198
Quentin Colombetaad20be2017-12-15 23:07:42 +00001199 void emitPredicateOpcodes(MatchTable &Table,
1200 RuleMatcher &Rule) const override {
1201 Table << MatchTable::Opcode("GIM_CheckPointerToAny")
1202 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1203 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1204 << MatchTable::Comment("SizeInBits")
Daniel Sandersa71f4542017-10-16 00:56:30 +00001205 << MatchTable::IntValue(SizeInBits) << MatchTable::LineBreak;
1206 }
1207};
1208
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001209/// Generates code to check that an operand is a particular target constant.
1210class ComplexPatternOperandMatcher : public OperandPredicateMatcher {
1211protected:
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001212 const OperandMatcher &Operand;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001213 const Record &TheDef;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001214
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001215 unsigned getAllocatedTemporariesBaseID() const;
1216
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001217public:
Quentin Colombet893e0f12017-12-15 23:24:39 +00001218 bool isIdentical(const PredicateMatcher &B) const override { return false; }
1219
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001220 ComplexPatternOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
1221 const OperandMatcher &Operand,
1222 const Record &TheDef)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001223 : OperandPredicateMatcher(OPM_ComplexPattern, InsnVarID, OpIdx),
1224 Operand(Operand), TheDef(TheDef) {}
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001225
Quentin Colombet063d7982017-12-14 23:44:07 +00001226 static bool classof(const PredicateMatcher *P) {
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001227 return P->getKind() == OPM_ComplexPattern;
1228 }
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001229
Quentin Colombetaad20be2017-12-15 23:07:42 +00001230 void emitPredicateOpcodes(MatchTable &Table,
1231 RuleMatcher &Rule) const override {
Daniel Sanders2deea182017-04-22 15:11:04 +00001232 unsigned ID = getAllocatedTemporariesBaseID();
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001233 Table << MatchTable::Opcode("GIM_CheckComplexPattern")
1234 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1235 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1236 << MatchTable::Comment("Renderer") << MatchTable::IntValue(ID)
1237 << MatchTable::NamedValue(("GICP_" + TheDef.getName()).str())
1238 << MatchTable::LineBreak;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001239 }
1240
Daniel Sanders2deea182017-04-22 15:11:04 +00001241 unsigned countRendererFns() const override {
1242 return 1;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001243 }
1244};
1245
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001246/// Generates code to check that an operand is in a particular register bank.
1247class RegisterBankOperandMatcher : public OperandPredicateMatcher {
1248protected:
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001249 const CodeGenRegisterClass &RC;
1250
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001251public:
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001252 RegisterBankOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
1253 const CodeGenRegisterClass &RC)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001254 : OperandPredicateMatcher(OPM_RegBank, InsnVarID, OpIdx), RC(RC) {}
Daniel Sanders759ff412017-02-24 13:58:11 +00001255
Quentin Colombet893e0f12017-12-15 23:24:39 +00001256 bool isIdentical(const PredicateMatcher &B) const override {
1257 return OperandPredicateMatcher::isIdentical(B) &&
1258 RC.getDef() == cast<RegisterBankOperandMatcher>(&B)->RC.getDef();
1259 }
1260
Quentin Colombet063d7982017-12-14 23:44:07 +00001261 static bool classof(const PredicateMatcher *P) {
Daniel Sanders759ff412017-02-24 13:58:11 +00001262 return P->getKind() == OPM_RegBank;
1263 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001264
Quentin Colombetaad20be2017-12-15 23:07:42 +00001265 void emitPredicateOpcodes(MatchTable &Table,
1266 RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001267 Table << MatchTable::Opcode("GIM_CheckRegBankForClass")
1268 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1269 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1270 << MatchTable::Comment("RC")
1271 << MatchTable::NamedValue(RC.getQualifiedName() + "RegClassID")
1272 << MatchTable::LineBreak;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001273 }
1274};
1275
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001276/// Generates code to check that an operand is a basic block.
1277class MBBOperandMatcher : public OperandPredicateMatcher {
1278public:
Quentin Colombetaad20be2017-12-15 23:07:42 +00001279 MBBOperandMatcher(unsigned InsnVarID, unsigned OpIdx)
1280 : OperandPredicateMatcher(OPM_MBB, InsnVarID, OpIdx) {}
Daniel Sanders759ff412017-02-24 13:58:11 +00001281
Quentin Colombet063d7982017-12-14 23:44:07 +00001282 static bool classof(const PredicateMatcher *P) {
Daniel Sanders759ff412017-02-24 13:58:11 +00001283 return P->getKind() == OPM_MBB;
1284 }
1285
Quentin Colombetaad20be2017-12-15 23:07:42 +00001286 void emitPredicateOpcodes(MatchTable &Table,
1287 RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001288 Table << MatchTable::Opcode("GIM_CheckIsMBB") << MatchTable::Comment("MI")
1289 << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Op")
1290 << MatchTable::IntValue(OpIdx) << MatchTable::LineBreak;
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001291 }
1292};
1293
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001294/// Generates code to check that an operand is a G_CONSTANT with a particular
1295/// int.
1296class ConstantIntOperandMatcher : public OperandPredicateMatcher {
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001297protected:
1298 int64_t Value;
1299
1300public:
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001301 ConstantIntOperandMatcher(unsigned InsnVarID, unsigned OpIdx, int64_t Value)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001302 : OperandPredicateMatcher(OPM_Int, InsnVarID, OpIdx), Value(Value) {}
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001303
Quentin Colombet893e0f12017-12-15 23:24:39 +00001304 bool isIdentical(const PredicateMatcher &B) const override {
1305 return OperandPredicateMatcher::isIdentical(B) &&
1306 Value == cast<ConstantIntOperandMatcher>(&B)->Value;
1307 }
1308
Quentin Colombet063d7982017-12-14 23:44:07 +00001309 static bool classof(const PredicateMatcher *P) {
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001310 return P->getKind() == OPM_Int;
1311 }
1312
Quentin Colombetaad20be2017-12-15 23:07:42 +00001313 void emitPredicateOpcodes(MatchTable &Table,
1314 RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001315 Table << MatchTable::Opcode("GIM_CheckConstantInt")
1316 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1317 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1318 << MatchTable::IntValue(Value) << MatchTable::LineBreak;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001319 }
1320};
1321
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001322/// Generates code to check that an operand is a raw int (where MO.isImm() or
1323/// MO.isCImm() is true).
1324class LiteralIntOperandMatcher : public OperandPredicateMatcher {
1325protected:
1326 int64_t Value;
1327
1328public:
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001329 LiteralIntOperandMatcher(unsigned InsnVarID, unsigned OpIdx, int64_t Value)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001330 : OperandPredicateMatcher(OPM_LiteralInt, InsnVarID, OpIdx),
1331 Value(Value) {}
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001332
Quentin Colombet893e0f12017-12-15 23:24:39 +00001333 bool isIdentical(const PredicateMatcher &B) const override {
1334 return OperandPredicateMatcher::isIdentical(B) &&
1335 Value == cast<LiteralIntOperandMatcher>(&B)->Value;
1336 }
1337
Quentin Colombet063d7982017-12-14 23:44:07 +00001338 static bool classof(const PredicateMatcher *P) {
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001339 return P->getKind() == OPM_LiteralInt;
1340 }
1341
Quentin Colombetaad20be2017-12-15 23:07:42 +00001342 void emitPredicateOpcodes(MatchTable &Table,
1343 RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001344 Table << MatchTable::Opcode("GIM_CheckLiteralInt")
1345 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1346 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1347 << MatchTable::IntValue(Value) << MatchTable::LineBreak;
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001348 }
1349};
1350
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00001351/// Generates code to check that an operand is an intrinsic ID.
1352class IntrinsicIDOperandMatcher : public OperandPredicateMatcher {
1353protected:
1354 const CodeGenIntrinsic *II;
1355
1356public:
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001357 IntrinsicIDOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
1358 const CodeGenIntrinsic *II)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001359 : OperandPredicateMatcher(OPM_IntrinsicID, InsnVarID, OpIdx), II(II) {}
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00001360
Quentin Colombet893e0f12017-12-15 23:24:39 +00001361 bool isIdentical(const PredicateMatcher &B) const override {
1362 return OperandPredicateMatcher::isIdentical(B) &&
1363 II == cast<IntrinsicIDOperandMatcher>(&B)->II;
1364 }
1365
Quentin Colombet063d7982017-12-14 23:44:07 +00001366 static bool classof(const PredicateMatcher *P) {
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00001367 return P->getKind() == OPM_IntrinsicID;
1368 }
1369
Quentin Colombetaad20be2017-12-15 23:07:42 +00001370 void emitPredicateOpcodes(MatchTable &Table,
1371 RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001372 Table << MatchTable::Opcode("GIM_CheckIntrinsicID")
1373 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1374 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1375 << MatchTable::NamedValue("Intrinsic::" + II->EnumName)
1376 << MatchTable::LineBreak;
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00001377 }
1378};
1379
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001380/// Generates code to check that a set of predicates match for a particular
1381/// operand.
1382class OperandMatcher : public PredicateListMatcher<OperandPredicateMatcher> {
1383protected:
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001384 InstructionMatcher &Insn;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001385 unsigned OpIdx;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001386 std::string SymbolicName;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001387
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001388 /// The index of the first temporary variable allocated to this operand. The
1389 /// number of allocated temporaries can be found with
Daniel Sanders2deea182017-04-22 15:11:04 +00001390 /// countRendererFns().
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001391 unsigned AllocatedTemporariesBaseID;
1392
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001393public:
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001394 OperandMatcher(InstructionMatcher &Insn, unsigned OpIdx,
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001395 const std::string &SymbolicName,
1396 unsigned AllocatedTemporariesBaseID)
1397 : Insn(Insn), OpIdx(OpIdx), SymbolicName(SymbolicName),
1398 AllocatedTemporariesBaseID(AllocatedTemporariesBaseID) {}
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001399
1400 bool hasSymbolicName() const { return !SymbolicName.empty(); }
1401 const StringRef getSymbolicName() const { return SymbolicName; }
Daniel Sandersffc7d582017-03-29 15:37:18 +00001402 void setSymbolicName(StringRef Name) {
1403 assert(SymbolicName.empty() && "Operand already has a symbolic name");
1404 SymbolicName = Name;
1405 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001406
1407 /// Construct a new operand predicate and add it to the matcher.
1408 template <class Kind, class... Args>
1409 Optional<Kind *> addPredicate(Args &&... args) {
1410 if (isSameAsAnotherOperand())
1411 return None;
1412 Predicates.emplace_back(llvm::make_unique<Kind>(
1413 getInsnVarID(), getOpIdx(), std::forward<Args>(args)...));
1414 return static_cast<Kind *>(Predicates.back().get());
1415 }
1416
1417 unsigned getOpIdx() const { return OpIdx; }
Quentin Colombetaad20be2017-12-15 23:07:42 +00001418 unsigned getInsnVarID() const;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001419
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001420 std::string getOperandExpr(unsigned InsnVarID) const {
1421 return "State.MIs[" + llvm::to_string(InsnVarID) + "]->getOperand(" +
1422 llvm::to_string(OpIdx) + ")";
Daniel Sanderse604ef52017-02-20 15:30:43 +00001423 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001424
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001425 InstructionMatcher &getInstructionMatcher() const { return Insn; }
1426
Daniel Sandersa71f4542017-10-16 00:56:30 +00001427 Error addTypeCheckPredicate(const TypeSetByHwMode &VTy,
Reid Klecknercfdd4a22017-10-16 20:31:16 +00001428 bool OperandIsAPointer);
Daniel Sandersa71f4542017-10-16 00:56:30 +00001429
Daniel Sanders9d662d22017-07-06 10:06:12 +00001430 /// Emit MatchTable opcodes that test whether the instruction named in
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001431 /// InsnVarID matches all the predicates and all the operands.
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001432 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule) {
1433 if (!Optimized) {
1434 std::string Comment;
1435 raw_string_ostream CommentOS(Comment);
1436 CommentOS << "MIs[" << getInsnVarID() << "] ";
1437 if (SymbolicName.empty())
1438 CommentOS << "Operand " << OpIdx;
1439 else
1440 CommentOS << SymbolicName;
1441 Table << MatchTable::Comment(CommentOS.str()) << MatchTable::LineBreak;
1442 }
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001443
Quentin Colombetaad20be2017-12-15 23:07:42 +00001444 emitPredicateListOpcodes(Table, Rule);
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001445 }
Daniel Sanders759ff412017-02-24 13:58:11 +00001446
1447 /// Compare the priority of this object and B.
1448 ///
1449 /// Returns true if this object is more important than B.
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001450 bool isHigherPriorityThan(OperandMatcher &B) {
Daniel Sanders759ff412017-02-24 13:58:11 +00001451 // Operand matchers involving more predicates have higher priority.
1452 if (predicates_size() > B.predicates_size())
1453 return true;
1454 if (predicates_size() < B.predicates_size())
1455 return false;
1456
1457 // This assumes that predicates are added in a consistent order.
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001458 for (auto &&Predicate : zip(predicates(), B.predicates())) {
Daniel Sanders759ff412017-02-24 13:58:11 +00001459 if (std::get<0>(Predicate)->isHigherPriorityThan(*std::get<1>(Predicate)))
1460 return true;
1461 if (std::get<1>(Predicate)->isHigherPriorityThan(*std::get<0>(Predicate)))
1462 return false;
1463 }
1464
1465 return false;
1466 };
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001467
1468 /// Report the maximum number of temporary operands needed by the operand
1469 /// matcher.
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001470 unsigned countRendererFns() {
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001471 return std::accumulate(
1472 predicates().begin(), predicates().end(), 0,
1473 [](unsigned A,
1474 const std::unique_ptr<OperandPredicateMatcher> &Predicate) {
Daniel Sanders2deea182017-04-22 15:11:04 +00001475 return A + Predicate->countRendererFns();
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001476 });
1477 }
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001478
1479 unsigned getAllocatedTemporariesBaseID() const {
1480 return AllocatedTemporariesBaseID;
1481 }
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001482
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001483 bool isSameAsAnotherOperand() {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001484 for (const auto &Predicate : predicates())
1485 if (isa<SameOperandMatcher>(Predicate))
1486 return true;
1487 return false;
1488 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001489};
1490
Reid Klecknercfdd4a22017-10-16 20:31:16 +00001491Error OperandMatcher::addTypeCheckPredicate(const TypeSetByHwMode &VTy,
Quentin Colombetaad20be2017-12-15 23:07:42 +00001492 bool OperandIsAPointer) {
Reid Klecknercfdd4a22017-10-16 20:31:16 +00001493 if (!VTy.isMachineValueType())
1494 return failedImport("unsupported typeset");
1495
1496 if (VTy.getMachineValueType() == MVT::iPTR && OperandIsAPointer) {
1497 addPredicate<PointerToAnyOperandMatcher>(0);
1498 return Error::success();
1499 }
1500
1501 auto OpTyOrNone = MVTToLLT(VTy.getMachineValueType().SimpleTy);
1502 if (!OpTyOrNone)
1503 return failedImport("unsupported type");
1504
1505 if (OperandIsAPointer)
1506 addPredicate<PointerToAnyOperandMatcher>(OpTyOrNone->get().getSizeInBits());
1507 else
1508 addPredicate<LLTOperandMatcher>(*OpTyOrNone);
1509 return Error::success();
1510}
1511
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001512unsigned ComplexPatternOperandMatcher::getAllocatedTemporariesBaseID() const {
1513 return Operand.getAllocatedTemporariesBaseID();
1514}
1515
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001516/// Generates code to check a predicate on an instruction.
1517///
1518/// Typical predicates include:
1519/// * The opcode of the instruction is a particular value.
1520/// * The nsw/nuw flag is/isn't set.
Quentin Colombet063d7982017-12-14 23:44:07 +00001521class InstructionPredicateMatcher : public PredicateMatcher {
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001522public:
Quentin Colombetaad20be2017-12-15 23:07:42 +00001523 InstructionPredicateMatcher(PredicateKind Kind, unsigned InsnVarID)
1524 : PredicateMatcher(Kind, InsnVarID) {}
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001525 virtual ~InstructionPredicateMatcher() {}
1526
Daniel Sanders759ff412017-02-24 13:58:11 +00001527 /// Compare the priority of this object and B.
1528 ///
1529 /// Returns true if this object is more important than B.
Daniel Sanders32291982017-06-28 13:50:04 +00001530 virtual bool
1531 isHigherPriorityThan(const InstructionPredicateMatcher &B) const {
Daniel Sanders759ff412017-02-24 13:58:11 +00001532 return Kind < B.Kind;
1533 };
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001534};
1535
Daniel Sanders2c269f62017-08-24 09:11:20 +00001536template <>
1537std::string
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001538PredicateListMatcher<PredicateMatcher>::getNoPredicateComment() const {
Daniel Sanders2c269f62017-08-24 09:11:20 +00001539 return "No instruction predicates";
1540}
1541
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001542/// Generates code to check the opcode of an instruction.
1543class InstructionOpcodeMatcher : public InstructionPredicateMatcher {
1544protected:
1545 const CodeGenInstruction *I;
1546
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001547 static DenseMap<const CodeGenInstruction *, unsigned> OpcodeValues;
1548
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001549public:
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001550 static void initOpcodeValuesMap(const CodeGenTarget &Target) {
1551 OpcodeValues.clear();
1552
1553 unsigned OpcodeValue = 0;
1554 for (const CodeGenInstruction *I : Target.getInstructionsByEnumValue())
1555 OpcodeValues[I] = OpcodeValue++;
1556 }
1557
Quentin Colombetaad20be2017-12-15 23:07:42 +00001558 InstructionOpcodeMatcher(unsigned InsnVarID, const CodeGenInstruction *I)
1559 : InstructionPredicateMatcher(IPM_Opcode, InsnVarID), I(I) {}
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001560
Quentin Colombet063d7982017-12-14 23:44:07 +00001561 static bool classof(const PredicateMatcher *P) {
Daniel Sanders759ff412017-02-24 13:58:11 +00001562 return P->getKind() == IPM_Opcode;
1563 }
1564
Quentin Colombet893e0f12017-12-15 23:24:39 +00001565 bool isIdentical(const PredicateMatcher &B) const override {
1566 return InstructionPredicateMatcher::isIdentical(B) &&
1567 I == cast<InstructionOpcodeMatcher>(&B)->I;
1568 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001569 MatchTableRecord getValue() const override {
1570 const auto VI = OpcodeValues.find(I);
1571 if (VI != OpcodeValues.end())
1572 return MatchTable::NamedValue(I->Namespace, I->TheDef->getName(),
1573 VI->second);
1574 return MatchTable::NamedValue(I->Namespace, I->TheDef->getName());
1575 }
1576 bool hasValue() const override { return OpcodeValues.count(I); }
Quentin Colombet893e0f12017-12-15 23:24:39 +00001577
Quentin Colombetaad20be2017-12-15 23:07:42 +00001578 void emitPredicateOpcodes(MatchTable &Table,
1579 RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001580 Table << MatchTable::Opcode("GIM_CheckOpcode") << MatchTable::Comment("MI")
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001581 << MatchTable::IntValue(InsnVarID) << getValue()
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001582 << MatchTable::LineBreak;
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001583 }
Daniel Sanders759ff412017-02-24 13:58:11 +00001584
1585 /// Compare the priority of this object and B.
1586 ///
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001587 /// Returns true if this object is more important than B.
Daniel Sanders32291982017-06-28 13:50:04 +00001588 bool
1589 isHigherPriorityThan(const InstructionPredicateMatcher &B) const override {
Daniel Sanders759ff412017-02-24 13:58:11 +00001590 if (InstructionPredicateMatcher::isHigherPriorityThan(B))
1591 return true;
1592 if (B.InstructionPredicateMatcher::isHigherPriorityThan(*this))
1593 return false;
1594
1595 // Prioritize opcodes for cosmetic reasons in the generated source. Although
1596 // this is cosmetic at the moment, we may want to drive a similar ordering
1597 // using instruction frequency information to improve compile time.
1598 if (const InstructionOpcodeMatcher *BO =
1599 dyn_cast<InstructionOpcodeMatcher>(&B))
1600 return I->TheDef->getName() < BO->I->TheDef->getName();
1601
1602 return false;
1603 };
Daniel Sanders05540042017-08-08 10:44:31 +00001604
1605 bool isConstantInstruction() const {
1606 return I->TheDef->getName() == "G_CONSTANT";
1607 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001608
Roman Tereshin19da6672018-05-22 04:31:50 +00001609 StringRef getOpcode() const { return I->TheDef->getName(); }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001610 unsigned getNumOperands() const { return I->Operands.size(); }
1611
1612 StringRef getOperandType(unsigned OpIdx) const {
1613 return I->Operands[OpIdx].OperandType;
1614 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001615};
1616
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001617DenseMap<const CodeGenInstruction *, unsigned>
1618 InstructionOpcodeMatcher::OpcodeValues;
1619
Roman Tereshin19da6672018-05-22 04:31:50 +00001620class InstructionNumOperandsMatcher final : public InstructionPredicateMatcher {
1621 unsigned NumOperands = 0;
1622
1623public:
1624 InstructionNumOperandsMatcher(unsigned InsnVarID, unsigned NumOperands)
1625 : InstructionPredicateMatcher(IPM_NumOperands, InsnVarID),
1626 NumOperands(NumOperands) {}
1627
1628 static bool classof(const PredicateMatcher *P) {
1629 return P->getKind() == IPM_NumOperands;
1630 }
1631
1632 bool isIdentical(const PredicateMatcher &B) const override {
1633 return InstructionPredicateMatcher::isIdentical(B) &&
1634 NumOperands == cast<InstructionNumOperandsMatcher>(&B)->NumOperands;
1635 }
1636
1637 void emitPredicateOpcodes(MatchTable &Table,
1638 RuleMatcher &Rule) const override {
1639 Table << MatchTable::Opcode("GIM_CheckNumOperands")
1640 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1641 << MatchTable::Comment("Expected")
1642 << MatchTable::IntValue(NumOperands) << MatchTable::LineBreak;
1643 }
1644};
1645
Daniel Sanders2c269f62017-08-24 09:11:20 +00001646/// Generates code to check that this instruction is a constant whose value
1647/// meets an immediate predicate.
1648///
1649/// Immediates are slightly odd since they are typically used like an operand
1650/// but are represented as an operator internally. We typically write simm8:$src
1651/// in a tablegen pattern, but this is just syntactic sugar for
1652/// (imm:i32)<<P:Predicate_simm8>>:$imm which more directly describes the nodes
1653/// that will be matched and the predicate (which is attached to the imm
1654/// operator) that will be tested. In SelectionDAG this describes a
1655/// ConstantSDNode whose internal value will be tested using the simm8 predicate.
1656///
1657/// The corresponding GlobalISel representation is %1 = G_CONSTANT iN Value. In
1658/// this representation, the immediate could be tested with an
1659/// InstructionMatcher, InstructionOpcodeMatcher, OperandMatcher, and a
1660/// OperandPredicateMatcher-subclass to check the Value meets the predicate but
1661/// there are two implementation issues with producing that matcher
1662/// configuration from the SelectionDAG pattern:
1663/// * ImmLeaf is a PatFrag whose root is an InstructionMatcher. This means that
1664/// were we to sink the immediate predicate to the operand we would have to
1665/// have two partial implementations of PatFrag support, one for immediates
1666/// and one for non-immediates.
1667/// * At the point we handle the predicate, the OperandMatcher hasn't been
1668/// created yet. If we were to sink the predicate to the OperandMatcher we
1669/// would also have to complicate (or duplicate) the code that descends and
1670/// creates matchers for the subtree.
1671/// Overall, it's simpler to handle it in the place it was found.
1672class InstructionImmPredicateMatcher : public InstructionPredicateMatcher {
1673protected:
1674 TreePredicateFn Predicate;
1675
1676public:
Quentin Colombetaad20be2017-12-15 23:07:42 +00001677 InstructionImmPredicateMatcher(unsigned InsnVarID,
1678 const TreePredicateFn &Predicate)
1679 : InstructionPredicateMatcher(IPM_ImmPredicate, InsnVarID),
1680 Predicate(Predicate) {}
Daniel Sanders2c269f62017-08-24 09:11:20 +00001681
Quentin Colombet893e0f12017-12-15 23:24:39 +00001682 bool isIdentical(const PredicateMatcher &B) const override {
1683 return InstructionPredicateMatcher::isIdentical(B) &&
1684 Predicate.getOrigPatFragRecord() ==
1685 cast<InstructionImmPredicateMatcher>(&B)
1686 ->Predicate.getOrigPatFragRecord();
1687 }
1688
Quentin Colombet063d7982017-12-14 23:44:07 +00001689 static bool classof(const PredicateMatcher *P) {
Daniel Sanders2c269f62017-08-24 09:11:20 +00001690 return P->getKind() == IPM_ImmPredicate;
1691 }
1692
Quentin Colombetaad20be2017-12-15 23:07:42 +00001693 void emitPredicateOpcodes(MatchTable &Table,
1694 RuleMatcher &Rule) const override {
Daniel Sanders11300ce2017-10-13 21:28:03 +00001695 Table << MatchTable::Opcode(getMatchOpcodeForPredicate(Predicate))
Daniel Sanders2c269f62017-08-24 09:11:20 +00001696 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1697 << MatchTable::Comment("Predicate")
Daniel Sanders11300ce2017-10-13 21:28:03 +00001698 << MatchTable::NamedValue(getEnumNameForPredicate(Predicate))
Daniel Sanders2c269f62017-08-24 09:11:20 +00001699 << MatchTable::LineBreak;
1700 }
1701};
1702
Daniel Sanders76664652017-11-28 22:07:05 +00001703/// Generates code to check that a memory instruction has a atomic ordering
1704/// MachineMemoryOperand.
1705class AtomicOrderingMMOPredicateMatcher : public InstructionPredicateMatcher {
Daniel Sanders0c43b3a2017-11-30 21:05:59 +00001706public:
1707 enum AOComparator {
1708 AO_Exactly,
1709 AO_OrStronger,
1710 AO_WeakerThan,
1711 };
1712
1713protected:
Daniel Sanders76664652017-11-28 22:07:05 +00001714 StringRef Order;
Daniel Sanders0c43b3a2017-11-30 21:05:59 +00001715 AOComparator Comparator;
Daniel Sanders76664652017-11-28 22:07:05 +00001716
Daniel Sanders39690bd2017-10-15 02:41:12 +00001717public:
Quentin Colombetaad20be2017-12-15 23:07:42 +00001718 AtomicOrderingMMOPredicateMatcher(unsigned InsnVarID, StringRef Order,
Daniel Sanders0c43b3a2017-11-30 21:05:59 +00001719 AOComparator Comparator = AO_Exactly)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001720 : InstructionPredicateMatcher(IPM_AtomicOrderingMMO, InsnVarID),
1721 Order(Order), Comparator(Comparator) {}
Daniel Sanders39690bd2017-10-15 02:41:12 +00001722
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001723 static bool classof(const PredicateMatcher *P) {
Daniel Sanders76664652017-11-28 22:07:05 +00001724 return P->getKind() == IPM_AtomicOrderingMMO;
Daniel Sanders39690bd2017-10-15 02:41:12 +00001725 }
1726
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001727 bool isIdentical(const PredicateMatcher &B) const override {
1728 if (!InstructionPredicateMatcher::isIdentical(B))
1729 return false;
1730 const auto &R = *cast<AtomicOrderingMMOPredicateMatcher>(&B);
1731 return Order == R.Order && Comparator == R.Comparator;
1732 }
1733
Quentin Colombetaad20be2017-12-15 23:07:42 +00001734 void emitPredicateOpcodes(MatchTable &Table,
1735 RuleMatcher &Rule) const override {
Daniel Sanders0c43b3a2017-11-30 21:05:59 +00001736 StringRef Opcode = "GIM_CheckAtomicOrdering";
1737
1738 if (Comparator == AO_OrStronger)
1739 Opcode = "GIM_CheckAtomicOrderingOrStrongerThan";
1740 if (Comparator == AO_WeakerThan)
1741 Opcode = "GIM_CheckAtomicOrderingWeakerThan";
1742
1743 Table << MatchTable::Opcode(Opcode) << MatchTable::Comment("MI")
1744 << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Order")
Daniel Sanders76664652017-11-28 22:07:05 +00001745 << MatchTable::NamedValue(("(int64_t)AtomicOrdering::" + Order).str())
Daniel Sanders39690bd2017-10-15 02:41:12 +00001746 << MatchTable::LineBreak;
1747 }
1748};
1749
Daniel Sandersf84bc372018-05-05 20:53:24 +00001750/// Generates code to check that the size of an MMO is exactly N bytes.
1751class MemorySizePredicateMatcher : public InstructionPredicateMatcher {
1752protected:
1753 unsigned MMOIdx;
1754 uint64_t Size;
1755
1756public:
1757 MemorySizePredicateMatcher(unsigned InsnVarID, unsigned MMOIdx, unsigned Size)
1758 : InstructionPredicateMatcher(IPM_MemoryLLTSize, InsnVarID),
1759 MMOIdx(MMOIdx), Size(Size) {}
1760
1761 static bool classof(const PredicateMatcher *P) {
1762 return P->getKind() == IPM_MemoryLLTSize;
1763 }
1764 bool isIdentical(const PredicateMatcher &B) const override {
1765 return InstructionPredicateMatcher::isIdentical(B) &&
1766 MMOIdx == cast<MemorySizePredicateMatcher>(&B)->MMOIdx &&
1767 Size == cast<MemorySizePredicateMatcher>(&B)->Size;
1768 }
1769
1770 void emitPredicateOpcodes(MatchTable &Table,
1771 RuleMatcher &Rule) const override {
1772 Table << MatchTable::Opcode("GIM_CheckMemorySizeEqualTo")
1773 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1774 << MatchTable::Comment("MMO") << MatchTable::IntValue(MMOIdx)
1775 << MatchTable::Comment("Size") << MatchTable::IntValue(Size)
1776 << MatchTable::LineBreak;
1777 }
1778};
1779
1780/// Generates code to check that the size of an MMO is less-than, equal-to, or
1781/// greater than a given LLT.
1782class MemoryVsLLTSizePredicateMatcher : public InstructionPredicateMatcher {
1783public:
1784 enum RelationKind {
1785 GreaterThan,
1786 EqualTo,
1787 LessThan,
1788 };
1789
1790protected:
1791 unsigned MMOIdx;
1792 RelationKind Relation;
1793 unsigned OpIdx;
1794
1795public:
1796 MemoryVsLLTSizePredicateMatcher(unsigned InsnVarID, unsigned MMOIdx,
1797 enum RelationKind Relation,
1798 unsigned OpIdx)
1799 : InstructionPredicateMatcher(IPM_MemoryVsLLTSize, InsnVarID),
1800 MMOIdx(MMOIdx), Relation(Relation), OpIdx(OpIdx) {}
1801
1802 static bool classof(const PredicateMatcher *P) {
1803 return P->getKind() == IPM_MemoryVsLLTSize;
1804 }
1805 bool isIdentical(const PredicateMatcher &B) const override {
1806 return InstructionPredicateMatcher::isIdentical(B) &&
1807 MMOIdx == cast<MemoryVsLLTSizePredicateMatcher>(&B)->MMOIdx &&
1808 Relation == cast<MemoryVsLLTSizePredicateMatcher>(&B)->Relation &&
1809 OpIdx == cast<MemoryVsLLTSizePredicateMatcher>(&B)->OpIdx;
1810 }
1811
1812 void emitPredicateOpcodes(MatchTable &Table,
1813 RuleMatcher &Rule) const override {
1814 Table << MatchTable::Opcode(Relation == EqualTo
1815 ? "GIM_CheckMemorySizeEqualToLLT"
1816 : Relation == GreaterThan
1817 ? "GIM_CheckMemorySizeGreaterThanLLT"
1818 : "GIM_CheckMemorySizeLessThanLLT")
1819 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1820 << MatchTable::Comment("MMO") << MatchTable::IntValue(MMOIdx)
1821 << MatchTable::Comment("OpIdx") << MatchTable::IntValue(OpIdx)
1822 << MatchTable::LineBreak;
1823 }
1824};
1825
Daniel Sanders8ead1292018-06-15 23:13:43 +00001826/// Generates code to check an arbitrary C++ instruction predicate.
1827class GenericInstructionPredicateMatcher : public InstructionPredicateMatcher {
1828protected:
1829 TreePredicateFn Predicate;
1830
1831public:
1832 GenericInstructionPredicateMatcher(unsigned InsnVarID,
1833 TreePredicateFn Predicate)
1834 : InstructionPredicateMatcher(IPM_GenericPredicate, InsnVarID),
1835 Predicate(Predicate) {}
1836
1837 static bool classof(const InstructionPredicateMatcher *P) {
1838 return P->getKind() == IPM_GenericPredicate;
1839 }
Daniel Sanders06f4ff12018-09-25 17:59:02 +00001840 bool isIdentical(const PredicateMatcher &B) const override {
1841 return InstructionPredicateMatcher::isIdentical(B) &&
1842 Predicate ==
1843 static_cast<const GenericInstructionPredicateMatcher &>(B)
1844 .Predicate;
1845 }
Daniel Sanders8ead1292018-06-15 23:13:43 +00001846 void emitPredicateOpcodes(MatchTable &Table,
1847 RuleMatcher &Rule) const override {
1848 Table << MatchTable::Opcode("GIM_CheckCxxInsnPredicate")
1849 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1850 << MatchTable::Comment("FnId")
1851 << MatchTable::NamedValue(getEnumNameForPredicate(Predicate))
1852 << MatchTable::LineBreak;
1853 }
1854};
1855
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001856/// Generates code to check that a set of predicates and operands match for a
1857/// particular instruction.
1858///
1859/// Typical predicates include:
1860/// * Has a specific opcode.
1861/// * Has an nsw/nuw flag or doesn't.
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001862class InstructionMatcher final : public PredicateListMatcher<PredicateMatcher> {
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001863protected:
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001864 typedef std::vector<std::unique_ptr<OperandMatcher>> OperandVec;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001865
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001866 RuleMatcher &Rule;
1867
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001868 /// The operands to match. All rendered operands must be present even if the
1869 /// condition is always true.
1870 OperandVec Operands;
Roman Tereshin19da6672018-05-22 04:31:50 +00001871 bool NumOperandsCheck = true;
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001872
Daniel Sanders05540042017-08-08 10:44:31 +00001873 std::string SymbolicName;
Quentin Colombetaad20be2017-12-15 23:07:42 +00001874 unsigned InsnVarID;
Daniel Sanders05540042017-08-08 10:44:31 +00001875
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001876public:
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001877 InstructionMatcher(RuleMatcher &Rule, StringRef SymbolicName)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001878 : Rule(Rule), SymbolicName(SymbolicName) {
1879 // We create a new instruction matcher.
1880 // Get a new ID for that instruction.
1881 InsnVarID = Rule.implicitlyDefineInsnVar(*this);
1882 }
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001883
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001884 /// Construct a new instruction predicate and add it to the matcher.
1885 template <class Kind, class... Args>
1886 Optional<Kind *> addPredicate(Args &&... args) {
1887 Predicates.emplace_back(
1888 llvm::make_unique<Kind>(getInsnVarID(), std::forward<Args>(args)...));
1889 return static_cast<Kind *>(Predicates.back().get());
1890 }
1891
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001892 RuleMatcher &getRuleMatcher() const { return Rule; }
Daniel Sanders05540042017-08-08 10:44:31 +00001893
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001894 unsigned getInsnVarID() const { return InsnVarID; }
Quentin Colombetaad20be2017-12-15 23:07:42 +00001895
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001896 /// Add an operand to the matcher.
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001897 OperandMatcher &addOperand(unsigned OpIdx, const std::string &SymbolicName,
1898 unsigned AllocatedTemporariesBaseID) {
1899 Operands.emplace_back(new OperandMatcher(*this, OpIdx, SymbolicName,
1900 AllocatedTemporariesBaseID));
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001901 if (!SymbolicName.empty())
1902 Rule.defineOperand(SymbolicName, *Operands.back());
1903
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001904 return *Operands.back();
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001905 }
1906
Daniel Sandersffc7d582017-03-29 15:37:18 +00001907 OperandMatcher &getOperand(unsigned OpIdx) {
1908 auto I = std::find_if(Operands.begin(), Operands.end(),
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001909 [&OpIdx](const std::unique_ptr<OperandMatcher> &X) {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001910 return X->getOpIdx() == OpIdx;
Daniel Sandersffc7d582017-03-29 15:37:18 +00001911 });
1912 if (I != Operands.end())
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001913 return **I;
Daniel Sandersffc7d582017-03-29 15:37:18 +00001914 llvm_unreachable("Failed to lookup operand");
1915 }
1916
Daniel Sanders05540042017-08-08 10:44:31 +00001917 StringRef getSymbolicName() const { return SymbolicName; }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001918 unsigned getNumOperands() const { return Operands.size(); }
Daniel Sandersbee57392017-04-04 13:25:23 +00001919 OperandVec::iterator operands_begin() { return Operands.begin(); }
1920 OperandVec::iterator operands_end() { return Operands.end(); }
1921 iterator_range<OperandVec::iterator> operands() {
1922 return make_range(operands_begin(), operands_end());
1923 }
Daniel Sandersffc7d582017-03-29 15:37:18 +00001924 OperandVec::const_iterator operands_begin() const { return Operands.begin(); }
1925 OperandVec::const_iterator operands_end() const { return Operands.end(); }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001926 iterator_range<OperandVec::const_iterator> operands() const {
1927 return make_range(operands_begin(), operands_end());
1928 }
Quentin Colombetec76d9c2017-12-18 19:47:41 +00001929 bool operands_empty() const { return Operands.empty(); }
1930
1931 void pop_front() { Operands.erase(Operands.begin()); }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001932
Roman Tereshin19da6672018-05-22 04:31:50 +00001933 void optimize();
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001934
1935 /// Emit MatchTable opcodes that test whether the instruction named in
1936 /// InsnVarName matches all the predicates and all the operands.
1937 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule) {
Roman Tereshin19da6672018-05-22 04:31:50 +00001938 if (NumOperandsCheck)
1939 InstructionNumOperandsMatcher(InsnVarID, getNumOperands())
1940 .emitPredicateOpcodes(Table, Rule);
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001941
Quentin Colombetaad20be2017-12-15 23:07:42 +00001942 emitPredicateListOpcodes(Table, Rule);
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001943
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001944 for (const auto &Operand : Operands)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001945 Operand->emitPredicateOpcodes(Table, Rule);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001946 }
Daniel Sanders759ff412017-02-24 13:58:11 +00001947
1948 /// Compare the priority of this object and B.
1949 ///
1950 /// Returns true if this object is more important than B.
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001951 bool isHigherPriorityThan(InstructionMatcher &B) {
Daniel Sanders759ff412017-02-24 13:58:11 +00001952 // Instruction matchers involving more operands have higher priority.
1953 if (Operands.size() > B.Operands.size())
1954 return true;
1955 if (Operands.size() < B.Operands.size())
1956 return false;
1957
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001958 for (auto &&P : zip(predicates(), B.predicates())) {
1959 auto L = static_cast<InstructionPredicateMatcher *>(std::get<0>(P).get());
1960 auto R = static_cast<InstructionPredicateMatcher *>(std::get<1>(P).get());
1961 if (L->isHigherPriorityThan(*R))
Daniel Sanders759ff412017-02-24 13:58:11 +00001962 return true;
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001963 if (R->isHigherPriorityThan(*L))
Daniel Sanders759ff412017-02-24 13:58:11 +00001964 return false;
1965 }
1966
1967 for (const auto &Operand : zip(Operands, B.Operands)) {
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001968 if (std::get<0>(Operand)->isHigherPriorityThan(*std::get<1>(Operand)))
Daniel Sanders759ff412017-02-24 13:58:11 +00001969 return true;
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001970 if (std::get<1>(Operand)->isHigherPriorityThan(*std::get<0>(Operand)))
Daniel Sanders759ff412017-02-24 13:58:11 +00001971 return false;
1972 }
1973
1974 return false;
1975 };
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001976
1977 /// Report the maximum number of temporary operands needed by the instruction
1978 /// matcher.
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001979 unsigned countRendererFns() {
1980 return std::accumulate(
1981 predicates().begin(), predicates().end(), 0,
1982 [](unsigned A,
1983 const std::unique_ptr<PredicateMatcher> &Predicate) {
1984 return A + Predicate->countRendererFns();
1985 }) +
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001986 std::accumulate(
1987 Operands.begin(), Operands.end(), 0,
1988 [](unsigned A, const std::unique_ptr<OperandMatcher> &Operand) {
Daniel Sanders2deea182017-04-22 15:11:04 +00001989 return A + Operand->countRendererFns();
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001990 });
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001991 }
Daniel Sanders05540042017-08-08 10:44:31 +00001992
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001993 InstructionOpcodeMatcher &getOpcodeMatcher() {
1994 for (auto &P : predicates())
1995 if (auto *OpMatcher = dyn_cast<InstructionOpcodeMatcher>(P.get()))
1996 return *OpMatcher;
1997 llvm_unreachable("Didn't find an opcode matcher");
1998 }
1999
2000 bool isConstantInstruction() {
2001 return getOpcodeMatcher().isConstantInstruction();
Daniel Sanders05540042017-08-08 10:44:31 +00002002 }
Roman Tereshin19da6672018-05-22 04:31:50 +00002003
2004 StringRef getOpcode() { return getOpcodeMatcher().getOpcode(); }
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002005};
2006
Roman Tereshin19da6672018-05-22 04:31:50 +00002007StringRef RuleMatcher::getOpcode() const {
2008 return Matchers.front()->getOpcode();
2009}
2010
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002011unsigned RuleMatcher::getNumOperands() const {
2012 return Matchers.front()->getNumOperands();
2013}
2014
Roman Tereshin9a9fa492018-05-23 21:30:16 +00002015LLTCodeGen RuleMatcher::getFirstConditionAsRootType() {
2016 InstructionMatcher &InsnMatcher = *Matchers.front();
2017 if (!InsnMatcher.predicates_empty())
2018 if (const auto *TM =
2019 dyn_cast<LLTOperandMatcher>(&**InsnMatcher.predicates_begin()))
2020 if (TM->getInsnVarID() == 0 && TM->getOpIdx() == 0)
2021 return TM->getTy();
2022 return {};
2023}
2024
Daniel Sandersbee57392017-04-04 13:25:23 +00002025/// Generates code to check that the operand is a register defined by an
2026/// instruction that matches the given instruction matcher.
2027///
2028/// For example, the pattern:
2029/// (set $dst, (G_MUL (G_ADD $src1, $src2), $src3))
2030/// would use an InstructionOperandMatcher for operand 1 of the G_MUL to match
2031/// the:
2032/// (G_ADD $src1, $src2)
2033/// subpattern.
2034class InstructionOperandMatcher : public OperandPredicateMatcher {
2035protected:
2036 std::unique_ptr<InstructionMatcher> InsnMatcher;
2037
2038public:
Quentin Colombeteba10cb2017-12-18 22:12:13 +00002039 InstructionOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
2040 RuleMatcher &Rule, StringRef SymbolicName)
Quentin Colombetaad20be2017-12-15 23:07:42 +00002041 : OperandPredicateMatcher(OPM_Instruction, InsnVarID, OpIdx),
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002042 InsnMatcher(new InstructionMatcher(Rule, SymbolicName)) {}
Daniel Sandersbee57392017-04-04 13:25:23 +00002043
Quentin Colombet063d7982017-12-14 23:44:07 +00002044 static bool classof(const PredicateMatcher *P) {
Daniel Sandersbee57392017-04-04 13:25:23 +00002045 return P->getKind() == OPM_Instruction;
2046 }
2047
2048 InstructionMatcher &getInsnMatcher() const { return *InsnMatcher; }
2049
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002050 void emitCaptureOpcodes(MatchTable &Table, RuleMatcher &Rule) const {
2051 const unsigned NewInsnVarID = InsnMatcher->getInsnVarID();
2052 Table << MatchTable::Opcode("GIM_RecordInsn")
2053 << MatchTable::Comment("DefineMI")
2054 << MatchTable::IntValue(NewInsnVarID) << MatchTable::Comment("MI")
2055 << MatchTable::IntValue(getInsnVarID())
2056 << MatchTable::Comment("OpIdx") << MatchTable::IntValue(getOpIdx())
2057 << MatchTable::Comment("MIs[" + llvm::to_string(NewInsnVarID) + "]")
2058 << MatchTable::LineBreak;
Daniel Sandersbee57392017-04-04 13:25:23 +00002059 }
2060
Quentin Colombetaad20be2017-12-15 23:07:42 +00002061 void emitPredicateOpcodes(MatchTable &Table,
2062 RuleMatcher &Rule) const override {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002063 emitCaptureOpcodes(Table, Rule);
Quentin Colombetaad20be2017-12-15 23:07:42 +00002064 InsnMatcher->emitPredicateOpcodes(Table, Rule);
Daniel Sandersbee57392017-04-04 13:25:23 +00002065 }
Daniel Sanders12e6e702018-01-17 20:34:29 +00002066
2067 bool isHigherPriorityThan(const OperandPredicateMatcher &B) const override {
2068 if (OperandPredicateMatcher::isHigherPriorityThan(B))
2069 return true;
2070 if (B.OperandPredicateMatcher::isHigherPriorityThan(*this))
2071 return false;
2072
2073 if (const InstructionOperandMatcher *BP =
2074 dyn_cast<InstructionOperandMatcher>(&B))
2075 if (InsnMatcher->isHigherPriorityThan(*BP->InsnMatcher))
2076 return true;
2077 return false;
2078 }
Daniel Sandersbee57392017-04-04 13:25:23 +00002079};
2080
Roman Tereshin19da6672018-05-22 04:31:50 +00002081void InstructionMatcher::optimize() {
2082 SmallVector<std::unique_ptr<PredicateMatcher>, 8> Stash;
2083 const auto &OpcMatcher = getOpcodeMatcher();
2084
2085 Stash.push_back(predicates_pop_front());
2086 if (Stash.back().get() == &OpcMatcher) {
2087 if (NumOperandsCheck && OpcMatcher.getNumOperands() < getNumOperands())
2088 Stash.emplace_back(
2089 new InstructionNumOperandsMatcher(InsnVarID, getNumOperands()));
2090 NumOperandsCheck = false;
Roman Tereshinfedae332018-05-23 02:04:19 +00002091
2092 for (auto &OM : Operands)
2093 for (auto &OP : OM->predicates())
2094 if (isa<IntrinsicIDOperandMatcher>(OP)) {
2095 Stash.push_back(std::move(OP));
2096 OM->eraseNullPredicates();
2097 break;
2098 }
Roman Tereshin19da6672018-05-22 04:31:50 +00002099 }
2100
2101 if (InsnVarID > 0) {
2102 assert(!Operands.empty() && "Nested instruction is expected to def a vreg");
2103 for (auto &OP : Operands[0]->predicates())
2104 OP.reset();
2105 Operands[0]->eraseNullPredicates();
2106 }
Roman Tereshinb1ba1272018-05-23 19:16:59 +00002107 for (auto &OM : Operands) {
2108 for (auto &OP : OM->predicates())
2109 if (isa<LLTOperandMatcher>(OP))
2110 Stash.push_back(std::move(OP));
2111 OM->eraseNullPredicates();
2112 }
Roman Tereshin19da6672018-05-22 04:31:50 +00002113 while (!Stash.empty())
2114 prependPredicate(Stash.pop_back_val());
2115}
2116
Daniel Sanders43c882c2017-02-01 10:53:10 +00002117//===- Actions ------------------------------------------------------------===//
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002118class OperandRenderer {
2119public:
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002120 enum RendererKind {
2121 OR_Copy,
Daniel Sandersd66e0902017-10-23 18:19:24 +00002122 OR_CopyOrAddZeroReg,
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002123 OR_CopySubReg,
Daniel Sanders05540042017-08-08 10:44:31 +00002124 OR_CopyConstantAsImm,
Daniel Sanders11300ce2017-10-13 21:28:03 +00002125 OR_CopyFConstantAsFPImm,
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002126 OR_Imm,
2127 OR_Register,
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002128 OR_TempRegister,
Volkan Kelesf7f25682018-01-16 18:44:05 +00002129 OR_ComplexPattern,
2130 OR_Custom
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002131 };
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002132
2133protected:
2134 RendererKind Kind;
2135
2136public:
2137 OperandRenderer(RendererKind Kind) : Kind(Kind) {}
2138 virtual ~OperandRenderer() {}
2139
2140 RendererKind getKind() const { return Kind; }
2141
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002142 virtual void emitRenderOpcodes(MatchTable &Table,
2143 RuleMatcher &Rule) const = 0;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002144};
2145
2146/// A CopyRenderer emits code to copy a single operand from an existing
2147/// instruction to the one being built.
2148class CopyRenderer : public OperandRenderer {
2149protected:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002150 unsigned NewInsnID;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002151 /// The name of the operand.
2152 const StringRef SymbolicName;
2153
2154public:
Daniel Sandersbd83ad42017-10-24 01:48:34 +00002155 CopyRenderer(unsigned NewInsnID, StringRef SymbolicName)
2156 : OperandRenderer(OR_Copy), NewInsnID(NewInsnID),
Daniel Sanders05540042017-08-08 10:44:31 +00002157 SymbolicName(SymbolicName) {
2158 assert(!SymbolicName.empty() && "Cannot copy from an unspecified source");
2159 }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002160
2161 static bool classof(const OperandRenderer *R) {
2162 return R->getKind() == OR_Copy;
2163 }
2164
2165 const StringRef getSymbolicName() const { return SymbolicName; }
2166
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002167 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002168 const OperandMatcher &Operand = Rule.getOperandMatcher(SymbolicName);
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002169 unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002170 Table << MatchTable::Opcode("GIR_Copy") << MatchTable::Comment("NewInsnID")
2171 << MatchTable::IntValue(NewInsnID) << MatchTable::Comment("OldInsnID")
2172 << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002173 << MatchTable::IntValue(Operand.getOpIdx())
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002174 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002175 }
2176};
2177
Daniel Sandersd66e0902017-10-23 18:19:24 +00002178/// A CopyOrAddZeroRegRenderer emits code to copy a single operand from an
2179/// existing instruction to the one being built. If the operand turns out to be
2180/// a 'G_CONSTANT 0' then it replaces the operand with a zero register.
2181class CopyOrAddZeroRegRenderer : public OperandRenderer {
2182protected:
2183 unsigned NewInsnID;
2184 /// The name of the operand.
2185 const StringRef SymbolicName;
2186 const Record *ZeroRegisterDef;
2187
2188public:
2189 CopyOrAddZeroRegRenderer(unsigned NewInsnID,
Daniel Sandersd66e0902017-10-23 18:19:24 +00002190 StringRef SymbolicName, Record *ZeroRegisterDef)
2191 : OperandRenderer(OR_CopyOrAddZeroReg), NewInsnID(NewInsnID),
2192 SymbolicName(SymbolicName), ZeroRegisterDef(ZeroRegisterDef) {
2193 assert(!SymbolicName.empty() && "Cannot copy from an unspecified source");
2194 }
2195
2196 static bool classof(const OperandRenderer *R) {
2197 return R->getKind() == OR_CopyOrAddZeroReg;
2198 }
2199
2200 const StringRef getSymbolicName() const { return SymbolicName; }
2201
2202 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2203 const OperandMatcher &Operand = Rule.getOperandMatcher(SymbolicName);
2204 unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
2205 Table << MatchTable::Opcode("GIR_CopyOrAddZeroReg")
2206 << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
2207 << MatchTable::Comment("OldInsnID")
2208 << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002209 << MatchTable::IntValue(Operand.getOpIdx())
Daniel Sandersd66e0902017-10-23 18:19:24 +00002210 << MatchTable::NamedValue(
2211 (ZeroRegisterDef->getValue("Namespace")
2212 ? ZeroRegisterDef->getValueAsString("Namespace")
2213 : ""),
2214 ZeroRegisterDef->getName())
2215 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2216 }
2217};
2218
Daniel Sanders05540042017-08-08 10:44:31 +00002219/// A CopyConstantAsImmRenderer emits code to render a G_CONSTANT instruction to
2220/// an extended immediate operand.
2221class CopyConstantAsImmRenderer : public OperandRenderer {
2222protected:
2223 unsigned NewInsnID;
2224 /// The name of the operand.
2225 const std::string SymbolicName;
2226 bool Signed;
2227
2228public:
2229 CopyConstantAsImmRenderer(unsigned NewInsnID, StringRef SymbolicName)
2230 : OperandRenderer(OR_CopyConstantAsImm), NewInsnID(NewInsnID),
2231 SymbolicName(SymbolicName), Signed(true) {}
2232
2233 static bool classof(const OperandRenderer *R) {
2234 return R->getKind() == OR_CopyConstantAsImm;
2235 }
2236
2237 const StringRef getSymbolicName() const { return SymbolicName; }
2238
2239 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002240 InstructionMatcher &InsnMatcher = Rule.getInstructionMatcher(SymbolicName);
Daniel Sanders05540042017-08-08 10:44:31 +00002241 unsigned OldInsnVarID = Rule.getInsnVarID(InsnMatcher);
2242 Table << MatchTable::Opcode(Signed ? "GIR_CopyConstantAsSImm"
2243 : "GIR_CopyConstantAsUImm")
2244 << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
2245 << MatchTable::Comment("OldInsnID")
2246 << MatchTable::IntValue(OldInsnVarID)
2247 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2248 }
2249};
2250
Daniel Sanders11300ce2017-10-13 21:28:03 +00002251/// A CopyFConstantAsFPImmRenderer emits code to render a G_FCONSTANT
2252/// instruction to an extended immediate operand.
2253class CopyFConstantAsFPImmRenderer : public OperandRenderer {
2254protected:
2255 unsigned NewInsnID;
2256 /// The name of the operand.
2257 const std::string SymbolicName;
2258
2259public:
2260 CopyFConstantAsFPImmRenderer(unsigned NewInsnID, StringRef SymbolicName)
2261 : OperandRenderer(OR_CopyFConstantAsFPImm), NewInsnID(NewInsnID),
2262 SymbolicName(SymbolicName) {}
2263
2264 static bool classof(const OperandRenderer *R) {
2265 return R->getKind() == OR_CopyFConstantAsFPImm;
2266 }
2267
2268 const StringRef getSymbolicName() const { return SymbolicName; }
2269
2270 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002271 InstructionMatcher &InsnMatcher = Rule.getInstructionMatcher(SymbolicName);
Daniel Sanders11300ce2017-10-13 21:28:03 +00002272 unsigned OldInsnVarID = Rule.getInsnVarID(InsnMatcher);
2273 Table << MatchTable::Opcode("GIR_CopyFConstantAsFPImm")
2274 << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
2275 << MatchTable::Comment("OldInsnID")
2276 << MatchTable::IntValue(OldInsnVarID)
2277 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2278 }
2279};
2280
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002281/// A CopySubRegRenderer emits code to copy a single register operand from an
2282/// existing instruction to the one being built and indicate that only a
2283/// subregister should be copied.
2284class CopySubRegRenderer : public OperandRenderer {
2285protected:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002286 unsigned NewInsnID;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002287 /// The name of the operand.
2288 const StringRef SymbolicName;
2289 /// The subregister to extract.
2290 const CodeGenSubRegIndex *SubReg;
2291
2292public:
Daniel Sandersbd83ad42017-10-24 01:48:34 +00002293 CopySubRegRenderer(unsigned NewInsnID, StringRef SymbolicName,
2294 const CodeGenSubRegIndex *SubReg)
2295 : OperandRenderer(OR_CopySubReg), NewInsnID(NewInsnID),
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002296 SymbolicName(SymbolicName), SubReg(SubReg) {}
2297
2298 static bool classof(const OperandRenderer *R) {
2299 return R->getKind() == OR_CopySubReg;
2300 }
2301
2302 const StringRef getSymbolicName() const { return SymbolicName; }
2303
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002304 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002305 const OperandMatcher &Operand = Rule.getOperandMatcher(SymbolicName);
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002306 unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002307 Table << MatchTable::Opcode("GIR_CopySubReg")
2308 << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
2309 << MatchTable::Comment("OldInsnID")
2310 << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002311 << MatchTable::IntValue(Operand.getOpIdx())
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002312 << MatchTable::Comment("SubRegIdx")
2313 << MatchTable::IntValue(SubReg->EnumValue)
2314 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002315 }
2316};
2317
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002318/// Adds a specific physical register to the instruction being built.
2319/// This is typically useful for WZR/XZR on AArch64.
2320class AddRegisterRenderer : public OperandRenderer {
2321protected:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002322 unsigned InsnID;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002323 const Record *RegisterDef;
2324
2325public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002326 AddRegisterRenderer(unsigned InsnID, const Record *RegisterDef)
2327 : OperandRenderer(OR_Register), InsnID(InsnID), RegisterDef(RegisterDef) {
2328 }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002329
2330 static bool classof(const OperandRenderer *R) {
2331 return R->getKind() == OR_Register;
2332 }
2333
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002334 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2335 Table << MatchTable::Opcode("GIR_AddRegister")
2336 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2337 << MatchTable::NamedValue(
2338 (RegisterDef->getValue("Namespace")
2339 ? RegisterDef->getValueAsString("Namespace")
2340 : ""),
2341 RegisterDef->getName())
2342 << MatchTable::LineBreak;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002343 }
2344};
2345
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002346/// Adds a specific temporary virtual register to the instruction being built.
2347/// This is used to chain instructions together when emitting multiple
2348/// instructions.
2349class TempRegRenderer : public OperandRenderer {
2350protected:
2351 unsigned InsnID;
2352 unsigned TempRegID;
2353 bool IsDef;
2354
2355public:
2356 TempRegRenderer(unsigned InsnID, unsigned TempRegID, bool IsDef = false)
2357 : OperandRenderer(OR_Register), InsnID(InsnID), TempRegID(TempRegID),
2358 IsDef(IsDef) {}
2359
2360 static bool classof(const OperandRenderer *R) {
2361 return R->getKind() == OR_TempRegister;
2362 }
2363
2364 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2365 Table << MatchTable::Opcode("GIR_AddTempRegister")
2366 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2367 << MatchTable::Comment("TempRegID") << MatchTable::IntValue(TempRegID)
2368 << MatchTable::Comment("TempRegFlags");
2369 if (IsDef)
2370 Table << MatchTable::NamedValue("RegState::Define");
2371 else
2372 Table << MatchTable::IntValue(0);
2373 Table << MatchTable::LineBreak;
2374 }
2375};
2376
Daniel Sanders0ed28822017-04-12 08:23:08 +00002377/// Adds a specific immediate to the instruction being built.
2378class ImmRenderer : public OperandRenderer {
2379protected:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002380 unsigned InsnID;
Daniel Sanders0ed28822017-04-12 08:23:08 +00002381 int64_t Imm;
2382
2383public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002384 ImmRenderer(unsigned InsnID, int64_t Imm)
2385 : OperandRenderer(OR_Imm), InsnID(InsnID), Imm(Imm) {}
Daniel Sanders0ed28822017-04-12 08:23:08 +00002386
2387 static bool classof(const OperandRenderer *R) {
2388 return R->getKind() == OR_Imm;
2389 }
2390
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002391 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2392 Table << MatchTable::Opcode("GIR_AddImm") << MatchTable::Comment("InsnID")
2393 << MatchTable::IntValue(InsnID) << MatchTable::Comment("Imm")
2394 << MatchTable::IntValue(Imm) << MatchTable::LineBreak;
Daniel Sanders0ed28822017-04-12 08:23:08 +00002395 }
2396};
2397
Daniel Sanders2deea182017-04-22 15:11:04 +00002398/// Adds operands by calling a renderer function supplied by the ComplexPattern
2399/// matcher function.
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002400class RenderComplexPatternOperand : public OperandRenderer {
2401private:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002402 unsigned InsnID;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002403 const Record &TheDef;
Daniel Sanders2deea182017-04-22 15:11:04 +00002404 /// The name of the operand.
2405 const StringRef SymbolicName;
2406 /// The renderer number. This must be unique within a rule since it's used to
2407 /// identify a temporary variable to hold the renderer function.
2408 unsigned RendererID;
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002409 /// When provided, this is the suboperand of the ComplexPattern operand to
2410 /// render. Otherwise all the suboperands will be rendered.
2411 Optional<unsigned> SubOperand;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002412
2413 unsigned getNumOperands() const {
2414 return TheDef.getValueAsDag("Operands")->getNumArgs();
2415 }
2416
2417public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002418 RenderComplexPatternOperand(unsigned InsnID, const Record &TheDef,
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002419 StringRef SymbolicName, unsigned RendererID,
2420 Optional<unsigned> SubOperand = None)
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002421 : OperandRenderer(OR_ComplexPattern), InsnID(InsnID), TheDef(TheDef),
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002422 SymbolicName(SymbolicName), RendererID(RendererID),
2423 SubOperand(SubOperand) {}
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002424
2425 static bool classof(const OperandRenderer *R) {
2426 return R->getKind() == OR_ComplexPattern;
2427 }
2428
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002429 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002430 Table << MatchTable::Opcode(SubOperand.hasValue() ? "GIR_ComplexSubOperandRenderer"
2431 : "GIR_ComplexRenderer")
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002432 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2433 << MatchTable::Comment("RendererID")
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002434 << MatchTable::IntValue(RendererID);
2435 if (SubOperand.hasValue())
2436 Table << MatchTable::Comment("SubOperand")
2437 << MatchTable::IntValue(SubOperand.getValue());
2438 Table << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002439 }
2440};
2441
Volkan Kelesf7f25682018-01-16 18:44:05 +00002442class CustomRenderer : public OperandRenderer {
2443protected:
2444 unsigned InsnID;
2445 const Record &Renderer;
2446 /// The name of the operand.
2447 const std::string SymbolicName;
2448
2449public:
2450 CustomRenderer(unsigned InsnID, const Record &Renderer,
2451 StringRef SymbolicName)
2452 : OperandRenderer(OR_Custom), InsnID(InsnID), Renderer(Renderer),
2453 SymbolicName(SymbolicName) {}
2454
2455 static bool classof(const OperandRenderer *R) {
2456 return R->getKind() == OR_Custom;
2457 }
2458
2459 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002460 InstructionMatcher &InsnMatcher = Rule.getInstructionMatcher(SymbolicName);
Volkan Kelesf7f25682018-01-16 18:44:05 +00002461 unsigned OldInsnVarID = Rule.getInsnVarID(InsnMatcher);
2462 Table << MatchTable::Opcode("GIR_CustomRenderer")
2463 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2464 << MatchTable::Comment("OldInsnID")
2465 << MatchTable::IntValue(OldInsnVarID)
2466 << MatchTable::Comment("Renderer")
2467 << MatchTable::NamedValue(
2468 "GICR_" + Renderer.getValueAsString("RendererFn").str())
2469 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2470 }
2471};
2472
Ahmed Bougacha56ca3a92017-02-04 00:47:10 +00002473/// An action taken when all Matcher predicates succeeded for a parent rule.
2474///
2475/// Typical actions include:
2476/// * Changing the opcode of an instruction.
2477/// * Adding an operand to an instruction.
Daniel Sanders43c882c2017-02-01 10:53:10 +00002478class MatchAction {
2479public:
2480 virtual ~MatchAction() {}
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002481
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002482 /// Emit the MatchTable opcodes to implement the action.
Daniel Sandersa7b75262017-10-31 18:50:24 +00002483 virtual void emitActionOpcodes(MatchTable &Table,
2484 RuleMatcher &Rule) const = 0;
Daniel Sanders43c882c2017-02-01 10:53:10 +00002485};
2486
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +00002487/// Generates a comment describing the matched rule being acted upon.
2488class DebugCommentAction : public MatchAction {
2489private:
Daniel Sanders6ea17ed2017-10-31 18:07:03 +00002490 std::string S;
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +00002491
2492public:
Daniel Sanders6ea17ed2017-10-31 18:07:03 +00002493 DebugCommentAction(StringRef S) : S(S) {}
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +00002494
Daniel Sandersa7b75262017-10-31 18:50:24 +00002495 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sanders6ea17ed2017-10-31 18:07:03 +00002496 Table << MatchTable::Comment(S) << MatchTable::LineBreak;
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +00002497 }
2498};
2499
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002500/// Generates code to build an instruction or mutate an existing instruction
2501/// into the desired instruction when this is possible.
2502class BuildMIAction : public MatchAction {
Daniel Sanders43c882c2017-02-01 10:53:10 +00002503private:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002504 unsigned InsnID;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002505 const CodeGenInstruction *I;
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002506 InstructionMatcher *Matched;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002507 std::vector<std::unique_ptr<OperandRenderer>> OperandRenderers;
2508
2509 /// True if the instruction can be built solely by mutating the opcode.
Daniel Sandersa7b75262017-10-31 18:50:24 +00002510 bool canMutate(RuleMatcher &Rule, const InstructionMatcher *Insn) const {
2511 if (!Insn)
Daniel Sandersab1d1192017-10-24 18:11:54 +00002512 return false;
2513
Daniel Sandersa7b75262017-10-31 18:50:24 +00002514 if (OperandRenderers.size() != Insn->getNumOperands())
Daniel Sanderse9fdba32017-04-29 17:30:09 +00002515 return false;
2516
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002517 for (const auto &Renderer : enumerate(OperandRenderers)) {
Zachary Turner309a0882017-03-13 16:24:10 +00002518 if (const auto *Copy = dyn_cast<CopyRenderer>(&*Renderer.value())) {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002519 const OperandMatcher &OM = Rule.getOperandMatcher(Copy->getSymbolicName());
Daniel Sandersa7b75262017-10-31 18:50:24 +00002520 if (Insn != &OM.getInstructionMatcher() ||
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002521 OM.getOpIdx() != Renderer.index())
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002522 return false;
2523 } else
2524 return false;
2525 }
2526
2527 return true;
2528 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002529
Daniel Sanders43c882c2017-02-01 10:53:10 +00002530public:
Daniel Sandersa7b75262017-10-31 18:50:24 +00002531 BuildMIAction(unsigned InsnID, const CodeGenInstruction *I)
2532 : InsnID(InsnID), I(I), Matched(nullptr) {}
2533
Daniel Sanders08464522018-01-29 21:09:12 +00002534 unsigned getInsnID() const { return InsnID; }
Daniel Sandersdf258e32017-10-31 19:09:29 +00002535 const CodeGenInstruction *getCGI() const { return I; }
2536
Daniel Sandersa7b75262017-10-31 18:50:24 +00002537 void chooseInsnToMutate(RuleMatcher &Rule) {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002538 for (auto *MutateCandidate : Rule.mutatable_insns()) {
Daniel Sandersa7b75262017-10-31 18:50:24 +00002539 if (canMutate(Rule, MutateCandidate)) {
2540 // Take the first one we're offered that we're able to mutate.
2541 Rule.reserveInsnMatcherForMutation(MutateCandidate);
2542 Matched = MutateCandidate;
2543 return;
2544 }
2545 }
2546 }
Daniel Sanders43c882c2017-02-01 10:53:10 +00002547
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002548 template <class Kind, class... Args>
2549 Kind &addRenderer(Args&&... args) {
2550 OperandRenderers.emplace_back(
Daniel Sanders198447a2017-11-01 00:29:47 +00002551 llvm::make_unique<Kind>(InsnID, std::forward<Args>(args)...));
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002552 return *static_cast<Kind *>(OperandRenderers.back().get());
2553 }
2554
Daniel Sandersa7b75262017-10-31 18:50:24 +00002555 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2556 if (Matched) {
2557 assert(canMutate(Rule, Matched) &&
2558 "Arranged to mutate an insn that isn't mutatable");
2559
2560 unsigned RecycleInsnID = Rule.getInsnVarID(*Matched);
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002561 Table << MatchTable::Opcode("GIR_MutateOpcode")
2562 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2563 << MatchTable::Comment("RecycleInsnID")
2564 << MatchTable::IntValue(RecycleInsnID)
2565 << MatchTable::Comment("Opcode")
2566 << MatchTable::NamedValue(I->Namespace, I->TheDef->getName())
2567 << MatchTable::LineBreak;
Tim Northover4340d642017-03-20 21:58:23 +00002568
2569 if (!I->ImplicitDefs.empty() || !I->ImplicitUses.empty()) {
Tim Northover4340d642017-03-20 21:58:23 +00002570 for (auto Def : I->ImplicitDefs) {
Diana Picus8abcbbb2017-05-02 09:40:49 +00002571 auto Namespace = Def->getValue("Namespace")
2572 ? Def->getValueAsString("Namespace")
2573 : "";
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002574 Table << MatchTable::Opcode("GIR_AddImplicitDef")
2575 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2576 << MatchTable::NamedValue(Namespace, Def->getName())
2577 << MatchTable::LineBreak;
Tim Northover4340d642017-03-20 21:58:23 +00002578 }
2579 for (auto Use : I->ImplicitUses) {
Diana Picus8abcbbb2017-05-02 09:40:49 +00002580 auto Namespace = Use->getValue("Namespace")
2581 ? Use->getValueAsString("Namespace")
2582 : "";
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002583 Table << MatchTable::Opcode("GIR_AddImplicitUse")
2584 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2585 << MatchTable::NamedValue(Namespace, Use->getName())
2586 << MatchTable::LineBreak;
Tim Northover4340d642017-03-20 21:58:23 +00002587 }
2588 }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002589 return;
2590 }
2591
2592 // TODO: Simple permutation looks like it could be almost as common as
2593 // mutation due to commutative operations.
2594
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002595 Table << MatchTable::Opcode("GIR_BuildMI") << MatchTable::Comment("InsnID")
2596 << MatchTable::IntValue(InsnID) << MatchTable::Comment("Opcode")
2597 << MatchTable::NamedValue(I->Namespace, I->TheDef->getName())
2598 << MatchTable::LineBreak;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002599 for (const auto &Renderer : OperandRenderers)
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002600 Renderer->emitRenderOpcodes(Table, Rule);
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002601
Florian Hahn3bc3ec62017-08-03 14:48:22 +00002602 if (I->mayLoad || I->mayStore) {
2603 Table << MatchTable::Opcode("GIR_MergeMemOperands")
2604 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2605 << MatchTable::Comment("MergeInsnID's");
2606 // Emit the ID's for all the instructions that are matched by this rule.
2607 // TODO: Limit this to matched instructions that mayLoad/mayStore or have
2608 // some other means of having a memoperand. Also limit this to
2609 // emitted instructions that expect to have a memoperand too. For
2610 // example, (G_SEXT (G_LOAD x)) that results in separate load and
2611 // sign-extend instructions shouldn't put the memoperand on the
2612 // sign-extend since it has no effect there.
2613 std::vector<unsigned> MergeInsnIDs;
2614 for (const auto &IDMatcherPair : Rule.defined_insn_vars())
2615 MergeInsnIDs.push_back(IDMatcherPair.second);
Mandeep Singh Grang1b0e2f22018-04-06 20:18:05 +00002616 llvm::sort(MergeInsnIDs.begin(), MergeInsnIDs.end());
Florian Hahn3bc3ec62017-08-03 14:48:22 +00002617 for (const auto &MergeInsnID : MergeInsnIDs)
2618 Table << MatchTable::IntValue(MergeInsnID);
Daniel Sanders05540042017-08-08 10:44:31 +00002619 Table << MatchTable::NamedValue("GIU_MergeMemOperands_EndOfList")
2620 << MatchTable::LineBreak;
Florian Hahn3bc3ec62017-08-03 14:48:22 +00002621 }
2622
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002623 // FIXME: This is a hack but it's sufficient for ISel. We'll need to do
2624 // better for combines. Particularly when there are multiple match
2625 // roots.
2626 if (InsnID == 0)
2627 Table << MatchTable::Opcode("GIR_EraseFromParent")
2628 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2629 << MatchTable::LineBreak;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002630 }
2631};
2632
2633/// Generates code to constrain the operands of an output instruction to the
2634/// register classes specified by the definition of that instruction.
2635class ConstrainOperandsToDefinitionAction : public MatchAction {
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002636 unsigned InsnID;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002637
2638public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002639 ConstrainOperandsToDefinitionAction(unsigned InsnID) : InsnID(InsnID) {}
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002640
Daniel Sandersa7b75262017-10-31 18:50:24 +00002641 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002642 Table << MatchTable::Opcode("GIR_ConstrainSelectedInstOperands")
2643 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2644 << MatchTable::LineBreak;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002645 }
2646};
2647
2648/// Generates code to constrain the specified operand of an output instruction
2649/// to the specified register class.
2650class ConstrainOperandToRegClassAction : public MatchAction {
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002651 unsigned InsnID;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002652 unsigned OpIdx;
2653 const CodeGenRegisterClass &RC;
2654
2655public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002656 ConstrainOperandToRegClassAction(unsigned InsnID, unsigned OpIdx,
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002657 const CodeGenRegisterClass &RC)
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002658 : InsnID(InsnID), OpIdx(OpIdx), RC(RC) {}
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002659
Daniel Sandersa7b75262017-10-31 18:50:24 +00002660 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002661 Table << MatchTable::Opcode("GIR_ConstrainOperandRC")
2662 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2663 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
2664 << MatchTable::Comment("RC " + RC.getName())
2665 << MatchTable::IntValue(RC.EnumValue) << MatchTable::LineBreak;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002666 }
2667};
2668
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002669/// Generates code to create a temporary register which can be used to chain
2670/// instructions together.
2671class MakeTempRegisterAction : public MatchAction {
2672private:
2673 LLTCodeGen Ty;
2674 unsigned TempRegID;
2675
2676public:
2677 MakeTempRegisterAction(const LLTCodeGen &Ty, unsigned TempRegID)
2678 : Ty(Ty), TempRegID(TempRegID) {}
2679
2680 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2681 Table << MatchTable::Opcode("GIR_MakeTempReg")
2682 << MatchTable::Comment("TempRegID") << MatchTable::IntValue(TempRegID)
2683 << MatchTable::Comment("TypeID")
2684 << MatchTable::NamedValue(Ty.getCxxEnumValue())
2685 << MatchTable::LineBreak;
2686 }
2687};
2688
Daniel Sanders05540042017-08-08 10:44:31 +00002689InstructionMatcher &RuleMatcher::addInstructionMatcher(StringRef SymbolicName) {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002690 Matchers.emplace_back(new InstructionMatcher(*this, SymbolicName));
Daniel Sandersa7b75262017-10-31 18:50:24 +00002691 MutatableInsns.insert(Matchers.back().get());
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002692 return *Matchers.back();
2693}
Ahmed Bougacha56ca3a92017-02-04 00:47:10 +00002694
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002695void RuleMatcher::addRequiredFeature(Record *Feature) {
2696 RequiredFeatures.push_back(Feature);
2697}
2698
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002699const std::vector<Record *> &RuleMatcher::getRequiredFeatures() const {
2700 return RequiredFeatures;
2701}
2702
Daniel Sanders7438b262017-10-31 23:03:18 +00002703// Emplaces an action of the specified Kind at the end of the action list.
2704//
2705// Returns a reference to the newly created action.
2706//
2707// Like std::vector::emplace_back(), may invalidate all iterators if the new
2708// size exceeds the capacity. Otherwise, only invalidates the past-the-end
2709// iterator.
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002710template <class Kind, class... Args>
2711Kind &RuleMatcher::addAction(Args &&... args) {
2712 Actions.emplace_back(llvm::make_unique<Kind>(std::forward<Args>(args)...));
2713 return *static_cast<Kind *>(Actions.back().get());
2714}
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002715
Daniel Sanders7438b262017-10-31 23:03:18 +00002716// Emplaces an action of the specified Kind before the given insertion point.
2717//
2718// Returns an iterator pointing at the newly created instruction.
2719//
2720// Like std::vector::insert(), may invalidate all iterators if the new size
2721// exceeds the capacity. Otherwise, only invalidates the iterators from the
2722// insertion point onwards.
2723template <class Kind, class... Args>
2724action_iterator RuleMatcher::insertAction(action_iterator InsertPt,
2725 Args &&... args) {
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002726 return Actions.emplace(InsertPt,
2727 llvm::make_unique<Kind>(std::forward<Args>(args)...));
Daniel Sanders7438b262017-10-31 23:03:18 +00002728}
Daniel Sandersdc662ff2017-01-26 11:10:14 +00002729
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002730unsigned RuleMatcher::implicitlyDefineInsnVar(InstructionMatcher &Matcher) {
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002731 unsigned NewInsnVarID = NextInsnVarID++;
2732 InsnVariableIDs[&Matcher] = NewInsnVarID;
2733 return NewInsnVarID;
Daniel Sandersb96f40d2017-03-20 15:20:42 +00002734}
2735
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002736unsigned RuleMatcher::getInsnVarID(InstructionMatcher &InsnMatcher) const {
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002737 const auto &I = InsnVariableIDs.find(&InsnMatcher);
2738 if (I != InsnVariableIDs.end())
Daniel Sandersb96f40d2017-03-20 15:20:42 +00002739 return I->second;
2740 llvm_unreachable("Matched Insn was not captured in a local variable");
2741}
2742
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002743void RuleMatcher::defineOperand(StringRef SymbolicName, OperandMatcher &OM) {
2744 if (DefinedOperands.find(SymbolicName) == DefinedOperands.end()) {
2745 DefinedOperands[SymbolicName] = &OM;
2746 return;
2747 }
2748
2749 // If the operand is already defined, then we must ensure both references in
2750 // the matcher have the exact same node.
2751 OM.addPredicate<SameOperandMatcher>(OM.getSymbolicName());
2752}
2753
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002754InstructionMatcher &
Daniel Sanders05540042017-08-08 10:44:31 +00002755RuleMatcher::getInstructionMatcher(StringRef SymbolicName) const {
2756 for (const auto &I : InsnVariableIDs)
2757 if (I.first->getSymbolicName() == SymbolicName)
2758 return *I.first;
2759 llvm_unreachable(
2760 ("Failed to lookup instruction " + SymbolicName).str().c_str());
2761}
2762
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002763const OperandMatcher &
2764RuleMatcher::getOperandMatcher(StringRef Name) const {
2765 const auto &I = DefinedOperands.find(Name);
2766
2767 if (I == DefinedOperands.end())
2768 PrintFatalError(SrcLoc, "Operand " + Name + " was not declared in matcher");
2769
2770 return *I->second;
2771}
2772
Daniel Sanders8e82af22017-07-27 11:03:45 +00002773void RuleMatcher::emit(MatchTable &Table) {
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002774 if (Matchers.empty())
2775 llvm_unreachable("Unexpected empty matcher!");
Daniel Sandersdc662ff2017-01-26 11:10:14 +00002776
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002777 // The representation supports rules that require multiple roots such as:
2778 // %ptr(p0) = ...
2779 // %elt0(s32) = G_LOAD %ptr
2780 // %1(p0) = G_ADD %ptr, 4
2781 // %elt1(s32) = G_LOAD p0 %1
2782 // which could be usefully folded into:
2783 // %ptr(p0) = ...
2784 // %elt0(s32), %elt1(s32) = TGT_LOAD_PAIR %ptr
2785 // on some targets but we don't need to make use of that yet.
2786 assert(Matchers.size() == 1 && "Cannot handle multi-root matchers yet");
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002787
Daniel Sanders8e82af22017-07-27 11:03:45 +00002788 unsigned LabelID = Table.allocateLabelID();
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002789 Table << MatchTable::Opcode("GIM_Try", +1)
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002790 << MatchTable::Comment("On fail goto")
2791 << MatchTable::JumpTarget(LabelID)
2792 << MatchTable::Comment(("Rule ID " + Twine(RuleID) + " //").str())
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002793 << MatchTable::LineBreak;
2794
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002795 if (!RequiredFeatures.empty()) {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002796 Table << MatchTable::Opcode("GIM_CheckFeatures")
2797 << MatchTable::NamedValue(getNameForFeatureBitset(RequiredFeatures))
2798 << MatchTable::LineBreak;
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002799 }
Daniel Sandersb96f40d2017-03-20 15:20:42 +00002800
Quentin Colombetaad20be2017-12-15 23:07:42 +00002801 Matchers.front()->emitPredicateOpcodes(Table, *this);
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002802
Daniel Sandersbee57392017-04-04 13:25:23 +00002803 // We must also check if it's safe to fold the matched instructions.
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002804 if (InsnVariableIDs.size() >= 2) {
Galina Kistanova1754fee2017-05-25 01:51:53 +00002805 // Invert the map to create stable ordering (by var names)
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002806 SmallVector<unsigned, 2> InsnIDs;
2807 for (const auto &Pair : InsnVariableIDs) {
Daniel Sandersbee57392017-04-04 13:25:23 +00002808 // Skip the root node since it isn't moving anywhere. Everything else is
2809 // sinking to meet it.
2810 if (Pair.first == Matchers.front().get())
2811 continue;
2812
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002813 InsnIDs.push_back(Pair.second);
Galina Kistanova1754fee2017-05-25 01:51:53 +00002814 }
Mandeep Singh Grang1b0e2f22018-04-06 20:18:05 +00002815 llvm::sort(InsnIDs.begin(), InsnIDs.end());
Galina Kistanova1754fee2017-05-25 01:51:53 +00002816
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002817 for (const auto &InsnID : InsnIDs) {
Daniel Sandersbee57392017-04-04 13:25:23 +00002818 // Reject the difficult cases until we have a more accurate check.
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002819 Table << MatchTable::Opcode("GIM_CheckIsSafeToFold")
2820 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2821 << MatchTable::LineBreak;
Daniel Sandersbee57392017-04-04 13:25:23 +00002822
2823 // FIXME: Emit checks to determine it's _actually_ safe to fold and/or
2824 // account for unsafe cases.
2825 //
2826 // Example:
2827 // MI1--> %0 = ...
2828 // %1 = ... %0
2829 // MI0--> %2 = ... %0
2830 // It's not safe to erase MI1. We currently handle this by not
2831 // erasing %0 (even when it's dead).
2832 //
2833 // Example:
2834 // MI1--> %0 = load volatile @a
2835 // %1 = load volatile @a
2836 // MI0--> %2 = ... %0
2837 // It's not safe to sink %0's def past %1. We currently handle
2838 // this by rejecting all loads.
2839 //
2840 // Example:
2841 // MI1--> %0 = load @a
2842 // %1 = store @a
2843 // MI0--> %2 = ... %0
2844 // It's not safe to sink %0's def past %1. We currently handle
2845 // this by rejecting all loads.
2846 //
2847 // Example:
2848 // G_CONDBR %cond, @BB1
2849 // BB0:
2850 // MI1--> %0 = load @a
2851 // G_BR @BB1
2852 // BB1:
2853 // MI0--> %2 = ... %0
2854 // It's not always safe to sink %0 across control flow. In this
2855 // case it may introduce a memory fault. We currentl handle this
2856 // by rejecting all loads.
2857 }
2858 }
2859
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002860 for (const auto &PM : EpilogueMatchers)
2861 PM->emitPredicateOpcodes(Table, *this);
2862
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002863 for (const auto &MA : Actions)
Daniel Sandersa7b75262017-10-31 18:50:24 +00002864 MA->emitActionOpcodes(Table, *this);
Daniel Sandersf76f3152017-11-16 00:46:35 +00002865
Roman Tereshinbeb39312018-05-02 20:15:11 +00002866 if (Table.isWithCoverage())
Daniel Sandersf76f3152017-11-16 00:46:35 +00002867 Table << MatchTable::Opcode("GIR_Coverage") << MatchTable::IntValue(RuleID)
2868 << MatchTable::LineBreak;
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002869 else
2870 Table << MatchTable::Comment(("GIR_Coverage, " + Twine(RuleID) + ",").str())
2871 << MatchTable::LineBreak;
Daniel Sandersf76f3152017-11-16 00:46:35 +00002872
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002873 Table << MatchTable::Opcode("GIR_Done", -1) << MatchTable::LineBreak
Daniel Sanders8e82af22017-07-27 11:03:45 +00002874 << MatchTable::Label(LabelID);
Volkan Keles4f3fa792018-01-25 00:18:52 +00002875 ++NumPatternEmitted;
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002876}
Daniel Sanders43c882c2017-02-01 10:53:10 +00002877
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002878bool RuleMatcher::isHigherPriorityThan(const RuleMatcher &B) const {
2879 // Rules involving more match roots have higher priority.
2880 if (Matchers.size() > B.Matchers.size())
2881 return true;
2882 if (Matchers.size() < B.Matchers.size())
Daniel Sanders759ff412017-02-24 13:58:11 +00002883 return false;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002884
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002885 for (const auto &Matcher : zip(Matchers, B.Matchers)) {
2886 if (std::get<0>(Matcher)->isHigherPriorityThan(*std::get<1>(Matcher)))
2887 return true;
2888 if (std::get<1>(Matcher)->isHigherPriorityThan(*std::get<0>(Matcher)))
2889 return false;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002890 }
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002891
2892 return false;
Simon Pilgrima7d1da82017-03-15 22:50:47 +00002893}
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002894
Daniel Sanders2deea182017-04-22 15:11:04 +00002895unsigned RuleMatcher::countRendererFns() const {
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002896 return std::accumulate(
2897 Matchers.begin(), Matchers.end(), 0,
2898 [](unsigned A, const std::unique_ptr<InstructionMatcher> &Matcher) {
Daniel Sanders2deea182017-04-22 15:11:04 +00002899 return A + Matcher->countRendererFns();
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002900 });
2901}
2902
Daniel Sanders05540042017-08-08 10:44:31 +00002903bool OperandPredicateMatcher::isHigherPriorityThan(
2904 const OperandPredicateMatcher &B) const {
2905 // Generally speaking, an instruction is more important than an Int or a
2906 // LiteralInt because it can cover more nodes but theres an exception to
2907 // this. G_CONSTANT's are less important than either of those two because they
2908 // are more permissive.
Daniel Sandersedd07842017-08-17 09:26:14 +00002909
2910 const InstructionOperandMatcher *AOM =
2911 dyn_cast<InstructionOperandMatcher>(this);
2912 const InstructionOperandMatcher *BOM =
2913 dyn_cast<InstructionOperandMatcher>(&B);
2914 bool AIsConstantInsn = AOM && AOM->getInsnMatcher().isConstantInstruction();
2915 bool BIsConstantInsn = BOM && BOM->getInsnMatcher().isConstantInstruction();
2916
2917 if (AOM && BOM) {
2918 // The relative priorities between a G_CONSTANT and any other instruction
2919 // don't actually matter but this code is needed to ensure a strict weak
2920 // ordering. This is particularly important on Windows where the rules will
2921 // be incorrectly sorted without it.
2922 if (AIsConstantInsn != BIsConstantInsn)
2923 return AIsConstantInsn < BIsConstantInsn;
2924 return false;
Daniel Sanders05540042017-08-08 10:44:31 +00002925 }
Daniel Sandersedd07842017-08-17 09:26:14 +00002926
2927 if (AOM && AIsConstantInsn && (B.Kind == OPM_Int || B.Kind == OPM_LiteralInt))
2928 return false;
2929 if (BOM && BIsConstantInsn && (Kind == OPM_Int || Kind == OPM_LiteralInt))
2930 return true;
Daniel Sanders05540042017-08-08 10:44:31 +00002931
2932 return Kind < B.Kind;
Daniel Sanders75b84fc2017-08-08 13:21:26 +00002933}
Daniel Sanders05540042017-08-08 10:44:31 +00002934
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002935void SameOperandMatcher::emitPredicateOpcodes(MatchTable &Table,
Quentin Colombetaad20be2017-12-15 23:07:42 +00002936 RuleMatcher &Rule) const {
Daniel Sanders1e4569f2017-10-20 20:55:29 +00002937 const OperandMatcher &OtherOM = Rule.getOperandMatcher(MatchingName);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002938 unsigned OtherInsnVarID = Rule.getInsnVarID(OtherOM.getInstructionMatcher());
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002939 assert(OtherInsnVarID == OtherOM.getInstructionMatcher().getInsnVarID());
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002940
2941 Table << MatchTable::Opcode("GIM_CheckIsSameOperand")
2942 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
2943 << MatchTable::Comment("OpIdx") << MatchTable::IntValue(OpIdx)
2944 << MatchTable::Comment("OtherMI")
2945 << MatchTable::IntValue(OtherInsnVarID)
2946 << MatchTable::Comment("OtherOpIdx")
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002947 << MatchTable::IntValue(OtherOM.getOpIdx())
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002948 << MatchTable::LineBreak;
2949}
2950
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002951//===- GlobalISelEmitter class --------------------------------------------===//
2952
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002953class GlobalISelEmitter {
2954public:
2955 explicit GlobalISelEmitter(RecordKeeper &RK);
2956 void run(raw_ostream &OS);
2957
2958private:
2959 const RecordKeeper &RK;
2960 const CodeGenDAGPatterns CGP;
2961 const CodeGenTarget &Target;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002962 CodeGenRegBank CGRegs;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002963
Daniel Sanders39690bd2017-10-15 02:41:12 +00002964 /// Keep track of the equivalence between SDNodes and Instruction by mapping
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00002965 /// SDNodes to the GINodeEquiv mapping. We need to map to the GINodeEquiv to
2966 /// check for attributes on the relation such as CheckMMOIsNonAtomic.
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002967 /// This is defined using 'GINodeEquiv' in the target description.
Daniel Sanders39690bd2017-10-15 02:41:12 +00002968 DenseMap<Record *, Record *> NodeEquivs;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002969
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002970 /// Keep track of the equivalence between ComplexPattern's and
2971 /// GIComplexOperandMatcher. Map entries are specified by subclassing
2972 /// GIComplexPatternEquiv.
2973 DenseMap<const Record *, const Record *> ComplexPatternEquivs;
2974
Volkan Kelesf7f25682018-01-16 18:44:05 +00002975 /// Keep track of the equivalence between SDNodeXForm's and
2976 /// GICustomOperandRenderer. Map entries are specified by subclassing
2977 /// GISDNodeXFormEquiv.
2978 DenseMap<const Record *, const Record *> SDNodeXFormEquivs;
2979
Aditya Nandakumarb63e7632018-02-16 22:37:15 +00002980 /// Keep track of Scores of PatternsToMatch similar to how the DAG does.
2981 /// This adds compatibility for RuleMatchers to use this for ordering rules.
2982 DenseMap<uint64_t, int> RuleMatcherScores;
2983
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002984 // Map of predicates to their subtarget features.
Daniel Sanderse9fdba32017-04-29 17:30:09 +00002985 SubtargetFeatureInfoMap SubtargetFeatures;
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002986
Daniel Sandersf76f3152017-11-16 00:46:35 +00002987 // Rule coverage information.
2988 Optional<CodeGenCoverage> RuleCoverage;
2989
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002990 void gatherOpcodeValues();
2991 void gatherTypeIDValues();
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002992 void gatherNodeEquivs();
Daniel Sanders8ead1292018-06-15 23:13:43 +00002993
Daniel Sanders39690bd2017-10-15 02:41:12 +00002994 Record *findNodeEquiv(Record *N) const;
Daniel Sandersf84bc372018-05-05 20:53:24 +00002995 const CodeGenInstruction *getEquivNode(Record &Equiv,
Florian Hahn6b1db822018-06-14 20:32:58 +00002996 const TreePatternNode *N) const;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002997
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002998 Error importRulePredicates(RuleMatcher &M, ArrayRef<Predicate> Predicates);
Daniel Sanders8ead1292018-06-15 23:13:43 +00002999 Expected<InstructionMatcher &>
3000 createAndImportSelDAGMatcher(RuleMatcher &Rule,
3001 InstructionMatcher &InsnMatcher,
3002 const TreePatternNode *Src, unsigned &TempOpIdx);
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003003 Error importComplexPatternOperandMatcher(OperandMatcher &OM, Record *R,
3004 unsigned &TempOpIdx) const;
3005 Error importChildMatcher(RuleMatcher &Rule, InstructionMatcher &InsnMatcher,
Florian Hahn6b1db822018-06-14 20:32:58 +00003006 const TreePatternNode *SrcChild,
Daniel Sandersa71f4542017-10-16 00:56:30 +00003007 bool OperandIsAPointer, unsigned OpIdx,
Daniel Sanders8ead1292018-06-15 23:13:43 +00003008 unsigned &TempOpIdx);
Daniel Sandersdf258e32017-10-31 19:09:29 +00003009
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00003010 Expected<BuildMIAction &>
Daniel Sandersa7b75262017-10-31 18:50:24 +00003011 createAndImportInstructionRenderer(RuleMatcher &M,
Florian Hahn6b1db822018-06-14 20:32:58 +00003012 const TreePatternNode *Dst);
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003013 Expected<action_iterator> createAndImportSubInstructionRenderer(
Florian Hahn6b1db822018-06-14 20:32:58 +00003014 action_iterator InsertPt, RuleMatcher &M, const TreePatternNode *Dst,
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003015 unsigned TempReg);
Daniel Sanders7438b262017-10-31 23:03:18 +00003016 Expected<action_iterator>
3017 createInstructionRenderer(action_iterator InsertPt, RuleMatcher &M,
Florian Hahn6b1db822018-06-14 20:32:58 +00003018 const TreePatternNode *Dst);
Daniel Sandersdf258e32017-10-31 19:09:29 +00003019 void importExplicitDefRenderers(BuildMIAction &DstMIBuilder);
Daniel Sanders7438b262017-10-31 23:03:18 +00003020 Expected<action_iterator>
3021 importExplicitUseRenderers(action_iterator InsertPt, RuleMatcher &M,
3022 BuildMIAction &DstMIBuilder,
Florian Hahn6b1db822018-06-14 20:32:58 +00003023 const llvm::TreePatternNode *Dst);
Daniel Sanders7438b262017-10-31 23:03:18 +00003024 Expected<action_iterator>
3025 importExplicitUseRenderer(action_iterator InsertPt, RuleMatcher &Rule,
3026 BuildMIAction &DstMIBuilder,
Florian Hahn6b1db822018-06-14 20:32:58 +00003027 TreePatternNode *DstChild);
Diana Picus382602f2017-05-17 08:57:28 +00003028 Error importDefaultOperandRenderers(BuildMIAction &DstMIBuilder,
3029 DagInit *DefaultOps) const;
Daniel Sandersc270c502017-03-30 09:36:33 +00003030 Error
Daniel Sandersffc7d582017-03-29 15:37:18 +00003031 importImplicitDefRenderers(BuildMIAction &DstMIBuilder,
3032 const std::vector<Record *> &ImplicitDefs) const;
3033
Daniel Sanders8ead1292018-06-15 23:13:43 +00003034 void emitCxxPredicateFns(raw_ostream &OS, StringRef CodeFieldName,
3035 StringRef TypeIdentifier, StringRef ArgType,
3036 StringRef ArgName, StringRef AdditionalDeclarations,
3037 std::function<bool(const Record *R)> Filter);
3038 void emitImmPredicateFns(raw_ostream &OS, StringRef TypeIdentifier,
3039 StringRef ArgType,
3040 std::function<bool(const Record *R)> Filter);
3041 void emitMIPredicateFns(raw_ostream &OS);
Daniel Sanders649c5852017-10-13 20:42:18 +00003042
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003043 /// Analyze pattern \p P, returning a matcher for it if possible.
3044 /// Otherwise, return an Error explaining why we don't support it.
3045 Expected<RuleMatcher> runOnPattern(const PatternToMatch &P);
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003046
3047 void declareSubtargetFeature(Record *Predicate);
Daniel Sanders7e523672017-11-11 03:23:44 +00003048
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003049 MatchTable buildMatchTable(MutableArrayRef<RuleMatcher> Rules, bool Optimize,
3050 bool WithCoverage);
3051
3052public:
Quentin Colombetec76d9c2017-12-18 19:47:41 +00003053 /// Takes a sequence of \p Rules and group them based on the predicates
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003054 /// they share. \p MatcherStorage is used as a memory container
Hiroshi Inoue501931b2018-01-24 05:04:35 +00003055 /// for the group that are created as part of this process.
Quentin Colombetec76d9c2017-12-18 19:47:41 +00003056 ///
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003057 /// What this optimization does looks like if GroupT = GroupMatcher:
Quentin Colombetec76d9c2017-12-18 19:47:41 +00003058 /// Output without optimization:
3059 /// \verbatim
3060 /// # R1
3061 /// # predicate A
3062 /// # predicate B
3063 /// ...
3064 /// # R2
3065 /// # predicate A // <-- effectively this is going to be checked twice.
3066 /// // Once in R1 and once in R2.
3067 /// # predicate C
3068 /// \endverbatim
3069 /// Output with optimization:
3070 /// \verbatim
3071 /// # Group1_2
3072 /// # predicate A // <-- Check is now shared.
3073 /// # R1
3074 /// # predicate B
3075 /// # R2
3076 /// # predicate C
3077 /// \endverbatim
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003078 template <class GroupT>
3079 static std::vector<Matcher *> optimizeRules(
Roman Tereshin2d6d3762018-05-02 20:08:14 +00003080 ArrayRef<Matcher *> Rules,
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003081 std::vector<std::unique_ptr<Matcher>> &MatcherStorage);
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003082};
3083
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003084void GlobalISelEmitter::gatherOpcodeValues() {
3085 InstructionOpcodeMatcher::initOpcodeValuesMap(Target);
3086}
3087
3088void GlobalISelEmitter::gatherTypeIDValues() {
3089 LLTOperandMatcher::initTypeIDValuesMap();
3090}
3091
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003092void GlobalISelEmitter::gatherNodeEquivs() {
3093 assert(NodeEquivs.empty());
3094 for (Record *Equiv : RK.getAllDerivedDefinitions("GINodeEquiv"))
Daniel Sanders39690bd2017-10-15 02:41:12 +00003095 NodeEquivs[Equiv->getValueAsDef("Node")] = Equiv;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00003096
3097 assert(ComplexPatternEquivs.empty());
3098 for (Record *Equiv : RK.getAllDerivedDefinitions("GIComplexPatternEquiv")) {
3099 Record *SelDAGEquiv = Equiv->getValueAsDef("SelDAGEquivalent");
3100 if (!SelDAGEquiv)
3101 continue;
3102 ComplexPatternEquivs[SelDAGEquiv] = Equiv;
3103 }
Volkan Kelesf7f25682018-01-16 18:44:05 +00003104
3105 assert(SDNodeXFormEquivs.empty());
3106 for (Record *Equiv : RK.getAllDerivedDefinitions("GISDNodeXFormEquiv")) {
3107 Record *SelDAGEquiv = Equiv->getValueAsDef("SelDAGEquivalent");
3108 if (!SelDAGEquiv)
3109 continue;
3110 SDNodeXFormEquivs[SelDAGEquiv] = Equiv;
3111 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003112}
3113
Daniel Sanders39690bd2017-10-15 02:41:12 +00003114Record *GlobalISelEmitter::findNodeEquiv(Record *N) const {
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003115 return NodeEquivs.lookup(N);
3116}
3117
Daniel Sandersf84bc372018-05-05 20:53:24 +00003118const CodeGenInstruction *
Florian Hahn6b1db822018-06-14 20:32:58 +00003119GlobalISelEmitter::getEquivNode(Record &Equiv, const TreePatternNode *N) const {
3120 for (const auto &Predicate : N->getPredicateFns()) {
Daniel Sandersf84bc372018-05-05 20:53:24 +00003121 if (!Equiv.isValueUnset("IfSignExtend") && Predicate.isLoad() &&
3122 Predicate.isSignExtLoad())
3123 return &Target.getInstruction(Equiv.getValueAsDef("IfSignExtend"));
3124 if (!Equiv.isValueUnset("IfZeroExtend") && Predicate.isLoad() &&
3125 Predicate.isZeroExtLoad())
3126 return &Target.getInstruction(Equiv.getValueAsDef("IfZeroExtend"));
3127 }
3128 return &Target.getInstruction(Equiv.getValueAsDef("I"));
3129}
3130
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003131GlobalISelEmitter::GlobalISelEmitter(RecordKeeper &RK)
Daniel Sandersf84bc372018-05-05 20:53:24 +00003132 : RK(RK), CGP(RK), Target(CGP.getTargetInfo()),
3133 CGRegs(RK, Target.getHwModes()) {}
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003134
3135//===- Emitter ------------------------------------------------------------===//
3136
Daniel Sandersc270c502017-03-30 09:36:33 +00003137Error
Daniel Sandersffc7d582017-03-29 15:37:18 +00003138GlobalISelEmitter::importRulePredicates(RuleMatcher &M,
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003139 ArrayRef<Predicate> Predicates) {
3140 for (const Predicate &P : Predicates) {
3141 if (!P.Def)
3142 continue;
3143 declareSubtargetFeature(P.Def);
3144 M.addRequiredFeature(P.Def);
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003145 }
3146
Daniel Sandersc270c502017-03-30 09:36:33 +00003147 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00003148}
Daniel Sanders8a4bae92017-03-14 21:32:08 +00003149
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003150Expected<InstructionMatcher &> GlobalISelEmitter::createAndImportSelDAGMatcher(
3151 RuleMatcher &Rule, InstructionMatcher &InsnMatcher,
Daniel Sanders8ead1292018-06-15 23:13:43 +00003152 const TreePatternNode *Src, unsigned &TempOpIdx) {
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003153 Record *SrcGIEquivOrNull = nullptr;
3154 const CodeGenInstruction *SrcGIOrNull = nullptr;
3155
3156 // Start with the defined operands (i.e., the results of the root operator).
Florian Hahn6b1db822018-06-14 20:32:58 +00003157 if (Src->getExtTypes().size() > 1)
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003158 return failedImport("Src pattern has multiple results");
3159
Florian Hahn6b1db822018-06-14 20:32:58 +00003160 if (Src->isLeaf()) {
3161 Init *SrcInit = Src->getLeafValue();
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003162 if (isa<IntInit>(SrcInit)) {
3163 InsnMatcher.addPredicate<InstructionOpcodeMatcher>(
3164 &Target.getInstruction(RK.getDef("G_CONSTANT")));
3165 } else
3166 return failedImport(
3167 "Unable to deduce gMIR opcode to handle Src (which is a leaf)");
3168 } else {
Florian Hahn6b1db822018-06-14 20:32:58 +00003169 SrcGIEquivOrNull = findNodeEquiv(Src->getOperator());
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003170 if (!SrcGIEquivOrNull)
3171 return failedImport("Pattern operator lacks an equivalent Instruction" +
Florian Hahn6b1db822018-06-14 20:32:58 +00003172 explainOperator(Src->getOperator()));
Daniel Sandersf84bc372018-05-05 20:53:24 +00003173 SrcGIOrNull = getEquivNode(*SrcGIEquivOrNull, Src);
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003174
3175 // The operators look good: match the opcode
3176 InsnMatcher.addPredicate<InstructionOpcodeMatcher>(SrcGIOrNull);
3177 }
3178
3179 unsigned OpIdx = 0;
Florian Hahn6b1db822018-06-14 20:32:58 +00003180 for (const TypeSetByHwMode &VTy : Src->getExtTypes()) {
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003181 // Results don't have a name unless they are the root node. The caller will
3182 // set the name if appropriate.
3183 OperandMatcher &OM = InsnMatcher.addOperand(OpIdx++, "", TempOpIdx);
3184 if (auto Error = OM.addTypeCheckPredicate(VTy, false /* OperandIsAPointer */))
3185 return failedImport(toString(std::move(Error)) +
3186 " for result of Src pattern operator");
3187 }
3188
Florian Hahn6b1db822018-06-14 20:32:58 +00003189 for (const auto &Predicate : Src->getPredicateFns()) {
Daniel Sanders2c269f62017-08-24 09:11:20 +00003190 if (Predicate.isAlwaysTrue())
3191 continue;
3192
3193 if (Predicate.isImmediatePattern()) {
3194 InsnMatcher.addPredicate<InstructionImmPredicateMatcher>(Predicate);
3195 continue;
3196 }
3197
Daniel Sandersf84bc372018-05-05 20:53:24 +00003198 // G_LOAD is used for both non-extending and any-extending loads.
3199 if (Predicate.isLoad() && Predicate.isNonExtLoad()) {
3200 InsnMatcher.addPredicate<MemoryVsLLTSizePredicateMatcher>(
3201 0, MemoryVsLLTSizePredicateMatcher::EqualTo, 0);
3202 continue;
3203 }
3204 if (Predicate.isLoad() && Predicate.isAnyExtLoad()) {
3205 InsnMatcher.addPredicate<MemoryVsLLTSizePredicateMatcher>(
3206 0, MemoryVsLLTSizePredicateMatcher::LessThan, 0);
3207 continue;
3208 }
3209
3210 // No check required. We already did it by swapping the opcode.
3211 if (!SrcGIEquivOrNull->isValueUnset("IfSignExtend") &&
3212 Predicate.isSignExtLoad())
3213 continue;
3214
3215 // No check required. We already did it by swapping the opcode.
3216 if (!SrcGIEquivOrNull->isValueUnset("IfZeroExtend") &&
3217 Predicate.isZeroExtLoad())
Daniel Sandersa71f4542017-10-16 00:56:30 +00003218 continue;
3219
Daniel Sandersd66e0902017-10-23 18:19:24 +00003220 // No check required. G_STORE by itself is a non-extending store.
3221 if (Predicate.isNonTruncStore())
3222 continue;
3223
Daniel Sanders76664652017-11-28 22:07:05 +00003224 if (Predicate.isLoad() || Predicate.isStore() || Predicate.isAtomic()) {
3225 if (Predicate.getMemoryVT() != nullptr) {
3226 Optional<LLTCodeGen> MemTyOrNone =
3227 MVTToLLT(getValueType(Predicate.getMemoryVT()));
Daniel Sandersd66e0902017-10-23 18:19:24 +00003228
Daniel Sanders76664652017-11-28 22:07:05 +00003229 if (!MemTyOrNone)
3230 return failedImport("MemVT could not be converted to LLT");
Daniel Sandersd66e0902017-10-23 18:19:24 +00003231
Daniel Sandersf84bc372018-05-05 20:53:24 +00003232 // MMO's work in bytes so we must take care of unusual types like i1
3233 // don't round down.
3234 unsigned MemSizeInBits =
3235 llvm::alignTo(MemTyOrNone->get().getSizeInBits(), 8);
3236
3237 InsnMatcher.addPredicate<MemorySizePredicateMatcher>(
3238 0, MemSizeInBits / 8);
Daniel Sanders76664652017-11-28 22:07:05 +00003239 continue;
3240 }
3241 }
3242
3243 if (Predicate.isLoad() || Predicate.isStore()) {
3244 // No check required. A G_LOAD/G_STORE is an unindexed load.
3245 if (Predicate.isUnindexed())
3246 continue;
3247 }
3248
3249 if (Predicate.isAtomic()) {
3250 if (Predicate.isAtomicOrderingMonotonic()) {
3251 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3252 "Monotonic");
3253 continue;
3254 }
3255 if (Predicate.isAtomicOrderingAcquire()) {
3256 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>("Acquire");
3257 continue;
3258 }
3259 if (Predicate.isAtomicOrderingRelease()) {
3260 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>("Release");
3261 continue;
3262 }
3263 if (Predicate.isAtomicOrderingAcquireRelease()) {
3264 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3265 "AcquireRelease");
3266 continue;
3267 }
3268 if (Predicate.isAtomicOrderingSequentiallyConsistent()) {
3269 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3270 "SequentiallyConsistent");
3271 continue;
3272 }
Daniel Sanders0c43b3a2017-11-30 21:05:59 +00003273
3274 if (Predicate.isAtomicOrderingAcquireOrStronger()) {
3275 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3276 "Acquire", AtomicOrderingMMOPredicateMatcher::AO_OrStronger);
3277 continue;
3278 }
3279 if (Predicate.isAtomicOrderingWeakerThanAcquire()) {
3280 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3281 "Acquire", AtomicOrderingMMOPredicateMatcher::AO_WeakerThan);
3282 continue;
3283 }
3284
3285 if (Predicate.isAtomicOrderingReleaseOrStronger()) {
3286 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3287 "Release", AtomicOrderingMMOPredicateMatcher::AO_OrStronger);
3288 continue;
3289 }
3290 if (Predicate.isAtomicOrderingWeakerThanRelease()) {
3291 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3292 "Release", AtomicOrderingMMOPredicateMatcher::AO_WeakerThan);
3293 continue;
3294 }
Daniel Sandersd66e0902017-10-23 18:19:24 +00003295 }
3296
Daniel Sanders8ead1292018-06-15 23:13:43 +00003297 if (Predicate.hasGISelPredicateCode()) {
3298 InsnMatcher.addPredicate<GenericInstructionPredicateMatcher>(Predicate);
3299 continue;
3300 }
3301
Daniel Sanders2c269f62017-08-24 09:11:20 +00003302 return failedImport("Src pattern child has predicate (" +
3303 explainPredicates(Src) + ")");
3304 }
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003305 if (SrcGIEquivOrNull && SrcGIEquivOrNull->getValueAsBit("CheckMMOIsNonAtomic"))
3306 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>("NotAtomic");
Daniel Sanders2c269f62017-08-24 09:11:20 +00003307
Florian Hahn6b1db822018-06-14 20:32:58 +00003308 if (Src->isLeaf()) {
3309 Init *SrcInit = Src->getLeafValue();
Daniel Sanders452c8ae2017-05-23 19:33:16 +00003310 if (IntInit *SrcIntInit = dyn_cast<IntInit>(SrcInit)) {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003311 OperandMatcher &OM =
Florian Hahn6b1db822018-06-14 20:32:58 +00003312 InsnMatcher.addOperand(OpIdx++, Src->getName(), TempOpIdx);
Daniel Sanders452c8ae2017-05-23 19:33:16 +00003313 OM.addPredicate<LiteralIntOperandMatcher>(SrcIntInit->getValue());
3314 } else
Daniel Sanders32291982017-06-28 13:50:04 +00003315 return failedImport(
3316 "Unable to deduce gMIR opcode to handle Src (which is a leaf)");
Daniel Sanders452c8ae2017-05-23 19:33:16 +00003317 } else {
Daniel Sanders85ffd362017-07-06 08:12:20 +00003318 assert(SrcGIOrNull &&
3319 "Expected to have already found an equivalent Instruction");
Daniel Sanders11300ce2017-10-13 21:28:03 +00003320 if (SrcGIOrNull->TheDef->getName() == "G_CONSTANT" ||
3321 SrcGIOrNull->TheDef->getName() == "G_FCONSTANT") {
3322 // imm/fpimm still have operands but we don't need to do anything with it
Daniel Sanders05540042017-08-08 10:44:31 +00003323 // here since we don't support ImmLeaf predicates yet. However, we still
3324 // need to note the hidden operand to get GIM_CheckNumOperands correct.
3325 InsnMatcher.addOperand(OpIdx++, "", TempOpIdx);
3326 return InsnMatcher;
3327 }
3328
Daniel Sanders452c8ae2017-05-23 19:33:16 +00003329 // Match the used operands (i.e. the children of the operator).
Florian Hahn6b1db822018-06-14 20:32:58 +00003330 for (unsigned i = 0, e = Src->getNumChildren(); i != e; ++i) {
3331 TreePatternNode *SrcChild = Src->getChild(i);
Daniel Sanders85ffd362017-07-06 08:12:20 +00003332
Daniel Sandersa71f4542017-10-16 00:56:30 +00003333 // SelectionDAG allows pointers to be represented with iN since it doesn't
3334 // distinguish between pointers and integers but they are different types in GlobalISel.
3335 // Coerce integers to pointers to address space 0 if the context indicates a pointer.
Daniel Sandersc54aa9c2017-11-18 00:16:44 +00003336 bool OperandIsAPointer = SrcGIOrNull->isOperandAPointer(i);
Daniel Sandersa71f4542017-10-16 00:56:30 +00003337
Daniel Sanders28887fe2017-09-19 12:56:36 +00003338 // For G_INTRINSIC/G_INTRINSIC_W_SIDE_EFFECTS, the operand immediately
3339 // following the defs is an intrinsic ID.
3340 if ((SrcGIOrNull->TheDef->getName() == "G_INTRINSIC" ||
3341 SrcGIOrNull->TheDef->getName() == "G_INTRINSIC_W_SIDE_EFFECTS") &&
3342 i == 0) {
Florian Hahn6b1db822018-06-14 20:32:58 +00003343 if (const CodeGenIntrinsic *II = Src->getIntrinsicInfo(CGP)) {
Daniel Sanders85ffd362017-07-06 08:12:20 +00003344 OperandMatcher &OM =
Florian Hahn6b1db822018-06-14 20:32:58 +00003345 InsnMatcher.addOperand(OpIdx++, SrcChild->getName(), TempOpIdx);
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00003346 OM.addPredicate<IntrinsicIDOperandMatcher>(II);
Daniel Sanders85ffd362017-07-06 08:12:20 +00003347 continue;
3348 }
3349
3350 return failedImport("Expected IntInit containing instrinsic ID)");
3351 }
3352
Daniel Sandersa71f4542017-10-16 00:56:30 +00003353 if (auto Error =
3354 importChildMatcher(Rule, InsnMatcher, SrcChild, OperandIsAPointer,
3355 OpIdx++, TempOpIdx))
Daniel Sanders452c8ae2017-05-23 19:33:16 +00003356 return std::move(Error);
3357 }
Daniel Sandersffc7d582017-03-29 15:37:18 +00003358 }
3359
3360 return InsnMatcher;
3361}
3362
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003363Error GlobalISelEmitter::importComplexPatternOperandMatcher(
3364 OperandMatcher &OM, Record *R, unsigned &TempOpIdx) const {
3365 const auto &ComplexPattern = ComplexPatternEquivs.find(R);
3366 if (ComplexPattern == ComplexPatternEquivs.end())
3367 return failedImport("SelectionDAG ComplexPattern (" + R->getName() +
3368 ") not mapped to GlobalISel");
3369
3370 OM.addPredicate<ComplexPatternOperandMatcher>(OM, *ComplexPattern->second);
3371 TempOpIdx++;
3372 return Error::success();
3373}
3374
3375Error GlobalISelEmitter::importChildMatcher(RuleMatcher &Rule,
3376 InstructionMatcher &InsnMatcher,
Florian Hahn6b1db822018-06-14 20:32:58 +00003377 const TreePatternNode *SrcChild,
Daniel Sandersa71f4542017-10-16 00:56:30 +00003378 bool OperandIsAPointer,
Daniel Sandersc270c502017-03-30 09:36:33 +00003379 unsigned OpIdx,
Daniel Sanders8ead1292018-06-15 23:13:43 +00003380 unsigned &TempOpIdx) {
Daniel Sanders4f3eb242017-04-05 13:14:03 +00003381 OperandMatcher &OM =
Florian Hahn6b1db822018-06-14 20:32:58 +00003382 InsnMatcher.addOperand(OpIdx, SrcChild->getName(), TempOpIdx);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003383 if (OM.isSameAsAnotherOperand())
3384 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00003385
Florian Hahn6b1db822018-06-14 20:32:58 +00003386 ArrayRef<TypeSetByHwMode> ChildTypes = SrcChild->getExtTypes();
Daniel Sandersffc7d582017-03-29 15:37:18 +00003387 if (ChildTypes.size() != 1)
3388 return failedImport("Src pattern child has multiple results");
3389
3390 // Check MBB's before the type check since they are not a known type.
Florian Hahn6b1db822018-06-14 20:32:58 +00003391 if (!SrcChild->isLeaf()) {
3392 if (SrcChild->getOperator()->isSubClassOf("SDNode")) {
3393 auto &ChildSDNI = CGP.getSDNodeInfo(SrcChild->getOperator());
Daniel Sandersffc7d582017-03-29 15:37:18 +00003394 if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") {
3395 OM.addPredicate<MBBOperandMatcher>();
Daniel Sandersc270c502017-03-30 09:36:33 +00003396 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00003397 }
3398 }
Daniel Sandersffc7d582017-03-29 15:37:18 +00003399 }
3400
Daniel Sandersa71f4542017-10-16 00:56:30 +00003401 if (auto Error =
3402 OM.addTypeCheckPredicate(ChildTypes.front(), OperandIsAPointer))
3403 return failedImport(toString(std::move(Error)) + " for Src operand (" +
Florian Hahn6b1db822018-06-14 20:32:58 +00003404 to_string(*SrcChild) + ")");
Daniel Sandersffc7d582017-03-29 15:37:18 +00003405
Daniel Sandersbee57392017-04-04 13:25:23 +00003406 // Check for nested instructions.
Florian Hahn6b1db822018-06-14 20:32:58 +00003407 if (!SrcChild->isLeaf()) {
3408 if (SrcChild->getOperator()->isSubClassOf("ComplexPattern")) {
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003409 // When a ComplexPattern is used as an operator, it should do the same
3410 // thing as when used as a leaf. However, the children of the operator
3411 // name the sub-operands that make up the complex operand and we must
3412 // prepare to reference them in the renderer too.
3413 unsigned RendererID = TempOpIdx;
3414 if (auto Error = importComplexPatternOperandMatcher(
Florian Hahn6b1db822018-06-14 20:32:58 +00003415 OM, SrcChild->getOperator(), TempOpIdx))
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003416 return Error;
3417
Florian Hahn6b1db822018-06-14 20:32:58 +00003418 for (unsigned i = 0, e = SrcChild->getNumChildren(); i != e; ++i) {
3419 auto *SubOperand = SrcChild->getChild(i);
3420 if (!SubOperand->getName().empty())
3421 Rule.defineComplexSubOperand(SubOperand->getName(),
3422 SrcChild->getOperator(), RendererID, i);
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003423 }
3424
3425 return Error::success();
3426 }
3427
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003428 auto MaybeInsnOperand = OM.addPredicate<InstructionOperandMatcher>(
Florian Hahn6b1db822018-06-14 20:32:58 +00003429 InsnMatcher.getRuleMatcher(), SrcChild->getName());
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003430 if (!MaybeInsnOperand.hasValue()) {
3431 // This isn't strictly true. If the user were to provide exactly the same
3432 // matchers as the original operand then we could allow it. However, it's
3433 // simpler to not permit the redundant specification.
3434 return failedImport("Nested instruction cannot be the same as another operand");
3435 }
3436
Daniel Sandersbee57392017-04-04 13:25:23 +00003437 // Map the node to a gMIR instruction.
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003438 InstructionOperandMatcher &InsnOperand = **MaybeInsnOperand;
Daniel Sanders57938df2017-07-11 10:40:18 +00003439 auto InsnMatcherOrError = createAndImportSelDAGMatcher(
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003440 Rule, InsnOperand.getInsnMatcher(), SrcChild, TempOpIdx);
Daniel Sandersbee57392017-04-04 13:25:23 +00003441 if (auto Error = InsnMatcherOrError.takeError())
3442 return Error;
3443
3444 return Error::success();
3445 }
3446
Florian Hahn6b1db822018-06-14 20:32:58 +00003447 if (SrcChild->hasAnyPredicate())
Diana Picusd1b61812017-11-03 10:30:19 +00003448 return failedImport("Src pattern child has unsupported predicate");
3449
Daniel Sandersffc7d582017-03-29 15:37:18 +00003450 // Check for constant immediates.
Florian Hahn6b1db822018-06-14 20:32:58 +00003451 if (auto *ChildInt = dyn_cast<IntInit>(SrcChild->getLeafValue())) {
Daniel Sanders452c8ae2017-05-23 19:33:16 +00003452 OM.addPredicate<ConstantIntOperandMatcher>(ChildInt->getValue());
Daniel Sandersc270c502017-03-30 09:36:33 +00003453 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00003454 }
3455
3456 // Check for def's like register classes or ComplexPattern's.
Florian Hahn6b1db822018-06-14 20:32:58 +00003457 if (auto *ChildDefInit = dyn_cast<DefInit>(SrcChild->getLeafValue())) {
Daniel Sandersffc7d582017-03-29 15:37:18 +00003458 auto *ChildRec = ChildDefInit->getDef();
3459
3460 // Check for register classes.
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003461 if (ChildRec->isSubClassOf("RegisterClass") ||
3462 ChildRec->isSubClassOf("RegisterOperand")) {
Daniel Sandersffc7d582017-03-29 15:37:18 +00003463 OM.addPredicate<RegisterBankOperandMatcher>(
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003464 Target.getRegisterClass(getInitValueAsRegClass(ChildDefInit)));
Daniel Sanders658541f2017-04-22 15:53:21 +00003465 return Error::success();
3466 }
3467
Daniel Sanders4d4e7652017-10-09 18:14:53 +00003468 // Check for ValueType.
3469 if (ChildRec->isSubClassOf("ValueType")) {
3470 // We already added a type check as standard practice so this doesn't need
3471 // to do anything.
3472 return Error::success();
3473 }
3474
Daniel Sandersffc7d582017-03-29 15:37:18 +00003475 // Check for ComplexPattern's.
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003476 if (ChildRec->isSubClassOf("ComplexPattern"))
3477 return importComplexPatternOperandMatcher(OM, ChildRec, TempOpIdx);
Daniel Sandersffc7d582017-03-29 15:37:18 +00003478
Daniel Sandersd0656a32017-04-13 09:45:37 +00003479 if (ChildRec->isSubClassOf("ImmLeaf")) {
3480 return failedImport(
3481 "Src pattern child def is an unsupported tablegen class (ImmLeaf)");
3482 }
3483
Daniel Sandersffc7d582017-03-29 15:37:18 +00003484 return failedImport(
3485 "Src pattern child def is an unsupported tablegen class");
3486 }
3487
3488 return failedImport("Src pattern child is an unsupported kind");
3489}
3490
Daniel Sanders7438b262017-10-31 23:03:18 +00003491Expected<action_iterator> GlobalISelEmitter::importExplicitUseRenderer(
3492 action_iterator InsertPt, RuleMatcher &Rule, BuildMIAction &DstMIBuilder,
Florian Hahn6b1db822018-06-14 20:32:58 +00003493 TreePatternNode *DstChild) {
Daniel Sanders2c269f62017-08-24 09:11:20 +00003494
Florian Hahn6b1db822018-06-14 20:32:58 +00003495 const auto &SubOperand = Rule.getComplexSubOperand(DstChild->getName());
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003496 if (SubOperand.hasValue()) {
3497 DstMIBuilder.addRenderer<RenderComplexPatternOperand>(
Florian Hahn6b1db822018-06-14 20:32:58 +00003498 *std::get<0>(*SubOperand), DstChild->getName(),
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003499 std::get<1>(*SubOperand), std::get<2>(*SubOperand));
Daniel Sanders7438b262017-10-31 23:03:18 +00003500 return InsertPt;
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003501 }
3502
Florian Hahn6b1db822018-06-14 20:32:58 +00003503 if (!DstChild->isLeaf()) {
Volkan Kelesf7f25682018-01-16 18:44:05 +00003504
Florian Hahn6b1db822018-06-14 20:32:58 +00003505 if (DstChild->getOperator()->isSubClassOf("SDNodeXForm")) {
3506 auto Child = DstChild->getChild(0);
3507 auto I = SDNodeXFormEquivs.find(DstChild->getOperator());
Volkan Kelesf7f25682018-01-16 18:44:05 +00003508 if (I != SDNodeXFormEquivs.end()) {
Florian Hahn6b1db822018-06-14 20:32:58 +00003509 DstMIBuilder.addRenderer<CustomRenderer>(*I->second, Child->getName());
Volkan Kelesf7f25682018-01-16 18:44:05 +00003510 return InsertPt;
3511 }
Florian Hahn6b1db822018-06-14 20:32:58 +00003512 return failedImport("SDNodeXForm " + Child->getName() +
Volkan Kelesf7f25682018-01-16 18:44:05 +00003513 " has no custom renderer");
3514 }
3515
Daniel Sanders05540042017-08-08 10:44:31 +00003516 // We accept 'bb' here. It's an operator because BasicBlockSDNode isn't
3517 // inline, but in MI it's just another operand.
Florian Hahn6b1db822018-06-14 20:32:58 +00003518 if (DstChild->getOperator()->isSubClassOf("SDNode")) {
3519 auto &ChildSDNI = CGP.getSDNodeInfo(DstChild->getOperator());
Daniel Sandersffc7d582017-03-29 15:37:18 +00003520 if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") {
Florian Hahn6b1db822018-06-14 20:32:58 +00003521 DstMIBuilder.addRenderer<CopyRenderer>(DstChild->getName());
Daniel Sanders7438b262017-10-31 23:03:18 +00003522 return InsertPt;
Daniel Sandersffc7d582017-03-29 15:37:18 +00003523 }
3524 }
Daniel Sanders05540042017-08-08 10:44:31 +00003525
3526 // Similarly, imm is an operator in TreePatternNode's view but must be
3527 // rendered as operands.
3528 // FIXME: The target should be able to choose sign-extended when appropriate
3529 // (e.g. on Mips).
Florian Hahn6b1db822018-06-14 20:32:58 +00003530 if (DstChild->getOperator()->getName() == "imm") {
3531 DstMIBuilder.addRenderer<CopyConstantAsImmRenderer>(DstChild->getName());
Daniel Sanders7438b262017-10-31 23:03:18 +00003532 return InsertPt;
Florian Hahn6b1db822018-06-14 20:32:58 +00003533 } else if (DstChild->getOperator()->getName() == "fpimm") {
Daniel Sanders11300ce2017-10-13 21:28:03 +00003534 DstMIBuilder.addRenderer<CopyFConstantAsFPImmRenderer>(
Florian Hahn6b1db822018-06-14 20:32:58 +00003535 DstChild->getName());
Daniel Sanders7438b262017-10-31 23:03:18 +00003536 return InsertPt;
Daniel Sanders05540042017-08-08 10:44:31 +00003537 }
3538
Florian Hahn6b1db822018-06-14 20:32:58 +00003539 if (DstChild->getOperator()->isSubClassOf("Instruction")) {
3540 ArrayRef<TypeSetByHwMode> ChildTypes = DstChild->getExtTypes();
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003541 if (ChildTypes.size() != 1)
3542 return failedImport("Dst pattern child has multiple results");
3543
3544 Optional<LLTCodeGen> OpTyOrNone = None;
3545 if (ChildTypes.front().isMachineValueType())
3546 OpTyOrNone =
3547 MVTToLLT(ChildTypes.front().getMachineValueType().SimpleTy);
3548 if (!OpTyOrNone)
3549 return failedImport("Dst operand has an unsupported type");
3550
3551 unsigned TempRegID = Rule.allocateTempRegID();
3552 InsertPt = Rule.insertAction<MakeTempRegisterAction>(
3553 InsertPt, OpTyOrNone.getValue(), TempRegID);
3554 DstMIBuilder.addRenderer<TempRegRenderer>(TempRegID);
3555
3556 auto InsertPtOrError = createAndImportSubInstructionRenderer(
3557 ++InsertPt, Rule, DstChild, TempRegID);
3558 if (auto Error = InsertPtOrError.takeError())
3559 return std::move(Error);
3560 return InsertPtOrError.get();
3561 }
3562
Florian Hahn6b1db822018-06-14 20:32:58 +00003563 return failedImport("Dst pattern child isn't a leaf node or an MBB" + llvm::to_string(*DstChild));
Daniel Sandersffc7d582017-03-29 15:37:18 +00003564 }
3565
Daniel Sandersf499b2b2017-11-30 18:48:35 +00003566 // It could be a specific immediate in which case we should just check for
3567 // that immediate.
3568 if (const IntInit *ChildIntInit =
Florian Hahn6b1db822018-06-14 20:32:58 +00003569 dyn_cast<IntInit>(DstChild->getLeafValue())) {
Daniel Sandersf499b2b2017-11-30 18:48:35 +00003570 DstMIBuilder.addRenderer<ImmRenderer>(ChildIntInit->getValue());
3571 return InsertPt;
3572 }
3573
Daniel Sandersffc7d582017-03-29 15:37:18 +00003574 // Otherwise, we're looking for a bog-standard RegisterClass operand.
Florian Hahn6b1db822018-06-14 20:32:58 +00003575 if (auto *ChildDefInit = dyn_cast<DefInit>(DstChild->getLeafValue())) {
Daniel Sandersffc7d582017-03-29 15:37:18 +00003576 auto *ChildRec = ChildDefInit->getDef();
3577
Florian Hahn6b1db822018-06-14 20:32:58 +00003578 ArrayRef<TypeSetByHwMode> ChildTypes = DstChild->getExtTypes();
Daniel Sandersffc7d582017-03-29 15:37:18 +00003579 if (ChildTypes.size() != 1)
3580 return failedImport("Dst pattern child has multiple results");
3581
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003582 Optional<LLTCodeGen> OpTyOrNone = None;
3583 if (ChildTypes.front().isMachineValueType())
3584 OpTyOrNone = MVTToLLT(ChildTypes.front().getMachineValueType().SimpleTy);
Daniel Sandersffc7d582017-03-29 15:37:18 +00003585 if (!OpTyOrNone)
3586 return failedImport("Dst operand has an unsupported type");
3587
3588 if (ChildRec->isSubClassOf("Register")) {
Daniel Sanders198447a2017-11-01 00:29:47 +00003589 DstMIBuilder.addRenderer<AddRegisterRenderer>(ChildRec);
Daniel Sanders7438b262017-10-31 23:03:18 +00003590 return InsertPt;
Daniel Sandersffc7d582017-03-29 15:37:18 +00003591 }
3592
Daniel Sanders658541f2017-04-22 15:53:21 +00003593 if (ChildRec->isSubClassOf("RegisterClass") ||
Daniel Sanders4d4e7652017-10-09 18:14:53 +00003594 ChildRec->isSubClassOf("RegisterOperand") ||
3595 ChildRec->isSubClassOf("ValueType")) {
Daniel Sandersd66e0902017-10-23 18:19:24 +00003596 if (ChildRec->isSubClassOf("RegisterOperand") &&
3597 !ChildRec->isValueUnset("GIZeroRegister")) {
3598 DstMIBuilder.addRenderer<CopyOrAddZeroRegRenderer>(
Florian Hahn6b1db822018-06-14 20:32:58 +00003599 DstChild->getName(), ChildRec->getValueAsDef("GIZeroRegister"));
Daniel Sanders7438b262017-10-31 23:03:18 +00003600 return InsertPt;
Daniel Sandersd66e0902017-10-23 18:19:24 +00003601 }
3602
Florian Hahn6b1db822018-06-14 20:32:58 +00003603 DstMIBuilder.addRenderer<CopyRenderer>(DstChild->getName());
Daniel Sanders7438b262017-10-31 23:03:18 +00003604 return InsertPt;
Daniel Sandersffc7d582017-03-29 15:37:18 +00003605 }
3606
3607 if (ChildRec->isSubClassOf("ComplexPattern")) {
3608 const auto &ComplexPattern = ComplexPatternEquivs.find(ChildRec);
3609 if (ComplexPattern == ComplexPatternEquivs.end())
3610 return failedImport(
3611 "SelectionDAG ComplexPattern not mapped to GlobalISel");
3612
Florian Hahn6b1db822018-06-14 20:32:58 +00003613 const OperandMatcher &OM = Rule.getOperandMatcher(DstChild->getName());
Daniel Sandersffc7d582017-03-29 15:37:18 +00003614 DstMIBuilder.addRenderer<RenderComplexPatternOperand>(
Florian Hahn6b1db822018-06-14 20:32:58 +00003615 *ComplexPattern->second, DstChild->getName(),
Daniel Sanders2deea182017-04-22 15:11:04 +00003616 OM.getAllocatedTemporariesBaseID());
Daniel Sanders7438b262017-10-31 23:03:18 +00003617 return InsertPt;
Daniel Sandersffc7d582017-03-29 15:37:18 +00003618 }
3619
3620 return failedImport(
3621 "Dst pattern child def is an unsupported tablegen class");
3622 }
3623
3624 return failedImport("Dst pattern child is an unsupported kind");
3625}
3626
Daniel Sandersc270c502017-03-30 09:36:33 +00003627Expected<BuildMIAction &> GlobalISelEmitter::createAndImportInstructionRenderer(
Florian Hahn6b1db822018-06-14 20:32:58 +00003628 RuleMatcher &M, const TreePatternNode *Dst) {
Daniel Sanders7438b262017-10-31 23:03:18 +00003629 auto InsertPtOrError = createInstructionRenderer(M.actions_end(), M, Dst);
3630 if (auto Error = InsertPtOrError.takeError())
Daniel Sandersdf258e32017-10-31 19:09:29 +00003631 return std::move(Error);
3632
Daniel Sanders7438b262017-10-31 23:03:18 +00003633 action_iterator InsertPt = InsertPtOrError.get();
3634 BuildMIAction &DstMIBuilder = *static_cast<BuildMIAction *>(InsertPt->get());
Daniel Sandersdf258e32017-10-31 19:09:29 +00003635
3636 importExplicitDefRenderers(DstMIBuilder);
3637
Daniel Sanders7438b262017-10-31 23:03:18 +00003638 if (auto Error = importExplicitUseRenderers(InsertPt, M, DstMIBuilder, Dst)
3639 .takeError())
Daniel Sandersdf258e32017-10-31 19:09:29 +00003640 return std::move(Error);
3641
3642 return DstMIBuilder;
3643}
3644
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003645Expected<action_iterator>
3646GlobalISelEmitter::createAndImportSubInstructionRenderer(
Florian Hahn6b1db822018-06-14 20:32:58 +00003647 const action_iterator InsertPt, RuleMatcher &M, const TreePatternNode *Dst,
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003648 unsigned TempRegID) {
3649 auto InsertPtOrError = createInstructionRenderer(InsertPt, M, Dst);
3650
3651 // TODO: Assert there's exactly one result.
3652
3653 if (auto Error = InsertPtOrError.takeError())
3654 return std::move(Error);
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003655
3656 BuildMIAction &DstMIBuilder =
3657 *static_cast<BuildMIAction *>(InsertPtOrError.get()->get());
3658
3659 // Assign the result to TempReg.
3660 DstMIBuilder.addRenderer<TempRegRenderer>(TempRegID, true);
3661
Daniel Sanders08464522018-01-29 21:09:12 +00003662 InsertPtOrError =
3663 importExplicitUseRenderers(InsertPtOrError.get(), M, DstMIBuilder, Dst);
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003664 if (auto Error = InsertPtOrError.takeError())
3665 return std::move(Error);
3666
Daniel Sanders08464522018-01-29 21:09:12 +00003667 M.insertAction<ConstrainOperandsToDefinitionAction>(InsertPt,
3668 DstMIBuilder.getInsnID());
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003669 return InsertPtOrError.get();
3670}
3671
Daniel Sanders7438b262017-10-31 23:03:18 +00003672Expected<action_iterator> GlobalISelEmitter::createInstructionRenderer(
Florian Hahn6b1db822018-06-14 20:32:58 +00003673 action_iterator InsertPt, RuleMatcher &M, const TreePatternNode *Dst) {
3674 Record *DstOp = Dst->getOperator();
Daniel Sandersd0656a32017-04-13 09:45:37 +00003675 if (!DstOp->isSubClassOf("Instruction")) {
3676 if (DstOp->isSubClassOf("ValueType"))
3677 return failedImport(
3678 "Pattern operator isn't an instruction (it's a ValueType)");
Daniel Sandersffc7d582017-03-29 15:37:18 +00003679 return failedImport("Pattern operator isn't an instruction");
Daniel Sandersd0656a32017-04-13 09:45:37 +00003680 }
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003681 CodeGenInstruction *DstI = &Target.getInstruction(DstOp);
Daniel Sandersffc7d582017-03-29 15:37:18 +00003682
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003683 // COPY_TO_REGCLASS is just a copy with a ConstrainOperandToRegClassAction
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00003684 // attached. Similarly for EXTRACT_SUBREG except that's a subregister copy.
Daniel Sandersdf258e32017-10-31 19:09:29 +00003685 if (DstI->TheDef->getName() == "COPY_TO_REGCLASS")
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003686 DstI = &Target.getInstruction(RK.getDef("COPY"));
Daniel Sandersdf258e32017-10-31 19:09:29 +00003687 else if (DstI->TheDef->getName() == "EXTRACT_SUBREG")
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00003688 DstI = &Target.getInstruction(RK.getDef("COPY"));
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003689 else if (DstI->TheDef->getName() == "REG_SEQUENCE")
3690 return failedImport("Unable to emit REG_SEQUENCE");
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003691
Daniel Sanders198447a2017-11-01 00:29:47 +00003692 return M.insertAction<BuildMIAction>(InsertPt, M.allocateOutputInsnID(),
3693 DstI);
Daniel Sandersdf258e32017-10-31 19:09:29 +00003694}
3695
3696void GlobalISelEmitter::importExplicitDefRenderers(
3697 BuildMIAction &DstMIBuilder) {
3698 const CodeGenInstruction *DstI = DstMIBuilder.getCGI();
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003699 for (unsigned I = 0; I < DstI->Operands.NumDefs; ++I) {
3700 const CGIOperandList::OperandInfo &DstIOperand = DstI->Operands[I];
Daniel Sanders198447a2017-11-01 00:29:47 +00003701 DstMIBuilder.addRenderer<CopyRenderer>(DstIOperand.Name);
Daniel Sandersffc7d582017-03-29 15:37:18 +00003702 }
Daniel Sandersdf258e32017-10-31 19:09:29 +00003703}
3704
Daniel Sanders7438b262017-10-31 23:03:18 +00003705Expected<action_iterator> GlobalISelEmitter::importExplicitUseRenderers(
3706 action_iterator InsertPt, RuleMatcher &M, BuildMIAction &DstMIBuilder,
Florian Hahn6b1db822018-06-14 20:32:58 +00003707 const llvm::TreePatternNode *Dst) {
Daniel Sandersdf258e32017-10-31 19:09:29 +00003708 const CodeGenInstruction *DstI = DstMIBuilder.getCGI();
Florian Hahn6b1db822018-06-14 20:32:58 +00003709 CodeGenInstruction *OrigDstI = &Target.getInstruction(Dst->getOperator());
Daniel Sandersffc7d582017-03-29 15:37:18 +00003710
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00003711 // EXTRACT_SUBREG needs to use a subregister COPY.
Daniel Sandersdf258e32017-10-31 19:09:29 +00003712 if (OrigDstI->TheDef->getName() == "EXTRACT_SUBREG") {
Florian Hahn6b1db822018-06-14 20:32:58 +00003713 if (!Dst->getChild(0)->isLeaf())
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00003714 return failedImport("EXTRACT_SUBREG child #1 is not a leaf");
3715
Daniel Sanders32291982017-06-28 13:50:04 +00003716 if (DefInit *SubRegInit =
Florian Hahn6b1db822018-06-14 20:32:58 +00003717 dyn_cast<DefInit>(Dst->getChild(1)->getLeafValue())) {
3718 Record *RCDef = getInitValueAsRegClass(Dst->getChild(0)->getLeafValue());
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003719 if (!RCDef)
3720 return failedImport("EXTRACT_SUBREG child #0 could not "
3721 "be coerced to a register class");
3722
3723 CodeGenRegisterClass *RC = CGRegs.getRegClass(RCDef);
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00003724 CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef());
3725
3726 const auto &SrcRCDstRCPair =
3727 RC->getMatchingSubClassWithSubRegs(CGRegs, SubIdx);
3728 if (SrcRCDstRCPair.hasValue()) {
3729 assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
3730 if (SrcRCDstRCPair->first != RC)
3731 return failedImport("EXTRACT_SUBREG requires an additional COPY");
3732 }
3733
Florian Hahn6b1db822018-06-14 20:32:58 +00003734 DstMIBuilder.addRenderer<CopySubRegRenderer>(Dst->getChild(0)->getName(),
Daniel Sanders198447a2017-11-01 00:29:47 +00003735 SubIdx);
Daniel Sanders7438b262017-10-31 23:03:18 +00003736 return InsertPt;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00003737 }
3738
3739 return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
3740 }
3741
Daniel Sandersffc7d582017-03-29 15:37:18 +00003742 // Render the explicit uses.
Daniel Sandersdf258e32017-10-31 19:09:29 +00003743 unsigned DstINumUses = OrigDstI->Operands.size() - OrigDstI->Operands.NumDefs;
Florian Hahn6b1db822018-06-14 20:32:58 +00003744 unsigned ExpectedDstINumUses = Dst->getNumChildren();
Daniel Sandersdf258e32017-10-31 19:09:29 +00003745 if (OrigDstI->TheDef->getName() == "COPY_TO_REGCLASS") {
3746 DstINumUses--; // Ignore the class constraint.
3747 ExpectedDstINumUses--;
3748 }
3749
Daniel Sanders0ed28822017-04-12 08:23:08 +00003750 unsigned Child = 0;
Diana Picus382602f2017-05-17 08:57:28 +00003751 unsigned NumDefaultOps = 0;
Daniel Sanders0ed28822017-04-12 08:23:08 +00003752 for (unsigned I = 0; I != DstINumUses; ++I) {
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003753 const CGIOperandList::OperandInfo &DstIOperand =
3754 DstI->Operands[DstI->Operands.NumDefs + I];
Daniel Sanders0ed28822017-04-12 08:23:08 +00003755
Diana Picus382602f2017-05-17 08:57:28 +00003756 // If the operand has default values, introduce them now.
3757 // FIXME: Until we have a decent test case that dictates we should do
3758 // otherwise, we're going to assume that operands with default values cannot
3759 // be specified in the patterns. Therefore, adding them will not cause us to
3760 // end up with too many rendered operands.
3761 if (DstIOperand.Rec->isSubClassOf("OperandWithDefaultOps")) {
Daniel Sanders0ed28822017-04-12 08:23:08 +00003762 DagInit *DefaultOps = DstIOperand.Rec->getValueAsDag("DefaultOps");
Diana Picus382602f2017-05-17 08:57:28 +00003763 if (auto Error = importDefaultOperandRenderers(DstMIBuilder, DefaultOps))
3764 return std::move(Error);
3765 ++NumDefaultOps;
Daniel Sanders0ed28822017-04-12 08:23:08 +00003766 continue;
3767 }
3768
Daniel Sanders7438b262017-10-31 23:03:18 +00003769 auto InsertPtOrError = importExplicitUseRenderer(InsertPt, M, DstMIBuilder,
Florian Hahn6b1db822018-06-14 20:32:58 +00003770 Dst->getChild(Child));
Daniel Sanders7438b262017-10-31 23:03:18 +00003771 if (auto Error = InsertPtOrError.takeError())
Daniel Sandersffc7d582017-03-29 15:37:18 +00003772 return std::move(Error);
Daniel Sanders7438b262017-10-31 23:03:18 +00003773 InsertPt = InsertPtOrError.get();
Daniel Sanders0ed28822017-04-12 08:23:08 +00003774 ++Child;
Daniel Sandersffc7d582017-03-29 15:37:18 +00003775 }
3776
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003777 if (NumDefaultOps + ExpectedDstINumUses != DstINumUses)
Diana Picuseb2057c2017-05-17 09:25:08 +00003778 return failedImport("Expected " + llvm::to_string(DstINumUses) +
Diana Picus382602f2017-05-17 08:57:28 +00003779 " used operands but found " +
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003780 llvm::to_string(ExpectedDstINumUses) +
Diana Picuseb2057c2017-05-17 09:25:08 +00003781 " explicit ones and " + llvm::to_string(NumDefaultOps) +
Diana Picus382602f2017-05-17 08:57:28 +00003782 " default ones");
3783
Daniel Sanders7438b262017-10-31 23:03:18 +00003784 return InsertPt;
Daniel Sandersffc7d582017-03-29 15:37:18 +00003785}
3786
Diana Picus382602f2017-05-17 08:57:28 +00003787Error GlobalISelEmitter::importDefaultOperandRenderers(
3788 BuildMIAction &DstMIBuilder, DagInit *DefaultOps) const {
Craig Topper481ff702017-05-29 21:49:34 +00003789 for (const auto *DefaultOp : DefaultOps->getArgs()) {
Diana Picus382602f2017-05-17 08:57:28 +00003790 // Look through ValueType operators.
3791 if (const DagInit *DefaultDagOp = dyn_cast<DagInit>(DefaultOp)) {
3792 if (const DefInit *DefaultDagOperator =
3793 dyn_cast<DefInit>(DefaultDagOp->getOperator())) {
3794 if (DefaultDagOperator->getDef()->isSubClassOf("ValueType"))
3795 DefaultOp = DefaultDagOp->getArg(0);
3796 }
3797 }
3798
3799 if (const DefInit *DefaultDefOp = dyn_cast<DefInit>(DefaultOp)) {
Daniel Sanders198447a2017-11-01 00:29:47 +00003800 DstMIBuilder.addRenderer<AddRegisterRenderer>(DefaultDefOp->getDef());
Diana Picus382602f2017-05-17 08:57:28 +00003801 continue;
3802 }
3803
3804 if (const IntInit *DefaultIntOp = dyn_cast<IntInit>(DefaultOp)) {
Daniel Sanders198447a2017-11-01 00:29:47 +00003805 DstMIBuilder.addRenderer<ImmRenderer>(DefaultIntOp->getValue());
Diana Picus382602f2017-05-17 08:57:28 +00003806 continue;
3807 }
3808
3809 return failedImport("Could not add default op");
3810 }
3811
3812 return Error::success();
3813}
3814
Daniel Sandersc270c502017-03-30 09:36:33 +00003815Error GlobalISelEmitter::importImplicitDefRenderers(
Daniel Sandersffc7d582017-03-29 15:37:18 +00003816 BuildMIAction &DstMIBuilder,
3817 const std::vector<Record *> &ImplicitDefs) const {
3818 if (!ImplicitDefs.empty())
3819 return failedImport("Pattern defines a physical register");
Daniel Sandersc270c502017-03-30 09:36:33 +00003820 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00003821}
3822
3823Expected<RuleMatcher> GlobalISelEmitter::runOnPattern(const PatternToMatch &P) {
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003824 // Keep track of the matchers and actions to emit.
Aditya Nandakumarb63e7632018-02-16 22:37:15 +00003825 int Score = P.getPatternComplexity(CGP);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003826 RuleMatcher M(P.getSrcRecord()->getLoc());
Aditya Nandakumarb63e7632018-02-16 22:37:15 +00003827 RuleMatcherScores[M.getRuleID()] = Score;
Daniel Sanders6ea17ed2017-10-31 18:07:03 +00003828 M.addAction<DebugCommentAction>(llvm::to_string(*P.getSrcPattern()) +
3829 " => " +
3830 llvm::to_string(*P.getDstPattern()));
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003831
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003832 if (auto Error = importRulePredicates(M, P.getPredicates()))
Daniel Sandersffc7d582017-03-29 15:37:18 +00003833 return std::move(Error);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003834
3835 // Next, analyze the pattern operators.
Florian Hahn6b1db822018-06-14 20:32:58 +00003836 TreePatternNode *Src = P.getSrcPattern();
3837 TreePatternNode *Dst = P.getDstPattern();
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003838
3839 // If the root of either pattern isn't a simple operator, ignore it.
Daniel Sandersd0656a32017-04-13 09:45:37 +00003840 if (auto Err = isTrivialOperatorNode(Dst))
3841 return failedImport("Dst pattern root isn't a trivial operator (" +
3842 toString(std::move(Err)) + ")");
3843 if (auto Err = isTrivialOperatorNode(Src))
3844 return failedImport("Src pattern root isn't a trivial operator (" +
3845 toString(std::move(Err)) + ")");
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003846
Quentin Colombetaad20be2017-12-15 23:07:42 +00003847 // The different predicates and matchers created during
3848 // addInstructionMatcher use the RuleMatcher M to set up their
3849 // instruction ID (InsnVarID) that are going to be used when
3850 // M is going to be emitted.
3851 // However, the code doing the emission still relies on the IDs
3852 // returned during that process by the RuleMatcher when issuing
3853 // the recordInsn opcodes.
3854 // Because of that:
3855 // 1. The order in which we created the predicates
3856 // and such must be the same as the order in which we emit them,
3857 // and
3858 // 2. We need to reset the generation of the IDs in M somewhere between
3859 // addInstructionMatcher and emit
3860 //
3861 // FIXME: Long term, we don't want to have to rely on this implicit
3862 // naming being the same. One possible solution would be to have
3863 // explicit operator for operation capture and reference those.
3864 // The plus side is that it would expose opportunities to share
3865 // the capture accross rules. The downside is that it would
3866 // introduce a dependency between predicates (captures must happen
3867 // before their first use.)
Florian Hahn6b1db822018-06-14 20:32:58 +00003868 InstructionMatcher &InsnMatcherTemp = M.addInstructionMatcher(Src->getName());
Daniel Sandersedd07842017-08-17 09:26:14 +00003869 unsigned TempOpIdx = 0;
3870 auto InsnMatcherOrError =
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003871 createAndImportSelDAGMatcher(M, InsnMatcherTemp, Src, TempOpIdx);
Daniel Sandersedd07842017-08-17 09:26:14 +00003872 if (auto Error = InsnMatcherOrError.takeError())
3873 return std::move(Error);
3874 InstructionMatcher &InsnMatcher = InsnMatcherOrError.get();
3875
Florian Hahn6b1db822018-06-14 20:32:58 +00003876 if (Dst->isLeaf()) {
3877 Record *RCDef = getInitValueAsRegClass(Dst->getLeafValue());
Daniel Sandersedd07842017-08-17 09:26:14 +00003878
3879 const CodeGenRegisterClass &RC = Target.getRegisterClass(RCDef);
3880 if (RCDef) {
3881 // We need to replace the def and all its uses with the specified
3882 // operand. However, we must also insert COPY's wherever needed.
3883 // For now, emit a copy and let the register allocator clean up.
3884 auto &DstI = Target.getInstruction(RK.getDef("COPY"));
3885 const auto &DstIOperand = DstI.Operands[0];
3886
3887 OperandMatcher &OM0 = InsnMatcher.getOperand(0);
3888 OM0.setSymbolicName(DstIOperand.Name);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003889 M.defineOperand(OM0.getSymbolicName(), OM0);
Daniel Sandersedd07842017-08-17 09:26:14 +00003890 OM0.addPredicate<RegisterBankOperandMatcher>(RC);
3891
Daniel Sanders198447a2017-11-01 00:29:47 +00003892 auto &DstMIBuilder =
3893 M.addAction<BuildMIAction>(M.allocateOutputInsnID(), &DstI);
3894 DstMIBuilder.addRenderer<CopyRenderer>(DstIOperand.Name);
Florian Hahn6b1db822018-06-14 20:32:58 +00003895 DstMIBuilder.addRenderer<CopyRenderer>(Dst->getName());
Daniel Sandersedd07842017-08-17 09:26:14 +00003896 M.addAction<ConstrainOperandToRegClassAction>(0, 0, RC);
3897
3898 // We're done with this pattern! It's eligible for GISel emission; return
3899 // it.
3900 ++NumPatternImported;
3901 return std::move(M);
3902 }
3903
Daniel Sanders452c8ae2017-05-23 19:33:16 +00003904 return failedImport("Dst pattern root isn't a known leaf");
Daniel Sandersedd07842017-08-17 09:26:14 +00003905 }
Daniel Sanders452c8ae2017-05-23 19:33:16 +00003906
Daniel Sandersbee57392017-04-04 13:25:23 +00003907 // Start with the defined operands (i.e., the results of the root operator).
Florian Hahn6b1db822018-06-14 20:32:58 +00003908 Record *DstOp = Dst->getOperator();
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003909 if (!DstOp->isSubClassOf("Instruction"))
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003910 return failedImport("Pattern operator isn't an instruction");
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003911
3912 auto &DstI = Target.getInstruction(DstOp);
Florian Hahn6b1db822018-06-14 20:32:58 +00003913 if (DstI.Operands.NumDefs != Src->getExtTypes().size())
Daniel Sandersd0656a32017-04-13 09:45:37 +00003914 return failedImport("Src pattern results and dst MI defs are different (" +
Florian Hahn6b1db822018-06-14 20:32:58 +00003915 to_string(Src->getExtTypes().size()) + " def(s) vs " +
Daniel Sandersd0656a32017-04-13 09:45:37 +00003916 to_string(DstI.Operands.NumDefs) + " def(s))");
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003917
Daniel Sandersffc7d582017-03-29 15:37:18 +00003918 // The root of the match also has constraints on the register bank so that it
3919 // matches the result instruction.
3920 unsigned OpIdx = 0;
Florian Hahn6b1db822018-06-14 20:32:58 +00003921 for (const TypeSetByHwMode &VTy : Src->getExtTypes()) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003922 (void)VTy;
Daniel Sandersffc7d582017-03-29 15:37:18 +00003923
Daniel Sanders066ebbf2017-02-24 15:43:30 +00003924 const auto &DstIOperand = DstI.Operands[OpIdx];
3925 Record *DstIOpRec = DstIOperand.Rec;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003926 if (DstI.TheDef->getName() == "COPY_TO_REGCLASS") {
Florian Hahn6b1db822018-06-14 20:32:58 +00003927 DstIOpRec = getInitValueAsRegClass(Dst->getChild(1)->getLeafValue());
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003928
3929 if (DstIOpRec == nullptr)
3930 return failedImport(
3931 "COPY_TO_REGCLASS operand #1 isn't a register class");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00003932 } else if (DstI.TheDef->getName() == "EXTRACT_SUBREG") {
Florian Hahn6b1db822018-06-14 20:32:58 +00003933 if (!Dst->getChild(0)->isLeaf())
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00003934 return failedImport("EXTRACT_SUBREG operand #0 isn't a leaf");
3935
Daniel Sanders32291982017-06-28 13:50:04 +00003936 // We can assume that a subregister is in the same bank as it's super
3937 // register.
Florian Hahn6b1db822018-06-14 20:32:58 +00003938 DstIOpRec = getInitValueAsRegClass(Dst->getChild(0)->getLeafValue());
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00003939
3940 if (DstIOpRec == nullptr)
3941 return failedImport(
3942 "EXTRACT_SUBREG operand #0 isn't a register class");
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003943 } else if (DstIOpRec->isSubClassOf("RegisterOperand"))
Daniel Sanders658541f2017-04-22 15:53:21 +00003944 DstIOpRec = DstIOpRec->getValueAsDef("RegClass");
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003945 else if (!DstIOpRec->isSubClassOf("RegisterClass"))
Florian Hahn6b1db822018-06-14 20:32:58 +00003946 return failedImport("Dst MI def isn't a register class" +
3947 to_string(*Dst));
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003948
Daniel Sandersffc7d582017-03-29 15:37:18 +00003949 OperandMatcher &OM = InsnMatcher.getOperand(OpIdx);
3950 OM.setSymbolicName(DstIOperand.Name);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003951 M.defineOperand(OM.getSymbolicName(), OM);
Daniel Sandersdc662ff2017-01-26 11:10:14 +00003952 OM.addPredicate<RegisterBankOperandMatcher>(
3953 Target.getRegisterClass(DstIOpRec));
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003954 ++OpIdx;
3955 }
3956
Daniel Sandersa7b75262017-10-31 18:50:24 +00003957 auto DstMIBuilderOrError = createAndImportInstructionRenderer(M, Dst);
Daniel Sandersffc7d582017-03-29 15:37:18 +00003958 if (auto Error = DstMIBuilderOrError.takeError())
3959 return std::move(Error);
3960 BuildMIAction &DstMIBuilder = DstMIBuilderOrError.get();
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003961
Daniel Sandersffc7d582017-03-29 15:37:18 +00003962 // Render the implicit defs.
3963 // These are only added to the root of the result.
Daniel Sandersc270c502017-03-30 09:36:33 +00003964 if (auto Error = importImplicitDefRenderers(DstMIBuilder, P.getDstRegs()))
Daniel Sandersffc7d582017-03-29 15:37:18 +00003965 return std::move(Error);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003966
Daniel Sandersa7b75262017-10-31 18:50:24 +00003967 DstMIBuilder.chooseInsnToMutate(M);
3968
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003969 // Constrain the registers to classes. This is normally derived from the
3970 // emitted instruction but a few instructions require special handling.
3971 if (DstI.TheDef->getName() == "COPY_TO_REGCLASS") {
3972 // COPY_TO_REGCLASS does not provide operand constraints itself but the
3973 // result is constrained to the class given by the second child.
3974 Record *DstIOpRec =
Florian Hahn6b1db822018-06-14 20:32:58 +00003975 getInitValueAsRegClass(Dst->getChild(1)->getLeafValue());
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003976
3977 if (DstIOpRec == nullptr)
3978 return failedImport("COPY_TO_REGCLASS operand #1 isn't a register class");
3979
3980 M.addAction<ConstrainOperandToRegClassAction>(
Daniel Sandersd93a35a2017-07-05 09:39:33 +00003981 0, 0, Target.getRegisterClass(DstIOpRec));
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00003982
3983 // We're done with this pattern! It's eligible for GISel emission; return
3984 // it.
3985 ++NumPatternImported;
3986 return std::move(M);
3987 }
3988
3989 if (DstI.TheDef->getName() == "EXTRACT_SUBREG") {
3990 // EXTRACT_SUBREG selects into a subregister COPY but unlike most
3991 // instructions, the result register class is controlled by the
3992 // subregisters of the operand. As a result, we must constrain the result
3993 // class rather than check that it's already the right one.
Florian Hahn6b1db822018-06-14 20:32:58 +00003994 if (!Dst->getChild(0)->isLeaf())
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00003995 return failedImport("EXTRACT_SUBREG child #1 is not a leaf");
3996
Florian Hahn6b1db822018-06-14 20:32:58 +00003997 DefInit *SubRegInit = dyn_cast<DefInit>(Dst->getChild(1)->getLeafValue());
Daniel Sanders320390b2017-06-28 15:16:03 +00003998 if (!SubRegInit)
3999 return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004000
Daniel Sanders320390b2017-06-28 15:16:03 +00004001 // Constrain the result to the same register bank as the operand.
4002 Record *DstIOpRec =
Florian Hahn6b1db822018-06-14 20:32:58 +00004003 getInitValueAsRegClass(Dst->getChild(0)->getLeafValue());
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004004
Daniel Sanders320390b2017-06-28 15:16:03 +00004005 if (DstIOpRec == nullptr)
4006 return failedImport("EXTRACT_SUBREG operand #1 isn't a register class");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004007
Daniel Sanders320390b2017-06-28 15:16:03 +00004008 CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef());
Daniel Sandersd93a35a2017-07-05 09:39:33 +00004009 CodeGenRegisterClass *SrcRC = CGRegs.getRegClass(DstIOpRec);
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004010
Daniel Sanders320390b2017-06-28 15:16:03 +00004011 // It would be nice to leave this constraint implicit but we're required
4012 // to pick a register class so constrain the result to a register class
4013 // that can hold the correct MVT.
4014 //
4015 // FIXME: This may introduce an extra copy if the chosen class doesn't
4016 // actually contain the subregisters.
Florian Hahn6b1db822018-06-14 20:32:58 +00004017 assert(Src->getExtTypes().size() == 1 &&
Daniel Sanders320390b2017-06-28 15:16:03 +00004018 "Expected Src of EXTRACT_SUBREG to have one result type");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004019
Daniel Sanders320390b2017-06-28 15:16:03 +00004020 const auto &SrcRCDstRCPair =
4021 SrcRC->getMatchingSubClassWithSubRegs(CGRegs, SubIdx);
4022 assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
Daniel Sandersd93a35a2017-07-05 09:39:33 +00004023 M.addAction<ConstrainOperandToRegClassAction>(0, 0, *SrcRCDstRCPair->second);
4024 M.addAction<ConstrainOperandToRegClassAction>(0, 1, *SrcRCDstRCPair->first);
4025
4026 // We're done with this pattern! It's eligible for GISel emission; return
4027 // it.
4028 ++NumPatternImported;
4029 return std::move(M);
4030 }
4031
4032 M.addAction<ConstrainOperandsToDefinitionAction>(0);
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004033
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00004034 // We're done with this pattern! It's eligible for GISel emission; return it.
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00004035 ++NumPatternImported;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00004036 return std::move(M);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004037}
4038
Daniel Sanders649c5852017-10-13 20:42:18 +00004039// Emit imm predicate table and an enum to reference them with.
4040// The 'Predicate_' part of the name is redundant but eliminating it is more
4041// trouble than it's worth.
Daniel Sanders8ead1292018-06-15 23:13:43 +00004042void GlobalISelEmitter::emitCxxPredicateFns(
4043 raw_ostream &OS, StringRef CodeFieldName, StringRef TypeIdentifier,
4044 StringRef ArgType, StringRef ArgName, StringRef AdditionalDeclarations,
Daniel Sanders11300ce2017-10-13 21:28:03 +00004045 std::function<bool(const Record *R)> Filter) {
Daniel Sanders649c5852017-10-13 20:42:18 +00004046 std::vector<const Record *> MatchedRecords;
4047 const auto &Defs = RK.getAllDerivedDefinitions("PatFrag");
4048 std::copy_if(Defs.begin(), Defs.end(), std::back_inserter(MatchedRecords),
4049 [&](Record *Record) {
Daniel Sanders8ead1292018-06-15 23:13:43 +00004050 return !Record->getValueAsString(CodeFieldName).empty() &&
Daniel Sanders649c5852017-10-13 20:42:18 +00004051 Filter(Record);
4052 });
4053
Daniel Sanders11300ce2017-10-13 21:28:03 +00004054 if (!MatchedRecords.empty()) {
4055 OS << "// PatFrag predicates.\n"
4056 << "enum {\n";
Daniel Sanders2fed4ff2017-10-13 21:51:20 +00004057 std::string EnumeratorSeparator =
Daniel Sanders11300ce2017-10-13 21:28:03 +00004058 (" = GIPFP_" + TypeIdentifier + "_Invalid + 1,\n").str();
4059 for (const auto *Record : MatchedRecords) {
4060 OS << " GIPFP_" << TypeIdentifier << "_Predicate_" << Record->getName()
4061 << EnumeratorSeparator;
4062 EnumeratorSeparator = ",\n";
4063 }
4064 OS << "};\n";
Daniel Sanders649c5852017-10-13 20:42:18 +00004065 }
Daniel Sanders11300ce2017-10-13 21:28:03 +00004066
Daniel Sanders8ead1292018-06-15 23:13:43 +00004067 OS << "bool " << Target.getName() << "InstructionSelector::test" << ArgName
4068 << "Predicate_" << TypeIdentifier << "(unsigned PredicateID, " << ArgType << " "
4069 << ArgName << ") const {\n"
4070 << AdditionalDeclarations;
4071 if (!AdditionalDeclarations.empty())
4072 OS << "\n";
Aaron Ballman82e17f52017-12-20 20:09:30 +00004073 if (!MatchedRecords.empty())
4074 OS << " switch (PredicateID) {\n";
Daniel Sanders32de8bb2017-12-20 14:41:51 +00004075 for (const auto *Record : MatchedRecords) {
4076 OS << " case GIPFP_" << TypeIdentifier << "_Predicate_"
4077 << Record->getName() << ": {\n"
Daniel Sanders8ead1292018-06-15 23:13:43 +00004078 << " " << Record->getValueAsString(CodeFieldName) << "\n"
4079 << " llvm_unreachable(\"" << CodeFieldName
4080 << " should have returned\");\n"
Daniel Sanders32de8bb2017-12-20 14:41:51 +00004081 << " return false;\n"
4082 << " }\n";
4083 }
Aaron Ballman82e17f52017-12-20 20:09:30 +00004084 if (!MatchedRecords.empty())
4085 OS << " }\n";
4086 OS << " llvm_unreachable(\"Unknown predicate\");\n"
Daniel Sanders32de8bb2017-12-20 14:41:51 +00004087 << " return false;\n"
4088 << "}\n";
Daniel Sanders649c5852017-10-13 20:42:18 +00004089}
4090
Daniel Sanders8ead1292018-06-15 23:13:43 +00004091void GlobalISelEmitter::emitImmPredicateFns(
4092 raw_ostream &OS, StringRef TypeIdentifier, StringRef ArgType,
4093 std::function<bool(const Record *R)> Filter) {
4094 return emitCxxPredicateFns(OS, "ImmediateCode", TypeIdentifier, ArgType,
4095 "Imm", "", Filter);
4096}
4097
4098void GlobalISelEmitter::emitMIPredicateFns(raw_ostream &OS) {
4099 return emitCxxPredicateFns(
4100 OS, "GISelPredicateCode", "MI", "const MachineInstr &", "MI",
4101 " const MachineFunction &MF = *MI.getParent()->getParent();\n"
Andrei Elovikov36cbbff2018-06-26 07:05:08 +00004102 " const MachineRegisterInfo &MRI = MF.getRegInfo();\n"
4103 " (void)MRI;",
Daniel Sanders8ead1292018-06-15 23:13:43 +00004104 [](const Record *R) { return true; });
4105}
4106
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004107template <class GroupT>
Quentin Colombetec76d9c2017-12-18 19:47:41 +00004108std::vector<Matcher *> GlobalISelEmitter::optimizeRules(
Roman Tereshin2d6d3762018-05-02 20:08:14 +00004109 ArrayRef<Matcher *> Rules,
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004110 std::vector<std::unique_ptr<Matcher>> &MatcherStorage) {
4111
Quentin Colombetec76d9c2017-12-18 19:47:41 +00004112 std::vector<Matcher *> OptRules;
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004113 std::unique_ptr<GroupT> CurrentGroup = make_unique<GroupT>();
4114 assert(CurrentGroup->empty() && "Newly created group isn't empty!");
4115 unsigned NumGroups = 0;
4116
4117 auto ProcessCurrentGroup = [&]() {
4118 if (CurrentGroup->empty())
4119 // An empty group is good to be reused:
4120 return;
4121
4122 // If the group isn't large enough to provide any benefit, move all the
4123 // added rules out of it and make sure to re-create the group to properly
4124 // re-initialize it:
4125 if (CurrentGroup->size() < 2)
4126 for (Matcher *M : CurrentGroup->matchers())
4127 OptRules.push_back(M);
4128 else {
4129 CurrentGroup->finalize();
Roman Tereshin8bdf7be2018-05-21 22:21:24 +00004130 OptRules.push_back(CurrentGroup.get());
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004131 MatcherStorage.emplace_back(std::move(CurrentGroup));
4132 ++NumGroups;
Roman Tereshin8bdf7be2018-05-21 22:21:24 +00004133 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004134 CurrentGroup = make_unique<GroupT>();
4135 };
4136 for (Matcher *Rule : Rules) {
4137 // Greedily add as many matchers as possible to the current group:
4138 if (CurrentGroup->addMatcher(*Rule))
4139 continue;
4140
4141 ProcessCurrentGroup();
4142 assert(CurrentGroup->empty() && "A group wasn't properly re-initialized");
4143
4144 // Try to add the pending matcher to a newly created empty group:
4145 if (!CurrentGroup->addMatcher(*Rule))
4146 // If we couldn't add the matcher to an empty group, that group type
4147 // doesn't support that kind of matchers at all, so just skip it:
4148 OptRules.push_back(Rule);
Quentin Colombetec76d9c2017-12-18 19:47:41 +00004149 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004150 ProcessCurrentGroup();
4151
Nicola Zaghen03d0b912018-05-23 15:09:29 +00004152 LLVM_DEBUG(dbgs() << "NumGroups: " << NumGroups << "\n");
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004153 assert(CurrentGroup->empty() && "The last group wasn't properly processed");
Quentin Colombetec76d9c2017-12-18 19:47:41 +00004154 return OptRules;
4155}
4156
Roman Tereshin2d6d3762018-05-02 20:08:14 +00004157MatchTable
4158GlobalISelEmitter::buildMatchTable(MutableArrayRef<RuleMatcher> Rules,
Roman Tereshinbeb39312018-05-02 20:15:11 +00004159 bool Optimize, bool WithCoverage) {
Roman Tereshin2d6d3762018-05-02 20:08:14 +00004160 std::vector<Matcher *> InputRules;
4161 for (Matcher &Rule : Rules)
4162 InputRules.push_back(&Rule);
4163
4164 if (!Optimize)
Roman Tereshinbeb39312018-05-02 20:15:11 +00004165 return MatchTable::buildTable(InputRules, WithCoverage);
Roman Tereshin2d6d3762018-05-02 20:08:14 +00004166
Roman Tereshin77013602018-05-22 16:54:27 +00004167 unsigned CurrentOrdering = 0;
4168 StringMap<unsigned> OpcodeOrder;
4169 for (RuleMatcher &Rule : Rules) {
4170 const StringRef Opcode = Rule.getOpcode();
4171 assert(!Opcode.empty() && "Didn't expect an undefined opcode");
4172 if (OpcodeOrder.count(Opcode) == 0)
4173 OpcodeOrder[Opcode] = CurrentOrdering++;
4174 }
4175
4176 std::stable_sort(InputRules.begin(), InputRules.end(),
4177 [&OpcodeOrder](const Matcher *A, const Matcher *B) {
4178 auto *L = static_cast<const RuleMatcher *>(A);
4179 auto *R = static_cast<const RuleMatcher *>(B);
4180 return std::make_tuple(OpcodeOrder[L->getOpcode()],
4181 L->getNumOperands()) <
4182 std::make_tuple(OpcodeOrder[R->getOpcode()],
4183 R->getNumOperands());
4184 });
4185
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004186 for (Matcher *Rule : InputRules)
4187 Rule->optimize();
4188
4189 std::vector<std::unique_ptr<Matcher>> MatcherStorage;
Roman Tereshin2d6d3762018-05-02 20:08:14 +00004190 std::vector<Matcher *> OptRules =
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004191 optimizeRules<GroupMatcher>(InputRules, MatcherStorage);
4192
4193 for (Matcher *Rule : OptRules)
4194 Rule->optimize();
Roman Tereshin2d6d3762018-05-02 20:08:14 +00004195
Roman Tereshin0ee082f2018-05-22 19:37:59 +00004196 OptRules = optimizeRules<SwitchMatcher>(OptRules, MatcherStorage);
4197
Roman Tereshinbeb39312018-05-02 20:15:11 +00004198 return MatchTable::buildTable(OptRules, WithCoverage);
Roman Tereshin2d6d3762018-05-02 20:08:14 +00004199}
4200
Roman Tereshinfedae332018-05-23 02:04:19 +00004201void GroupMatcher::optimize() {
Roman Tereshin9a9fa492018-05-23 21:30:16 +00004202 // Make sure we only sort by a specific predicate within a range of rules that
4203 // all have that predicate checked against a specific value (not a wildcard):
4204 auto F = Matchers.begin();
4205 auto T = F;
4206 auto E = Matchers.end();
4207 while (T != E) {
4208 while (T != E) {
4209 auto *R = static_cast<RuleMatcher *>(*T);
4210 if (!R->getFirstConditionAsRootType().get().isValid())
4211 break;
4212 ++T;
4213 }
4214 std::stable_sort(F, T, [](Matcher *A, Matcher *B) {
4215 auto *L = static_cast<RuleMatcher *>(A);
4216 auto *R = static_cast<RuleMatcher *>(B);
4217 return L->getFirstConditionAsRootType() <
4218 R->getFirstConditionAsRootType();
4219 });
4220 if (T != E)
4221 F = ++T;
4222 }
Roman Tereshinfedae332018-05-23 02:04:19 +00004223 GlobalISelEmitter::optimizeRules<GroupMatcher>(Matchers, MatcherStorage)
4224 .swap(Matchers);
Roman Tereshina4c410d2018-05-24 00:24:15 +00004225 GlobalISelEmitter::optimizeRules<SwitchMatcher>(Matchers, MatcherStorage)
4226 .swap(Matchers);
Roman Tereshinfedae332018-05-23 02:04:19 +00004227}
4228
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004229void GlobalISelEmitter::run(raw_ostream &OS) {
Daniel Sandersf76f3152017-11-16 00:46:35 +00004230 if (!UseCoverageFile.empty()) {
4231 RuleCoverage = CodeGenCoverage();
4232 auto RuleCoverageBufOrErr = MemoryBuffer::getFile(UseCoverageFile);
4233 if (!RuleCoverageBufOrErr) {
4234 PrintWarning(SMLoc(), "Missing rule coverage data");
4235 RuleCoverage = None;
4236 } else {
4237 if (!RuleCoverage->parse(*RuleCoverageBufOrErr.get(), Target.getName())) {
4238 PrintWarning(SMLoc(), "Ignoring invalid or missing rule coverage data");
4239 RuleCoverage = None;
4240 }
4241 }
4242 }
4243
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004244 // Track the run-time opcode values
4245 gatherOpcodeValues();
4246 // Track the run-time LLT ID values
4247 gatherTypeIDValues();
4248
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004249 // Track the GINodeEquiv definitions.
4250 gatherNodeEquivs();
4251
4252 emitSourceFileHeader(("Global Instruction Selector for the " +
4253 Target.getName() + " target").str(), OS);
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00004254 std::vector<RuleMatcher> Rules;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004255 // Look through the SelectionDAG patterns we found, possibly emitting some.
4256 for (const PatternToMatch &Pat : CGP.ptms()) {
4257 ++NumPatternTotal;
Daniel Sanders7e523672017-11-11 03:23:44 +00004258
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00004259 auto MatcherOrErr = runOnPattern(Pat);
4260
4261 // The pattern analysis can fail, indicating an unsupported pattern.
4262 // Report that if we've been asked to do so.
4263 if (auto Err = MatcherOrErr.takeError()) {
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004264 if (WarnOnSkippedPatterns) {
4265 PrintWarning(Pat.getSrcRecord()->getLoc(),
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00004266 "Skipped pattern: " + toString(std::move(Err)));
4267 } else {
4268 consumeError(std::move(Err));
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004269 }
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00004270 ++NumPatternImportsSkipped;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00004271 continue;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004272 }
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00004273
Daniel Sandersf76f3152017-11-16 00:46:35 +00004274 if (RuleCoverage) {
4275 if (RuleCoverage->isCovered(MatcherOrErr->getRuleID()))
4276 ++NumPatternsTested;
4277 else
4278 PrintWarning(Pat.getSrcRecord()->getLoc(),
4279 "Pattern is not covered by a test");
4280 }
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00004281 Rules.push_back(std::move(MatcherOrErr.get()));
4282 }
4283
Volkan Kelesf7f25682018-01-16 18:44:05 +00004284 // Comparison function to order records by name.
4285 auto orderByName = [](const Record *A, const Record *B) {
4286 return A->getName() < B->getName();
4287 };
4288
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00004289 std::vector<Record *> ComplexPredicates =
4290 RK.getAllDerivedDefinitions("GIComplexOperandMatcher");
Mandeep Singh Grang1b0e2f22018-04-06 20:18:05 +00004291 llvm::sort(ComplexPredicates.begin(), ComplexPredicates.end(), orderByName);
Volkan Kelesf7f25682018-01-16 18:44:05 +00004292
4293 std::vector<Record *> CustomRendererFns =
4294 RK.getAllDerivedDefinitions("GICustomOperandRenderer");
Mandeep Singh Grang1b0e2f22018-04-06 20:18:05 +00004295 llvm::sort(CustomRendererFns.begin(), CustomRendererFns.end(), orderByName);
Volkan Kelesf7f25682018-01-16 18:44:05 +00004296
Daniel Sanders8a4bae92017-03-14 21:32:08 +00004297 unsigned MaxTemporaries = 0;
4298 for (const auto &Rule : Rules)
Daniel Sanders2deea182017-04-22 15:11:04 +00004299 MaxTemporaries = std::max(MaxTemporaries, Rule.countRendererFns());
Daniel Sanders8a4bae92017-03-14 21:32:08 +00004300
Daniel Sanderse7b0d662017-04-21 15:59:56 +00004301 OS << "#ifdef GET_GLOBALISEL_PREDICATE_BITSET\n"
4302 << "const unsigned MAX_SUBTARGET_PREDICATES = " << SubtargetFeatures.size()
4303 << ";\n"
4304 << "using PredicateBitset = "
4305 "llvm::PredicateBitsetImpl<MAX_SUBTARGET_PREDICATES>;\n"
4306 << "#endif // ifdef GET_GLOBALISEL_PREDICATE_BITSET\n\n";
4307
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00004308 OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n"
4309 << " mutable MatcherState State;\n"
4310 << " typedef "
Daniel Sanders1e4569f2017-10-20 20:55:29 +00004311 "ComplexRendererFns("
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00004312 << Target.getName()
4313 << "InstructionSelector::*ComplexMatcherMemFn)(MachineOperand &) const;\n"
Volkan Kelesf7f25682018-01-16 18:44:05 +00004314
4315 << " typedef void(" << Target.getName()
4316 << "InstructionSelector::*CustomRendererFn)(MachineInstrBuilder &, const "
4317 "MachineInstr&) "
4318 "const;\n"
4319 << " const ISelInfoTy<PredicateBitset, ComplexMatcherMemFn, "
4320 "CustomRendererFn> "
4321 "ISelInfo;\n";
4322 OS << " static " << Target.getName()
Daniel Sandersea8711b2017-10-16 03:36:29 +00004323 << "InstructionSelector::ComplexMatcherMemFn ComplexPredicateFns[];\n"
Volkan Kelesf7f25682018-01-16 18:44:05 +00004324 << " static " << Target.getName()
4325 << "InstructionSelector::CustomRendererFn CustomRenderers[];\n"
Roman Tereshin2df4c222018-05-02 20:07:15 +00004326 << " bool testImmPredicate_I64(unsigned PredicateID, int64_t Imm) const "
Daniel Sanders32de8bb2017-12-20 14:41:51 +00004327 "override;\n"
Roman Tereshin2df4c222018-05-02 20:07:15 +00004328 << " bool testImmPredicate_APInt(unsigned PredicateID, const APInt &Imm) "
Daniel Sanders32de8bb2017-12-20 14:41:51 +00004329 "const override;\n"
Roman Tereshin2df4c222018-05-02 20:07:15 +00004330 << " bool testImmPredicate_APFloat(unsigned PredicateID, const APFloat "
Daniel Sanders32de8bb2017-12-20 14:41:51 +00004331 "&Imm) const override;\n"
Roman Tereshin2df4c222018-05-02 20:07:15 +00004332 << " const int64_t *getMatchTable() const override;\n"
Daniel Sanders8ead1292018-06-15 23:13:43 +00004333 << " bool testMIPredicate_MI(unsigned PredicateID, const MachineInstr &MI) "
4334 "const override;\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00004335 << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n\n";
Daniel Sanders8a4bae92017-03-14 21:32:08 +00004336
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00004337 OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n"
4338 << ", State(" << MaxTemporaries << "),\n"
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004339 << "ISelInfo(TypeObjects, NumTypeObjects, FeatureBitsets"
4340 << ", ComplexPredicateFns, CustomRenderers)\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00004341 << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n\n";
Daniel Sanders8a4bae92017-03-14 21:32:08 +00004342
Daniel Sanderse7b0d662017-04-21 15:59:56 +00004343 OS << "#ifdef GET_GLOBALISEL_IMPL\n";
4344 SubtargetFeatureInfo::emitSubtargetFeatureBitEnumeration(SubtargetFeatures,
4345 OS);
Daniel Sanderse9fdba32017-04-29 17:30:09 +00004346
4347 // Separate subtarget features by how often they must be recomputed.
4348 SubtargetFeatureInfoMap ModuleFeatures;
4349 std::copy_if(SubtargetFeatures.begin(), SubtargetFeatures.end(),
4350 std::inserter(ModuleFeatures, ModuleFeatures.end()),
4351 [](const SubtargetFeatureInfoMap::value_type &X) {
4352 return !X.second.mustRecomputePerFunction();
4353 });
4354 SubtargetFeatureInfoMap FunctionFeatures;
4355 std::copy_if(SubtargetFeatures.begin(), SubtargetFeatures.end(),
4356 std::inserter(FunctionFeatures, FunctionFeatures.end()),
4357 [](const SubtargetFeatureInfoMap::value_type &X) {
4358 return X.second.mustRecomputePerFunction();
4359 });
4360
Daniel Sanderse7b0d662017-04-21 15:59:56 +00004361 SubtargetFeatureInfo::emitComputeAvailableFeatures(
Daniel Sanderse9fdba32017-04-29 17:30:09 +00004362 Target.getName(), "InstructionSelector", "computeAvailableModuleFeatures",
4363 ModuleFeatures, OS);
4364 SubtargetFeatureInfo::emitComputeAvailableFeatures(
4365 Target.getName(), "InstructionSelector",
4366 "computeAvailableFunctionFeatures", FunctionFeatures, OS,
4367 "const MachineFunction *MF");
Daniel Sanderse7b0d662017-04-21 15:59:56 +00004368
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00004369 // Emit a table containing the LLT objects needed by the matcher and an enum
4370 // for the matcher to reference them with.
Daniel Sanders032e7f22017-08-17 13:18:35 +00004371 std::vector<LLTCodeGen> TypeObjects;
Daniel Sandersf84bc372018-05-05 20:53:24 +00004372 for (const auto &Ty : KnownTypes)
Daniel Sanders032e7f22017-08-17 13:18:35 +00004373 TypeObjects.push_back(Ty);
Mandeep Singh Grang1b0e2f22018-04-06 20:18:05 +00004374 llvm::sort(TypeObjects.begin(), TypeObjects.end());
Daniel Sanders49980702017-08-23 10:09:25 +00004375 OS << "// LLT Objects.\n"
4376 << "enum {\n";
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00004377 for (const auto &TypeObject : TypeObjects) {
4378 OS << " ";
4379 TypeObject.emitCxxEnumValue(OS);
4380 OS << ",\n";
4381 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004382 OS << "};\n";
4383 OS << "const static size_t NumTypeObjects = " << TypeObjects.size() << ";\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00004384 << "const static LLT TypeObjects[] = {\n";
4385 for (const auto &TypeObject : TypeObjects) {
4386 OS << " ";
4387 TypeObject.emitCxxConstructorCall(OS);
4388 OS << ",\n";
4389 }
4390 OS << "};\n\n";
4391
4392 // Emit a table containing the PredicateBitsets objects needed by the matcher
4393 // and an enum for the matcher to reference them with.
4394 std::vector<std::vector<Record *>> FeatureBitsets;
4395 for (auto &Rule : Rules)
4396 FeatureBitsets.push_back(Rule.getRequiredFeatures());
Mandeep Singh Grang1b0e2f22018-04-06 20:18:05 +00004397 llvm::sort(
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00004398 FeatureBitsets.begin(), FeatureBitsets.end(),
4399 [&](const std::vector<Record *> &A, const std::vector<Record *> &B) {
4400 if (A.size() < B.size())
4401 return true;
4402 if (A.size() > B.size())
4403 return false;
4404 for (const auto &Pair : zip(A, B)) {
4405 if (std::get<0>(Pair)->getName() < std::get<1>(Pair)->getName())
4406 return true;
4407 if (std::get<0>(Pair)->getName() > std::get<1>(Pair)->getName())
4408 return false;
4409 }
4410 return false;
4411 });
4412 FeatureBitsets.erase(
4413 std::unique(FeatureBitsets.begin(), FeatureBitsets.end()),
4414 FeatureBitsets.end());
Daniel Sanders49980702017-08-23 10:09:25 +00004415 OS << "// Feature bitsets.\n"
4416 << "enum {\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00004417 << " GIFBS_Invalid,\n";
4418 for (const auto &FeatureBitset : FeatureBitsets) {
4419 if (FeatureBitset.empty())
4420 continue;
4421 OS << " " << getNameForFeatureBitset(FeatureBitset) << ",\n";
4422 }
4423 OS << "};\n"
4424 << "const static PredicateBitset FeatureBitsets[] {\n"
4425 << " {}, // GIFBS_Invalid\n";
4426 for (const auto &FeatureBitset : FeatureBitsets) {
4427 if (FeatureBitset.empty())
4428 continue;
4429 OS << " {";
4430 for (const auto &Feature : FeatureBitset) {
4431 const auto &I = SubtargetFeatures.find(Feature);
4432 assert(I != SubtargetFeatures.end() && "Didn't import predicate?");
4433 OS << I->second.getEnumBitName() << ", ";
4434 }
4435 OS << "},\n";
4436 }
4437 OS << "};\n\n";
4438
4439 // Emit complex predicate table and an enum to reference them with.
Daniel Sanders49980702017-08-23 10:09:25 +00004440 OS << "// ComplexPattern predicates.\n"
4441 << "enum {\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00004442 << " GICP_Invalid,\n";
4443 for (const auto &Record : ComplexPredicates)
4444 OS << " GICP_" << Record->getName() << ",\n";
4445 OS << "};\n"
4446 << "// See constructor for table contents\n\n";
4447
Daniel Sanders8ead1292018-06-15 23:13:43 +00004448 emitImmPredicateFns(OS, "I64", "int64_t", [](const Record *R) {
Daniel Sanders649c5852017-10-13 20:42:18 +00004449 bool Unset;
4450 return !R->getValueAsBitOrUnset("IsAPFloat", Unset) &&
4451 !R->getValueAsBit("IsAPInt");
4452 });
Daniel Sanders8ead1292018-06-15 23:13:43 +00004453 emitImmPredicateFns(OS, "APFloat", "const APFloat &", [](const Record *R) {
Daniel Sanders11300ce2017-10-13 21:28:03 +00004454 bool Unset;
4455 return R->getValueAsBitOrUnset("IsAPFloat", Unset);
4456 });
Daniel Sanders8ead1292018-06-15 23:13:43 +00004457 emitImmPredicateFns(OS, "APInt", "const APInt &", [](const Record *R) {
Daniel Sanders11300ce2017-10-13 21:28:03 +00004458 return R->getValueAsBit("IsAPInt");
4459 });
Daniel Sanders8ead1292018-06-15 23:13:43 +00004460 emitMIPredicateFns(OS);
Daniel Sandersea8711b2017-10-16 03:36:29 +00004461 OS << "\n";
4462
4463 OS << Target.getName() << "InstructionSelector::ComplexMatcherMemFn\n"
4464 << Target.getName() << "InstructionSelector::ComplexPredicateFns[] = {\n"
4465 << " nullptr, // GICP_Invalid\n";
4466 for (const auto &Record : ComplexPredicates)
4467 OS << " &" << Target.getName()
4468 << "InstructionSelector::" << Record->getValueAsString("MatcherFn")
4469 << ", // " << Record->getName() << "\n";
4470 OS << "};\n\n";
Daniel Sanders2c269f62017-08-24 09:11:20 +00004471
Volkan Kelesf7f25682018-01-16 18:44:05 +00004472 OS << "// Custom renderers.\n"
4473 << "enum {\n"
4474 << " GICR_Invalid,\n";
4475 for (const auto &Record : CustomRendererFns)
4476 OS << " GICR_" << Record->getValueAsString("RendererFn") << ", \n";
4477 OS << "};\n";
4478
4479 OS << Target.getName() << "InstructionSelector::CustomRendererFn\n"
4480 << Target.getName() << "InstructionSelector::CustomRenderers[] = {\n"
4481 << " nullptr, // GICP_Invalid\n";
4482 for (const auto &Record : CustomRendererFns)
4483 OS << " &" << Target.getName()
4484 << "InstructionSelector::" << Record->getValueAsString("RendererFn")
4485 << ", // " << Record->getName() << "\n";
4486 OS << "};\n\n";
4487
Quentin Colombetec76d9c2017-12-18 19:47:41 +00004488 std::stable_sort(Rules.begin(), Rules.end(), [&](const RuleMatcher &A,
4489 const RuleMatcher &B) {
Aditya Nandakumarb63e7632018-02-16 22:37:15 +00004490 int ScoreA = RuleMatcherScores[A.getRuleID()];
4491 int ScoreB = RuleMatcherScores[B.getRuleID()];
4492 if (ScoreA > ScoreB)
4493 return true;
4494 if (ScoreB > ScoreA)
4495 return false;
Quentin Colombetec76d9c2017-12-18 19:47:41 +00004496 if (A.isHigherPriorityThan(B)) {
4497 assert(!B.isHigherPriorityThan(A) && "Cannot be more important "
4498 "and less important at "
4499 "the same time");
4500 return true;
4501 }
4502 return false;
4503 });
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004504
Roman Tereshin2df4c222018-05-02 20:07:15 +00004505 OS << "bool " << Target.getName()
4506 << "InstructionSelector::selectImpl(MachineInstr &I, CodeGenCoverage "
4507 "&CoverageInfo) const {\n"
4508 << " MachineFunction &MF = *I.getParent()->getParent();\n"
4509 << " MachineRegisterInfo &MRI = MF.getRegInfo();\n"
4510 << " // FIXME: This should be computed on a per-function basis rather "
4511 "than per-insn.\n"
4512 << " AvailableFunctionFeatures = computeAvailableFunctionFeatures(&STI, "
4513 "&MF);\n"
4514 << " const PredicateBitset AvailableFeatures = getAvailableFeatures();\n"
4515 << " NewMIVector OutMIs;\n"
4516 << " State.MIs.clear();\n"
4517 << " State.MIs.push_back(&I);\n\n"
4518 << " if (executeMatchTable(*this, OutMIs, State, ISelInfo"
4519 << ", getMatchTable(), TII, MRI, TRI, RBI, AvailableFeatures"
4520 << ", CoverageInfo)) {\n"
4521 << " return true;\n"
4522 << " }\n\n"
4523 << " return false;\n"
4524 << "}\n\n";
4525
Roman Tereshinbeb39312018-05-02 20:15:11 +00004526 const MatchTable Table =
4527 buildMatchTable(Rules, OptimizeMatchTable, GenerateCoverage);
Roman Tereshin2df4c222018-05-02 20:07:15 +00004528 OS << "const int64_t *" << Target.getName()
4529 << "InstructionSelector::getMatchTable() const {\n";
4530 Table.emitDeclaration(OS);
4531 OS << " return ";
4532 Table.emitUse(OS);
4533 OS << ";\n}\n";
4534 OS << "#endif // ifdef GET_GLOBALISEL_IMPL\n";
Daniel Sanderse9fdba32017-04-29 17:30:09 +00004535
4536 OS << "#ifdef GET_GLOBALISEL_PREDICATES_DECL\n"
4537 << "PredicateBitset AvailableModuleFeatures;\n"
4538 << "mutable PredicateBitset AvailableFunctionFeatures;\n"
4539 << "PredicateBitset getAvailableFeatures() const {\n"
4540 << " return AvailableModuleFeatures | AvailableFunctionFeatures;\n"
4541 << "}\n"
4542 << "PredicateBitset\n"
4543 << "computeAvailableModuleFeatures(const " << Target.getName()
4544 << "Subtarget *Subtarget) const;\n"
4545 << "PredicateBitset\n"
4546 << "computeAvailableFunctionFeatures(const " << Target.getName()
4547 << "Subtarget *Subtarget,\n"
4548 << " const MachineFunction *MF) const;\n"
4549 << "#endif // ifdef GET_GLOBALISEL_PREDICATES_DECL\n";
4550
4551 OS << "#ifdef GET_GLOBALISEL_PREDICATES_INIT\n"
4552 << "AvailableModuleFeatures(computeAvailableModuleFeatures(&STI)),\n"
4553 << "AvailableFunctionFeatures()\n"
4554 << "#endif // ifdef GET_GLOBALISEL_PREDICATES_INIT\n";
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004555}
4556
Daniel Sanderse7b0d662017-04-21 15:59:56 +00004557void GlobalISelEmitter::declareSubtargetFeature(Record *Predicate) {
4558 if (SubtargetFeatures.count(Predicate) == 0)
4559 SubtargetFeatures.emplace(
4560 Predicate, SubtargetFeatureInfo(Predicate, SubtargetFeatures.size()));
4561}
4562
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004563void RuleMatcher::optimize() {
4564 for (auto &Item : InsnVariableIDs) {
4565 InstructionMatcher &InsnMatcher = *Item.first;
4566 for (auto &OM : InsnMatcher.operands()) {
Roman Tereshin5f5e5502018-05-23 23:58:10 +00004567 // Complex Patterns are usually expensive and they relatively rarely fail
4568 // on their own: more often we end up throwing away all the work done by a
4569 // matching part of a complex pattern because some other part of the
4570 // enclosing pattern didn't match. All of this makes it beneficial to
4571 // delay complex patterns until the very end of the rule matching,
4572 // especially for targets having lots of complex patterns.
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004573 for (auto &OP : OM->predicates())
Roman Tereshin5f5e5502018-05-23 23:58:10 +00004574 if (isa<ComplexPatternOperandMatcher>(OP))
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004575 EpilogueMatchers.emplace_back(std::move(OP));
4576 OM->eraseNullPredicates();
4577 }
4578 InsnMatcher.optimize();
Quentin Colombetec76d9c2017-12-18 19:47:41 +00004579 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004580 llvm::sort(
4581 EpilogueMatchers.begin(), EpilogueMatchers.end(),
4582 [](const std::unique_ptr<PredicateMatcher> &L,
4583 const std::unique_ptr<PredicateMatcher> &R) {
4584 return std::make_tuple(L->getKind(), L->getInsnVarID(), L->getOpIdx()) <
4585 std::make_tuple(R->getKind(), R->getInsnVarID(), R->getOpIdx());
4586 });
Quentin Colombetec76d9c2017-12-18 19:47:41 +00004587}
4588
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004589bool RuleMatcher::hasFirstCondition() const {
4590 if (insnmatchers_empty())
4591 return false;
4592 InstructionMatcher &Matcher = insnmatchers_front();
4593 if (!Matcher.predicates_empty())
4594 return true;
4595 for (auto &OM : Matcher.operands())
4596 for (auto &OP : OM->predicates())
4597 if (!isa<InstructionOperandMatcher>(OP))
4598 return true;
4599 return false;
4600}
4601
4602const PredicateMatcher &RuleMatcher::getFirstCondition() const {
4603 assert(!insnmatchers_empty() &&
4604 "Trying to get a condition from an empty RuleMatcher");
4605
4606 InstructionMatcher &Matcher = insnmatchers_front();
4607 if (!Matcher.predicates_empty())
4608 return **Matcher.predicates_begin();
4609 // If there is no more predicate on the instruction itself, look at its
4610 // operands.
4611 for (auto &OM : Matcher.operands())
4612 for (auto &OP : OM->predicates())
4613 if (!isa<InstructionOperandMatcher>(OP))
4614 return *OP;
4615
4616 llvm_unreachable("Trying to get a condition from an InstructionMatcher with "
4617 "no conditions");
4618}
4619
4620std::unique_ptr<PredicateMatcher> RuleMatcher::popFirstCondition() {
4621 assert(!insnmatchers_empty() &&
4622 "Trying to pop a condition from an empty RuleMatcher");
4623
4624 InstructionMatcher &Matcher = insnmatchers_front();
4625 if (!Matcher.predicates_empty())
4626 return Matcher.predicates_pop_front();
4627 // If there is no more predicate on the instruction itself, look at its
4628 // operands.
4629 for (auto &OM : Matcher.operands())
4630 for (auto &OP : OM->predicates())
4631 if (!isa<InstructionOperandMatcher>(OP)) {
4632 std::unique_ptr<PredicateMatcher> Result = std::move(OP);
4633 OM->eraseNullPredicates();
4634 return Result;
4635 }
4636
4637 llvm_unreachable("Trying to pop a condition from an InstructionMatcher with "
4638 "no conditions");
4639}
4640
4641bool GroupMatcher::candidateConditionMatches(
Quentin Colombetec76d9c2017-12-18 19:47:41 +00004642 const PredicateMatcher &Predicate) const {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004643
4644 if (empty()) {
4645 // Sharing predicates for nested instructions is not supported yet as we
4646 // currently don't hoist the GIM_RecordInsn's properly, therefore we can
4647 // only work on the original root instruction (InsnVarID == 0):
4648 if (Predicate.getInsnVarID() != 0)
4649 return false;
4650 // ... otherwise an empty group can handle any predicate with no specific
4651 // requirements:
4652 return true;
4653 }
4654
4655 const Matcher &Representative = **Matchers.begin();
4656 const auto &RepresentativeCondition = Representative.getFirstCondition();
4657 // ... if not empty, the group can only accomodate matchers with the exact
4658 // same first condition:
4659 return Predicate.isIdentical(RepresentativeCondition);
4660}
4661
4662bool GroupMatcher::addMatcher(Matcher &Candidate) {
4663 if (!Candidate.hasFirstCondition())
4664 return false;
4665
4666 const PredicateMatcher &Predicate = Candidate.getFirstCondition();
4667 if (!candidateConditionMatches(Predicate))
4668 return false;
4669
4670 Matchers.push_back(&Candidate);
4671 return true;
4672}
4673
4674void GroupMatcher::finalize() {
4675 assert(Conditions.empty() && "Already finalized?");
4676 if (empty())
4677 return;
4678
4679 Matcher &FirstRule = **Matchers.begin();
Roman Tereshin152fc162018-05-23 22:50:53 +00004680 for (;;) {
4681 // All the checks are expected to succeed during the first iteration:
4682 for (const auto &Rule : Matchers)
4683 if (!Rule->hasFirstCondition())
4684 return;
4685 const auto &FirstCondition = FirstRule.getFirstCondition();
4686 for (unsigned I = 1, E = Matchers.size(); I < E; ++I)
4687 if (!Matchers[I]->getFirstCondition().isIdentical(FirstCondition))
4688 return;
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004689
Roman Tereshin152fc162018-05-23 22:50:53 +00004690 Conditions.push_back(FirstRule.popFirstCondition());
4691 for (unsigned I = 1, E = Matchers.size(); I < E; ++I)
4692 Matchers[I]->popFirstCondition();
4693 }
Quentin Colombetec76d9c2017-12-18 19:47:41 +00004694}
4695
4696void GroupMatcher::emit(MatchTable &Table) {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004697 unsigned LabelID = ~0U;
4698 if (!Conditions.empty()) {
4699 LabelID = Table.allocateLabelID();
Quentin Colombetec76d9c2017-12-18 19:47:41 +00004700 Table << MatchTable::Opcode("GIM_Try", +1)
4701 << MatchTable::Comment("On fail goto")
4702 << MatchTable::JumpTarget(LabelID) << MatchTable::LineBreak;
Quentin Colombetec76d9c2017-12-18 19:47:41 +00004703 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004704 for (auto &Condition : Conditions)
4705 Condition->emitPredicateOpcodes(
4706 Table, *static_cast<RuleMatcher *>(*Matchers.begin()));
4707
4708 for (const auto &M : Matchers)
4709 M->emit(Table);
4710
4711 // Exit the group
4712 if (!Conditions.empty())
4713 Table << MatchTable::Opcode("GIM_Reject", -1) << MatchTable::LineBreak
Quentin Colombetec76d9c2017-12-18 19:47:41 +00004714 << MatchTable::Label(LabelID);
Quentin Colombetec76d9c2017-12-18 19:47:41 +00004715}
4716
Roman Tereshin0ee082f2018-05-22 19:37:59 +00004717bool SwitchMatcher::isSupportedPredicateType(const PredicateMatcher &P) {
Roman Tereshina4c410d2018-05-24 00:24:15 +00004718 return isa<InstructionOpcodeMatcher>(P) || isa<LLTOperandMatcher>(P);
Roman Tereshin0ee082f2018-05-22 19:37:59 +00004719}
4720
4721bool SwitchMatcher::candidateConditionMatches(
4722 const PredicateMatcher &Predicate) const {
4723
4724 if (empty()) {
4725 // Sharing predicates for nested instructions is not supported yet as we
4726 // currently don't hoist the GIM_RecordInsn's properly, therefore we can
4727 // only work on the original root instruction (InsnVarID == 0):
4728 if (Predicate.getInsnVarID() != 0)
4729 return false;
4730 // ... while an attempt to add even a root matcher to an empty SwitchMatcher
4731 // could fail as not all the types of conditions are supported:
4732 if (!isSupportedPredicateType(Predicate))
4733 return false;
4734 // ... or the condition might not have a proper implementation of
4735 // getValue() / isIdenticalDownToValue() yet:
4736 if (!Predicate.hasValue())
4737 return false;
4738 // ... otherwise an empty Switch can accomodate the condition with no
4739 // further requirements:
4740 return true;
4741 }
4742
4743 const Matcher &CaseRepresentative = **Matchers.begin();
4744 const auto &RepresentativeCondition = CaseRepresentative.getFirstCondition();
4745 // Switch-cases must share the same kind of condition and path to the value it
4746 // checks:
4747 if (!Predicate.isIdenticalDownToValue(RepresentativeCondition))
4748 return false;
4749
4750 const auto Value = Predicate.getValue();
4751 // ... but be unique with respect to the actual value they check:
4752 return Values.count(Value) == 0;
4753}
4754
4755bool SwitchMatcher::addMatcher(Matcher &Candidate) {
4756 if (!Candidate.hasFirstCondition())
4757 return false;
4758
4759 const PredicateMatcher &Predicate = Candidate.getFirstCondition();
4760 if (!candidateConditionMatches(Predicate))
4761 return false;
4762 const auto Value = Predicate.getValue();
4763 Values.insert(Value);
4764
4765 Matchers.push_back(&Candidate);
4766 return true;
4767}
4768
4769void SwitchMatcher::finalize() {
4770 assert(Condition == nullptr && "Already finalized");
4771 assert(Values.size() == Matchers.size() && "Broken SwitchMatcher");
4772 if (empty())
4773 return;
4774
4775 std::stable_sort(Matchers.begin(), Matchers.end(),
4776 [](const Matcher *L, const Matcher *R) {
4777 return L->getFirstCondition().getValue() <
4778 R->getFirstCondition().getValue();
4779 });
4780 Condition = Matchers[0]->popFirstCondition();
4781 for (unsigned I = 1, E = Values.size(); I < E; ++I)
4782 Matchers[I]->popFirstCondition();
4783}
4784
4785void SwitchMatcher::emitPredicateSpecificOpcodes(const PredicateMatcher &P,
4786 MatchTable &Table) {
4787 assert(isSupportedPredicateType(P) && "Predicate type is not supported");
4788
4789 if (const auto *Condition = dyn_cast<InstructionOpcodeMatcher>(&P)) {
4790 Table << MatchTable::Opcode("GIM_SwitchOpcode") << MatchTable::Comment("MI")
4791 << MatchTable::IntValue(Condition->getInsnVarID());
4792 return;
4793 }
Roman Tereshina4c410d2018-05-24 00:24:15 +00004794 if (const auto *Condition = dyn_cast<LLTOperandMatcher>(&P)) {
4795 Table << MatchTable::Opcode("GIM_SwitchType") << MatchTable::Comment("MI")
4796 << MatchTable::IntValue(Condition->getInsnVarID())
4797 << MatchTable::Comment("Op")
4798 << MatchTable::IntValue(Condition->getOpIdx());
4799 return;
4800 }
Roman Tereshin0ee082f2018-05-22 19:37:59 +00004801
4802 llvm_unreachable("emitPredicateSpecificOpcodes is broken: can not handle a "
4803 "predicate type that is claimed to be supported");
4804}
4805
4806void SwitchMatcher::emit(MatchTable &Table) {
4807 assert(Values.size() == Matchers.size() && "Broken SwitchMatcher");
4808 if (empty())
4809 return;
4810 assert(Condition != nullptr &&
4811 "Broken SwitchMatcher, hasn't been finalized?");
4812
4813 std::vector<unsigned> LabelIDs(Values.size());
4814 std::generate(LabelIDs.begin(), LabelIDs.end(),
4815 [&Table]() { return Table.allocateLabelID(); });
4816 const unsigned Default = Table.allocateLabelID();
4817
4818 const int64_t LowerBound = Values.begin()->getRawValue();
4819 const int64_t UpperBound = Values.rbegin()->getRawValue() + 1;
4820
4821 emitPredicateSpecificOpcodes(*Condition, Table);
4822
4823 Table << MatchTable::Comment("[") << MatchTable::IntValue(LowerBound)
4824 << MatchTable::IntValue(UpperBound) << MatchTable::Comment(")")
4825 << MatchTable::Comment("default:") << MatchTable::JumpTarget(Default);
4826
4827 int64_t J = LowerBound;
4828 auto VI = Values.begin();
4829 for (unsigned I = 0, E = Values.size(); I < E; ++I) {
4830 auto V = *VI++;
4831 while (J++ < V.getRawValue())
4832 Table << MatchTable::IntValue(0);
4833 V.turnIntoComment();
4834 Table << MatchTable::LineBreak << V << MatchTable::JumpTarget(LabelIDs[I]);
4835 }
4836 Table << MatchTable::LineBreak;
4837
4838 for (unsigned I = 0, E = Values.size(); I < E; ++I) {
4839 Table << MatchTable::Label(LabelIDs[I]);
4840 Matchers[I]->emit(Table);
4841 Table << MatchTable::Opcode("GIM_Reject") << MatchTable::LineBreak;
4842 }
4843 Table << MatchTable::Label(Default);
4844}
4845
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004846unsigned OperandMatcher::getInsnVarID() const { return Insn.getInsnVarID(); }
Quentin Colombetaad20be2017-12-15 23:07:42 +00004847
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00004848} // end anonymous namespace
4849
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004850//===----------------------------------------------------------------------===//
4851
4852namespace llvm {
4853void EmitGlobalISel(RecordKeeper &RK, raw_ostream &OS) {
4854 GlobalISelEmitter(RK).run(OS);
4855}
4856} // End llvm namespace