blob: 61d17a53e36adf5f2e145dbd97f6f2ce2715d869 [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 }
1840 void emitPredicateOpcodes(MatchTable &Table,
1841 RuleMatcher &Rule) const override {
1842 Table << MatchTable::Opcode("GIM_CheckCxxInsnPredicate")
1843 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1844 << MatchTable::Comment("FnId")
1845 << MatchTable::NamedValue(getEnumNameForPredicate(Predicate))
1846 << MatchTable::LineBreak;
1847 }
1848};
1849
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001850/// Generates code to check that a set of predicates and operands match for a
1851/// particular instruction.
1852///
1853/// Typical predicates include:
1854/// * Has a specific opcode.
1855/// * Has an nsw/nuw flag or doesn't.
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001856class InstructionMatcher final : public PredicateListMatcher<PredicateMatcher> {
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001857protected:
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001858 typedef std::vector<std::unique_ptr<OperandMatcher>> OperandVec;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001859
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001860 RuleMatcher &Rule;
1861
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001862 /// The operands to match. All rendered operands must be present even if the
1863 /// condition is always true.
1864 OperandVec Operands;
Roman Tereshin19da6672018-05-22 04:31:50 +00001865 bool NumOperandsCheck = true;
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001866
Daniel Sanders05540042017-08-08 10:44:31 +00001867 std::string SymbolicName;
Quentin Colombetaad20be2017-12-15 23:07:42 +00001868 unsigned InsnVarID;
Daniel Sanders05540042017-08-08 10:44:31 +00001869
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001870public:
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001871 InstructionMatcher(RuleMatcher &Rule, StringRef SymbolicName)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001872 : Rule(Rule), SymbolicName(SymbolicName) {
1873 // We create a new instruction matcher.
1874 // Get a new ID for that instruction.
1875 InsnVarID = Rule.implicitlyDefineInsnVar(*this);
1876 }
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001877
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001878 /// Construct a new instruction predicate and add it to the matcher.
1879 template <class Kind, class... Args>
1880 Optional<Kind *> addPredicate(Args &&... args) {
1881 Predicates.emplace_back(
1882 llvm::make_unique<Kind>(getInsnVarID(), std::forward<Args>(args)...));
1883 return static_cast<Kind *>(Predicates.back().get());
1884 }
1885
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001886 RuleMatcher &getRuleMatcher() const { return Rule; }
Daniel Sanders05540042017-08-08 10:44:31 +00001887
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001888 unsigned getInsnVarID() const { return InsnVarID; }
Quentin Colombetaad20be2017-12-15 23:07:42 +00001889
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001890 /// Add an operand to the matcher.
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001891 OperandMatcher &addOperand(unsigned OpIdx, const std::string &SymbolicName,
1892 unsigned AllocatedTemporariesBaseID) {
1893 Operands.emplace_back(new OperandMatcher(*this, OpIdx, SymbolicName,
1894 AllocatedTemporariesBaseID));
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001895 if (!SymbolicName.empty())
1896 Rule.defineOperand(SymbolicName, *Operands.back());
1897
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001898 return *Operands.back();
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001899 }
1900
Daniel Sandersffc7d582017-03-29 15:37:18 +00001901 OperandMatcher &getOperand(unsigned OpIdx) {
1902 auto I = std::find_if(Operands.begin(), Operands.end(),
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001903 [&OpIdx](const std::unique_ptr<OperandMatcher> &X) {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001904 return X->getOpIdx() == OpIdx;
Daniel Sandersffc7d582017-03-29 15:37:18 +00001905 });
1906 if (I != Operands.end())
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001907 return **I;
Daniel Sandersffc7d582017-03-29 15:37:18 +00001908 llvm_unreachable("Failed to lookup operand");
1909 }
1910
Daniel Sanders05540042017-08-08 10:44:31 +00001911 StringRef getSymbolicName() const { return SymbolicName; }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001912 unsigned getNumOperands() const { return Operands.size(); }
Daniel Sandersbee57392017-04-04 13:25:23 +00001913 OperandVec::iterator operands_begin() { return Operands.begin(); }
1914 OperandVec::iterator operands_end() { return Operands.end(); }
1915 iterator_range<OperandVec::iterator> operands() {
1916 return make_range(operands_begin(), operands_end());
1917 }
Daniel Sandersffc7d582017-03-29 15:37:18 +00001918 OperandVec::const_iterator operands_begin() const { return Operands.begin(); }
1919 OperandVec::const_iterator operands_end() const { return Operands.end(); }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001920 iterator_range<OperandVec::const_iterator> operands() const {
1921 return make_range(operands_begin(), operands_end());
1922 }
Quentin Colombetec76d9c2017-12-18 19:47:41 +00001923 bool operands_empty() const { return Operands.empty(); }
1924
1925 void pop_front() { Operands.erase(Operands.begin()); }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001926
Roman Tereshin19da6672018-05-22 04:31:50 +00001927 void optimize();
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001928
1929 /// Emit MatchTable opcodes that test whether the instruction named in
1930 /// InsnVarName matches all the predicates and all the operands.
1931 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule) {
Roman Tereshin19da6672018-05-22 04:31:50 +00001932 if (NumOperandsCheck)
1933 InstructionNumOperandsMatcher(InsnVarID, getNumOperands())
1934 .emitPredicateOpcodes(Table, Rule);
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001935
Quentin Colombetaad20be2017-12-15 23:07:42 +00001936 emitPredicateListOpcodes(Table, Rule);
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001937
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001938 for (const auto &Operand : Operands)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001939 Operand->emitPredicateOpcodes(Table, Rule);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001940 }
Daniel Sanders759ff412017-02-24 13:58:11 +00001941
1942 /// Compare the priority of this object and B.
1943 ///
1944 /// Returns true if this object is more important than B.
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001945 bool isHigherPriorityThan(InstructionMatcher &B) {
Daniel Sanders759ff412017-02-24 13:58:11 +00001946 // Instruction matchers involving more operands have higher priority.
1947 if (Operands.size() > B.Operands.size())
1948 return true;
1949 if (Operands.size() < B.Operands.size())
1950 return false;
1951
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001952 for (auto &&P : zip(predicates(), B.predicates())) {
1953 auto L = static_cast<InstructionPredicateMatcher *>(std::get<0>(P).get());
1954 auto R = static_cast<InstructionPredicateMatcher *>(std::get<1>(P).get());
1955 if (L->isHigherPriorityThan(*R))
Daniel Sanders759ff412017-02-24 13:58:11 +00001956 return true;
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001957 if (R->isHigherPriorityThan(*L))
Daniel Sanders759ff412017-02-24 13:58:11 +00001958 return false;
1959 }
1960
1961 for (const auto &Operand : zip(Operands, B.Operands)) {
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001962 if (std::get<0>(Operand)->isHigherPriorityThan(*std::get<1>(Operand)))
Daniel Sanders759ff412017-02-24 13:58:11 +00001963 return true;
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001964 if (std::get<1>(Operand)->isHigherPriorityThan(*std::get<0>(Operand)))
Daniel Sanders759ff412017-02-24 13:58:11 +00001965 return false;
1966 }
1967
1968 return false;
1969 };
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001970
1971 /// Report the maximum number of temporary operands needed by the instruction
1972 /// matcher.
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001973 unsigned countRendererFns() {
1974 return std::accumulate(
1975 predicates().begin(), predicates().end(), 0,
1976 [](unsigned A,
1977 const std::unique_ptr<PredicateMatcher> &Predicate) {
1978 return A + Predicate->countRendererFns();
1979 }) +
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001980 std::accumulate(
1981 Operands.begin(), Operands.end(), 0,
1982 [](unsigned A, const std::unique_ptr<OperandMatcher> &Operand) {
Daniel Sanders2deea182017-04-22 15:11:04 +00001983 return A + Operand->countRendererFns();
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001984 });
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001985 }
Daniel Sanders05540042017-08-08 10:44:31 +00001986
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001987 InstructionOpcodeMatcher &getOpcodeMatcher() {
1988 for (auto &P : predicates())
1989 if (auto *OpMatcher = dyn_cast<InstructionOpcodeMatcher>(P.get()))
1990 return *OpMatcher;
1991 llvm_unreachable("Didn't find an opcode matcher");
1992 }
1993
1994 bool isConstantInstruction() {
1995 return getOpcodeMatcher().isConstantInstruction();
Daniel Sanders05540042017-08-08 10:44:31 +00001996 }
Roman Tereshin19da6672018-05-22 04:31:50 +00001997
1998 StringRef getOpcode() { return getOpcodeMatcher().getOpcode(); }
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001999};
2000
Roman Tereshin19da6672018-05-22 04:31:50 +00002001StringRef RuleMatcher::getOpcode() const {
2002 return Matchers.front()->getOpcode();
2003}
2004
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002005unsigned RuleMatcher::getNumOperands() const {
2006 return Matchers.front()->getNumOperands();
2007}
2008
Roman Tereshin9a9fa492018-05-23 21:30:16 +00002009LLTCodeGen RuleMatcher::getFirstConditionAsRootType() {
2010 InstructionMatcher &InsnMatcher = *Matchers.front();
2011 if (!InsnMatcher.predicates_empty())
2012 if (const auto *TM =
2013 dyn_cast<LLTOperandMatcher>(&**InsnMatcher.predicates_begin()))
2014 if (TM->getInsnVarID() == 0 && TM->getOpIdx() == 0)
2015 return TM->getTy();
2016 return {};
2017}
2018
Daniel Sandersbee57392017-04-04 13:25:23 +00002019/// Generates code to check that the operand is a register defined by an
2020/// instruction that matches the given instruction matcher.
2021///
2022/// For example, the pattern:
2023/// (set $dst, (G_MUL (G_ADD $src1, $src2), $src3))
2024/// would use an InstructionOperandMatcher for operand 1 of the G_MUL to match
2025/// the:
2026/// (G_ADD $src1, $src2)
2027/// subpattern.
2028class InstructionOperandMatcher : public OperandPredicateMatcher {
2029protected:
2030 std::unique_ptr<InstructionMatcher> InsnMatcher;
2031
2032public:
Quentin Colombeteba10cb2017-12-18 22:12:13 +00002033 InstructionOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
2034 RuleMatcher &Rule, StringRef SymbolicName)
Quentin Colombetaad20be2017-12-15 23:07:42 +00002035 : OperandPredicateMatcher(OPM_Instruction, InsnVarID, OpIdx),
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002036 InsnMatcher(new InstructionMatcher(Rule, SymbolicName)) {}
Daniel Sandersbee57392017-04-04 13:25:23 +00002037
Quentin Colombet063d7982017-12-14 23:44:07 +00002038 static bool classof(const PredicateMatcher *P) {
Daniel Sandersbee57392017-04-04 13:25:23 +00002039 return P->getKind() == OPM_Instruction;
2040 }
2041
2042 InstructionMatcher &getInsnMatcher() const { return *InsnMatcher; }
2043
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002044 void emitCaptureOpcodes(MatchTable &Table, RuleMatcher &Rule) const {
2045 const unsigned NewInsnVarID = InsnMatcher->getInsnVarID();
2046 Table << MatchTable::Opcode("GIM_RecordInsn")
2047 << MatchTable::Comment("DefineMI")
2048 << MatchTable::IntValue(NewInsnVarID) << MatchTable::Comment("MI")
2049 << MatchTable::IntValue(getInsnVarID())
2050 << MatchTable::Comment("OpIdx") << MatchTable::IntValue(getOpIdx())
2051 << MatchTable::Comment("MIs[" + llvm::to_string(NewInsnVarID) + "]")
2052 << MatchTable::LineBreak;
Daniel Sandersbee57392017-04-04 13:25:23 +00002053 }
2054
Quentin Colombetaad20be2017-12-15 23:07:42 +00002055 void emitPredicateOpcodes(MatchTable &Table,
2056 RuleMatcher &Rule) const override {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002057 emitCaptureOpcodes(Table, Rule);
Quentin Colombetaad20be2017-12-15 23:07:42 +00002058 InsnMatcher->emitPredicateOpcodes(Table, Rule);
Daniel Sandersbee57392017-04-04 13:25:23 +00002059 }
Daniel Sanders12e6e702018-01-17 20:34:29 +00002060
2061 bool isHigherPriorityThan(const OperandPredicateMatcher &B) const override {
2062 if (OperandPredicateMatcher::isHigherPriorityThan(B))
2063 return true;
2064 if (B.OperandPredicateMatcher::isHigherPriorityThan(*this))
2065 return false;
2066
2067 if (const InstructionOperandMatcher *BP =
2068 dyn_cast<InstructionOperandMatcher>(&B))
2069 if (InsnMatcher->isHigherPriorityThan(*BP->InsnMatcher))
2070 return true;
2071 return false;
2072 }
Daniel Sandersbee57392017-04-04 13:25:23 +00002073};
2074
Roman Tereshin19da6672018-05-22 04:31:50 +00002075void InstructionMatcher::optimize() {
2076 SmallVector<std::unique_ptr<PredicateMatcher>, 8> Stash;
2077 const auto &OpcMatcher = getOpcodeMatcher();
2078
2079 Stash.push_back(predicates_pop_front());
2080 if (Stash.back().get() == &OpcMatcher) {
2081 if (NumOperandsCheck && OpcMatcher.getNumOperands() < getNumOperands())
2082 Stash.emplace_back(
2083 new InstructionNumOperandsMatcher(InsnVarID, getNumOperands()));
2084 NumOperandsCheck = false;
Roman Tereshinfedae332018-05-23 02:04:19 +00002085
2086 for (auto &OM : Operands)
2087 for (auto &OP : OM->predicates())
2088 if (isa<IntrinsicIDOperandMatcher>(OP)) {
2089 Stash.push_back(std::move(OP));
2090 OM->eraseNullPredicates();
2091 break;
2092 }
Roman Tereshin19da6672018-05-22 04:31:50 +00002093 }
2094
2095 if (InsnVarID > 0) {
2096 assert(!Operands.empty() && "Nested instruction is expected to def a vreg");
2097 for (auto &OP : Operands[0]->predicates())
2098 OP.reset();
2099 Operands[0]->eraseNullPredicates();
2100 }
Roman Tereshinb1ba1272018-05-23 19:16:59 +00002101 for (auto &OM : Operands) {
2102 for (auto &OP : OM->predicates())
2103 if (isa<LLTOperandMatcher>(OP))
2104 Stash.push_back(std::move(OP));
2105 OM->eraseNullPredicates();
2106 }
Roman Tereshin19da6672018-05-22 04:31:50 +00002107 while (!Stash.empty())
2108 prependPredicate(Stash.pop_back_val());
2109}
2110
Daniel Sanders43c882c2017-02-01 10:53:10 +00002111//===- Actions ------------------------------------------------------------===//
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002112class OperandRenderer {
2113public:
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002114 enum RendererKind {
2115 OR_Copy,
Daniel Sandersd66e0902017-10-23 18:19:24 +00002116 OR_CopyOrAddZeroReg,
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002117 OR_CopySubReg,
Daniel Sanders05540042017-08-08 10:44:31 +00002118 OR_CopyConstantAsImm,
Daniel Sanders11300ce2017-10-13 21:28:03 +00002119 OR_CopyFConstantAsFPImm,
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002120 OR_Imm,
2121 OR_Register,
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002122 OR_TempRegister,
Volkan Kelesf7f25682018-01-16 18:44:05 +00002123 OR_ComplexPattern,
2124 OR_Custom
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002125 };
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002126
2127protected:
2128 RendererKind Kind;
2129
2130public:
2131 OperandRenderer(RendererKind Kind) : Kind(Kind) {}
2132 virtual ~OperandRenderer() {}
2133
2134 RendererKind getKind() const { return Kind; }
2135
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002136 virtual void emitRenderOpcodes(MatchTable &Table,
2137 RuleMatcher &Rule) const = 0;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002138};
2139
2140/// A CopyRenderer emits code to copy a single operand from an existing
2141/// instruction to the one being built.
2142class CopyRenderer : public OperandRenderer {
2143protected:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002144 unsigned NewInsnID;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002145 /// The name of the operand.
2146 const StringRef SymbolicName;
2147
2148public:
Daniel Sandersbd83ad42017-10-24 01:48:34 +00002149 CopyRenderer(unsigned NewInsnID, StringRef SymbolicName)
2150 : OperandRenderer(OR_Copy), NewInsnID(NewInsnID),
Daniel Sanders05540042017-08-08 10:44:31 +00002151 SymbolicName(SymbolicName) {
2152 assert(!SymbolicName.empty() && "Cannot copy from an unspecified source");
2153 }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002154
2155 static bool classof(const OperandRenderer *R) {
2156 return R->getKind() == OR_Copy;
2157 }
2158
2159 const StringRef getSymbolicName() const { return SymbolicName; }
2160
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002161 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002162 const OperandMatcher &Operand = Rule.getOperandMatcher(SymbolicName);
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002163 unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002164 Table << MatchTable::Opcode("GIR_Copy") << MatchTable::Comment("NewInsnID")
2165 << MatchTable::IntValue(NewInsnID) << MatchTable::Comment("OldInsnID")
2166 << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002167 << MatchTable::IntValue(Operand.getOpIdx())
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002168 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002169 }
2170};
2171
Daniel Sandersd66e0902017-10-23 18:19:24 +00002172/// A CopyOrAddZeroRegRenderer emits code to copy a single operand from an
2173/// existing instruction to the one being built. If the operand turns out to be
2174/// a 'G_CONSTANT 0' then it replaces the operand with a zero register.
2175class CopyOrAddZeroRegRenderer : public OperandRenderer {
2176protected:
2177 unsigned NewInsnID;
2178 /// The name of the operand.
2179 const StringRef SymbolicName;
2180 const Record *ZeroRegisterDef;
2181
2182public:
2183 CopyOrAddZeroRegRenderer(unsigned NewInsnID,
Daniel Sandersd66e0902017-10-23 18:19:24 +00002184 StringRef SymbolicName, Record *ZeroRegisterDef)
2185 : OperandRenderer(OR_CopyOrAddZeroReg), NewInsnID(NewInsnID),
2186 SymbolicName(SymbolicName), ZeroRegisterDef(ZeroRegisterDef) {
2187 assert(!SymbolicName.empty() && "Cannot copy from an unspecified source");
2188 }
2189
2190 static bool classof(const OperandRenderer *R) {
2191 return R->getKind() == OR_CopyOrAddZeroReg;
2192 }
2193
2194 const StringRef getSymbolicName() const { return SymbolicName; }
2195
2196 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2197 const OperandMatcher &Operand = Rule.getOperandMatcher(SymbolicName);
2198 unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
2199 Table << MatchTable::Opcode("GIR_CopyOrAddZeroReg")
2200 << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
2201 << MatchTable::Comment("OldInsnID")
2202 << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002203 << MatchTable::IntValue(Operand.getOpIdx())
Daniel Sandersd66e0902017-10-23 18:19:24 +00002204 << MatchTable::NamedValue(
2205 (ZeroRegisterDef->getValue("Namespace")
2206 ? ZeroRegisterDef->getValueAsString("Namespace")
2207 : ""),
2208 ZeroRegisterDef->getName())
2209 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2210 }
2211};
2212
Daniel Sanders05540042017-08-08 10:44:31 +00002213/// A CopyConstantAsImmRenderer emits code to render a G_CONSTANT instruction to
2214/// an extended immediate operand.
2215class CopyConstantAsImmRenderer : public OperandRenderer {
2216protected:
2217 unsigned NewInsnID;
2218 /// The name of the operand.
2219 const std::string SymbolicName;
2220 bool Signed;
2221
2222public:
2223 CopyConstantAsImmRenderer(unsigned NewInsnID, StringRef SymbolicName)
2224 : OperandRenderer(OR_CopyConstantAsImm), NewInsnID(NewInsnID),
2225 SymbolicName(SymbolicName), Signed(true) {}
2226
2227 static bool classof(const OperandRenderer *R) {
2228 return R->getKind() == OR_CopyConstantAsImm;
2229 }
2230
2231 const StringRef getSymbolicName() const { return SymbolicName; }
2232
2233 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002234 InstructionMatcher &InsnMatcher = Rule.getInstructionMatcher(SymbolicName);
Daniel Sanders05540042017-08-08 10:44:31 +00002235 unsigned OldInsnVarID = Rule.getInsnVarID(InsnMatcher);
2236 Table << MatchTable::Opcode(Signed ? "GIR_CopyConstantAsSImm"
2237 : "GIR_CopyConstantAsUImm")
2238 << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
2239 << MatchTable::Comment("OldInsnID")
2240 << MatchTable::IntValue(OldInsnVarID)
2241 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2242 }
2243};
2244
Daniel Sanders11300ce2017-10-13 21:28:03 +00002245/// A CopyFConstantAsFPImmRenderer emits code to render a G_FCONSTANT
2246/// instruction to an extended immediate operand.
2247class CopyFConstantAsFPImmRenderer : public OperandRenderer {
2248protected:
2249 unsigned NewInsnID;
2250 /// The name of the operand.
2251 const std::string SymbolicName;
2252
2253public:
2254 CopyFConstantAsFPImmRenderer(unsigned NewInsnID, StringRef SymbolicName)
2255 : OperandRenderer(OR_CopyFConstantAsFPImm), NewInsnID(NewInsnID),
2256 SymbolicName(SymbolicName) {}
2257
2258 static bool classof(const OperandRenderer *R) {
2259 return R->getKind() == OR_CopyFConstantAsFPImm;
2260 }
2261
2262 const StringRef getSymbolicName() const { return SymbolicName; }
2263
2264 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002265 InstructionMatcher &InsnMatcher = Rule.getInstructionMatcher(SymbolicName);
Daniel Sanders11300ce2017-10-13 21:28:03 +00002266 unsigned OldInsnVarID = Rule.getInsnVarID(InsnMatcher);
2267 Table << MatchTable::Opcode("GIR_CopyFConstantAsFPImm")
2268 << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
2269 << MatchTable::Comment("OldInsnID")
2270 << MatchTable::IntValue(OldInsnVarID)
2271 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2272 }
2273};
2274
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002275/// A CopySubRegRenderer emits code to copy a single register operand from an
2276/// existing instruction to the one being built and indicate that only a
2277/// subregister should be copied.
2278class CopySubRegRenderer : public OperandRenderer {
2279protected:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002280 unsigned NewInsnID;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002281 /// The name of the operand.
2282 const StringRef SymbolicName;
2283 /// The subregister to extract.
2284 const CodeGenSubRegIndex *SubReg;
2285
2286public:
Daniel Sandersbd83ad42017-10-24 01:48:34 +00002287 CopySubRegRenderer(unsigned NewInsnID, StringRef SymbolicName,
2288 const CodeGenSubRegIndex *SubReg)
2289 : OperandRenderer(OR_CopySubReg), NewInsnID(NewInsnID),
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002290 SymbolicName(SymbolicName), SubReg(SubReg) {}
2291
2292 static bool classof(const OperandRenderer *R) {
2293 return R->getKind() == OR_CopySubReg;
2294 }
2295
2296 const StringRef getSymbolicName() const { return SymbolicName; }
2297
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002298 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002299 const OperandMatcher &Operand = Rule.getOperandMatcher(SymbolicName);
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002300 unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002301 Table << MatchTable::Opcode("GIR_CopySubReg")
2302 << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
2303 << MatchTable::Comment("OldInsnID")
2304 << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002305 << MatchTable::IntValue(Operand.getOpIdx())
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002306 << MatchTable::Comment("SubRegIdx")
2307 << MatchTable::IntValue(SubReg->EnumValue)
2308 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002309 }
2310};
2311
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002312/// Adds a specific physical register to the instruction being built.
2313/// This is typically useful for WZR/XZR on AArch64.
2314class AddRegisterRenderer : public OperandRenderer {
2315protected:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002316 unsigned InsnID;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002317 const Record *RegisterDef;
2318
2319public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002320 AddRegisterRenderer(unsigned InsnID, const Record *RegisterDef)
2321 : OperandRenderer(OR_Register), InsnID(InsnID), RegisterDef(RegisterDef) {
2322 }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002323
2324 static bool classof(const OperandRenderer *R) {
2325 return R->getKind() == OR_Register;
2326 }
2327
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002328 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2329 Table << MatchTable::Opcode("GIR_AddRegister")
2330 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2331 << MatchTable::NamedValue(
2332 (RegisterDef->getValue("Namespace")
2333 ? RegisterDef->getValueAsString("Namespace")
2334 : ""),
2335 RegisterDef->getName())
2336 << MatchTable::LineBreak;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002337 }
2338};
2339
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002340/// Adds a specific temporary virtual register to the instruction being built.
2341/// This is used to chain instructions together when emitting multiple
2342/// instructions.
2343class TempRegRenderer : public OperandRenderer {
2344protected:
2345 unsigned InsnID;
2346 unsigned TempRegID;
2347 bool IsDef;
2348
2349public:
2350 TempRegRenderer(unsigned InsnID, unsigned TempRegID, bool IsDef = false)
2351 : OperandRenderer(OR_Register), InsnID(InsnID), TempRegID(TempRegID),
2352 IsDef(IsDef) {}
2353
2354 static bool classof(const OperandRenderer *R) {
2355 return R->getKind() == OR_TempRegister;
2356 }
2357
2358 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2359 Table << MatchTable::Opcode("GIR_AddTempRegister")
2360 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2361 << MatchTable::Comment("TempRegID") << MatchTable::IntValue(TempRegID)
2362 << MatchTable::Comment("TempRegFlags");
2363 if (IsDef)
2364 Table << MatchTable::NamedValue("RegState::Define");
2365 else
2366 Table << MatchTable::IntValue(0);
2367 Table << MatchTable::LineBreak;
2368 }
2369};
2370
Daniel Sanders0ed28822017-04-12 08:23:08 +00002371/// Adds a specific immediate to the instruction being built.
2372class ImmRenderer : public OperandRenderer {
2373protected:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002374 unsigned InsnID;
Daniel Sanders0ed28822017-04-12 08:23:08 +00002375 int64_t Imm;
2376
2377public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002378 ImmRenderer(unsigned InsnID, int64_t Imm)
2379 : OperandRenderer(OR_Imm), InsnID(InsnID), Imm(Imm) {}
Daniel Sanders0ed28822017-04-12 08:23:08 +00002380
2381 static bool classof(const OperandRenderer *R) {
2382 return R->getKind() == OR_Imm;
2383 }
2384
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002385 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2386 Table << MatchTable::Opcode("GIR_AddImm") << MatchTable::Comment("InsnID")
2387 << MatchTable::IntValue(InsnID) << MatchTable::Comment("Imm")
2388 << MatchTable::IntValue(Imm) << MatchTable::LineBreak;
Daniel Sanders0ed28822017-04-12 08:23:08 +00002389 }
2390};
2391
Daniel Sanders2deea182017-04-22 15:11:04 +00002392/// Adds operands by calling a renderer function supplied by the ComplexPattern
2393/// matcher function.
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002394class RenderComplexPatternOperand : public OperandRenderer {
2395private:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002396 unsigned InsnID;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002397 const Record &TheDef;
Daniel Sanders2deea182017-04-22 15:11:04 +00002398 /// The name of the operand.
2399 const StringRef SymbolicName;
2400 /// The renderer number. This must be unique within a rule since it's used to
2401 /// identify a temporary variable to hold the renderer function.
2402 unsigned RendererID;
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002403 /// When provided, this is the suboperand of the ComplexPattern operand to
2404 /// render. Otherwise all the suboperands will be rendered.
2405 Optional<unsigned> SubOperand;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002406
2407 unsigned getNumOperands() const {
2408 return TheDef.getValueAsDag("Operands")->getNumArgs();
2409 }
2410
2411public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002412 RenderComplexPatternOperand(unsigned InsnID, const Record &TheDef,
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002413 StringRef SymbolicName, unsigned RendererID,
2414 Optional<unsigned> SubOperand = None)
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002415 : OperandRenderer(OR_ComplexPattern), InsnID(InsnID), TheDef(TheDef),
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002416 SymbolicName(SymbolicName), RendererID(RendererID),
2417 SubOperand(SubOperand) {}
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002418
2419 static bool classof(const OperandRenderer *R) {
2420 return R->getKind() == OR_ComplexPattern;
2421 }
2422
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002423 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002424 Table << MatchTable::Opcode(SubOperand.hasValue() ? "GIR_ComplexSubOperandRenderer"
2425 : "GIR_ComplexRenderer")
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002426 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2427 << MatchTable::Comment("RendererID")
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002428 << MatchTable::IntValue(RendererID);
2429 if (SubOperand.hasValue())
2430 Table << MatchTable::Comment("SubOperand")
2431 << MatchTable::IntValue(SubOperand.getValue());
2432 Table << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002433 }
2434};
2435
Volkan Kelesf7f25682018-01-16 18:44:05 +00002436class CustomRenderer : public OperandRenderer {
2437protected:
2438 unsigned InsnID;
2439 const Record &Renderer;
2440 /// The name of the operand.
2441 const std::string SymbolicName;
2442
2443public:
2444 CustomRenderer(unsigned InsnID, const Record &Renderer,
2445 StringRef SymbolicName)
2446 : OperandRenderer(OR_Custom), InsnID(InsnID), Renderer(Renderer),
2447 SymbolicName(SymbolicName) {}
2448
2449 static bool classof(const OperandRenderer *R) {
2450 return R->getKind() == OR_Custom;
2451 }
2452
2453 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002454 InstructionMatcher &InsnMatcher = Rule.getInstructionMatcher(SymbolicName);
Volkan Kelesf7f25682018-01-16 18:44:05 +00002455 unsigned OldInsnVarID = Rule.getInsnVarID(InsnMatcher);
2456 Table << MatchTable::Opcode("GIR_CustomRenderer")
2457 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2458 << MatchTable::Comment("OldInsnID")
2459 << MatchTable::IntValue(OldInsnVarID)
2460 << MatchTable::Comment("Renderer")
2461 << MatchTable::NamedValue(
2462 "GICR_" + Renderer.getValueAsString("RendererFn").str())
2463 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2464 }
2465};
2466
Ahmed Bougacha56ca3a92017-02-04 00:47:10 +00002467/// An action taken when all Matcher predicates succeeded for a parent rule.
2468///
2469/// Typical actions include:
2470/// * Changing the opcode of an instruction.
2471/// * Adding an operand to an instruction.
Daniel Sanders43c882c2017-02-01 10:53:10 +00002472class MatchAction {
2473public:
2474 virtual ~MatchAction() {}
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002475
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002476 /// Emit the MatchTable opcodes to implement the action.
Daniel Sandersa7b75262017-10-31 18:50:24 +00002477 virtual void emitActionOpcodes(MatchTable &Table,
2478 RuleMatcher &Rule) const = 0;
Daniel Sanders43c882c2017-02-01 10:53:10 +00002479};
2480
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +00002481/// Generates a comment describing the matched rule being acted upon.
2482class DebugCommentAction : public MatchAction {
2483private:
Daniel Sanders6ea17ed2017-10-31 18:07:03 +00002484 std::string S;
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +00002485
2486public:
Daniel Sanders6ea17ed2017-10-31 18:07:03 +00002487 DebugCommentAction(StringRef S) : S(S) {}
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +00002488
Daniel Sandersa7b75262017-10-31 18:50:24 +00002489 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sanders6ea17ed2017-10-31 18:07:03 +00002490 Table << MatchTable::Comment(S) << MatchTable::LineBreak;
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +00002491 }
2492};
2493
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002494/// Generates code to build an instruction or mutate an existing instruction
2495/// into the desired instruction when this is possible.
2496class BuildMIAction : public MatchAction {
Daniel Sanders43c882c2017-02-01 10:53:10 +00002497private:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002498 unsigned InsnID;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002499 const CodeGenInstruction *I;
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002500 InstructionMatcher *Matched;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002501 std::vector<std::unique_ptr<OperandRenderer>> OperandRenderers;
2502
2503 /// True if the instruction can be built solely by mutating the opcode.
Daniel Sandersa7b75262017-10-31 18:50:24 +00002504 bool canMutate(RuleMatcher &Rule, const InstructionMatcher *Insn) const {
2505 if (!Insn)
Daniel Sandersab1d1192017-10-24 18:11:54 +00002506 return false;
2507
Daniel Sandersa7b75262017-10-31 18:50:24 +00002508 if (OperandRenderers.size() != Insn->getNumOperands())
Daniel Sanderse9fdba32017-04-29 17:30:09 +00002509 return false;
2510
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002511 for (const auto &Renderer : enumerate(OperandRenderers)) {
Zachary Turner309a0882017-03-13 16:24:10 +00002512 if (const auto *Copy = dyn_cast<CopyRenderer>(&*Renderer.value())) {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002513 const OperandMatcher &OM = Rule.getOperandMatcher(Copy->getSymbolicName());
Daniel Sandersa7b75262017-10-31 18:50:24 +00002514 if (Insn != &OM.getInstructionMatcher() ||
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002515 OM.getOpIdx() != Renderer.index())
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002516 return false;
2517 } else
2518 return false;
2519 }
2520
2521 return true;
2522 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002523
Daniel Sanders43c882c2017-02-01 10:53:10 +00002524public:
Daniel Sandersa7b75262017-10-31 18:50:24 +00002525 BuildMIAction(unsigned InsnID, const CodeGenInstruction *I)
2526 : InsnID(InsnID), I(I), Matched(nullptr) {}
2527
Daniel Sanders08464522018-01-29 21:09:12 +00002528 unsigned getInsnID() const { return InsnID; }
Daniel Sandersdf258e32017-10-31 19:09:29 +00002529 const CodeGenInstruction *getCGI() const { return I; }
2530
Daniel Sandersa7b75262017-10-31 18:50:24 +00002531 void chooseInsnToMutate(RuleMatcher &Rule) {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002532 for (auto *MutateCandidate : Rule.mutatable_insns()) {
Daniel Sandersa7b75262017-10-31 18:50:24 +00002533 if (canMutate(Rule, MutateCandidate)) {
2534 // Take the first one we're offered that we're able to mutate.
2535 Rule.reserveInsnMatcherForMutation(MutateCandidate);
2536 Matched = MutateCandidate;
2537 return;
2538 }
2539 }
2540 }
Daniel Sanders43c882c2017-02-01 10:53:10 +00002541
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002542 template <class Kind, class... Args>
2543 Kind &addRenderer(Args&&... args) {
2544 OperandRenderers.emplace_back(
Daniel Sanders198447a2017-11-01 00:29:47 +00002545 llvm::make_unique<Kind>(InsnID, std::forward<Args>(args)...));
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002546 return *static_cast<Kind *>(OperandRenderers.back().get());
2547 }
2548
Daniel Sandersa7b75262017-10-31 18:50:24 +00002549 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2550 if (Matched) {
2551 assert(canMutate(Rule, Matched) &&
2552 "Arranged to mutate an insn that isn't mutatable");
2553
2554 unsigned RecycleInsnID = Rule.getInsnVarID(*Matched);
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002555 Table << MatchTable::Opcode("GIR_MutateOpcode")
2556 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2557 << MatchTable::Comment("RecycleInsnID")
2558 << MatchTable::IntValue(RecycleInsnID)
2559 << MatchTable::Comment("Opcode")
2560 << MatchTable::NamedValue(I->Namespace, I->TheDef->getName())
2561 << MatchTable::LineBreak;
Tim Northover4340d642017-03-20 21:58:23 +00002562
2563 if (!I->ImplicitDefs.empty() || !I->ImplicitUses.empty()) {
Tim Northover4340d642017-03-20 21:58:23 +00002564 for (auto Def : I->ImplicitDefs) {
Diana Picus8abcbbb2017-05-02 09:40:49 +00002565 auto Namespace = Def->getValue("Namespace")
2566 ? Def->getValueAsString("Namespace")
2567 : "";
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002568 Table << MatchTable::Opcode("GIR_AddImplicitDef")
2569 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2570 << MatchTable::NamedValue(Namespace, Def->getName())
2571 << MatchTable::LineBreak;
Tim Northover4340d642017-03-20 21:58:23 +00002572 }
2573 for (auto Use : I->ImplicitUses) {
Diana Picus8abcbbb2017-05-02 09:40:49 +00002574 auto Namespace = Use->getValue("Namespace")
2575 ? Use->getValueAsString("Namespace")
2576 : "";
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002577 Table << MatchTable::Opcode("GIR_AddImplicitUse")
2578 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2579 << MatchTable::NamedValue(Namespace, Use->getName())
2580 << MatchTable::LineBreak;
Tim Northover4340d642017-03-20 21:58:23 +00002581 }
2582 }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002583 return;
2584 }
2585
2586 // TODO: Simple permutation looks like it could be almost as common as
2587 // mutation due to commutative operations.
2588
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002589 Table << MatchTable::Opcode("GIR_BuildMI") << MatchTable::Comment("InsnID")
2590 << MatchTable::IntValue(InsnID) << MatchTable::Comment("Opcode")
2591 << MatchTable::NamedValue(I->Namespace, I->TheDef->getName())
2592 << MatchTable::LineBreak;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002593 for (const auto &Renderer : OperandRenderers)
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002594 Renderer->emitRenderOpcodes(Table, Rule);
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002595
Florian Hahn3bc3ec62017-08-03 14:48:22 +00002596 if (I->mayLoad || I->mayStore) {
2597 Table << MatchTable::Opcode("GIR_MergeMemOperands")
2598 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2599 << MatchTable::Comment("MergeInsnID's");
2600 // Emit the ID's for all the instructions that are matched by this rule.
2601 // TODO: Limit this to matched instructions that mayLoad/mayStore or have
2602 // some other means of having a memoperand. Also limit this to
2603 // emitted instructions that expect to have a memoperand too. For
2604 // example, (G_SEXT (G_LOAD x)) that results in separate load and
2605 // sign-extend instructions shouldn't put the memoperand on the
2606 // sign-extend since it has no effect there.
2607 std::vector<unsigned> MergeInsnIDs;
2608 for (const auto &IDMatcherPair : Rule.defined_insn_vars())
2609 MergeInsnIDs.push_back(IDMatcherPair.second);
Mandeep Singh Grang1b0e2f22018-04-06 20:18:05 +00002610 llvm::sort(MergeInsnIDs.begin(), MergeInsnIDs.end());
Florian Hahn3bc3ec62017-08-03 14:48:22 +00002611 for (const auto &MergeInsnID : MergeInsnIDs)
2612 Table << MatchTable::IntValue(MergeInsnID);
Daniel Sanders05540042017-08-08 10:44:31 +00002613 Table << MatchTable::NamedValue("GIU_MergeMemOperands_EndOfList")
2614 << MatchTable::LineBreak;
Florian Hahn3bc3ec62017-08-03 14:48:22 +00002615 }
2616
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002617 // FIXME: This is a hack but it's sufficient for ISel. We'll need to do
2618 // better for combines. Particularly when there are multiple match
2619 // roots.
2620 if (InsnID == 0)
2621 Table << MatchTable::Opcode("GIR_EraseFromParent")
2622 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2623 << MatchTable::LineBreak;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002624 }
2625};
2626
2627/// Generates code to constrain the operands of an output instruction to the
2628/// register classes specified by the definition of that instruction.
2629class ConstrainOperandsToDefinitionAction : public MatchAction {
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002630 unsigned InsnID;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002631
2632public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002633 ConstrainOperandsToDefinitionAction(unsigned InsnID) : InsnID(InsnID) {}
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002634
Daniel Sandersa7b75262017-10-31 18:50:24 +00002635 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002636 Table << MatchTable::Opcode("GIR_ConstrainSelectedInstOperands")
2637 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2638 << MatchTable::LineBreak;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002639 }
2640};
2641
2642/// Generates code to constrain the specified operand of an output instruction
2643/// to the specified register class.
2644class ConstrainOperandToRegClassAction : public MatchAction {
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002645 unsigned InsnID;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002646 unsigned OpIdx;
2647 const CodeGenRegisterClass &RC;
2648
2649public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002650 ConstrainOperandToRegClassAction(unsigned InsnID, unsigned OpIdx,
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002651 const CodeGenRegisterClass &RC)
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002652 : InsnID(InsnID), OpIdx(OpIdx), RC(RC) {}
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002653
Daniel Sandersa7b75262017-10-31 18:50:24 +00002654 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002655 Table << MatchTable::Opcode("GIR_ConstrainOperandRC")
2656 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2657 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
2658 << MatchTable::Comment("RC " + RC.getName())
2659 << MatchTable::IntValue(RC.EnumValue) << MatchTable::LineBreak;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002660 }
2661};
2662
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002663/// Generates code to create a temporary register which can be used to chain
2664/// instructions together.
2665class MakeTempRegisterAction : public MatchAction {
2666private:
2667 LLTCodeGen Ty;
2668 unsigned TempRegID;
2669
2670public:
2671 MakeTempRegisterAction(const LLTCodeGen &Ty, unsigned TempRegID)
2672 : Ty(Ty), TempRegID(TempRegID) {}
2673
2674 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2675 Table << MatchTable::Opcode("GIR_MakeTempReg")
2676 << MatchTable::Comment("TempRegID") << MatchTable::IntValue(TempRegID)
2677 << MatchTable::Comment("TypeID")
2678 << MatchTable::NamedValue(Ty.getCxxEnumValue())
2679 << MatchTable::LineBreak;
2680 }
2681};
2682
Daniel Sanders05540042017-08-08 10:44:31 +00002683InstructionMatcher &RuleMatcher::addInstructionMatcher(StringRef SymbolicName) {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002684 Matchers.emplace_back(new InstructionMatcher(*this, SymbolicName));
Daniel Sandersa7b75262017-10-31 18:50:24 +00002685 MutatableInsns.insert(Matchers.back().get());
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002686 return *Matchers.back();
2687}
Ahmed Bougacha56ca3a92017-02-04 00:47:10 +00002688
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002689void RuleMatcher::addRequiredFeature(Record *Feature) {
2690 RequiredFeatures.push_back(Feature);
2691}
2692
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002693const std::vector<Record *> &RuleMatcher::getRequiredFeatures() const {
2694 return RequiredFeatures;
2695}
2696
Daniel Sanders7438b262017-10-31 23:03:18 +00002697// Emplaces an action of the specified Kind at the end of the action list.
2698//
2699// Returns a reference to the newly created action.
2700//
2701// Like std::vector::emplace_back(), may invalidate all iterators if the new
2702// size exceeds the capacity. Otherwise, only invalidates the past-the-end
2703// iterator.
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002704template <class Kind, class... Args>
2705Kind &RuleMatcher::addAction(Args &&... args) {
2706 Actions.emplace_back(llvm::make_unique<Kind>(std::forward<Args>(args)...));
2707 return *static_cast<Kind *>(Actions.back().get());
2708}
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002709
Daniel Sanders7438b262017-10-31 23:03:18 +00002710// Emplaces an action of the specified Kind before the given insertion point.
2711//
2712// Returns an iterator pointing at the newly created instruction.
2713//
2714// Like std::vector::insert(), may invalidate all iterators if the new size
2715// exceeds the capacity. Otherwise, only invalidates the iterators from the
2716// insertion point onwards.
2717template <class Kind, class... Args>
2718action_iterator RuleMatcher::insertAction(action_iterator InsertPt,
2719 Args &&... args) {
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002720 return Actions.emplace(InsertPt,
2721 llvm::make_unique<Kind>(std::forward<Args>(args)...));
Daniel Sanders7438b262017-10-31 23:03:18 +00002722}
Daniel Sandersdc662ff2017-01-26 11:10:14 +00002723
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002724unsigned RuleMatcher::implicitlyDefineInsnVar(InstructionMatcher &Matcher) {
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002725 unsigned NewInsnVarID = NextInsnVarID++;
2726 InsnVariableIDs[&Matcher] = NewInsnVarID;
2727 return NewInsnVarID;
Daniel Sandersb96f40d2017-03-20 15:20:42 +00002728}
2729
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002730unsigned RuleMatcher::getInsnVarID(InstructionMatcher &InsnMatcher) const {
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002731 const auto &I = InsnVariableIDs.find(&InsnMatcher);
2732 if (I != InsnVariableIDs.end())
Daniel Sandersb96f40d2017-03-20 15:20:42 +00002733 return I->second;
2734 llvm_unreachable("Matched Insn was not captured in a local variable");
2735}
2736
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002737void RuleMatcher::defineOperand(StringRef SymbolicName, OperandMatcher &OM) {
2738 if (DefinedOperands.find(SymbolicName) == DefinedOperands.end()) {
2739 DefinedOperands[SymbolicName] = &OM;
2740 return;
2741 }
2742
2743 // If the operand is already defined, then we must ensure both references in
2744 // the matcher have the exact same node.
2745 OM.addPredicate<SameOperandMatcher>(OM.getSymbolicName());
2746}
2747
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002748InstructionMatcher &
Daniel Sanders05540042017-08-08 10:44:31 +00002749RuleMatcher::getInstructionMatcher(StringRef SymbolicName) const {
2750 for (const auto &I : InsnVariableIDs)
2751 if (I.first->getSymbolicName() == SymbolicName)
2752 return *I.first;
2753 llvm_unreachable(
2754 ("Failed to lookup instruction " + SymbolicName).str().c_str());
2755}
2756
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002757const OperandMatcher &
2758RuleMatcher::getOperandMatcher(StringRef Name) const {
2759 const auto &I = DefinedOperands.find(Name);
2760
2761 if (I == DefinedOperands.end())
2762 PrintFatalError(SrcLoc, "Operand " + Name + " was not declared in matcher");
2763
2764 return *I->second;
2765}
2766
Daniel Sanders8e82af22017-07-27 11:03:45 +00002767void RuleMatcher::emit(MatchTable &Table) {
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002768 if (Matchers.empty())
2769 llvm_unreachable("Unexpected empty matcher!");
Daniel Sandersdc662ff2017-01-26 11:10:14 +00002770
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002771 // The representation supports rules that require multiple roots such as:
2772 // %ptr(p0) = ...
2773 // %elt0(s32) = G_LOAD %ptr
2774 // %1(p0) = G_ADD %ptr, 4
2775 // %elt1(s32) = G_LOAD p0 %1
2776 // which could be usefully folded into:
2777 // %ptr(p0) = ...
2778 // %elt0(s32), %elt1(s32) = TGT_LOAD_PAIR %ptr
2779 // on some targets but we don't need to make use of that yet.
2780 assert(Matchers.size() == 1 && "Cannot handle multi-root matchers yet");
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002781
Daniel Sanders8e82af22017-07-27 11:03:45 +00002782 unsigned LabelID = Table.allocateLabelID();
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002783 Table << MatchTable::Opcode("GIM_Try", +1)
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002784 << MatchTable::Comment("On fail goto")
2785 << MatchTable::JumpTarget(LabelID)
2786 << MatchTable::Comment(("Rule ID " + Twine(RuleID) + " //").str())
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002787 << MatchTable::LineBreak;
2788
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002789 if (!RequiredFeatures.empty()) {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002790 Table << MatchTable::Opcode("GIM_CheckFeatures")
2791 << MatchTable::NamedValue(getNameForFeatureBitset(RequiredFeatures))
2792 << MatchTable::LineBreak;
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002793 }
Daniel Sandersb96f40d2017-03-20 15:20:42 +00002794
Quentin Colombetaad20be2017-12-15 23:07:42 +00002795 Matchers.front()->emitPredicateOpcodes(Table, *this);
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002796
Daniel Sandersbee57392017-04-04 13:25:23 +00002797 // We must also check if it's safe to fold the matched instructions.
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002798 if (InsnVariableIDs.size() >= 2) {
Galina Kistanova1754fee2017-05-25 01:51:53 +00002799 // Invert the map to create stable ordering (by var names)
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002800 SmallVector<unsigned, 2> InsnIDs;
2801 for (const auto &Pair : InsnVariableIDs) {
Daniel Sandersbee57392017-04-04 13:25:23 +00002802 // Skip the root node since it isn't moving anywhere. Everything else is
2803 // sinking to meet it.
2804 if (Pair.first == Matchers.front().get())
2805 continue;
2806
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002807 InsnIDs.push_back(Pair.second);
Galina Kistanova1754fee2017-05-25 01:51:53 +00002808 }
Mandeep Singh Grang1b0e2f22018-04-06 20:18:05 +00002809 llvm::sort(InsnIDs.begin(), InsnIDs.end());
Galina Kistanova1754fee2017-05-25 01:51:53 +00002810
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002811 for (const auto &InsnID : InsnIDs) {
Daniel Sandersbee57392017-04-04 13:25:23 +00002812 // Reject the difficult cases until we have a more accurate check.
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002813 Table << MatchTable::Opcode("GIM_CheckIsSafeToFold")
2814 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2815 << MatchTable::LineBreak;
Daniel Sandersbee57392017-04-04 13:25:23 +00002816
2817 // FIXME: Emit checks to determine it's _actually_ safe to fold and/or
2818 // account for unsafe cases.
2819 //
2820 // Example:
2821 // MI1--> %0 = ...
2822 // %1 = ... %0
2823 // MI0--> %2 = ... %0
2824 // It's not safe to erase MI1. We currently handle this by not
2825 // erasing %0 (even when it's dead).
2826 //
2827 // Example:
2828 // MI1--> %0 = load volatile @a
2829 // %1 = load volatile @a
2830 // MI0--> %2 = ... %0
2831 // It's not safe to sink %0's def past %1. We currently handle
2832 // this by rejecting all loads.
2833 //
2834 // Example:
2835 // MI1--> %0 = load @a
2836 // %1 = store @a
2837 // MI0--> %2 = ... %0
2838 // It's not safe to sink %0's def past %1. We currently handle
2839 // this by rejecting all loads.
2840 //
2841 // Example:
2842 // G_CONDBR %cond, @BB1
2843 // BB0:
2844 // MI1--> %0 = load @a
2845 // G_BR @BB1
2846 // BB1:
2847 // MI0--> %2 = ... %0
2848 // It's not always safe to sink %0 across control flow. In this
2849 // case it may introduce a memory fault. We currentl handle this
2850 // by rejecting all loads.
2851 }
2852 }
2853
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002854 for (const auto &PM : EpilogueMatchers)
2855 PM->emitPredicateOpcodes(Table, *this);
2856
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002857 for (const auto &MA : Actions)
Daniel Sandersa7b75262017-10-31 18:50:24 +00002858 MA->emitActionOpcodes(Table, *this);
Daniel Sandersf76f3152017-11-16 00:46:35 +00002859
Roman Tereshinbeb39312018-05-02 20:15:11 +00002860 if (Table.isWithCoverage())
Daniel Sandersf76f3152017-11-16 00:46:35 +00002861 Table << MatchTable::Opcode("GIR_Coverage") << MatchTable::IntValue(RuleID)
2862 << MatchTable::LineBreak;
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002863 else
2864 Table << MatchTable::Comment(("GIR_Coverage, " + Twine(RuleID) + ",").str())
2865 << MatchTable::LineBreak;
Daniel Sandersf76f3152017-11-16 00:46:35 +00002866
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002867 Table << MatchTable::Opcode("GIR_Done", -1) << MatchTable::LineBreak
Daniel Sanders8e82af22017-07-27 11:03:45 +00002868 << MatchTable::Label(LabelID);
Volkan Keles4f3fa792018-01-25 00:18:52 +00002869 ++NumPatternEmitted;
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002870}
Daniel Sanders43c882c2017-02-01 10:53:10 +00002871
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002872bool RuleMatcher::isHigherPriorityThan(const RuleMatcher &B) const {
2873 // Rules involving more match roots have higher priority.
2874 if (Matchers.size() > B.Matchers.size())
2875 return true;
2876 if (Matchers.size() < B.Matchers.size())
Daniel Sanders759ff412017-02-24 13:58:11 +00002877 return false;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002878
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002879 for (const auto &Matcher : zip(Matchers, B.Matchers)) {
2880 if (std::get<0>(Matcher)->isHigherPriorityThan(*std::get<1>(Matcher)))
2881 return true;
2882 if (std::get<1>(Matcher)->isHigherPriorityThan(*std::get<0>(Matcher)))
2883 return false;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002884 }
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002885
2886 return false;
Simon Pilgrima7d1da82017-03-15 22:50:47 +00002887}
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002888
Daniel Sanders2deea182017-04-22 15:11:04 +00002889unsigned RuleMatcher::countRendererFns() const {
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002890 return std::accumulate(
2891 Matchers.begin(), Matchers.end(), 0,
2892 [](unsigned A, const std::unique_ptr<InstructionMatcher> &Matcher) {
Daniel Sanders2deea182017-04-22 15:11:04 +00002893 return A + Matcher->countRendererFns();
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002894 });
2895}
2896
Daniel Sanders05540042017-08-08 10:44:31 +00002897bool OperandPredicateMatcher::isHigherPriorityThan(
2898 const OperandPredicateMatcher &B) const {
2899 // Generally speaking, an instruction is more important than an Int or a
2900 // LiteralInt because it can cover more nodes but theres an exception to
2901 // this. G_CONSTANT's are less important than either of those two because they
2902 // are more permissive.
Daniel Sandersedd07842017-08-17 09:26:14 +00002903
2904 const InstructionOperandMatcher *AOM =
2905 dyn_cast<InstructionOperandMatcher>(this);
2906 const InstructionOperandMatcher *BOM =
2907 dyn_cast<InstructionOperandMatcher>(&B);
2908 bool AIsConstantInsn = AOM && AOM->getInsnMatcher().isConstantInstruction();
2909 bool BIsConstantInsn = BOM && BOM->getInsnMatcher().isConstantInstruction();
2910
2911 if (AOM && BOM) {
2912 // The relative priorities between a G_CONSTANT and any other instruction
2913 // don't actually matter but this code is needed to ensure a strict weak
2914 // ordering. This is particularly important on Windows where the rules will
2915 // be incorrectly sorted without it.
2916 if (AIsConstantInsn != BIsConstantInsn)
2917 return AIsConstantInsn < BIsConstantInsn;
2918 return false;
Daniel Sanders05540042017-08-08 10:44:31 +00002919 }
Daniel Sandersedd07842017-08-17 09:26:14 +00002920
2921 if (AOM && AIsConstantInsn && (B.Kind == OPM_Int || B.Kind == OPM_LiteralInt))
2922 return false;
2923 if (BOM && BIsConstantInsn && (Kind == OPM_Int || Kind == OPM_LiteralInt))
2924 return true;
Daniel Sanders05540042017-08-08 10:44:31 +00002925
2926 return Kind < B.Kind;
Daniel Sanders75b84fc2017-08-08 13:21:26 +00002927}
Daniel Sanders05540042017-08-08 10:44:31 +00002928
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002929void SameOperandMatcher::emitPredicateOpcodes(MatchTable &Table,
Quentin Colombetaad20be2017-12-15 23:07:42 +00002930 RuleMatcher &Rule) const {
Daniel Sanders1e4569f2017-10-20 20:55:29 +00002931 const OperandMatcher &OtherOM = Rule.getOperandMatcher(MatchingName);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002932 unsigned OtherInsnVarID = Rule.getInsnVarID(OtherOM.getInstructionMatcher());
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002933 assert(OtherInsnVarID == OtherOM.getInstructionMatcher().getInsnVarID());
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002934
2935 Table << MatchTable::Opcode("GIM_CheckIsSameOperand")
2936 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
2937 << MatchTable::Comment("OpIdx") << MatchTable::IntValue(OpIdx)
2938 << MatchTable::Comment("OtherMI")
2939 << MatchTable::IntValue(OtherInsnVarID)
2940 << MatchTable::Comment("OtherOpIdx")
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002941 << MatchTable::IntValue(OtherOM.getOpIdx())
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002942 << MatchTable::LineBreak;
2943}
2944
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002945//===- GlobalISelEmitter class --------------------------------------------===//
2946
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002947class GlobalISelEmitter {
2948public:
2949 explicit GlobalISelEmitter(RecordKeeper &RK);
2950 void run(raw_ostream &OS);
2951
2952private:
2953 const RecordKeeper &RK;
2954 const CodeGenDAGPatterns CGP;
2955 const CodeGenTarget &Target;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002956 CodeGenRegBank CGRegs;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002957
Daniel Sanders39690bd2017-10-15 02:41:12 +00002958 /// Keep track of the equivalence between SDNodes and Instruction by mapping
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00002959 /// SDNodes to the GINodeEquiv mapping. We need to map to the GINodeEquiv to
2960 /// check for attributes on the relation such as CheckMMOIsNonAtomic.
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002961 /// This is defined using 'GINodeEquiv' in the target description.
Daniel Sanders39690bd2017-10-15 02:41:12 +00002962 DenseMap<Record *, Record *> NodeEquivs;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002963
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002964 /// Keep track of the equivalence between ComplexPattern's and
2965 /// GIComplexOperandMatcher. Map entries are specified by subclassing
2966 /// GIComplexPatternEquiv.
2967 DenseMap<const Record *, const Record *> ComplexPatternEquivs;
2968
Volkan Kelesf7f25682018-01-16 18:44:05 +00002969 /// Keep track of the equivalence between SDNodeXForm's and
2970 /// GICustomOperandRenderer. Map entries are specified by subclassing
2971 /// GISDNodeXFormEquiv.
2972 DenseMap<const Record *, const Record *> SDNodeXFormEquivs;
2973
Aditya Nandakumarb63e7632018-02-16 22:37:15 +00002974 /// Keep track of Scores of PatternsToMatch similar to how the DAG does.
2975 /// This adds compatibility for RuleMatchers to use this for ordering rules.
2976 DenseMap<uint64_t, int> RuleMatcherScores;
2977
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002978 // Map of predicates to their subtarget features.
Daniel Sanderse9fdba32017-04-29 17:30:09 +00002979 SubtargetFeatureInfoMap SubtargetFeatures;
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002980
Daniel Sandersf76f3152017-11-16 00:46:35 +00002981 // Rule coverage information.
2982 Optional<CodeGenCoverage> RuleCoverage;
2983
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002984 void gatherOpcodeValues();
2985 void gatherTypeIDValues();
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002986 void gatherNodeEquivs();
Daniel Sanders8ead1292018-06-15 23:13:43 +00002987 // Instruction predicate code that will be emitted in generated functions.
2988 SmallVector<std::string, 2> InstructionPredicateCodes;
2989 unsigned getOrCreateInstructionPredicateFnId(StringRef Code);
2990
Daniel Sanders39690bd2017-10-15 02:41:12 +00002991 Record *findNodeEquiv(Record *N) const;
Daniel Sandersf84bc372018-05-05 20:53:24 +00002992 const CodeGenInstruction *getEquivNode(Record &Equiv,
Florian Hahn6b1db822018-06-14 20:32:58 +00002993 const TreePatternNode *N) const;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002994
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002995 Error importRulePredicates(RuleMatcher &M, ArrayRef<Predicate> Predicates);
Daniel Sanders8ead1292018-06-15 23:13:43 +00002996 Expected<InstructionMatcher &>
2997 createAndImportSelDAGMatcher(RuleMatcher &Rule,
2998 InstructionMatcher &InsnMatcher,
2999 const TreePatternNode *Src, unsigned &TempOpIdx);
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003000 Error importComplexPatternOperandMatcher(OperandMatcher &OM, Record *R,
3001 unsigned &TempOpIdx) const;
3002 Error importChildMatcher(RuleMatcher &Rule, InstructionMatcher &InsnMatcher,
Florian Hahn6b1db822018-06-14 20:32:58 +00003003 const TreePatternNode *SrcChild,
Daniel Sandersa71f4542017-10-16 00:56:30 +00003004 bool OperandIsAPointer, unsigned OpIdx,
Daniel Sanders8ead1292018-06-15 23:13:43 +00003005 unsigned &TempOpIdx);
Daniel Sandersdf258e32017-10-31 19:09:29 +00003006
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00003007 Expected<BuildMIAction &>
Daniel Sandersa7b75262017-10-31 18:50:24 +00003008 createAndImportInstructionRenderer(RuleMatcher &M,
Florian Hahn6b1db822018-06-14 20:32:58 +00003009 const TreePatternNode *Dst);
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003010 Expected<action_iterator> createAndImportSubInstructionRenderer(
Florian Hahn6b1db822018-06-14 20:32:58 +00003011 action_iterator InsertPt, RuleMatcher &M, const TreePatternNode *Dst,
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003012 unsigned TempReg);
Daniel Sanders7438b262017-10-31 23:03:18 +00003013 Expected<action_iterator>
3014 createInstructionRenderer(action_iterator InsertPt, RuleMatcher &M,
Florian Hahn6b1db822018-06-14 20:32:58 +00003015 const TreePatternNode *Dst);
Daniel Sandersdf258e32017-10-31 19:09:29 +00003016 void importExplicitDefRenderers(BuildMIAction &DstMIBuilder);
Daniel Sanders7438b262017-10-31 23:03:18 +00003017 Expected<action_iterator>
3018 importExplicitUseRenderers(action_iterator InsertPt, RuleMatcher &M,
3019 BuildMIAction &DstMIBuilder,
Florian Hahn6b1db822018-06-14 20:32:58 +00003020 const llvm::TreePatternNode *Dst);
Daniel Sanders7438b262017-10-31 23:03:18 +00003021 Expected<action_iterator>
3022 importExplicitUseRenderer(action_iterator InsertPt, RuleMatcher &Rule,
3023 BuildMIAction &DstMIBuilder,
Florian Hahn6b1db822018-06-14 20:32:58 +00003024 TreePatternNode *DstChild);
Diana Picus382602f2017-05-17 08:57:28 +00003025 Error importDefaultOperandRenderers(BuildMIAction &DstMIBuilder,
3026 DagInit *DefaultOps) const;
Daniel Sandersc270c502017-03-30 09:36:33 +00003027 Error
Daniel Sandersffc7d582017-03-29 15:37:18 +00003028 importImplicitDefRenderers(BuildMIAction &DstMIBuilder,
3029 const std::vector<Record *> &ImplicitDefs) const;
3030
Daniel Sanders8ead1292018-06-15 23:13:43 +00003031 void emitCxxPredicateFns(raw_ostream &OS, StringRef CodeFieldName,
3032 StringRef TypeIdentifier, StringRef ArgType,
3033 StringRef ArgName, StringRef AdditionalDeclarations,
3034 std::function<bool(const Record *R)> Filter);
3035 void emitImmPredicateFns(raw_ostream &OS, StringRef TypeIdentifier,
3036 StringRef ArgType,
3037 std::function<bool(const Record *R)> Filter);
3038 void emitMIPredicateFns(raw_ostream &OS);
Daniel Sanders649c5852017-10-13 20:42:18 +00003039
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003040 /// Analyze pattern \p P, returning a matcher for it if possible.
3041 /// Otherwise, return an Error explaining why we don't support it.
3042 Expected<RuleMatcher> runOnPattern(const PatternToMatch &P);
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003043
3044 void declareSubtargetFeature(Record *Predicate);
Daniel Sanders7e523672017-11-11 03:23:44 +00003045
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003046 MatchTable buildMatchTable(MutableArrayRef<RuleMatcher> Rules, bool Optimize,
3047 bool WithCoverage);
3048
3049public:
Quentin Colombetec76d9c2017-12-18 19:47:41 +00003050 /// Takes a sequence of \p Rules and group them based on the predicates
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003051 /// they share. \p MatcherStorage is used as a memory container
Hiroshi Inoue501931b2018-01-24 05:04:35 +00003052 /// for the group that are created as part of this process.
Quentin Colombetec76d9c2017-12-18 19:47:41 +00003053 ///
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003054 /// What this optimization does looks like if GroupT = GroupMatcher:
Quentin Colombetec76d9c2017-12-18 19:47:41 +00003055 /// Output without optimization:
3056 /// \verbatim
3057 /// # R1
3058 /// # predicate A
3059 /// # predicate B
3060 /// ...
3061 /// # R2
3062 /// # predicate A // <-- effectively this is going to be checked twice.
3063 /// // Once in R1 and once in R2.
3064 /// # predicate C
3065 /// \endverbatim
3066 /// Output with optimization:
3067 /// \verbatim
3068 /// # Group1_2
3069 /// # predicate A // <-- Check is now shared.
3070 /// # R1
3071 /// # predicate B
3072 /// # R2
3073 /// # predicate C
3074 /// \endverbatim
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003075 template <class GroupT>
3076 static std::vector<Matcher *> optimizeRules(
Roman Tereshin2d6d3762018-05-02 20:08:14 +00003077 ArrayRef<Matcher *> Rules,
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003078 std::vector<std::unique_ptr<Matcher>> &MatcherStorage);
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003079};
3080
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003081void GlobalISelEmitter::gatherOpcodeValues() {
3082 InstructionOpcodeMatcher::initOpcodeValuesMap(Target);
3083}
3084
3085void GlobalISelEmitter::gatherTypeIDValues() {
3086 LLTOperandMatcher::initTypeIDValuesMap();
3087}
Daniel Sanders8ead1292018-06-15 23:13:43 +00003088unsigned GlobalISelEmitter::getOrCreateInstructionPredicateFnId(StringRef Code) {
3089 // There's not very many predicates that need to be here at the moment so we
3090 // just maintain a simple set-like vector. If it grows then we'll need to do
3091 // something more efficient.
3092 const auto &I = std::find(InstructionPredicateCodes.begin(),
3093 InstructionPredicateCodes.end(),
3094 Code);
3095 if (I == InstructionPredicateCodes.end()) {
3096 unsigned ID = InstructionPredicateCodes.size();
3097 InstructionPredicateCodes.push_back(Code);
3098 return ID;
3099 }
3100 return std::distance(InstructionPredicateCodes.begin(), I);
3101}
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003102
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003103void GlobalISelEmitter::gatherNodeEquivs() {
3104 assert(NodeEquivs.empty());
3105 for (Record *Equiv : RK.getAllDerivedDefinitions("GINodeEquiv"))
Daniel Sanders39690bd2017-10-15 02:41:12 +00003106 NodeEquivs[Equiv->getValueAsDef("Node")] = Equiv;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00003107
3108 assert(ComplexPatternEquivs.empty());
3109 for (Record *Equiv : RK.getAllDerivedDefinitions("GIComplexPatternEquiv")) {
3110 Record *SelDAGEquiv = Equiv->getValueAsDef("SelDAGEquivalent");
3111 if (!SelDAGEquiv)
3112 continue;
3113 ComplexPatternEquivs[SelDAGEquiv] = Equiv;
3114 }
Volkan Kelesf7f25682018-01-16 18:44:05 +00003115
3116 assert(SDNodeXFormEquivs.empty());
3117 for (Record *Equiv : RK.getAllDerivedDefinitions("GISDNodeXFormEquiv")) {
3118 Record *SelDAGEquiv = Equiv->getValueAsDef("SelDAGEquivalent");
3119 if (!SelDAGEquiv)
3120 continue;
3121 SDNodeXFormEquivs[SelDAGEquiv] = Equiv;
3122 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003123}
3124
Daniel Sanders39690bd2017-10-15 02:41:12 +00003125Record *GlobalISelEmitter::findNodeEquiv(Record *N) const {
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003126 return NodeEquivs.lookup(N);
3127}
3128
Daniel Sandersf84bc372018-05-05 20:53:24 +00003129const CodeGenInstruction *
Florian Hahn6b1db822018-06-14 20:32:58 +00003130GlobalISelEmitter::getEquivNode(Record &Equiv, const TreePatternNode *N) const {
3131 for (const auto &Predicate : N->getPredicateFns()) {
Daniel Sandersf84bc372018-05-05 20:53:24 +00003132 if (!Equiv.isValueUnset("IfSignExtend") && Predicate.isLoad() &&
3133 Predicate.isSignExtLoad())
3134 return &Target.getInstruction(Equiv.getValueAsDef("IfSignExtend"));
3135 if (!Equiv.isValueUnset("IfZeroExtend") && Predicate.isLoad() &&
3136 Predicate.isZeroExtLoad())
3137 return &Target.getInstruction(Equiv.getValueAsDef("IfZeroExtend"));
3138 }
3139 return &Target.getInstruction(Equiv.getValueAsDef("I"));
3140}
3141
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003142GlobalISelEmitter::GlobalISelEmitter(RecordKeeper &RK)
Daniel Sandersf84bc372018-05-05 20:53:24 +00003143 : RK(RK), CGP(RK), Target(CGP.getTargetInfo()),
3144 CGRegs(RK, Target.getHwModes()) {}
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003145
3146//===- Emitter ------------------------------------------------------------===//
3147
Daniel Sandersc270c502017-03-30 09:36:33 +00003148Error
Daniel Sandersffc7d582017-03-29 15:37:18 +00003149GlobalISelEmitter::importRulePredicates(RuleMatcher &M,
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003150 ArrayRef<Predicate> Predicates) {
3151 for (const Predicate &P : Predicates) {
3152 if (!P.Def)
3153 continue;
3154 declareSubtargetFeature(P.Def);
3155 M.addRequiredFeature(P.Def);
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003156 }
3157
Daniel Sandersc270c502017-03-30 09:36:33 +00003158 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00003159}
Daniel Sanders8a4bae92017-03-14 21:32:08 +00003160
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003161Expected<InstructionMatcher &> GlobalISelEmitter::createAndImportSelDAGMatcher(
3162 RuleMatcher &Rule, InstructionMatcher &InsnMatcher,
Daniel Sanders8ead1292018-06-15 23:13:43 +00003163 const TreePatternNode *Src, unsigned &TempOpIdx) {
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003164 Record *SrcGIEquivOrNull = nullptr;
3165 const CodeGenInstruction *SrcGIOrNull = nullptr;
3166
3167 // Start with the defined operands (i.e., the results of the root operator).
Florian Hahn6b1db822018-06-14 20:32:58 +00003168 if (Src->getExtTypes().size() > 1)
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003169 return failedImport("Src pattern has multiple results");
3170
Florian Hahn6b1db822018-06-14 20:32:58 +00003171 if (Src->isLeaf()) {
3172 Init *SrcInit = Src->getLeafValue();
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003173 if (isa<IntInit>(SrcInit)) {
3174 InsnMatcher.addPredicate<InstructionOpcodeMatcher>(
3175 &Target.getInstruction(RK.getDef("G_CONSTANT")));
3176 } else
3177 return failedImport(
3178 "Unable to deduce gMIR opcode to handle Src (which is a leaf)");
3179 } else {
Florian Hahn6b1db822018-06-14 20:32:58 +00003180 SrcGIEquivOrNull = findNodeEquiv(Src->getOperator());
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003181 if (!SrcGIEquivOrNull)
3182 return failedImport("Pattern operator lacks an equivalent Instruction" +
Florian Hahn6b1db822018-06-14 20:32:58 +00003183 explainOperator(Src->getOperator()));
Daniel Sandersf84bc372018-05-05 20:53:24 +00003184 SrcGIOrNull = getEquivNode(*SrcGIEquivOrNull, Src);
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003185
3186 // The operators look good: match the opcode
3187 InsnMatcher.addPredicate<InstructionOpcodeMatcher>(SrcGIOrNull);
3188 }
3189
3190 unsigned OpIdx = 0;
Florian Hahn6b1db822018-06-14 20:32:58 +00003191 for (const TypeSetByHwMode &VTy : Src->getExtTypes()) {
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003192 // Results don't have a name unless they are the root node. The caller will
3193 // set the name if appropriate.
3194 OperandMatcher &OM = InsnMatcher.addOperand(OpIdx++, "", TempOpIdx);
3195 if (auto Error = OM.addTypeCheckPredicate(VTy, false /* OperandIsAPointer */))
3196 return failedImport(toString(std::move(Error)) +
3197 " for result of Src pattern operator");
3198 }
3199
Florian Hahn6b1db822018-06-14 20:32:58 +00003200 for (const auto &Predicate : Src->getPredicateFns()) {
Daniel Sanders2c269f62017-08-24 09:11:20 +00003201 if (Predicate.isAlwaysTrue())
3202 continue;
3203
3204 if (Predicate.isImmediatePattern()) {
3205 InsnMatcher.addPredicate<InstructionImmPredicateMatcher>(Predicate);
3206 continue;
3207 }
3208
Daniel Sandersf84bc372018-05-05 20:53:24 +00003209 // G_LOAD is used for both non-extending and any-extending loads.
3210 if (Predicate.isLoad() && Predicate.isNonExtLoad()) {
3211 InsnMatcher.addPredicate<MemoryVsLLTSizePredicateMatcher>(
3212 0, MemoryVsLLTSizePredicateMatcher::EqualTo, 0);
3213 continue;
3214 }
3215 if (Predicate.isLoad() && Predicate.isAnyExtLoad()) {
3216 InsnMatcher.addPredicate<MemoryVsLLTSizePredicateMatcher>(
3217 0, MemoryVsLLTSizePredicateMatcher::LessThan, 0);
3218 continue;
3219 }
3220
3221 // No check required. We already did it by swapping the opcode.
3222 if (!SrcGIEquivOrNull->isValueUnset("IfSignExtend") &&
3223 Predicate.isSignExtLoad())
3224 continue;
3225
3226 // No check required. We already did it by swapping the opcode.
3227 if (!SrcGIEquivOrNull->isValueUnset("IfZeroExtend") &&
3228 Predicate.isZeroExtLoad())
Daniel Sandersa71f4542017-10-16 00:56:30 +00003229 continue;
3230
Daniel Sandersd66e0902017-10-23 18:19:24 +00003231 // No check required. G_STORE by itself is a non-extending store.
3232 if (Predicate.isNonTruncStore())
3233 continue;
3234
Daniel Sanders76664652017-11-28 22:07:05 +00003235 if (Predicate.isLoad() || Predicate.isStore() || Predicate.isAtomic()) {
3236 if (Predicate.getMemoryVT() != nullptr) {
3237 Optional<LLTCodeGen> MemTyOrNone =
3238 MVTToLLT(getValueType(Predicate.getMemoryVT()));
Daniel Sandersd66e0902017-10-23 18:19:24 +00003239
Daniel Sanders76664652017-11-28 22:07:05 +00003240 if (!MemTyOrNone)
3241 return failedImport("MemVT could not be converted to LLT");
Daniel Sandersd66e0902017-10-23 18:19:24 +00003242
Daniel Sandersf84bc372018-05-05 20:53:24 +00003243 // MMO's work in bytes so we must take care of unusual types like i1
3244 // don't round down.
3245 unsigned MemSizeInBits =
3246 llvm::alignTo(MemTyOrNone->get().getSizeInBits(), 8);
3247
3248 InsnMatcher.addPredicate<MemorySizePredicateMatcher>(
3249 0, MemSizeInBits / 8);
Daniel Sanders76664652017-11-28 22:07:05 +00003250 continue;
3251 }
3252 }
3253
3254 if (Predicate.isLoad() || Predicate.isStore()) {
3255 // No check required. A G_LOAD/G_STORE is an unindexed load.
3256 if (Predicate.isUnindexed())
3257 continue;
3258 }
3259
3260 if (Predicate.isAtomic()) {
3261 if (Predicate.isAtomicOrderingMonotonic()) {
3262 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3263 "Monotonic");
3264 continue;
3265 }
3266 if (Predicate.isAtomicOrderingAcquire()) {
3267 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>("Acquire");
3268 continue;
3269 }
3270 if (Predicate.isAtomicOrderingRelease()) {
3271 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>("Release");
3272 continue;
3273 }
3274 if (Predicate.isAtomicOrderingAcquireRelease()) {
3275 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3276 "AcquireRelease");
3277 continue;
3278 }
3279 if (Predicate.isAtomicOrderingSequentiallyConsistent()) {
3280 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3281 "SequentiallyConsistent");
3282 continue;
3283 }
Daniel Sanders0c43b3a2017-11-30 21:05:59 +00003284
3285 if (Predicate.isAtomicOrderingAcquireOrStronger()) {
3286 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3287 "Acquire", AtomicOrderingMMOPredicateMatcher::AO_OrStronger);
3288 continue;
3289 }
3290 if (Predicate.isAtomicOrderingWeakerThanAcquire()) {
3291 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3292 "Acquire", AtomicOrderingMMOPredicateMatcher::AO_WeakerThan);
3293 continue;
3294 }
3295
3296 if (Predicate.isAtomicOrderingReleaseOrStronger()) {
3297 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3298 "Release", AtomicOrderingMMOPredicateMatcher::AO_OrStronger);
3299 continue;
3300 }
3301 if (Predicate.isAtomicOrderingWeakerThanRelease()) {
3302 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3303 "Release", AtomicOrderingMMOPredicateMatcher::AO_WeakerThan);
3304 continue;
3305 }
Daniel Sandersd66e0902017-10-23 18:19:24 +00003306 }
3307
Daniel Sanders8ead1292018-06-15 23:13:43 +00003308 if (Predicate.hasGISelPredicateCode()) {
3309 InsnMatcher.addPredicate<GenericInstructionPredicateMatcher>(Predicate);
3310 continue;
3311 }
3312
Daniel Sanders2c269f62017-08-24 09:11:20 +00003313 return failedImport("Src pattern child has predicate (" +
3314 explainPredicates(Src) + ")");
3315 }
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003316 if (SrcGIEquivOrNull && SrcGIEquivOrNull->getValueAsBit("CheckMMOIsNonAtomic"))
3317 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>("NotAtomic");
Daniel Sanders2c269f62017-08-24 09:11:20 +00003318
Florian Hahn6b1db822018-06-14 20:32:58 +00003319 if (Src->isLeaf()) {
3320 Init *SrcInit = Src->getLeafValue();
Daniel Sanders452c8ae2017-05-23 19:33:16 +00003321 if (IntInit *SrcIntInit = dyn_cast<IntInit>(SrcInit)) {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003322 OperandMatcher &OM =
Florian Hahn6b1db822018-06-14 20:32:58 +00003323 InsnMatcher.addOperand(OpIdx++, Src->getName(), TempOpIdx);
Daniel Sanders452c8ae2017-05-23 19:33:16 +00003324 OM.addPredicate<LiteralIntOperandMatcher>(SrcIntInit->getValue());
3325 } else
Daniel Sanders32291982017-06-28 13:50:04 +00003326 return failedImport(
3327 "Unable to deduce gMIR opcode to handle Src (which is a leaf)");
Daniel Sanders452c8ae2017-05-23 19:33:16 +00003328 } else {
Daniel Sanders85ffd362017-07-06 08:12:20 +00003329 assert(SrcGIOrNull &&
3330 "Expected to have already found an equivalent Instruction");
Daniel Sanders11300ce2017-10-13 21:28:03 +00003331 if (SrcGIOrNull->TheDef->getName() == "G_CONSTANT" ||
3332 SrcGIOrNull->TheDef->getName() == "G_FCONSTANT") {
3333 // imm/fpimm still have operands but we don't need to do anything with it
Daniel Sanders05540042017-08-08 10:44:31 +00003334 // here since we don't support ImmLeaf predicates yet. However, we still
3335 // need to note the hidden operand to get GIM_CheckNumOperands correct.
3336 InsnMatcher.addOperand(OpIdx++, "", TempOpIdx);
3337 return InsnMatcher;
3338 }
3339
Daniel Sanders452c8ae2017-05-23 19:33:16 +00003340 // Match the used operands (i.e. the children of the operator).
Florian Hahn6b1db822018-06-14 20:32:58 +00003341 for (unsigned i = 0, e = Src->getNumChildren(); i != e; ++i) {
3342 TreePatternNode *SrcChild = Src->getChild(i);
Daniel Sanders85ffd362017-07-06 08:12:20 +00003343
Daniel Sandersa71f4542017-10-16 00:56:30 +00003344 // SelectionDAG allows pointers to be represented with iN since it doesn't
3345 // distinguish between pointers and integers but they are different types in GlobalISel.
3346 // Coerce integers to pointers to address space 0 if the context indicates a pointer.
Daniel Sandersc54aa9c2017-11-18 00:16:44 +00003347 bool OperandIsAPointer = SrcGIOrNull->isOperandAPointer(i);
Daniel Sandersa71f4542017-10-16 00:56:30 +00003348
Daniel Sanders28887fe2017-09-19 12:56:36 +00003349 // For G_INTRINSIC/G_INTRINSIC_W_SIDE_EFFECTS, the operand immediately
3350 // following the defs is an intrinsic ID.
3351 if ((SrcGIOrNull->TheDef->getName() == "G_INTRINSIC" ||
3352 SrcGIOrNull->TheDef->getName() == "G_INTRINSIC_W_SIDE_EFFECTS") &&
3353 i == 0) {
Florian Hahn6b1db822018-06-14 20:32:58 +00003354 if (const CodeGenIntrinsic *II = Src->getIntrinsicInfo(CGP)) {
Daniel Sanders85ffd362017-07-06 08:12:20 +00003355 OperandMatcher &OM =
Florian Hahn6b1db822018-06-14 20:32:58 +00003356 InsnMatcher.addOperand(OpIdx++, SrcChild->getName(), TempOpIdx);
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00003357 OM.addPredicate<IntrinsicIDOperandMatcher>(II);
Daniel Sanders85ffd362017-07-06 08:12:20 +00003358 continue;
3359 }
3360
3361 return failedImport("Expected IntInit containing instrinsic ID)");
3362 }
3363
Daniel Sandersa71f4542017-10-16 00:56:30 +00003364 if (auto Error =
3365 importChildMatcher(Rule, InsnMatcher, SrcChild, OperandIsAPointer,
3366 OpIdx++, TempOpIdx))
Daniel Sanders452c8ae2017-05-23 19:33:16 +00003367 return std::move(Error);
3368 }
Daniel Sandersffc7d582017-03-29 15:37:18 +00003369 }
3370
3371 return InsnMatcher;
3372}
3373
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003374Error GlobalISelEmitter::importComplexPatternOperandMatcher(
3375 OperandMatcher &OM, Record *R, unsigned &TempOpIdx) const {
3376 const auto &ComplexPattern = ComplexPatternEquivs.find(R);
3377 if (ComplexPattern == ComplexPatternEquivs.end())
3378 return failedImport("SelectionDAG ComplexPattern (" + R->getName() +
3379 ") not mapped to GlobalISel");
3380
3381 OM.addPredicate<ComplexPatternOperandMatcher>(OM, *ComplexPattern->second);
3382 TempOpIdx++;
3383 return Error::success();
3384}
3385
3386Error GlobalISelEmitter::importChildMatcher(RuleMatcher &Rule,
3387 InstructionMatcher &InsnMatcher,
Florian Hahn6b1db822018-06-14 20:32:58 +00003388 const TreePatternNode *SrcChild,
Daniel Sandersa71f4542017-10-16 00:56:30 +00003389 bool OperandIsAPointer,
Daniel Sandersc270c502017-03-30 09:36:33 +00003390 unsigned OpIdx,
Daniel Sanders8ead1292018-06-15 23:13:43 +00003391 unsigned &TempOpIdx) {
Daniel Sanders4f3eb242017-04-05 13:14:03 +00003392 OperandMatcher &OM =
Florian Hahn6b1db822018-06-14 20:32:58 +00003393 InsnMatcher.addOperand(OpIdx, SrcChild->getName(), TempOpIdx);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003394 if (OM.isSameAsAnotherOperand())
3395 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00003396
Florian Hahn6b1db822018-06-14 20:32:58 +00003397 ArrayRef<TypeSetByHwMode> ChildTypes = SrcChild->getExtTypes();
Daniel Sandersffc7d582017-03-29 15:37:18 +00003398 if (ChildTypes.size() != 1)
3399 return failedImport("Src pattern child has multiple results");
3400
3401 // Check MBB's before the type check since they are not a known type.
Florian Hahn6b1db822018-06-14 20:32:58 +00003402 if (!SrcChild->isLeaf()) {
3403 if (SrcChild->getOperator()->isSubClassOf("SDNode")) {
3404 auto &ChildSDNI = CGP.getSDNodeInfo(SrcChild->getOperator());
Daniel Sandersffc7d582017-03-29 15:37:18 +00003405 if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") {
3406 OM.addPredicate<MBBOperandMatcher>();
Daniel Sandersc270c502017-03-30 09:36:33 +00003407 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00003408 }
3409 }
Daniel Sandersffc7d582017-03-29 15:37:18 +00003410 }
3411
Daniel Sandersa71f4542017-10-16 00:56:30 +00003412 if (auto Error =
3413 OM.addTypeCheckPredicate(ChildTypes.front(), OperandIsAPointer))
3414 return failedImport(toString(std::move(Error)) + " for Src operand (" +
Florian Hahn6b1db822018-06-14 20:32:58 +00003415 to_string(*SrcChild) + ")");
Daniel Sandersffc7d582017-03-29 15:37:18 +00003416
Daniel Sandersbee57392017-04-04 13:25:23 +00003417 // Check for nested instructions.
Florian Hahn6b1db822018-06-14 20:32:58 +00003418 if (!SrcChild->isLeaf()) {
3419 if (SrcChild->getOperator()->isSubClassOf("ComplexPattern")) {
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003420 // When a ComplexPattern is used as an operator, it should do the same
3421 // thing as when used as a leaf. However, the children of the operator
3422 // name the sub-operands that make up the complex operand and we must
3423 // prepare to reference them in the renderer too.
3424 unsigned RendererID = TempOpIdx;
3425 if (auto Error = importComplexPatternOperandMatcher(
Florian Hahn6b1db822018-06-14 20:32:58 +00003426 OM, SrcChild->getOperator(), TempOpIdx))
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003427 return Error;
3428
Florian Hahn6b1db822018-06-14 20:32:58 +00003429 for (unsigned i = 0, e = SrcChild->getNumChildren(); i != e; ++i) {
3430 auto *SubOperand = SrcChild->getChild(i);
3431 if (!SubOperand->getName().empty())
3432 Rule.defineComplexSubOperand(SubOperand->getName(),
3433 SrcChild->getOperator(), RendererID, i);
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003434 }
3435
3436 return Error::success();
3437 }
3438
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003439 auto MaybeInsnOperand = OM.addPredicate<InstructionOperandMatcher>(
Florian Hahn6b1db822018-06-14 20:32:58 +00003440 InsnMatcher.getRuleMatcher(), SrcChild->getName());
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003441 if (!MaybeInsnOperand.hasValue()) {
3442 // This isn't strictly true. If the user were to provide exactly the same
3443 // matchers as the original operand then we could allow it. However, it's
3444 // simpler to not permit the redundant specification.
3445 return failedImport("Nested instruction cannot be the same as another operand");
3446 }
3447
Daniel Sandersbee57392017-04-04 13:25:23 +00003448 // Map the node to a gMIR instruction.
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003449 InstructionOperandMatcher &InsnOperand = **MaybeInsnOperand;
Daniel Sanders57938df2017-07-11 10:40:18 +00003450 auto InsnMatcherOrError = createAndImportSelDAGMatcher(
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003451 Rule, InsnOperand.getInsnMatcher(), SrcChild, TempOpIdx);
Daniel Sandersbee57392017-04-04 13:25:23 +00003452 if (auto Error = InsnMatcherOrError.takeError())
3453 return Error;
3454
3455 return Error::success();
3456 }
3457
Florian Hahn6b1db822018-06-14 20:32:58 +00003458 if (SrcChild->hasAnyPredicate())
Diana Picusd1b61812017-11-03 10:30:19 +00003459 return failedImport("Src pattern child has unsupported predicate");
3460
Daniel Sandersffc7d582017-03-29 15:37:18 +00003461 // Check for constant immediates.
Florian Hahn6b1db822018-06-14 20:32:58 +00003462 if (auto *ChildInt = dyn_cast<IntInit>(SrcChild->getLeafValue())) {
Daniel Sanders452c8ae2017-05-23 19:33:16 +00003463 OM.addPredicate<ConstantIntOperandMatcher>(ChildInt->getValue());
Daniel Sandersc270c502017-03-30 09:36:33 +00003464 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00003465 }
3466
3467 // Check for def's like register classes or ComplexPattern's.
Florian Hahn6b1db822018-06-14 20:32:58 +00003468 if (auto *ChildDefInit = dyn_cast<DefInit>(SrcChild->getLeafValue())) {
Daniel Sandersffc7d582017-03-29 15:37:18 +00003469 auto *ChildRec = ChildDefInit->getDef();
3470
3471 // Check for register classes.
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003472 if (ChildRec->isSubClassOf("RegisterClass") ||
3473 ChildRec->isSubClassOf("RegisterOperand")) {
Daniel Sandersffc7d582017-03-29 15:37:18 +00003474 OM.addPredicate<RegisterBankOperandMatcher>(
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003475 Target.getRegisterClass(getInitValueAsRegClass(ChildDefInit)));
Daniel Sanders658541f2017-04-22 15:53:21 +00003476 return Error::success();
3477 }
3478
Daniel Sanders4d4e7652017-10-09 18:14:53 +00003479 // Check for ValueType.
3480 if (ChildRec->isSubClassOf("ValueType")) {
3481 // We already added a type check as standard practice so this doesn't need
3482 // to do anything.
3483 return Error::success();
3484 }
3485
Daniel Sandersffc7d582017-03-29 15:37:18 +00003486 // Check for ComplexPattern's.
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003487 if (ChildRec->isSubClassOf("ComplexPattern"))
3488 return importComplexPatternOperandMatcher(OM, ChildRec, TempOpIdx);
Daniel Sandersffc7d582017-03-29 15:37:18 +00003489
Daniel Sandersd0656a32017-04-13 09:45:37 +00003490 if (ChildRec->isSubClassOf("ImmLeaf")) {
3491 return failedImport(
3492 "Src pattern child def is an unsupported tablegen class (ImmLeaf)");
3493 }
3494
Daniel Sandersffc7d582017-03-29 15:37:18 +00003495 return failedImport(
3496 "Src pattern child def is an unsupported tablegen class");
3497 }
3498
3499 return failedImport("Src pattern child is an unsupported kind");
3500}
3501
Daniel Sanders7438b262017-10-31 23:03:18 +00003502Expected<action_iterator> GlobalISelEmitter::importExplicitUseRenderer(
3503 action_iterator InsertPt, RuleMatcher &Rule, BuildMIAction &DstMIBuilder,
Florian Hahn6b1db822018-06-14 20:32:58 +00003504 TreePatternNode *DstChild) {
Daniel Sanders2c269f62017-08-24 09:11:20 +00003505
Florian Hahn6b1db822018-06-14 20:32:58 +00003506 const auto &SubOperand = Rule.getComplexSubOperand(DstChild->getName());
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003507 if (SubOperand.hasValue()) {
3508 DstMIBuilder.addRenderer<RenderComplexPatternOperand>(
Florian Hahn6b1db822018-06-14 20:32:58 +00003509 *std::get<0>(*SubOperand), DstChild->getName(),
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003510 std::get<1>(*SubOperand), std::get<2>(*SubOperand));
Daniel Sanders7438b262017-10-31 23:03:18 +00003511 return InsertPt;
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003512 }
3513
Florian Hahn6b1db822018-06-14 20:32:58 +00003514 if (!DstChild->isLeaf()) {
Volkan Kelesf7f25682018-01-16 18:44:05 +00003515
Florian Hahn6b1db822018-06-14 20:32:58 +00003516 if (DstChild->getOperator()->isSubClassOf("SDNodeXForm")) {
3517 auto Child = DstChild->getChild(0);
3518 auto I = SDNodeXFormEquivs.find(DstChild->getOperator());
Volkan Kelesf7f25682018-01-16 18:44:05 +00003519 if (I != SDNodeXFormEquivs.end()) {
Florian Hahn6b1db822018-06-14 20:32:58 +00003520 DstMIBuilder.addRenderer<CustomRenderer>(*I->second, Child->getName());
Volkan Kelesf7f25682018-01-16 18:44:05 +00003521 return InsertPt;
3522 }
Florian Hahn6b1db822018-06-14 20:32:58 +00003523 return failedImport("SDNodeXForm " + Child->getName() +
Volkan Kelesf7f25682018-01-16 18:44:05 +00003524 " has no custom renderer");
3525 }
3526
Daniel Sanders05540042017-08-08 10:44:31 +00003527 // We accept 'bb' here. It's an operator because BasicBlockSDNode isn't
3528 // inline, but in MI it's just another operand.
Florian Hahn6b1db822018-06-14 20:32:58 +00003529 if (DstChild->getOperator()->isSubClassOf("SDNode")) {
3530 auto &ChildSDNI = CGP.getSDNodeInfo(DstChild->getOperator());
Daniel Sandersffc7d582017-03-29 15:37:18 +00003531 if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") {
Florian Hahn6b1db822018-06-14 20:32:58 +00003532 DstMIBuilder.addRenderer<CopyRenderer>(DstChild->getName());
Daniel Sanders7438b262017-10-31 23:03:18 +00003533 return InsertPt;
Daniel Sandersffc7d582017-03-29 15:37:18 +00003534 }
3535 }
Daniel Sanders05540042017-08-08 10:44:31 +00003536
3537 // Similarly, imm is an operator in TreePatternNode's view but must be
3538 // rendered as operands.
3539 // FIXME: The target should be able to choose sign-extended when appropriate
3540 // (e.g. on Mips).
Florian Hahn6b1db822018-06-14 20:32:58 +00003541 if (DstChild->getOperator()->getName() == "imm") {
3542 DstMIBuilder.addRenderer<CopyConstantAsImmRenderer>(DstChild->getName());
Daniel Sanders7438b262017-10-31 23:03:18 +00003543 return InsertPt;
Florian Hahn6b1db822018-06-14 20:32:58 +00003544 } else if (DstChild->getOperator()->getName() == "fpimm") {
Daniel Sanders11300ce2017-10-13 21:28:03 +00003545 DstMIBuilder.addRenderer<CopyFConstantAsFPImmRenderer>(
Florian Hahn6b1db822018-06-14 20:32:58 +00003546 DstChild->getName());
Daniel Sanders7438b262017-10-31 23:03:18 +00003547 return InsertPt;
Daniel Sanders05540042017-08-08 10:44:31 +00003548 }
3549
Florian Hahn6b1db822018-06-14 20:32:58 +00003550 if (DstChild->getOperator()->isSubClassOf("Instruction")) {
3551 ArrayRef<TypeSetByHwMode> ChildTypes = DstChild->getExtTypes();
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003552 if (ChildTypes.size() != 1)
3553 return failedImport("Dst pattern child has multiple results");
3554
3555 Optional<LLTCodeGen> OpTyOrNone = None;
3556 if (ChildTypes.front().isMachineValueType())
3557 OpTyOrNone =
3558 MVTToLLT(ChildTypes.front().getMachineValueType().SimpleTy);
3559 if (!OpTyOrNone)
3560 return failedImport("Dst operand has an unsupported type");
3561
3562 unsigned TempRegID = Rule.allocateTempRegID();
3563 InsertPt = Rule.insertAction<MakeTempRegisterAction>(
3564 InsertPt, OpTyOrNone.getValue(), TempRegID);
3565 DstMIBuilder.addRenderer<TempRegRenderer>(TempRegID);
3566
3567 auto InsertPtOrError = createAndImportSubInstructionRenderer(
3568 ++InsertPt, Rule, DstChild, TempRegID);
3569 if (auto Error = InsertPtOrError.takeError())
3570 return std::move(Error);
3571 return InsertPtOrError.get();
3572 }
3573
Florian Hahn6b1db822018-06-14 20:32:58 +00003574 return failedImport("Dst pattern child isn't a leaf node or an MBB" + llvm::to_string(*DstChild));
Daniel Sandersffc7d582017-03-29 15:37:18 +00003575 }
3576
Daniel Sandersf499b2b2017-11-30 18:48:35 +00003577 // It could be a specific immediate in which case we should just check for
3578 // that immediate.
3579 if (const IntInit *ChildIntInit =
Florian Hahn6b1db822018-06-14 20:32:58 +00003580 dyn_cast<IntInit>(DstChild->getLeafValue())) {
Daniel Sandersf499b2b2017-11-30 18:48:35 +00003581 DstMIBuilder.addRenderer<ImmRenderer>(ChildIntInit->getValue());
3582 return InsertPt;
3583 }
3584
Daniel Sandersffc7d582017-03-29 15:37:18 +00003585 // Otherwise, we're looking for a bog-standard RegisterClass operand.
Florian Hahn6b1db822018-06-14 20:32:58 +00003586 if (auto *ChildDefInit = dyn_cast<DefInit>(DstChild->getLeafValue())) {
Daniel Sandersffc7d582017-03-29 15:37:18 +00003587 auto *ChildRec = ChildDefInit->getDef();
3588
Florian Hahn6b1db822018-06-14 20:32:58 +00003589 ArrayRef<TypeSetByHwMode> ChildTypes = DstChild->getExtTypes();
Daniel Sandersffc7d582017-03-29 15:37:18 +00003590 if (ChildTypes.size() != 1)
3591 return failedImport("Dst pattern child has multiple results");
3592
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003593 Optional<LLTCodeGen> OpTyOrNone = None;
3594 if (ChildTypes.front().isMachineValueType())
3595 OpTyOrNone = MVTToLLT(ChildTypes.front().getMachineValueType().SimpleTy);
Daniel Sandersffc7d582017-03-29 15:37:18 +00003596 if (!OpTyOrNone)
3597 return failedImport("Dst operand has an unsupported type");
3598
3599 if (ChildRec->isSubClassOf("Register")) {
Daniel Sanders198447a2017-11-01 00:29:47 +00003600 DstMIBuilder.addRenderer<AddRegisterRenderer>(ChildRec);
Daniel Sanders7438b262017-10-31 23:03:18 +00003601 return InsertPt;
Daniel Sandersffc7d582017-03-29 15:37:18 +00003602 }
3603
Daniel Sanders658541f2017-04-22 15:53:21 +00003604 if (ChildRec->isSubClassOf("RegisterClass") ||
Daniel Sanders4d4e7652017-10-09 18:14:53 +00003605 ChildRec->isSubClassOf("RegisterOperand") ||
3606 ChildRec->isSubClassOf("ValueType")) {
Daniel Sandersd66e0902017-10-23 18:19:24 +00003607 if (ChildRec->isSubClassOf("RegisterOperand") &&
3608 !ChildRec->isValueUnset("GIZeroRegister")) {
3609 DstMIBuilder.addRenderer<CopyOrAddZeroRegRenderer>(
Florian Hahn6b1db822018-06-14 20:32:58 +00003610 DstChild->getName(), ChildRec->getValueAsDef("GIZeroRegister"));
Daniel Sanders7438b262017-10-31 23:03:18 +00003611 return InsertPt;
Daniel Sandersd66e0902017-10-23 18:19:24 +00003612 }
3613
Florian Hahn6b1db822018-06-14 20:32:58 +00003614 DstMIBuilder.addRenderer<CopyRenderer>(DstChild->getName());
Daniel Sanders7438b262017-10-31 23:03:18 +00003615 return InsertPt;
Daniel Sandersffc7d582017-03-29 15:37:18 +00003616 }
3617
3618 if (ChildRec->isSubClassOf("ComplexPattern")) {
3619 const auto &ComplexPattern = ComplexPatternEquivs.find(ChildRec);
3620 if (ComplexPattern == ComplexPatternEquivs.end())
3621 return failedImport(
3622 "SelectionDAG ComplexPattern not mapped to GlobalISel");
3623
Florian Hahn6b1db822018-06-14 20:32:58 +00003624 const OperandMatcher &OM = Rule.getOperandMatcher(DstChild->getName());
Daniel Sandersffc7d582017-03-29 15:37:18 +00003625 DstMIBuilder.addRenderer<RenderComplexPatternOperand>(
Florian Hahn6b1db822018-06-14 20:32:58 +00003626 *ComplexPattern->second, DstChild->getName(),
Daniel Sanders2deea182017-04-22 15:11:04 +00003627 OM.getAllocatedTemporariesBaseID());
Daniel Sanders7438b262017-10-31 23:03:18 +00003628 return InsertPt;
Daniel Sandersffc7d582017-03-29 15:37:18 +00003629 }
3630
3631 return failedImport(
3632 "Dst pattern child def is an unsupported tablegen class");
3633 }
3634
3635 return failedImport("Dst pattern child is an unsupported kind");
3636}
3637
Daniel Sandersc270c502017-03-30 09:36:33 +00003638Expected<BuildMIAction &> GlobalISelEmitter::createAndImportInstructionRenderer(
Florian Hahn6b1db822018-06-14 20:32:58 +00003639 RuleMatcher &M, const TreePatternNode *Dst) {
Daniel Sanders7438b262017-10-31 23:03:18 +00003640 auto InsertPtOrError = createInstructionRenderer(M.actions_end(), M, Dst);
3641 if (auto Error = InsertPtOrError.takeError())
Daniel Sandersdf258e32017-10-31 19:09:29 +00003642 return std::move(Error);
3643
Daniel Sanders7438b262017-10-31 23:03:18 +00003644 action_iterator InsertPt = InsertPtOrError.get();
3645 BuildMIAction &DstMIBuilder = *static_cast<BuildMIAction *>(InsertPt->get());
Daniel Sandersdf258e32017-10-31 19:09:29 +00003646
3647 importExplicitDefRenderers(DstMIBuilder);
3648
Daniel Sanders7438b262017-10-31 23:03:18 +00003649 if (auto Error = importExplicitUseRenderers(InsertPt, M, DstMIBuilder, Dst)
3650 .takeError())
Daniel Sandersdf258e32017-10-31 19:09:29 +00003651 return std::move(Error);
3652
3653 return DstMIBuilder;
3654}
3655
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003656Expected<action_iterator>
3657GlobalISelEmitter::createAndImportSubInstructionRenderer(
Florian Hahn6b1db822018-06-14 20:32:58 +00003658 const action_iterator InsertPt, RuleMatcher &M, const TreePatternNode *Dst,
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003659 unsigned TempRegID) {
3660 auto InsertPtOrError = createInstructionRenderer(InsertPt, M, Dst);
3661
3662 // TODO: Assert there's exactly one result.
3663
3664 if (auto Error = InsertPtOrError.takeError())
3665 return std::move(Error);
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003666
3667 BuildMIAction &DstMIBuilder =
3668 *static_cast<BuildMIAction *>(InsertPtOrError.get()->get());
3669
3670 // Assign the result to TempReg.
3671 DstMIBuilder.addRenderer<TempRegRenderer>(TempRegID, true);
3672
Daniel Sanders08464522018-01-29 21:09:12 +00003673 InsertPtOrError =
3674 importExplicitUseRenderers(InsertPtOrError.get(), M, DstMIBuilder, Dst);
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003675 if (auto Error = InsertPtOrError.takeError())
3676 return std::move(Error);
3677
Daniel Sanders08464522018-01-29 21:09:12 +00003678 M.insertAction<ConstrainOperandsToDefinitionAction>(InsertPt,
3679 DstMIBuilder.getInsnID());
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003680 return InsertPtOrError.get();
3681}
3682
Daniel Sanders7438b262017-10-31 23:03:18 +00003683Expected<action_iterator> GlobalISelEmitter::createInstructionRenderer(
Florian Hahn6b1db822018-06-14 20:32:58 +00003684 action_iterator InsertPt, RuleMatcher &M, const TreePatternNode *Dst) {
3685 Record *DstOp = Dst->getOperator();
Daniel Sandersd0656a32017-04-13 09:45:37 +00003686 if (!DstOp->isSubClassOf("Instruction")) {
3687 if (DstOp->isSubClassOf("ValueType"))
3688 return failedImport(
3689 "Pattern operator isn't an instruction (it's a ValueType)");
Daniel Sandersffc7d582017-03-29 15:37:18 +00003690 return failedImport("Pattern operator isn't an instruction");
Daniel Sandersd0656a32017-04-13 09:45:37 +00003691 }
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003692 CodeGenInstruction *DstI = &Target.getInstruction(DstOp);
Daniel Sandersffc7d582017-03-29 15:37:18 +00003693
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003694 // COPY_TO_REGCLASS is just a copy with a ConstrainOperandToRegClassAction
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00003695 // attached. Similarly for EXTRACT_SUBREG except that's a subregister copy.
Daniel Sandersdf258e32017-10-31 19:09:29 +00003696 if (DstI->TheDef->getName() == "COPY_TO_REGCLASS")
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003697 DstI = &Target.getInstruction(RK.getDef("COPY"));
Daniel Sandersdf258e32017-10-31 19:09:29 +00003698 else if (DstI->TheDef->getName() == "EXTRACT_SUBREG")
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00003699 DstI = &Target.getInstruction(RK.getDef("COPY"));
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003700 else if (DstI->TheDef->getName() == "REG_SEQUENCE")
3701 return failedImport("Unable to emit REG_SEQUENCE");
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003702
Daniel Sanders198447a2017-11-01 00:29:47 +00003703 return M.insertAction<BuildMIAction>(InsertPt, M.allocateOutputInsnID(),
3704 DstI);
Daniel Sandersdf258e32017-10-31 19:09:29 +00003705}
3706
3707void GlobalISelEmitter::importExplicitDefRenderers(
3708 BuildMIAction &DstMIBuilder) {
3709 const CodeGenInstruction *DstI = DstMIBuilder.getCGI();
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003710 for (unsigned I = 0; I < DstI->Operands.NumDefs; ++I) {
3711 const CGIOperandList::OperandInfo &DstIOperand = DstI->Operands[I];
Daniel Sanders198447a2017-11-01 00:29:47 +00003712 DstMIBuilder.addRenderer<CopyRenderer>(DstIOperand.Name);
Daniel Sandersffc7d582017-03-29 15:37:18 +00003713 }
Daniel Sandersdf258e32017-10-31 19:09:29 +00003714}
3715
Daniel Sanders7438b262017-10-31 23:03:18 +00003716Expected<action_iterator> GlobalISelEmitter::importExplicitUseRenderers(
3717 action_iterator InsertPt, RuleMatcher &M, BuildMIAction &DstMIBuilder,
Florian Hahn6b1db822018-06-14 20:32:58 +00003718 const llvm::TreePatternNode *Dst) {
Daniel Sandersdf258e32017-10-31 19:09:29 +00003719 const CodeGenInstruction *DstI = DstMIBuilder.getCGI();
Florian Hahn6b1db822018-06-14 20:32:58 +00003720 CodeGenInstruction *OrigDstI = &Target.getInstruction(Dst->getOperator());
Daniel Sandersffc7d582017-03-29 15:37:18 +00003721
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00003722 // EXTRACT_SUBREG needs to use a subregister COPY.
Daniel Sandersdf258e32017-10-31 19:09:29 +00003723 if (OrigDstI->TheDef->getName() == "EXTRACT_SUBREG") {
Florian Hahn6b1db822018-06-14 20:32:58 +00003724 if (!Dst->getChild(0)->isLeaf())
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00003725 return failedImport("EXTRACT_SUBREG child #1 is not a leaf");
3726
Daniel Sanders32291982017-06-28 13:50:04 +00003727 if (DefInit *SubRegInit =
Florian Hahn6b1db822018-06-14 20:32:58 +00003728 dyn_cast<DefInit>(Dst->getChild(1)->getLeafValue())) {
3729 Record *RCDef = getInitValueAsRegClass(Dst->getChild(0)->getLeafValue());
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003730 if (!RCDef)
3731 return failedImport("EXTRACT_SUBREG child #0 could not "
3732 "be coerced to a register class");
3733
3734 CodeGenRegisterClass *RC = CGRegs.getRegClass(RCDef);
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00003735 CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef());
3736
3737 const auto &SrcRCDstRCPair =
3738 RC->getMatchingSubClassWithSubRegs(CGRegs, SubIdx);
3739 if (SrcRCDstRCPair.hasValue()) {
3740 assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
3741 if (SrcRCDstRCPair->first != RC)
3742 return failedImport("EXTRACT_SUBREG requires an additional COPY");
3743 }
3744
Florian Hahn6b1db822018-06-14 20:32:58 +00003745 DstMIBuilder.addRenderer<CopySubRegRenderer>(Dst->getChild(0)->getName(),
Daniel Sanders198447a2017-11-01 00:29:47 +00003746 SubIdx);
Daniel Sanders7438b262017-10-31 23:03:18 +00003747 return InsertPt;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00003748 }
3749
3750 return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
3751 }
3752
Daniel Sandersffc7d582017-03-29 15:37:18 +00003753 // Render the explicit uses.
Daniel Sandersdf258e32017-10-31 19:09:29 +00003754 unsigned DstINumUses = OrigDstI->Operands.size() - OrigDstI->Operands.NumDefs;
Florian Hahn6b1db822018-06-14 20:32:58 +00003755 unsigned ExpectedDstINumUses = Dst->getNumChildren();
Daniel Sandersdf258e32017-10-31 19:09:29 +00003756 if (OrigDstI->TheDef->getName() == "COPY_TO_REGCLASS") {
3757 DstINumUses--; // Ignore the class constraint.
3758 ExpectedDstINumUses--;
3759 }
3760
Daniel Sanders0ed28822017-04-12 08:23:08 +00003761 unsigned Child = 0;
Diana Picus382602f2017-05-17 08:57:28 +00003762 unsigned NumDefaultOps = 0;
Daniel Sanders0ed28822017-04-12 08:23:08 +00003763 for (unsigned I = 0; I != DstINumUses; ++I) {
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003764 const CGIOperandList::OperandInfo &DstIOperand =
3765 DstI->Operands[DstI->Operands.NumDefs + I];
Daniel Sanders0ed28822017-04-12 08:23:08 +00003766
Diana Picus382602f2017-05-17 08:57:28 +00003767 // If the operand has default values, introduce them now.
3768 // FIXME: Until we have a decent test case that dictates we should do
3769 // otherwise, we're going to assume that operands with default values cannot
3770 // be specified in the patterns. Therefore, adding them will not cause us to
3771 // end up with too many rendered operands.
3772 if (DstIOperand.Rec->isSubClassOf("OperandWithDefaultOps")) {
Daniel Sanders0ed28822017-04-12 08:23:08 +00003773 DagInit *DefaultOps = DstIOperand.Rec->getValueAsDag("DefaultOps");
Diana Picus382602f2017-05-17 08:57:28 +00003774 if (auto Error = importDefaultOperandRenderers(DstMIBuilder, DefaultOps))
3775 return std::move(Error);
3776 ++NumDefaultOps;
Daniel Sanders0ed28822017-04-12 08:23:08 +00003777 continue;
3778 }
3779
Daniel Sanders7438b262017-10-31 23:03:18 +00003780 auto InsertPtOrError = importExplicitUseRenderer(InsertPt, M, DstMIBuilder,
Florian Hahn6b1db822018-06-14 20:32:58 +00003781 Dst->getChild(Child));
Daniel Sanders7438b262017-10-31 23:03:18 +00003782 if (auto Error = InsertPtOrError.takeError())
Daniel Sandersffc7d582017-03-29 15:37:18 +00003783 return std::move(Error);
Daniel Sanders7438b262017-10-31 23:03:18 +00003784 InsertPt = InsertPtOrError.get();
Daniel Sanders0ed28822017-04-12 08:23:08 +00003785 ++Child;
Daniel Sandersffc7d582017-03-29 15:37:18 +00003786 }
3787
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003788 if (NumDefaultOps + ExpectedDstINumUses != DstINumUses)
Diana Picuseb2057c2017-05-17 09:25:08 +00003789 return failedImport("Expected " + llvm::to_string(DstINumUses) +
Diana Picus382602f2017-05-17 08:57:28 +00003790 " used operands but found " +
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003791 llvm::to_string(ExpectedDstINumUses) +
Diana Picuseb2057c2017-05-17 09:25:08 +00003792 " explicit ones and " + llvm::to_string(NumDefaultOps) +
Diana Picus382602f2017-05-17 08:57:28 +00003793 " default ones");
3794
Daniel Sanders7438b262017-10-31 23:03:18 +00003795 return InsertPt;
Daniel Sandersffc7d582017-03-29 15:37:18 +00003796}
3797
Diana Picus382602f2017-05-17 08:57:28 +00003798Error GlobalISelEmitter::importDefaultOperandRenderers(
3799 BuildMIAction &DstMIBuilder, DagInit *DefaultOps) const {
Craig Topper481ff702017-05-29 21:49:34 +00003800 for (const auto *DefaultOp : DefaultOps->getArgs()) {
Diana Picus382602f2017-05-17 08:57:28 +00003801 // Look through ValueType operators.
3802 if (const DagInit *DefaultDagOp = dyn_cast<DagInit>(DefaultOp)) {
3803 if (const DefInit *DefaultDagOperator =
3804 dyn_cast<DefInit>(DefaultDagOp->getOperator())) {
3805 if (DefaultDagOperator->getDef()->isSubClassOf("ValueType"))
3806 DefaultOp = DefaultDagOp->getArg(0);
3807 }
3808 }
3809
3810 if (const DefInit *DefaultDefOp = dyn_cast<DefInit>(DefaultOp)) {
Daniel Sanders198447a2017-11-01 00:29:47 +00003811 DstMIBuilder.addRenderer<AddRegisterRenderer>(DefaultDefOp->getDef());
Diana Picus382602f2017-05-17 08:57:28 +00003812 continue;
3813 }
3814
3815 if (const IntInit *DefaultIntOp = dyn_cast<IntInit>(DefaultOp)) {
Daniel Sanders198447a2017-11-01 00:29:47 +00003816 DstMIBuilder.addRenderer<ImmRenderer>(DefaultIntOp->getValue());
Diana Picus382602f2017-05-17 08:57:28 +00003817 continue;
3818 }
3819
3820 return failedImport("Could not add default op");
3821 }
3822
3823 return Error::success();
3824}
3825
Daniel Sandersc270c502017-03-30 09:36:33 +00003826Error GlobalISelEmitter::importImplicitDefRenderers(
Daniel Sandersffc7d582017-03-29 15:37:18 +00003827 BuildMIAction &DstMIBuilder,
3828 const std::vector<Record *> &ImplicitDefs) const {
3829 if (!ImplicitDefs.empty())
3830 return failedImport("Pattern defines a physical register");
Daniel Sandersc270c502017-03-30 09:36:33 +00003831 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00003832}
3833
3834Expected<RuleMatcher> GlobalISelEmitter::runOnPattern(const PatternToMatch &P) {
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003835 // Keep track of the matchers and actions to emit.
Aditya Nandakumarb63e7632018-02-16 22:37:15 +00003836 int Score = P.getPatternComplexity(CGP);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003837 RuleMatcher M(P.getSrcRecord()->getLoc());
Aditya Nandakumarb63e7632018-02-16 22:37:15 +00003838 RuleMatcherScores[M.getRuleID()] = Score;
Daniel Sanders6ea17ed2017-10-31 18:07:03 +00003839 M.addAction<DebugCommentAction>(llvm::to_string(*P.getSrcPattern()) +
3840 " => " +
3841 llvm::to_string(*P.getDstPattern()));
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003842
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003843 if (auto Error = importRulePredicates(M, P.getPredicates()))
Daniel Sandersffc7d582017-03-29 15:37:18 +00003844 return std::move(Error);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003845
3846 // Next, analyze the pattern operators.
Florian Hahn6b1db822018-06-14 20:32:58 +00003847 TreePatternNode *Src = P.getSrcPattern();
3848 TreePatternNode *Dst = P.getDstPattern();
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003849
3850 // If the root of either pattern isn't a simple operator, ignore it.
Daniel Sandersd0656a32017-04-13 09:45:37 +00003851 if (auto Err = isTrivialOperatorNode(Dst))
3852 return failedImport("Dst pattern root isn't a trivial operator (" +
3853 toString(std::move(Err)) + ")");
3854 if (auto Err = isTrivialOperatorNode(Src))
3855 return failedImport("Src pattern root isn't a trivial operator (" +
3856 toString(std::move(Err)) + ")");
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003857
Quentin Colombetaad20be2017-12-15 23:07:42 +00003858 // The different predicates and matchers created during
3859 // addInstructionMatcher use the RuleMatcher M to set up their
3860 // instruction ID (InsnVarID) that are going to be used when
3861 // M is going to be emitted.
3862 // However, the code doing the emission still relies on the IDs
3863 // returned during that process by the RuleMatcher when issuing
3864 // the recordInsn opcodes.
3865 // Because of that:
3866 // 1. The order in which we created the predicates
3867 // and such must be the same as the order in which we emit them,
3868 // and
3869 // 2. We need to reset the generation of the IDs in M somewhere between
3870 // addInstructionMatcher and emit
3871 //
3872 // FIXME: Long term, we don't want to have to rely on this implicit
3873 // naming being the same. One possible solution would be to have
3874 // explicit operator for operation capture and reference those.
3875 // The plus side is that it would expose opportunities to share
3876 // the capture accross rules. The downside is that it would
3877 // introduce a dependency between predicates (captures must happen
3878 // before their first use.)
Florian Hahn6b1db822018-06-14 20:32:58 +00003879 InstructionMatcher &InsnMatcherTemp = M.addInstructionMatcher(Src->getName());
Daniel Sandersedd07842017-08-17 09:26:14 +00003880 unsigned TempOpIdx = 0;
3881 auto InsnMatcherOrError =
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003882 createAndImportSelDAGMatcher(M, InsnMatcherTemp, Src, TempOpIdx);
Daniel Sandersedd07842017-08-17 09:26:14 +00003883 if (auto Error = InsnMatcherOrError.takeError())
3884 return std::move(Error);
3885 InstructionMatcher &InsnMatcher = InsnMatcherOrError.get();
3886
Florian Hahn6b1db822018-06-14 20:32:58 +00003887 if (Dst->isLeaf()) {
3888 Record *RCDef = getInitValueAsRegClass(Dst->getLeafValue());
Daniel Sandersedd07842017-08-17 09:26:14 +00003889
3890 const CodeGenRegisterClass &RC = Target.getRegisterClass(RCDef);
3891 if (RCDef) {
3892 // We need to replace the def and all its uses with the specified
3893 // operand. However, we must also insert COPY's wherever needed.
3894 // For now, emit a copy and let the register allocator clean up.
3895 auto &DstI = Target.getInstruction(RK.getDef("COPY"));
3896 const auto &DstIOperand = DstI.Operands[0];
3897
3898 OperandMatcher &OM0 = InsnMatcher.getOperand(0);
3899 OM0.setSymbolicName(DstIOperand.Name);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003900 M.defineOperand(OM0.getSymbolicName(), OM0);
Daniel Sandersedd07842017-08-17 09:26:14 +00003901 OM0.addPredicate<RegisterBankOperandMatcher>(RC);
3902
Daniel Sanders198447a2017-11-01 00:29:47 +00003903 auto &DstMIBuilder =
3904 M.addAction<BuildMIAction>(M.allocateOutputInsnID(), &DstI);
3905 DstMIBuilder.addRenderer<CopyRenderer>(DstIOperand.Name);
Florian Hahn6b1db822018-06-14 20:32:58 +00003906 DstMIBuilder.addRenderer<CopyRenderer>(Dst->getName());
Daniel Sandersedd07842017-08-17 09:26:14 +00003907 M.addAction<ConstrainOperandToRegClassAction>(0, 0, RC);
3908
3909 // We're done with this pattern! It's eligible for GISel emission; return
3910 // it.
3911 ++NumPatternImported;
3912 return std::move(M);
3913 }
3914
Daniel Sanders452c8ae2017-05-23 19:33:16 +00003915 return failedImport("Dst pattern root isn't a known leaf");
Daniel Sandersedd07842017-08-17 09:26:14 +00003916 }
Daniel Sanders452c8ae2017-05-23 19:33:16 +00003917
Daniel Sandersbee57392017-04-04 13:25:23 +00003918 // Start with the defined operands (i.e., the results of the root operator).
Florian Hahn6b1db822018-06-14 20:32:58 +00003919 Record *DstOp = Dst->getOperator();
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003920 if (!DstOp->isSubClassOf("Instruction"))
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003921 return failedImport("Pattern operator isn't an instruction");
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003922
3923 auto &DstI = Target.getInstruction(DstOp);
Florian Hahn6b1db822018-06-14 20:32:58 +00003924 if (DstI.Operands.NumDefs != Src->getExtTypes().size())
Daniel Sandersd0656a32017-04-13 09:45:37 +00003925 return failedImport("Src pattern results and dst MI defs are different (" +
Florian Hahn6b1db822018-06-14 20:32:58 +00003926 to_string(Src->getExtTypes().size()) + " def(s) vs " +
Daniel Sandersd0656a32017-04-13 09:45:37 +00003927 to_string(DstI.Operands.NumDefs) + " def(s))");
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003928
Daniel Sandersffc7d582017-03-29 15:37:18 +00003929 // The root of the match also has constraints on the register bank so that it
3930 // matches the result instruction.
3931 unsigned OpIdx = 0;
Florian Hahn6b1db822018-06-14 20:32:58 +00003932 for (const TypeSetByHwMode &VTy : Src->getExtTypes()) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003933 (void)VTy;
Daniel Sandersffc7d582017-03-29 15:37:18 +00003934
Daniel Sanders066ebbf2017-02-24 15:43:30 +00003935 const auto &DstIOperand = DstI.Operands[OpIdx];
3936 Record *DstIOpRec = DstIOperand.Rec;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003937 if (DstI.TheDef->getName() == "COPY_TO_REGCLASS") {
Florian Hahn6b1db822018-06-14 20:32:58 +00003938 DstIOpRec = getInitValueAsRegClass(Dst->getChild(1)->getLeafValue());
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003939
3940 if (DstIOpRec == nullptr)
3941 return failedImport(
3942 "COPY_TO_REGCLASS operand #1 isn't a register class");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00003943 } else if (DstI.TheDef->getName() == "EXTRACT_SUBREG") {
Florian Hahn6b1db822018-06-14 20:32:58 +00003944 if (!Dst->getChild(0)->isLeaf())
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00003945 return failedImport("EXTRACT_SUBREG operand #0 isn't a leaf");
3946
Daniel Sanders32291982017-06-28 13:50:04 +00003947 // We can assume that a subregister is in the same bank as it's super
3948 // register.
Florian Hahn6b1db822018-06-14 20:32:58 +00003949 DstIOpRec = getInitValueAsRegClass(Dst->getChild(0)->getLeafValue());
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00003950
3951 if (DstIOpRec == nullptr)
3952 return failedImport(
3953 "EXTRACT_SUBREG operand #0 isn't a register class");
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003954 } else if (DstIOpRec->isSubClassOf("RegisterOperand"))
Daniel Sanders658541f2017-04-22 15:53:21 +00003955 DstIOpRec = DstIOpRec->getValueAsDef("RegClass");
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003956 else if (!DstIOpRec->isSubClassOf("RegisterClass"))
Florian Hahn6b1db822018-06-14 20:32:58 +00003957 return failedImport("Dst MI def isn't a register class" +
3958 to_string(*Dst));
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003959
Daniel Sandersffc7d582017-03-29 15:37:18 +00003960 OperandMatcher &OM = InsnMatcher.getOperand(OpIdx);
3961 OM.setSymbolicName(DstIOperand.Name);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003962 M.defineOperand(OM.getSymbolicName(), OM);
Daniel Sandersdc662ff2017-01-26 11:10:14 +00003963 OM.addPredicate<RegisterBankOperandMatcher>(
3964 Target.getRegisterClass(DstIOpRec));
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003965 ++OpIdx;
3966 }
3967
Daniel Sandersa7b75262017-10-31 18:50:24 +00003968 auto DstMIBuilderOrError = createAndImportInstructionRenderer(M, Dst);
Daniel Sandersffc7d582017-03-29 15:37:18 +00003969 if (auto Error = DstMIBuilderOrError.takeError())
3970 return std::move(Error);
3971 BuildMIAction &DstMIBuilder = DstMIBuilderOrError.get();
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003972
Daniel Sandersffc7d582017-03-29 15:37:18 +00003973 // Render the implicit defs.
3974 // These are only added to the root of the result.
Daniel Sandersc270c502017-03-30 09:36:33 +00003975 if (auto Error = importImplicitDefRenderers(DstMIBuilder, P.getDstRegs()))
Daniel Sandersffc7d582017-03-29 15:37:18 +00003976 return std::move(Error);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003977
Daniel Sandersa7b75262017-10-31 18:50:24 +00003978 DstMIBuilder.chooseInsnToMutate(M);
3979
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003980 // Constrain the registers to classes. This is normally derived from the
3981 // emitted instruction but a few instructions require special handling.
3982 if (DstI.TheDef->getName() == "COPY_TO_REGCLASS") {
3983 // COPY_TO_REGCLASS does not provide operand constraints itself but the
3984 // result is constrained to the class given by the second child.
3985 Record *DstIOpRec =
Florian Hahn6b1db822018-06-14 20:32:58 +00003986 getInitValueAsRegClass(Dst->getChild(1)->getLeafValue());
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003987
3988 if (DstIOpRec == nullptr)
3989 return failedImport("COPY_TO_REGCLASS operand #1 isn't a register class");
3990
3991 M.addAction<ConstrainOperandToRegClassAction>(
Daniel Sandersd93a35a2017-07-05 09:39:33 +00003992 0, 0, Target.getRegisterClass(DstIOpRec));
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00003993
3994 // We're done with this pattern! It's eligible for GISel emission; return
3995 // it.
3996 ++NumPatternImported;
3997 return std::move(M);
3998 }
3999
4000 if (DstI.TheDef->getName() == "EXTRACT_SUBREG") {
4001 // EXTRACT_SUBREG selects into a subregister COPY but unlike most
4002 // instructions, the result register class is controlled by the
4003 // subregisters of the operand. As a result, we must constrain the result
4004 // class rather than check that it's already the right one.
Florian Hahn6b1db822018-06-14 20:32:58 +00004005 if (!Dst->getChild(0)->isLeaf())
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004006 return failedImport("EXTRACT_SUBREG child #1 is not a leaf");
4007
Florian Hahn6b1db822018-06-14 20:32:58 +00004008 DefInit *SubRegInit = dyn_cast<DefInit>(Dst->getChild(1)->getLeafValue());
Daniel Sanders320390b2017-06-28 15:16:03 +00004009 if (!SubRegInit)
4010 return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004011
Daniel Sanders320390b2017-06-28 15:16:03 +00004012 // Constrain the result to the same register bank as the operand.
4013 Record *DstIOpRec =
Florian Hahn6b1db822018-06-14 20:32:58 +00004014 getInitValueAsRegClass(Dst->getChild(0)->getLeafValue());
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004015
Daniel Sanders320390b2017-06-28 15:16:03 +00004016 if (DstIOpRec == nullptr)
4017 return failedImport("EXTRACT_SUBREG operand #1 isn't a register class");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004018
Daniel Sanders320390b2017-06-28 15:16:03 +00004019 CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef());
Daniel Sandersd93a35a2017-07-05 09:39:33 +00004020 CodeGenRegisterClass *SrcRC = CGRegs.getRegClass(DstIOpRec);
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004021
Daniel Sanders320390b2017-06-28 15:16:03 +00004022 // It would be nice to leave this constraint implicit but we're required
4023 // to pick a register class so constrain the result to a register class
4024 // that can hold the correct MVT.
4025 //
4026 // FIXME: This may introduce an extra copy if the chosen class doesn't
4027 // actually contain the subregisters.
Florian Hahn6b1db822018-06-14 20:32:58 +00004028 assert(Src->getExtTypes().size() == 1 &&
Daniel Sanders320390b2017-06-28 15:16:03 +00004029 "Expected Src of EXTRACT_SUBREG to have one result type");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004030
Daniel Sanders320390b2017-06-28 15:16:03 +00004031 const auto &SrcRCDstRCPair =
4032 SrcRC->getMatchingSubClassWithSubRegs(CGRegs, SubIdx);
4033 assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
Daniel Sandersd93a35a2017-07-05 09:39:33 +00004034 M.addAction<ConstrainOperandToRegClassAction>(0, 0, *SrcRCDstRCPair->second);
4035 M.addAction<ConstrainOperandToRegClassAction>(0, 1, *SrcRCDstRCPair->first);
4036
4037 // We're done with this pattern! It's eligible for GISel emission; return
4038 // it.
4039 ++NumPatternImported;
4040 return std::move(M);
4041 }
4042
4043 M.addAction<ConstrainOperandsToDefinitionAction>(0);
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004044
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00004045 // We're done with this pattern! It's eligible for GISel emission; return it.
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00004046 ++NumPatternImported;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00004047 return std::move(M);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004048}
4049
Daniel Sanders649c5852017-10-13 20:42:18 +00004050// Emit imm predicate table and an enum to reference them with.
4051// The 'Predicate_' part of the name is redundant but eliminating it is more
4052// trouble than it's worth.
Daniel Sanders8ead1292018-06-15 23:13:43 +00004053void GlobalISelEmitter::emitCxxPredicateFns(
4054 raw_ostream &OS, StringRef CodeFieldName, StringRef TypeIdentifier,
4055 StringRef ArgType, StringRef ArgName, StringRef AdditionalDeclarations,
Daniel Sanders11300ce2017-10-13 21:28:03 +00004056 std::function<bool(const Record *R)> Filter) {
Daniel Sanders649c5852017-10-13 20:42:18 +00004057 std::vector<const Record *> MatchedRecords;
4058 const auto &Defs = RK.getAllDerivedDefinitions("PatFrag");
4059 std::copy_if(Defs.begin(), Defs.end(), std::back_inserter(MatchedRecords),
4060 [&](Record *Record) {
Daniel Sanders8ead1292018-06-15 23:13:43 +00004061 return !Record->getValueAsString(CodeFieldName).empty() &&
Daniel Sanders649c5852017-10-13 20:42:18 +00004062 Filter(Record);
4063 });
4064
Daniel Sanders11300ce2017-10-13 21:28:03 +00004065 if (!MatchedRecords.empty()) {
4066 OS << "// PatFrag predicates.\n"
4067 << "enum {\n";
Daniel Sanders2fed4ff2017-10-13 21:51:20 +00004068 std::string EnumeratorSeparator =
Daniel Sanders11300ce2017-10-13 21:28:03 +00004069 (" = GIPFP_" + TypeIdentifier + "_Invalid + 1,\n").str();
4070 for (const auto *Record : MatchedRecords) {
4071 OS << " GIPFP_" << TypeIdentifier << "_Predicate_" << Record->getName()
4072 << EnumeratorSeparator;
4073 EnumeratorSeparator = ",\n";
4074 }
4075 OS << "};\n";
Daniel Sanders649c5852017-10-13 20:42:18 +00004076 }
Daniel Sanders11300ce2017-10-13 21:28:03 +00004077
Daniel Sanders8ead1292018-06-15 23:13:43 +00004078 OS << "bool " << Target.getName() << "InstructionSelector::test" << ArgName
4079 << "Predicate_" << TypeIdentifier << "(unsigned PredicateID, " << ArgType << " "
4080 << ArgName << ") const {\n"
4081 << AdditionalDeclarations;
4082 if (!AdditionalDeclarations.empty())
4083 OS << "\n";
Aaron Ballman82e17f52017-12-20 20:09:30 +00004084 if (!MatchedRecords.empty())
4085 OS << " switch (PredicateID) {\n";
Daniel Sanders32de8bb2017-12-20 14:41:51 +00004086 for (const auto *Record : MatchedRecords) {
4087 OS << " case GIPFP_" << TypeIdentifier << "_Predicate_"
4088 << Record->getName() << ": {\n"
Daniel Sanders8ead1292018-06-15 23:13:43 +00004089 << " " << Record->getValueAsString(CodeFieldName) << "\n"
4090 << " llvm_unreachable(\"" << CodeFieldName
4091 << " should have returned\");\n"
Daniel Sanders32de8bb2017-12-20 14:41:51 +00004092 << " return false;\n"
4093 << " }\n";
4094 }
Aaron Ballman82e17f52017-12-20 20:09:30 +00004095 if (!MatchedRecords.empty())
4096 OS << " }\n";
4097 OS << " llvm_unreachable(\"Unknown predicate\");\n"
Daniel Sanders32de8bb2017-12-20 14:41:51 +00004098 << " return false;\n"
4099 << "}\n";
Daniel Sanders649c5852017-10-13 20:42:18 +00004100}
4101
Daniel Sanders8ead1292018-06-15 23:13:43 +00004102void GlobalISelEmitter::emitImmPredicateFns(
4103 raw_ostream &OS, StringRef TypeIdentifier, StringRef ArgType,
4104 std::function<bool(const Record *R)> Filter) {
4105 return emitCxxPredicateFns(OS, "ImmediateCode", TypeIdentifier, ArgType,
4106 "Imm", "", Filter);
4107}
4108
4109void GlobalISelEmitter::emitMIPredicateFns(raw_ostream &OS) {
4110 return emitCxxPredicateFns(
4111 OS, "GISelPredicateCode", "MI", "const MachineInstr &", "MI",
4112 " const MachineFunction &MF = *MI.getParent()->getParent();\n"
4113 " const LLVM_ATTRIBUTE_UNUSED MachineRegisterInfo &MRI = "
4114 "MF.getRegInfo();",
4115 [](const Record *R) { return true; });
4116}
4117
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004118template <class GroupT>
Quentin Colombetec76d9c2017-12-18 19:47:41 +00004119std::vector<Matcher *> GlobalISelEmitter::optimizeRules(
Roman Tereshin2d6d3762018-05-02 20:08:14 +00004120 ArrayRef<Matcher *> Rules,
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004121 std::vector<std::unique_ptr<Matcher>> &MatcherStorage) {
4122
Quentin Colombetec76d9c2017-12-18 19:47:41 +00004123 std::vector<Matcher *> OptRules;
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004124 std::unique_ptr<GroupT> CurrentGroup = make_unique<GroupT>();
4125 assert(CurrentGroup->empty() && "Newly created group isn't empty!");
4126 unsigned NumGroups = 0;
4127
4128 auto ProcessCurrentGroup = [&]() {
4129 if (CurrentGroup->empty())
4130 // An empty group is good to be reused:
4131 return;
4132
4133 // If the group isn't large enough to provide any benefit, move all the
4134 // added rules out of it and make sure to re-create the group to properly
4135 // re-initialize it:
4136 if (CurrentGroup->size() < 2)
4137 for (Matcher *M : CurrentGroup->matchers())
4138 OptRules.push_back(M);
4139 else {
4140 CurrentGroup->finalize();
Roman Tereshin8bdf7be2018-05-21 22:21:24 +00004141 OptRules.push_back(CurrentGroup.get());
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004142 MatcherStorage.emplace_back(std::move(CurrentGroup));
4143 ++NumGroups;
Roman Tereshin8bdf7be2018-05-21 22:21:24 +00004144 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004145 CurrentGroup = make_unique<GroupT>();
4146 };
4147 for (Matcher *Rule : Rules) {
4148 // Greedily add as many matchers as possible to the current group:
4149 if (CurrentGroup->addMatcher(*Rule))
4150 continue;
4151
4152 ProcessCurrentGroup();
4153 assert(CurrentGroup->empty() && "A group wasn't properly re-initialized");
4154
4155 // Try to add the pending matcher to a newly created empty group:
4156 if (!CurrentGroup->addMatcher(*Rule))
4157 // If we couldn't add the matcher to an empty group, that group type
4158 // doesn't support that kind of matchers at all, so just skip it:
4159 OptRules.push_back(Rule);
Quentin Colombetec76d9c2017-12-18 19:47:41 +00004160 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004161 ProcessCurrentGroup();
4162
Nicola Zaghen03d0b912018-05-23 15:09:29 +00004163 LLVM_DEBUG(dbgs() << "NumGroups: " << NumGroups << "\n");
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004164 assert(CurrentGroup->empty() && "The last group wasn't properly processed");
Quentin Colombetec76d9c2017-12-18 19:47:41 +00004165 return OptRules;
4166}
4167
Roman Tereshin2d6d3762018-05-02 20:08:14 +00004168MatchTable
4169GlobalISelEmitter::buildMatchTable(MutableArrayRef<RuleMatcher> Rules,
Roman Tereshinbeb39312018-05-02 20:15:11 +00004170 bool Optimize, bool WithCoverage) {
Roman Tereshin2d6d3762018-05-02 20:08:14 +00004171 std::vector<Matcher *> InputRules;
4172 for (Matcher &Rule : Rules)
4173 InputRules.push_back(&Rule);
4174
4175 if (!Optimize)
Roman Tereshinbeb39312018-05-02 20:15:11 +00004176 return MatchTable::buildTable(InputRules, WithCoverage);
Roman Tereshin2d6d3762018-05-02 20:08:14 +00004177
Roman Tereshin77013602018-05-22 16:54:27 +00004178 unsigned CurrentOrdering = 0;
4179 StringMap<unsigned> OpcodeOrder;
4180 for (RuleMatcher &Rule : Rules) {
4181 const StringRef Opcode = Rule.getOpcode();
4182 assert(!Opcode.empty() && "Didn't expect an undefined opcode");
4183 if (OpcodeOrder.count(Opcode) == 0)
4184 OpcodeOrder[Opcode] = CurrentOrdering++;
4185 }
4186
4187 std::stable_sort(InputRules.begin(), InputRules.end(),
4188 [&OpcodeOrder](const Matcher *A, const Matcher *B) {
4189 auto *L = static_cast<const RuleMatcher *>(A);
4190 auto *R = static_cast<const RuleMatcher *>(B);
4191 return std::make_tuple(OpcodeOrder[L->getOpcode()],
4192 L->getNumOperands()) <
4193 std::make_tuple(OpcodeOrder[R->getOpcode()],
4194 R->getNumOperands());
4195 });
4196
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004197 for (Matcher *Rule : InputRules)
4198 Rule->optimize();
4199
4200 std::vector<std::unique_ptr<Matcher>> MatcherStorage;
Roman Tereshin2d6d3762018-05-02 20:08:14 +00004201 std::vector<Matcher *> OptRules =
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004202 optimizeRules<GroupMatcher>(InputRules, MatcherStorage);
4203
4204 for (Matcher *Rule : OptRules)
4205 Rule->optimize();
Roman Tereshin2d6d3762018-05-02 20:08:14 +00004206
Roman Tereshin0ee082f2018-05-22 19:37:59 +00004207 OptRules = optimizeRules<SwitchMatcher>(OptRules, MatcherStorage);
4208
Roman Tereshinbeb39312018-05-02 20:15:11 +00004209 return MatchTable::buildTable(OptRules, WithCoverage);
Roman Tereshin2d6d3762018-05-02 20:08:14 +00004210}
4211
Roman Tereshinfedae332018-05-23 02:04:19 +00004212void GroupMatcher::optimize() {
Roman Tereshin9a9fa492018-05-23 21:30:16 +00004213 // Make sure we only sort by a specific predicate within a range of rules that
4214 // all have that predicate checked against a specific value (not a wildcard):
4215 auto F = Matchers.begin();
4216 auto T = F;
4217 auto E = Matchers.end();
4218 while (T != E) {
4219 while (T != E) {
4220 auto *R = static_cast<RuleMatcher *>(*T);
4221 if (!R->getFirstConditionAsRootType().get().isValid())
4222 break;
4223 ++T;
4224 }
4225 std::stable_sort(F, T, [](Matcher *A, Matcher *B) {
4226 auto *L = static_cast<RuleMatcher *>(A);
4227 auto *R = static_cast<RuleMatcher *>(B);
4228 return L->getFirstConditionAsRootType() <
4229 R->getFirstConditionAsRootType();
4230 });
4231 if (T != E)
4232 F = ++T;
4233 }
Roman Tereshinfedae332018-05-23 02:04:19 +00004234 GlobalISelEmitter::optimizeRules<GroupMatcher>(Matchers, MatcherStorage)
4235 .swap(Matchers);
Roman Tereshina4c410d2018-05-24 00:24:15 +00004236 GlobalISelEmitter::optimizeRules<SwitchMatcher>(Matchers, MatcherStorage)
4237 .swap(Matchers);
Roman Tereshinfedae332018-05-23 02:04:19 +00004238}
4239
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004240void GlobalISelEmitter::run(raw_ostream &OS) {
Daniel Sandersf76f3152017-11-16 00:46:35 +00004241 if (!UseCoverageFile.empty()) {
4242 RuleCoverage = CodeGenCoverage();
4243 auto RuleCoverageBufOrErr = MemoryBuffer::getFile(UseCoverageFile);
4244 if (!RuleCoverageBufOrErr) {
4245 PrintWarning(SMLoc(), "Missing rule coverage data");
4246 RuleCoverage = None;
4247 } else {
4248 if (!RuleCoverage->parse(*RuleCoverageBufOrErr.get(), Target.getName())) {
4249 PrintWarning(SMLoc(), "Ignoring invalid or missing rule coverage data");
4250 RuleCoverage = None;
4251 }
4252 }
4253 }
4254
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004255 // Track the run-time opcode values
4256 gatherOpcodeValues();
4257 // Track the run-time LLT ID values
4258 gatherTypeIDValues();
4259
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004260 // Track the GINodeEquiv definitions.
4261 gatherNodeEquivs();
4262
4263 emitSourceFileHeader(("Global Instruction Selector for the " +
4264 Target.getName() + " target").str(), OS);
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00004265 std::vector<RuleMatcher> Rules;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004266 // Look through the SelectionDAG patterns we found, possibly emitting some.
4267 for (const PatternToMatch &Pat : CGP.ptms()) {
4268 ++NumPatternTotal;
Daniel Sanders7e523672017-11-11 03:23:44 +00004269
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00004270 auto MatcherOrErr = runOnPattern(Pat);
4271
4272 // The pattern analysis can fail, indicating an unsupported pattern.
4273 // Report that if we've been asked to do so.
4274 if (auto Err = MatcherOrErr.takeError()) {
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004275 if (WarnOnSkippedPatterns) {
4276 PrintWarning(Pat.getSrcRecord()->getLoc(),
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00004277 "Skipped pattern: " + toString(std::move(Err)));
4278 } else {
4279 consumeError(std::move(Err));
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004280 }
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00004281 ++NumPatternImportsSkipped;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00004282 continue;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004283 }
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00004284
Daniel Sandersf76f3152017-11-16 00:46:35 +00004285 if (RuleCoverage) {
4286 if (RuleCoverage->isCovered(MatcherOrErr->getRuleID()))
4287 ++NumPatternsTested;
4288 else
4289 PrintWarning(Pat.getSrcRecord()->getLoc(),
4290 "Pattern is not covered by a test");
4291 }
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00004292 Rules.push_back(std::move(MatcherOrErr.get()));
4293 }
4294
Volkan Kelesf7f25682018-01-16 18:44:05 +00004295 // Comparison function to order records by name.
4296 auto orderByName = [](const Record *A, const Record *B) {
4297 return A->getName() < B->getName();
4298 };
4299
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00004300 std::vector<Record *> ComplexPredicates =
4301 RK.getAllDerivedDefinitions("GIComplexOperandMatcher");
Mandeep Singh Grang1b0e2f22018-04-06 20:18:05 +00004302 llvm::sort(ComplexPredicates.begin(), ComplexPredicates.end(), orderByName);
Volkan Kelesf7f25682018-01-16 18:44:05 +00004303
4304 std::vector<Record *> CustomRendererFns =
4305 RK.getAllDerivedDefinitions("GICustomOperandRenderer");
Mandeep Singh Grang1b0e2f22018-04-06 20:18:05 +00004306 llvm::sort(CustomRendererFns.begin(), CustomRendererFns.end(), orderByName);
Volkan Kelesf7f25682018-01-16 18:44:05 +00004307
Daniel Sanders8a4bae92017-03-14 21:32:08 +00004308 unsigned MaxTemporaries = 0;
4309 for (const auto &Rule : Rules)
Daniel Sanders2deea182017-04-22 15:11:04 +00004310 MaxTemporaries = std::max(MaxTemporaries, Rule.countRendererFns());
Daniel Sanders8a4bae92017-03-14 21:32:08 +00004311
Daniel Sanderse7b0d662017-04-21 15:59:56 +00004312 OS << "#ifdef GET_GLOBALISEL_PREDICATE_BITSET\n"
4313 << "const unsigned MAX_SUBTARGET_PREDICATES = " << SubtargetFeatures.size()
4314 << ";\n"
4315 << "using PredicateBitset = "
4316 "llvm::PredicateBitsetImpl<MAX_SUBTARGET_PREDICATES>;\n"
4317 << "#endif // ifdef GET_GLOBALISEL_PREDICATE_BITSET\n\n";
4318
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00004319 OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n"
4320 << " mutable MatcherState State;\n"
4321 << " typedef "
Daniel Sanders1e4569f2017-10-20 20:55:29 +00004322 "ComplexRendererFns("
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00004323 << Target.getName()
4324 << "InstructionSelector::*ComplexMatcherMemFn)(MachineOperand &) const;\n"
Volkan Kelesf7f25682018-01-16 18:44:05 +00004325
4326 << " typedef void(" << Target.getName()
4327 << "InstructionSelector::*CustomRendererFn)(MachineInstrBuilder &, const "
4328 "MachineInstr&) "
4329 "const;\n"
4330 << " const ISelInfoTy<PredicateBitset, ComplexMatcherMemFn, "
4331 "CustomRendererFn> "
4332 "ISelInfo;\n";
4333 OS << " static " << Target.getName()
Daniel Sandersea8711b2017-10-16 03:36:29 +00004334 << "InstructionSelector::ComplexMatcherMemFn ComplexPredicateFns[];\n"
Volkan Kelesf7f25682018-01-16 18:44:05 +00004335 << " static " << Target.getName()
4336 << "InstructionSelector::CustomRendererFn CustomRenderers[];\n"
Roman Tereshin2df4c222018-05-02 20:07:15 +00004337 << " bool testImmPredicate_I64(unsigned PredicateID, int64_t Imm) const "
Daniel Sanders32de8bb2017-12-20 14:41:51 +00004338 "override;\n"
Roman Tereshin2df4c222018-05-02 20:07:15 +00004339 << " bool testImmPredicate_APInt(unsigned PredicateID, const APInt &Imm) "
Daniel Sanders32de8bb2017-12-20 14:41:51 +00004340 "const override;\n"
Roman Tereshin2df4c222018-05-02 20:07:15 +00004341 << " bool testImmPredicate_APFloat(unsigned PredicateID, const APFloat "
Daniel Sanders32de8bb2017-12-20 14:41:51 +00004342 "&Imm) const override;\n"
Roman Tereshin2df4c222018-05-02 20:07:15 +00004343 << " const int64_t *getMatchTable() const override;\n"
Daniel Sanders8ead1292018-06-15 23:13:43 +00004344 << " bool testMIPredicate_MI(unsigned PredicateID, const MachineInstr &MI) "
4345 "const override;\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00004346 << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n\n";
Daniel Sanders8a4bae92017-03-14 21:32:08 +00004347
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00004348 OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n"
4349 << ", State(" << MaxTemporaries << "),\n"
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004350 << "ISelInfo(TypeObjects, NumTypeObjects, FeatureBitsets"
4351 << ", ComplexPredicateFns, CustomRenderers)\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00004352 << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n\n";
Daniel Sanders8a4bae92017-03-14 21:32:08 +00004353
Daniel Sanderse7b0d662017-04-21 15:59:56 +00004354 OS << "#ifdef GET_GLOBALISEL_IMPL\n";
4355 SubtargetFeatureInfo::emitSubtargetFeatureBitEnumeration(SubtargetFeatures,
4356 OS);
Daniel Sanderse9fdba32017-04-29 17:30:09 +00004357
4358 // Separate subtarget features by how often they must be recomputed.
4359 SubtargetFeatureInfoMap ModuleFeatures;
4360 std::copy_if(SubtargetFeatures.begin(), SubtargetFeatures.end(),
4361 std::inserter(ModuleFeatures, ModuleFeatures.end()),
4362 [](const SubtargetFeatureInfoMap::value_type &X) {
4363 return !X.second.mustRecomputePerFunction();
4364 });
4365 SubtargetFeatureInfoMap FunctionFeatures;
4366 std::copy_if(SubtargetFeatures.begin(), SubtargetFeatures.end(),
4367 std::inserter(FunctionFeatures, FunctionFeatures.end()),
4368 [](const SubtargetFeatureInfoMap::value_type &X) {
4369 return X.second.mustRecomputePerFunction();
4370 });
4371
Daniel Sanderse7b0d662017-04-21 15:59:56 +00004372 SubtargetFeatureInfo::emitComputeAvailableFeatures(
Daniel Sanderse9fdba32017-04-29 17:30:09 +00004373 Target.getName(), "InstructionSelector", "computeAvailableModuleFeatures",
4374 ModuleFeatures, OS);
4375 SubtargetFeatureInfo::emitComputeAvailableFeatures(
4376 Target.getName(), "InstructionSelector",
4377 "computeAvailableFunctionFeatures", FunctionFeatures, OS,
4378 "const MachineFunction *MF");
Daniel Sanderse7b0d662017-04-21 15:59:56 +00004379
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00004380 // Emit a table containing the LLT objects needed by the matcher and an enum
4381 // for the matcher to reference them with.
Daniel Sanders032e7f22017-08-17 13:18:35 +00004382 std::vector<LLTCodeGen> TypeObjects;
Daniel Sandersf84bc372018-05-05 20:53:24 +00004383 for (const auto &Ty : KnownTypes)
Daniel Sanders032e7f22017-08-17 13:18:35 +00004384 TypeObjects.push_back(Ty);
Mandeep Singh Grang1b0e2f22018-04-06 20:18:05 +00004385 llvm::sort(TypeObjects.begin(), TypeObjects.end());
Daniel Sanders49980702017-08-23 10:09:25 +00004386 OS << "// LLT Objects.\n"
4387 << "enum {\n";
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00004388 for (const auto &TypeObject : TypeObjects) {
4389 OS << " ";
4390 TypeObject.emitCxxEnumValue(OS);
4391 OS << ",\n";
4392 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004393 OS << "};\n";
4394 OS << "const static size_t NumTypeObjects = " << TypeObjects.size() << ";\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00004395 << "const static LLT TypeObjects[] = {\n";
4396 for (const auto &TypeObject : TypeObjects) {
4397 OS << " ";
4398 TypeObject.emitCxxConstructorCall(OS);
4399 OS << ",\n";
4400 }
4401 OS << "};\n\n";
4402
4403 // Emit a table containing the PredicateBitsets objects needed by the matcher
4404 // and an enum for the matcher to reference them with.
4405 std::vector<std::vector<Record *>> FeatureBitsets;
4406 for (auto &Rule : Rules)
4407 FeatureBitsets.push_back(Rule.getRequiredFeatures());
Mandeep Singh Grang1b0e2f22018-04-06 20:18:05 +00004408 llvm::sort(
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00004409 FeatureBitsets.begin(), FeatureBitsets.end(),
4410 [&](const std::vector<Record *> &A, const std::vector<Record *> &B) {
4411 if (A.size() < B.size())
4412 return true;
4413 if (A.size() > B.size())
4414 return false;
4415 for (const auto &Pair : zip(A, B)) {
4416 if (std::get<0>(Pair)->getName() < std::get<1>(Pair)->getName())
4417 return true;
4418 if (std::get<0>(Pair)->getName() > std::get<1>(Pair)->getName())
4419 return false;
4420 }
4421 return false;
4422 });
4423 FeatureBitsets.erase(
4424 std::unique(FeatureBitsets.begin(), FeatureBitsets.end()),
4425 FeatureBitsets.end());
Daniel Sanders49980702017-08-23 10:09:25 +00004426 OS << "// Feature bitsets.\n"
4427 << "enum {\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00004428 << " GIFBS_Invalid,\n";
4429 for (const auto &FeatureBitset : FeatureBitsets) {
4430 if (FeatureBitset.empty())
4431 continue;
4432 OS << " " << getNameForFeatureBitset(FeatureBitset) << ",\n";
4433 }
4434 OS << "};\n"
4435 << "const static PredicateBitset FeatureBitsets[] {\n"
4436 << " {}, // GIFBS_Invalid\n";
4437 for (const auto &FeatureBitset : FeatureBitsets) {
4438 if (FeatureBitset.empty())
4439 continue;
4440 OS << " {";
4441 for (const auto &Feature : FeatureBitset) {
4442 const auto &I = SubtargetFeatures.find(Feature);
4443 assert(I != SubtargetFeatures.end() && "Didn't import predicate?");
4444 OS << I->second.getEnumBitName() << ", ";
4445 }
4446 OS << "},\n";
4447 }
4448 OS << "};\n\n";
4449
4450 // Emit complex predicate table and an enum to reference them with.
Daniel Sanders49980702017-08-23 10:09:25 +00004451 OS << "// ComplexPattern predicates.\n"
4452 << "enum {\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00004453 << " GICP_Invalid,\n";
4454 for (const auto &Record : ComplexPredicates)
4455 OS << " GICP_" << Record->getName() << ",\n";
4456 OS << "};\n"
4457 << "// See constructor for table contents\n\n";
4458
Daniel Sanders8ead1292018-06-15 23:13:43 +00004459 emitImmPredicateFns(OS, "I64", "int64_t", [](const Record *R) {
Daniel Sanders649c5852017-10-13 20:42:18 +00004460 bool Unset;
4461 return !R->getValueAsBitOrUnset("IsAPFloat", Unset) &&
4462 !R->getValueAsBit("IsAPInt");
4463 });
Daniel Sanders8ead1292018-06-15 23:13:43 +00004464 emitImmPredicateFns(OS, "APFloat", "const APFloat &", [](const Record *R) {
Daniel Sanders11300ce2017-10-13 21:28:03 +00004465 bool Unset;
4466 return R->getValueAsBitOrUnset("IsAPFloat", Unset);
4467 });
Daniel Sanders8ead1292018-06-15 23:13:43 +00004468 emitImmPredicateFns(OS, "APInt", "const APInt &", [](const Record *R) {
Daniel Sanders11300ce2017-10-13 21:28:03 +00004469 return R->getValueAsBit("IsAPInt");
4470 });
Daniel Sanders8ead1292018-06-15 23:13:43 +00004471 emitMIPredicateFns(OS);
Daniel Sandersea8711b2017-10-16 03:36:29 +00004472 OS << "\n";
4473
4474 OS << Target.getName() << "InstructionSelector::ComplexMatcherMemFn\n"
4475 << Target.getName() << "InstructionSelector::ComplexPredicateFns[] = {\n"
4476 << " nullptr, // GICP_Invalid\n";
4477 for (const auto &Record : ComplexPredicates)
4478 OS << " &" << Target.getName()
4479 << "InstructionSelector::" << Record->getValueAsString("MatcherFn")
4480 << ", // " << Record->getName() << "\n";
4481 OS << "};\n\n";
Daniel Sanders2c269f62017-08-24 09:11:20 +00004482
Volkan Kelesf7f25682018-01-16 18:44:05 +00004483 OS << "// Custom renderers.\n"
4484 << "enum {\n"
4485 << " GICR_Invalid,\n";
4486 for (const auto &Record : CustomRendererFns)
4487 OS << " GICR_" << Record->getValueAsString("RendererFn") << ", \n";
4488 OS << "};\n";
4489
4490 OS << Target.getName() << "InstructionSelector::CustomRendererFn\n"
4491 << Target.getName() << "InstructionSelector::CustomRenderers[] = {\n"
4492 << " nullptr, // GICP_Invalid\n";
4493 for (const auto &Record : CustomRendererFns)
4494 OS << " &" << Target.getName()
4495 << "InstructionSelector::" << Record->getValueAsString("RendererFn")
4496 << ", // " << Record->getName() << "\n";
4497 OS << "};\n\n";
4498
Quentin Colombetec76d9c2017-12-18 19:47:41 +00004499 std::stable_sort(Rules.begin(), Rules.end(), [&](const RuleMatcher &A,
4500 const RuleMatcher &B) {
Aditya Nandakumarb63e7632018-02-16 22:37:15 +00004501 int ScoreA = RuleMatcherScores[A.getRuleID()];
4502 int ScoreB = RuleMatcherScores[B.getRuleID()];
4503 if (ScoreA > ScoreB)
4504 return true;
4505 if (ScoreB > ScoreA)
4506 return false;
Quentin Colombetec76d9c2017-12-18 19:47:41 +00004507 if (A.isHigherPriorityThan(B)) {
4508 assert(!B.isHigherPriorityThan(A) && "Cannot be more important "
4509 "and less important at "
4510 "the same time");
4511 return true;
4512 }
4513 return false;
4514 });
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004515
Roman Tereshin2df4c222018-05-02 20:07:15 +00004516 OS << "bool " << Target.getName()
4517 << "InstructionSelector::selectImpl(MachineInstr &I, CodeGenCoverage "
4518 "&CoverageInfo) const {\n"
4519 << " MachineFunction &MF = *I.getParent()->getParent();\n"
4520 << " MachineRegisterInfo &MRI = MF.getRegInfo();\n"
4521 << " // FIXME: This should be computed on a per-function basis rather "
4522 "than per-insn.\n"
4523 << " AvailableFunctionFeatures = computeAvailableFunctionFeatures(&STI, "
4524 "&MF);\n"
4525 << " const PredicateBitset AvailableFeatures = getAvailableFeatures();\n"
4526 << " NewMIVector OutMIs;\n"
4527 << " State.MIs.clear();\n"
4528 << " State.MIs.push_back(&I);\n\n"
4529 << " if (executeMatchTable(*this, OutMIs, State, ISelInfo"
4530 << ", getMatchTable(), TII, MRI, TRI, RBI, AvailableFeatures"
4531 << ", CoverageInfo)) {\n"
4532 << " return true;\n"
4533 << " }\n\n"
4534 << " return false;\n"
4535 << "}\n\n";
4536
Roman Tereshinbeb39312018-05-02 20:15:11 +00004537 const MatchTable Table =
4538 buildMatchTable(Rules, OptimizeMatchTable, GenerateCoverage);
Roman Tereshin2df4c222018-05-02 20:07:15 +00004539 OS << "const int64_t *" << Target.getName()
4540 << "InstructionSelector::getMatchTable() const {\n";
4541 Table.emitDeclaration(OS);
4542 OS << " return ";
4543 Table.emitUse(OS);
4544 OS << ";\n}\n";
4545 OS << "#endif // ifdef GET_GLOBALISEL_IMPL\n";
Daniel Sanderse9fdba32017-04-29 17:30:09 +00004546
4547 OS << "#ifdef GET_GLOBALISEL_PREDICATES_DECL\n"
4548 << "PredicateBitset AvailableModuleFeatures;\n"
4549 << "mutable PredicateBitset AvailableFunctionFeatures;\n"
4550 << "PredicateBitset getAvailableFeatures() const {\n"
4551 << " return AvailableModuleFeatures | AvailableFunctionFeatures;\n"
4552 << "}\n"
4553 << "PredicateBitset\n"
4554 << "computeAvailableModuleFeatures(const " << Target.getName()
4555 << "Subtarget *Subtarget) const;\n"
4556 << "PredicateBitset\n"
4557 << "computeAvailableFunctionFeatures(const " << Target.getName()
4558 << "Subtarget *Subtarget,\n"
4559 << " const MachineFunction *MF) const;\n"
4560 << "#endif // ifdef GET_GLOBALISEL_PREDICATES_DECL\n";
4561
4562 OS << "#ifdef GET_GLOBALISEL_PREDICATES_INIT\n"
4563 << "AvailableModuleFeatures(computeAvailableModuleFeatures(&STI)),\n"
4564 << "AvailableFunctionFeatures()\n"
4565 << "#endif // ifdef GET_GLOBALISEL_PREDICATES_INIT\n";
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004566}
4567
Daniel Sanderse7b0d662017-04-21 15:59:56 +00004568void GlobalISelEmitter::declareSubtargetFeature(Record *Predicate) {
4569 if (SubtargetFeatures.count(Predicate) == 0)
4570 SubtargetFeatures.emplace(
4571 Predicate, SubtargetFeatureInfo(Predicate, SubtargetFeatures.size()));
4572}
4573
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004574void RuleMatcher::optimize() {
4575 for (auto &Item : InsnVariableIDs) {
4576 InstructionMatcher &InsnMatcher = *Item.first;
4577 for (auto &OM : InsnMatcher.operands()) {
Roman Tereshin5f5e5502018-05-23 23:58:10 +00004578 // Complex Patterns are usually expensive and they relatively rarely fail
4579 // on their own: more often we end up throwing away all the work done by a
4580 // matching part of a complex pattern because some other part of the
4581 // enclosing pattern didn't match. All of this makes it beneficial to
4582 // delay complex patterns until the very end of the rule matching,
4583 // especially for targets having lots of complex patterns.
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004584 for (auto &OP : OM->predicates())
Roman Tereshin5f5e5502018-05-23 23:58:10 +00004585 if (isa<ComplexPatternOperandMatcher>(OP))
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004586 EpilogueMatchers.emplace_back(std::move(OP));
4587 OM->eraseNullPredicates();
4588 }
4589 InsnMatcher.optimize();
Quentin Colombetec76d9c2017-12-18 19:47:41 +00004590 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004591 llvm::sort(
4592 EpilogueMatchers.begin(), EpilogueMatchers.end(),
4593 [](const std::unique_ptr<PredicateMatcher> &L,
4594 const std::unique_ptr<PredicateMatcher> &R) {
4595 return std::make_tuple(L->getKind(), L->getInsnVarID(), L->getOpIdx()) <
4596 std::make_tuple(R->getKind(), R->getInsnVarID(), R->getOpIdx());
4597 });
Quentin Colombetec76d9c2017-12-18 19:47:41 +00004598}
4599
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004600bool RuleMatcher::hasFirstCondition() const {
4601 if (insnmatchers_empty())
4602 return false;
4603 InstructionMatcher &Matcher = insnmatchers_front();
4604 if (!Matcher.predicates_empty())
4605 return true;
4606 for (auto &OM : Matcher.operands())
4607 for (auto &OP : OM->predicates())
4608 if (!isa<InstructionOperandMatcher>(OP))
4609 return true;
4610 return false;
4611}
4612
4613const PredicateMatcher &RuleMatcher::getFirstCondition() const {
4614 assert(!insnmatchers_empty() &&
4615 "Trying to get a condition from an empty RuleMatcher");
4616
4617 InstructionMatcher &Matcher = insnmatchers_front();
4618 if (!Matcher.predicates_empty())
4619 return **Matcher.predicates_begin();
4620 // If there is no more predicate on the instruction itself, look at its
4621 // operands.
4622 for (auto &OM : Matcher.operands())
4623 for (auto &OP : OM->predicates())
4624 if (!isa<InstructionOperandMatcher>(OP))
4625 return *OP;
4626
4627 llvm_unreachable("Trying to get a condition from an InstructionMatcher with "
4628 "no conditions");
4629}
4630
4631std::unique_ptr<PredicateMatcher> RuleMatcher::popFirstCondition() {
4632 assert(!insnmatchers_empty() &&
4633 "Trying to pop a condition from an empty RuleMatcher");
4634
4635 InstructionMatcher &Matcher = insnmatchers_front();
4636 if (!Matcher.predicates_empty())
4637 return Matcher.predicates_pop_front();
4638 // If there is no more predicate on the instruction itself, look at its
4639 // operands.
4640 for (auto &OM : Matcher.operands())
4641 for (auto &OP : OM->predicates())
4642 if (!isa<InstructionOperandMatcher>(OP)) {
4643 std::unique_ptr<PredicateMatcher> Result = std::move(OP);
4644 OM->eraseNullPredicates();
4645 return Result;
4646 }
4647
4648 llvm_unreachable("Trying to pop a condition from an InstructionMatcher with "
4649 "no conditions");
4650}
4651
4652bool GroupMatcher::candidateConditionMatches(
Quentin Colombetec76d9c2017-12-18 19:47:41 +00004653 const PredicateMatcher &Predicate) const {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004654
4655 if (empty()) {
4656 // Sharing predicates for nested instructions is not supported yet as we
4657 // currently don't hoist the GIM_RecordInsn's properly, therefore we can
4658 // only work on the original root instruction (InsnVarID == 0):
4659 if (Predicate.getInsnVarID() != 0)
4660 return false;
4661 // ... otherwise an empty group can handle any predicate with no specific
4662 // requirements:
4663 return true;
4664 }
4665
4666 const Matcher &Representative = **Matchers.begin();
4667 const auto &RepresentativeCondition = Representative.getFirstCondition();
4668 // ... if not empty, the group can only accomodate matchers with the exact
4669 // same first condition:
4670 return Predicate.isIdentical(RepresentativeCondition);
4671}
4672
4673bool GroupMatcher::addMatcher(Matcher &Candidate) {
4674 if (!Candidate.hasFirstCondition())
4675 return false;
4676
4677 const PredicateMatcher &Predicate = Candidate.getFirstCondition();
4678 if (!candidateConditionMatches(Predicate))
4679 return false;
4680
4681 Matchers.push_back(&Candidate);
4682 return true;
4683}
4684
4685void GroupMatcher::finalize() {
4686 assert(Conditions.empty() && "Already finalized?");
4687 if (empty())
4688 return;
4689
4690 Matcher &FirstRule = **Matchers.begin();
Roman Tereshin152fc162018-05-23 22:50:53 +00004691 for (;;) {
4692 // All the checks are expected to succeed during the first iteration:
4693 for (const auto &Rule : Matchers)
4694 if (!Rule->hasFirstCondition())
4695 return;
4696 const auto &FirstCondition = FirstRule.getFirstCondition();
4697 for (unsigned I = 1, E = Matchers.size(); I < E; ++I)
4698 if (!Matchers[I]->getFirstCondition().isIdentical(FirstCondition))
4699 return;
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004700
Roman Tereshin152fc162018-05-23 22:50:53 +00004701 Conditions.push_back(FirstRule.popFirstCondition());
4702 for (unsigned I = 1, E = Matchers.size(); I < E; ++I)
4703 Matchers[I]->popFirstCondition();
4704 }
Quentin Colombetec76d9c2017-12-18 19:47:41 +00004705}
4706
4707void GroupMatcher::emit(MatchTable &Table) {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004708 unsigned LabelID = ~0U;
4709 if (!Conditions.empty()) {
4710 LabelID = Table.allocateLabelID();
Quentin Colombetec76d9c2017-12-18 19:47:41 +00004711 Table << MatchTable::Opcode("GIM_Try", +1)
4712 << MatchTable::Comment("On fail goto")
4713 << MatchTable::JumpTarget(LabelID) << MatchTable::LineBreak;
Quentin Colombetec76d9c2017-12-18 19:47:41 +00004714 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004715 for (auto &Condition : Conditions)
4716 Condition->emitPredicateOpcodes(
4717 Table, *static_cast<RuleMatcher *>(*Matchers.begin()));
4718
4719 for (const auto &M : Matchers)
4720 M->emit(Table);
4721
4722 // Exit the group
4723 if (!Conditions.empty())
4724 Table << MatchTable::Opcode("GIM_Reject", -1) << MatchTable::LineBreak
Quentin Colombetec76d9c2017-12-18 19:47:41 +00004725 << MatchTable::Label(LabelID);
Quentin Colombetec76d9c2017-12-18 19:47:41 +00004726}
4727
Roman Tereshin0ee082f2018-05-22 19:37:59 +00004728bool SwitchMatcher::isSupportedPredicateType(const PredicateMatcher &P) {
Roman Tereshina4c410d2018-05-24 00:24:15 +00004729 return isa<InstructionOpcodeMatcher>(P) || isa<LLTOperandMatcher>(P);
Roman Tereshin0ee082f2018-05-22 19:37:59 +00004730}
4731
4732bool SwitchMatcher::candidateConditionMatches(
4733 const PredicateMatcher &Predicate) const {
4734
4735 if (empty()) {
4736 // Sharing predicates for nested instructions is not supported yet as we
4737 // currently don't hoist the GIM_RecordInsn's properly, therefore we can
4738 // only work on the original root instruction (InsnVarID == 0):
4739 if (Predicate.getInsnVarID() != 0)
4740 return false;
4741 // ... while an attempt to add even a root matcher to an empty SwitchMatcher
4742 // could fail as not all the types of conditions are supported:
4743 if (!isSupportedPredicateType(Predicate))
4744 return false;
4745 // ... or the condition might not have a proper implementation of
4746 // getValue() / isIdenticalDownToValue() yet:
4747 if (!Predicate.hasValue())
4748 return false;
4749 // ... otherwise an empty Switch can accomodate the condition with no
4750 // further requirements:
4751 return true;
4752 }
4753
4754 const Matcher &CaseRepresentative = **Matchers.begin();
4755 const auto &RepresentativeCondition = CaseRepresentative.getFirstCondition();
4756 // Switch-cases must share the same kind of condition and path to the value it
4757 // checks:
4758 if (!Predicate.isIdenticalDownToValue(RepresentativeCondition))
4759 return false;
4760
4761 const auto Value = Predicate.getValue();
4762 // ... but be unique with respect to the actual value they check:
4763 return Values.count(Value) == 0;
4764}
4765
4766bool SwitchMatcher::addMatcher(Matcher &Candidate) {
4767 if (!Candidate.hasFirstCondition())
4768 return false;
4769
4770 const PredicateMatcher &Predicate = Candidate.getFirstCondition();
4771 if (!candidateConditionMatches(Predicate))
4772 return false;
4773 const auto Value = Predicate.getValue();
4774 Values.insert(Value);
4775
4776 Matchers.push_back(&Candidate);
4777 return true;
4778}
4779
4780void SwitchMatcher::finalize() {
4781 assert(Condition == nullptr && "Already finalized");
4782 assert(Values.size() == Matchers.size() && "Broken SwitchMatcher");
4783 if (empty())
4784 return;
4785
4786 std::stable_sort(Matchers.begin(), Matchers.end(),
4787 [](const Matcher *L, const Matcher *R) {
4788 return L->getFirstCondition().getValue() <
4789 R->getFirstCondition().getValue();
4790 });
4791 Condition = Matchers[0]->popFirstCondition();
4792 for (unsigned I = 1, E = Values.size(); I < E; ++I)
4793 Matchers[I]->popFirstCondition();
4794}
4795
4796void SwitchMatcher::emitPredicateSpecificOpcodes(const PredicateMatcher &P,
4797 MatchTable &Table) {
4798 assert(isSupportedPredicateType(P) && "Predicate type is not supported");
4799
4800 if (const auto *Condition = dyn_cast<InstructionOpcodeMatcher>(&P)) {
4801 Table << MatchTable::Opcode("GIM_SwitchOpcode") << MatchTable::Comment("MI")
4802 << MatchTable::IntValue(Condition->getInsnVarID());
4803 return;
4804 }
Roman Tereshina4c410d2018-05-24 00:24:15 +00004805 if (const auto *Condition = dyn_cast<LLTOperandMatcher>(&P)) {
4806 Table << MatchTable::Opcode("GIM_SwitchType") << MatchTable::Comment("MI")
4807 << MatchTable::IntValue(Condition->getInsnVarID())
4808 << MatchTable::Comment("Op")
4809 << MatchTable::IntValue(Condition->getOpIdx());
4810 return;
4811 }
Roman Tereshin0ee082f2018-05-22 19:37:59 +00004812
4813 llvm_unreachable("emitPredicateSpecificOpcodes is broken: can not handle a "
4814 "predicate type that is claimed to be supported");
4815}
4816
4817void SwitchMatcher::emit(MatchTable &Table) {
4818 assert(Values.size() == Matchers.size() && "Broken SwitchMatcher");
4819 if (empty())
4820 return;
4821 assert(Condition != nullptr &&
4822 "Broken SwitchMatcher, hasn't been finalized?");
4823
4824 std::vector<unsigned> LabelIDs(Values.size());
4825 std::generate(LabelIDs.begin(), LabelIDs.end(),
4826 [&Table]() { return Table.allocateLabelID(); });
4827 const unsigned Default = Table.allocateLabelID();
4828
4829 const int64_t LowerBound = Values.begin()->getRawValue();
4830 const int64_t UpperBound = Values.rbegin()->getRawValue() + 1;
4831
4832 emitPredicateSpecificOpcodes(*Condition, Table);
4833
4834 Table << MatchTable::Comment("[") << MatchTable::IntValue(LowerBound)
4835 << MatchTable::IntValue(UpperBound) << MatchTable::Comment(")")
4836 << MatchTable::Comment("default:") << MatchTable::JumpTarget(Default);
4837
4838 int64_t J = LowerBound;
4839 auto VI = Values.begin();
4840 for (unsigned I = 0, E = Values.size(); I < E; ++I) {
4841 auto V = *VI++;
4842 while (J++ < V.getRawValue())
4843 Table << MatchTable::IntValue(0);
4844 V.turnIntoComment();
4845 Table << MatchTable::LineBreak << V << MatchTable::JumpTarget(LabelIDs[I]);
4846 }
4847 Table << MatchTable::LineBreak;
4848
4849 for (unsigned I = 0, E = Values.size(); I < E; ++I) {
4850 Table << MatchTable::Label(LabelIDs[I]);
4851 Matchers[I]->emit(Table);
4852 Table << MatchTable::Opcode("GIM_Reject") << MatchTable::LineBreak;
4853 }
4854 Table << MatchTable::Label(Default);
4855}
4856
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004857unsigned OperandMatcher::getInsnVarID() const { return Insn.getInsnVarID(); }
Quentin Colombetaad20be2017-12-15 23:07:42 +00004858
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00004859} // end anonymous namespace
4860
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004861//===----------------------------------------------------------------------===//
4862
4863namespace llvm {
4864void EmitGlobalISel(RecordKeeper &RK, raw_ostream &OS) {
4865 GlobalISelEmitter(RK).run(OS);
4866}
4867} // End llvm namespace