blob: ad461f592560f934461bff11b36f3672cc4c7e58 [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) {
Simon Pilgrim6ecae9f2017-10-14 21:27:53 +000087 return "GIPFP_" + Predicate.getImmTypeIdentifier().str() + "_" +
Daniel Sanders11300ce2017-10-13 21:28:03 +000088 Predicate.getFnName();
89}
90
91/// Get the opcode used to check this predicate.
92std::string getMatchOpcodeForPredicate(const TreePredicateFn &Predicate) {
Simon Pilgrim6ecae9f2017-10-14 21:27:53 +000093 return "GIM_Check" + Predicate.getImmTypeIdentifier().str() + "ImmPredicate";
Daniel Sanders11300ce2017-10-13 21:28:03 +000094}
95
Daniel Sanders52b4ce72017-03-07 23:20:35 +000096/// This class stands in for LLT wherever we want to tablegen-erate an
97/// equivalent at compiler run-time.
98class LLTCodeGen {
99private:
100 LLT Ty;
101
102public:
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000103 LLTCodeGen() = default;
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000104 LLTCodeGen(const LLT &Ty) : Ty(Ty) {}
105
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000106 std::string getCxxEnumValue() const {
107 std::string Str;
108 raw_string_ostream OS(Str);
109
110 emitCxxEnumValue(OS);
111 return OS.str();
112 }
113
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000114 void emitCxxEnumValue(raw_ostream &OS) const {
115 if (Ty.isScalar()) {
116 OS << "GILLT_s" << Ty.getSizeInBits();
117 return;
118 }
119 if (Ty.isVector()) {
120 OS << "GILLT_v" << Ty.getNumElements() << "s" << Ty.getScalarSizeInBits();
121 return;
122 }
Daniel Sandersa71f4542017-10-16 00:56:30 +0000123 if (Ty.isPointer()) {
124 OS << "GILLT_p" << Ty.getAddressSpace();
125 if (Ty.getSizeInBits() > 0)
126 OS << "s" << Ty.getSizeInBits();
127 return;
128 }
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000129 llvm_unreachable("Unhandled LLT");
130 }
131
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000132 void emitCxxConstructorCall(raw_ostream &OS) const {
133 if (Ty.isScalar()) {
134 OS << "LLT::scalar(" << Ty.getSizeInBits() << ")";
135 return;
136 }
137 if (Ty.isVector()) {
Daniel Sanders32291982017-06-28 13:50:04 +0000138 OS << "LLT::vector(" << Ty.getNumElements() << ", "
139 << Ty.getScalarSizeInBits() << ")";
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000140 return;
141 }
Daniel Sandersa71f4542017-10-16 00:56:30 +0000142 if (Ty.isPointer() && Ty.getSizeInBits() > 0) {
143 OS << "LLT::pointer(" << Ty.getAddressSpace() << ", "
144 << Ty.getSizeInBits() << ")";
145 return;
146 }
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000147 llvm_unreachable("Unhandled LLT");
148 }
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000149
150 const LLT &get() const { return Ty; }
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000151
Mandeep Singh Grang1b0e2f22018-04-06 20:18:05 +0000152 /// This ordering is used for std::unique() and llvm::sort(). There's no
Daniel Sanders032e7f22017-08-17 13:18:35 +0000153 /// particular logic behind the order but either A < B or B < A must be
154 /// true if A != B.
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000155 bool operator<(const LLTCodeGen &Other) const {
Daniel Sanders032e7f22017-08-17 13:18:35 +0000156 if (Ty.isValid() != Other.Ty.isValid())
157 return Ty.isValid() < Other.Ty.isValid();
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000158 if (!Ty.isValid())
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000159 return false;
Daniel Sanders032e7f22017-08-17 13:18:35 +0000160
161 if (Ty.isVector() != Other.Ty.isVector())
162 return Ty.isVector() < Other.Ty.isVector();
163 if (Ty.isScalar() != Other.Ty.isScalar())
164 return Ty.isScalar() < Other.Ty.isScalar();
165 if (Ty.isPointer() != Other.Ty.isPointer())
166 return Ty.isPointer() < Other.Ty.isPointer();
167
168 if (Ty.isPointer() && Ty.getAddressSpace() != Other.Ty.getAddressSpace())
169 return Ty.getAddressSpace() < Other.Ty.getAddressSpace();
170
171 if (Ty.isVector() && Ty.getNumElements() != Other.Ty.getNumElements())
172 return Ty.getNumElements() < Other.Ty.getNumElements();
173
174 return Ty.getSizeInBits() < Other.Ty.getSizeInBits();
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000175 }
Quentin Colombet893e0f12017-12-15 23:24:39 +0000176
177 bool operator==(const LLTCodeGen &B) const { return Ty == B.Ty; }
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000178};
179
Daniel Sandersf84bc372018-05-05 20:53:24 +0000180// Track all types that are used so we can emit the corresponding enum.
181std::set<LLTCodeGen> KnownTypes;
182
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000183class InstructionMatcher;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000184/// Convert an MVT to an equivalent LLT if possible, or the invalid LLT() for
185/// MVTs that don't map cleanly to an LLT (e.g., iPTR, *any, ...).
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000186static Optional<LLTCodeGen> MVTToLLT(MVT::SimpleValueType SVT) {
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000187 MVT VT(SVT);
Daniel Sandersa71f4542017-10-16 00:56:30 +0000188
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000189 if (VT.isVector() && VT.getVectorNumElements() != 1)
Daniel Sanders32291982017-06-28 13:50:04 +0000190 return LLTCodeGen(
191 LLT::vector(VT.getVectorNumElements(), VT.getScalarSizeInBits()));
Daniel Sandersa71f4542017-10-16 00:56:30 +0000192
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000193 if (VT.isInteger() || VT.isFloatingPoint())
194 return LLTCodeGen(LLT::scalar(VT.getSizeInBits()));
195 return None;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000196}
197
Daniel Sandersd0656a32017-04-13 09:45:37 +0000198static std::string explainPredicates(const TreePatternNode *N) {
199 std::string Explanation = "";
200 StringRef Separator = "";
201 for (const auto &P : N->getPredicateFns()) {
202 Explanation +=
203 (Separator + P.getOrigPatFragRecord()->getRecord()->getName()).str();
Daniel Sanders76664652017-11-28 22:07:05 +0000204 Separator = ", ";
205
Daniel Sandersd0656a32017-04-13 09:45:37 +0000206 if (P.isAlwaysTrue())
207 Explanation += " always-true";
208 if (P.isImmediatePattern())
209 Explanation += " immediate";
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000210
211 if (P.isUnindexed())
212 Explanation += " unindexed";
213
214 if (P.isNonExtLoad())
215 Explanation += " non-extload";
216 if (P.isAnyExtLoad())
217 Explanation += " extload";
218 if (P.isSignExtLoad())
219 Explanation += " sextload";
220 if (P.isZeroExtLoad())
221 Explanation += " zextload";
222
223 if (P.isNonTruncStore())
224 Explanation += " non-truncstore";
225 if (P.isTruncStore())
226 Explanation += " truncstore";
227
228 if (Record *VT = P.getMemoryVT())
229 Explanation += (" MemVT=" + VT->getName()).str();
230 if (Record *VT = P.getScalarMemoryVT())
231 Explanation += (" ScalarVT(MemVT)=" + VT->getName()).str();
Daniel Sanders76664652017-11-28 22:07:05 +0000232
233 if (P.isAtomicOrderingMonotonic())
234 Explanation += " monotonic";
235 if (P.isAtomicOrderingAcquire())
236 Explanation += " acquire";
237 if (P.isAtomicOrderingRelease())
238 Explanation += " release";
239 if (P.isAtomicOrderingAcquireRelease())
240 Explanation += " acq_rel";
241 if (P.isAtomicOrderingSequentiallyConsistent())
242 Explanation += " seq_cst";
Daniel Sanders0c43b3a2017-11-30 21:05:59 +0000243 if (P.isAtomicOrderingAcquireOrStronger())
244 Explanation += " >=acquire";
245 if (P.isAtomicOrderingWeakerThanAcquire())
246 Explanation += " <acquire";
247 if (P.isAtomicOrderingReleaseOrStronger())
248 Explanation += " >=release";
249 if (P.isAtomicOrderingWeakerThanRelease())
250 Explanation += " <release";
Daniel Sandersd0656a32017-04-13 09:45:37 +0000251 }
252 return Explanation;
253}
254
Daniel Sandersd0656a32017-04-13 09:45:37 +0000255std::string explainOperator(Record *Operator) {
256 if (Operator->isSubClassOf("SDNode"))
Craig Topper2b8419a2017-05-31 19:01:11 +0000257 return (" (" + Operator->getValueAsString("Opcode") + ")").str();
Daniel Sandersd0656a32017-04-13 09:45:37 +0000258
259 if (Operator->isSubClassOf("Intrinsic"))
260 return (" (Operator is an Intrinsic, " + Operator->getName() + ")").str();
261
Daniel Sandersdf39cba2017-10-15 18:22:54 +0000262 if (Operator->isSubClassOf("ComplexPattern"))
263 return (" (Operator is an unmapped ComplexPattern, " + Operator->getName() +
264 ")")
265 .str();
266
Volkan Kelesf7f25682018-01-16 18:44:05 +0000267 if (Operator->isSubClassOf("SDNodeXForm"))
268 return (" (Operator is an unmapped SDNodeXForm, " + Operator->getName() +
269 ")")
270 .str();
271
Daniel Sandersdf39cba2017-10-15 18:22:54 +0000272 return (" (Operator " + Operator->getName() + " not understood)").str();
Daniel Sandersd0656a32017-04-13 09:45:37 +0000273}
274
275/// Helper function to let the emitter report skip reason error messages.
276static Error failedImport(const Twine &Reason) {
277 return make_error<StringError>(Reason, inconvertibleErrorCode());
278}
279
280static Error isTrivialOperatorNode(const TreePatternNode *N) {
281 std::string Explanation = "";
282 std::string Separator = "";
Daniel Sanders2c269f62017-08-24 09:11:20 +0000283
284 bool HasUnsupportedPredicate = false;
285 for (const auto &Predicate : N->getPredicateFns()) {
286 if (Predicate.isAlwaysTrue())
287 continue;
288
289 if (Predicate.isImmediatePattern())
290 continue;
291
Daniel Sandersf84bc372018-05-05 20:53:24 +0000292 if (Predicate.isNonExtLoad() || Predicate.isAnyExtLoad() ||
293 Predicate.isSignExtLoad() || Predicate.isZeroExtLoad())
Daniel Sandersa71f4542017-10-16 00:56:30 +0000294 continue;
Daniel Sandersd66e0902017-10-23 18:19:24 +0000295
Daniel Sanders76664652017-11-28 22:07:05 +0000296 if (Predicate.isNonTruncStore())
Daniel Sandersd66e0902017-10-23 18:19:24 +0000297 continue;
298
Daniel Sandersf84bc372018-05-05 20:53:24 +0000299 if (Predicate.isLoad() && Predicate.getMemoryVT())
300 continue;
301
Daniel Sanders76664652017-11-28 22:07:05 +0000302 if (Predicate.isLoad() || Predicate.isStore()) {
303 if (Predicate.isUnindexed())
304 continue;
305 }
306
307 if (Predicate.isAtomic() && Predicate.getMemoryVT())
308 continue;
309
310 if (Predicate.isAtomic() &&
311 (Predicate.isAtomicOrderingMonotonic() ||
312 Predicate.isAtomicOrderingAcquire() ||
313 Predicate.isAtomicOrderingRelease() ||
314 Predicate.isAtomicOrderingAcquireRelease() ||
Daniel Sanders0c43b3a2017-11-30 21:05:59 +0000315 Predicate.isAtomicOrderingSequentiallyConsistent() ||
316 Predicate.isAtomicOrderingAcquireOrStronger() ||
317 Predicate.isAtomicOrderingWeakerThanAcquire() ||
318 Predicate.isAtomicOrderingReleaseOrStronger() ||
319 Predicate.isAtomicOrderingWeakerThanRelease()))
Daniel Sandersd66e0902017-10-23 18:19:24 +0000320 continue;
321
Daniel Sanders2c269f62017-08-24 09:11:20 +0000322 HasUnsupportedPredicate = true;
Daniel Sandersd0656a32017-04-13 09:45:37 +0000323 Explanation = Separator + "Has a predicate (" + explainPredicates(N) + ")";
324 Separator = ", ";
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000325 Explanation += (Separator + "first-failing:" +
326 Predicate.getOrigPatFragRecord()->getRecord()->getName())
327 .str();
Daniel Sanders2c269f62017-08-24 09:11:20 +0000328 break;
Daniel Sandersd0656a32017-04-13 09:45:37 +0000329 }
330
Volkan Kelesf7f25682018-01-16 18:44:05 +0000331 if (!HasUnsupportedPredicate)
Daniel Sandersd0656a32017-04-13 09:45:37 +0000332 return Error::success();
333
334 return failedImport(Explanation);
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000335}
336
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +0000337static Record *getInitValueAsRegClass(Init *V) {
338 if (DefInit *VDefInit = dyn_cast<DefInit>(V)) {
339 if (VDefInit->getDef()->isSubClassOf("RegisterOperand"))
340 return VDefInit->getDef()->getValueAsDef("RegClass");
341 if (VDefInit->getDef()->isSubClassOf("RegisterClass"))
342 return VDefInit->getDef();
343 }
344 return nullptr;
345}
346
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000347std::string
348getNameForFeatureBitset(const std::vector<Record *> &FeatureBitset) {
349 std::string Name = "GIFBS";
350 for (const auto &Feature : FeatureBitset)
351 Name += ("_" + Feature->getName()).str();
352 return Name;
353}
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000354
355//===- MatchTable Helpers -------------------------------------------------===//
356
357class MatchTable;
358
359/// A record to be stored in a MatchTable.
360///
361/// This class represents any and all output that may be required to emit the
362/// MatchTable. Instances are most often configured to represent an opcode or
363/// value that will be emitted to the table with some formatting but it can also
364/// represent commas, comments, and other formatting instructions.
365struct MatchTableRecord {
366 enum RecordFlagsBits {
367 MTRF_None = 0x0,
368 /// Causes EmitStr to be formatted as comment when emitted.
369 MTRF_Comment = 0x1,
370 /// Causes the record value to be followed by a comma when emitted.
371 MTRF_CommaFollows = 0x2,
372 /// Causes the record value to be followed by a line break when emitted.
373 MTRF_LineBreakFollows = 0x4,
374 /// Indicates that the record defines a label and causes an additional
375 /// comment to be emitted containing the index of the label.
376 MTRF_Label = 0x8,
377 /// Causes the record to be emitted as the index of the label specified by
378 /// LabelID along with a comment indicating where that label is.
379 MTRF_JumpTarget = 0x10,
380 /// Causes the formatter to add a level of indentation before emitting the
381 /// record.
382 MTRF_Indent = 0x20,
383 /// Causes the formatter to remove a level of indentation after emitting the
384 /// record.
385 MTRF_Outdent = 0x40,
386 };
387
388 /// When MTRF_Label or MTRF_JumpTarget is used, indicates a label id to
389 /// reference or define.
390 unsigned LabelID;
391 /// The string to emit. Depending on the MTRF_* flags it may be a comment, a
392 /// value, a label name.
393 std::string EmitStr;
394
395private:
396 /// The number of MatchTable elements described by this record. Comments are 0
397 /// while values are typically 1. Values >1 may occur when we need to emit
398 /// values that exceed the size of a MatchTable element.
399 unsigned NumElements;
400
401public:
402 /// A bitfield of RecordFlagsBits flags.
403 unsigned Flags;
404
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000405 /// The actual run-time value, if known
406 int64_t RawValue;
407
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000408 MatchTableRecord(Optional<unsigned> LabelID_, StringRef EmitStr,
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000409 unsigned NumElements, unsigned Flags,
410 int64_t RawValue = std::numeric_limits<int64_t>::min())
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000411 : LabelID(LabelID_.hasValue() ? LabelID_.getValue() : ~0u),
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000412 EmitStr(EmitStr), NumElements(NumElements), Flags(Flags),
413 RawValue(RawValue) {
414
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000415 assert((!LabelID_.hasValue() || LabelID != ~0u) &&
416 "This value is reserved for non-labels");
417 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000418 MatchTableRecord(const MatchTableRecord &Other) = default;
419 MatchTableRecord(MatchTableRecord &&Other) = default;
420
421 /// Useful if a Match Table Record gets optimized out
422 void turnIntoComment() {
423 Flags |= MTRF_Comment;
424 Flags &= ~MTRF_CommaFollows;
425 NumElements = 0;
426 }
427
428 /// For Jump Table generation purposes
429 bool operator<(const MatchTableRecord &Other) const {
430 return RawValue < Other.RawValue;
431 }
432 int64_t getRawValue() const { return RawValue; }
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000433
434 void emit(raw_ostream &OS, bool LineBreakNextAfterThis,
435 const MatchTable &Table) const;
436 unsigned size() const { return NumElements; }
437};
438
Roman Tereshin2d6d3762018-05-02 20:08:14 +0000439class Matcher;
440
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000441/// Holds the contents of a generated MatchTable to enable formatting and the
442/// necessary index tracking needed to support GIM_Try.
443class MatchTable {
444 /// An unique identifier for the table. The generated table will be named
445 /// MatchTable${ID}.
446 unsigned ID;
447 /// The records that make up the table. Also includes comments describing the
448 /// values being emitted and line breaks to format it.
449 std::vector<MatchTableRecord> Contents;
450 /// The currently defined labels.
451 DenseMap<unsigned, unsigned> LabelMap;
452 /// Tracks the sum of MatchTableRecord::NumElements as the table is built.
Roman Tereshin2d6d3762018-05-02 20:08:14 +0000453 unsigned CurrentSize = 0;
Daniel Sanders8e82af22017-07-27 11:03:45 +0000454 /// A unique identifier for a MatchTable label.
Roman Tereshin2d6d3762018-05-02 20:08:14 +0000455 unsigned CurrentLabelID = 0;
Roman Tereshinbeb39312018-05-02 20:15:11 +0000456 /// Determines if the table should be instrumented for rule coverage tracking.
457 bool IsWithCoverage;
Daniel Sanders8e82af22017-07-27 11:03:45 +0000458
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000459public:
460 static MatchTableRecord LineBreak;
461 static MatchTableRecord Comment(StringRef Comment) {
462 return MatchTableRecord(None, Comment, 0, MatchTableRecord::MTRF_Comment);
463 }
464 static MatchTableRecord Opcode(StringRef Opcode, int IndentAdjust = 0) {
465 unsigned ExtraFlags = 0;
466 if (IndentAdjust > 0)
467 ExtraFlags |= MatchTableRecord::MTRF_Indent;
468 if (IndentAdjust < 0)
469 ExtraFlags |= MatchTableRecord::MTRF_Outdent;
470
471 return MatchTableRecord(None, Opcode, 1,
472 MatchTableRecord::MTRF_CommaFollows | ExtraFlags);
473 }
474 static MatchTableRecord NamedValue(StringRef NamedValue) {
475 return MatchTableRecord(None, NamedValue, 1,
476 MatchTableRecord::MTRF_CommaFollows);
477 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000478 static MatchTableRecord NamedValue(StringRef NamedValue, int64_t RawValue) {
479 return MatchTableRecord(None, NamedValue, 1,
480 MatchTableRecord::MTRF_CommaFollows, RawValue);
481 }
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000482 static MatchTableRecord NamedValue(StringRef Namespace,
483 StringRef NamedValue) {
484 return MatchTableRecord(None, (Namespace + "::" + NamedValue).str(), 1,
485 MatchTableRecord::MTRF_CommaFollows);
486 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000487 static MatchTableRecord NamedValue(StringRef Namespace, StringRef NamedValue,
488 int64_t RawValue) {
489 return MatchTableRecord(None, (Namespace + "::" + NamedValue).str(), 1,
490 MatchTableRecord::MTRF_CommaFollows, RawValue);
491 }
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000492 static MatchTableRecord IntValue(int64_t IntValue) {
493 return MatchTableRecord(None, llvm::to_string(IntValue), 1,
494 MatchTableRecord::MTRF_CommaFollows);
495 }
496 static MatchTableRecord Label(unsigned LabelID) {
497 return MatchTableRecord(LabelID, "Label " + llvm::to_string(LabelID), 0,
498 MatchTableRecord::MTRF_Label |
499 MatchTableRecord::MTRF_Comment |
500 MatchTableRecord::MTRF_LineBreakFollows);
501 }
502 static MatchTableRecord JumpTarget(unsigned LabelID) {
Daniel Sanders8e82af22017-07-27 11:03:45 +0000503 return MatchTableRecord(LabelID, "Label " + llvm::to_string(LabelID), 1,
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000504 MatchTableRecord::MTRF_JumpTarget |
505 MatchTableRecord::MTRF_Comment |
506 MatchTableRecord::MTRF_CommaFollows);
507 }
508
Roman Tereshinbeb39312018-05-02 20:15:11 +0000509 static MatchTable buildTable(ArrayRef<Matcher *> Rules, bool WithCoverage);
Roman Tereshin2d6d3762018-05-02 20:08:14 +0000510
Roman Tereshinbeb39312018-05-02 20:15:11 +0000511 MatchTable(bool WithCoverage, unsigned ID = 0)
512 : ID(ID), IsWithCoverage(WithCoverage) {}
513
514 bool isWithCoverage() const { return IsWithCoverage; }
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000515
516 void push_back(const MatchTableRecord &Value) {
517 if (Value.Flags & MatchTableRecord::MTRF_Label)
518 defineLabel(Value.LabelID);
519 Contents.push_back(Value);
520 CurrentSize += Value.size();
521 }
522
Roman Tereshin2d6d3762018-05-02 20:08:14 +0000523 unsigned allocateLabelID() { return CurrentLabelID++; }
Daniel Sanders8e82af22017-07-27 11:03:45 +0000524
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000525 void defineLabel(unsigned LabelID) {
Daniel Sanders8e82af22017-07-27 11:03:45 +0000526 LabelMap.insert(std::make_pair(LabelID, CurrentSize));
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000527 }
528
529 unsigned getLabelIndex(unsigned LabelID) const {
530 const auto I = LabelMap.find(LabelID);
531 assert(I != LabelMap.end() && "Use of undeclared label");
532 return I->second;
533 }
534
Daniel Sanders8e82af22017-07-27 11:03:45 +0000535 void emitUse(raw_ostream &OS) const { OS << "MatchTable" << ID; }
536
537 void emitDeclaration(raw_ostream &OS) const {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000538 unsigned Indentation = 4;
Daniel Sanderscbbbfe42017-07-27 12:47:31 +0000539 OS << " constexpr static int64_t MatchTable" << ID << "[] = {";
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000540 LineBreak.emit(OS, true, *this);
541 OS << std::string(Indentation, ' ');
542
543 for (auto I = Contents.begin(), E = Contents.end(); I != E;
544 ++I) {
545 bool LineBreakIsNext = false;
546 const auto &NextI = std::next(I);
547
548 if (NextI != E) {
549 if (NextI->EmitStr == "" &&
550 NextI->Flags == MatchTableRecord::MTRF_LineBreakFollows)
551 LineBreakIsNext = true;
552 }
553
554 if (I->Flags & MatchTableRecord::MTRF_Indent)
555 Indentation += 2;
556
557 I->emit(OS, LineBreakIsNext, *this);
558 if (I->Flags & MatchTableRecord::MTRF_LineBreakFollows)
559 OS << std::string(Indentation, ' ');
560
561 if (I->Flags & MatchTableRecord::MTRF_Outdent)
562 Indentation -= 2;
563 }
564 OS << "};\n";
565 }
566};
567
568MatchTableRecord MatchTable::LineBreak = {
569 None, "" /* Emit String */, 0 /* Elements */,
570 MatchTableRecord::MTRF_LineBreakFollows};
571
572void MatchTableRecord::emit(raw_ostream &OS, bool LineBreakIsNextAfterThis,
573 const MatchTable &Table) const {
574 bool UseLineComment =
575 LineBreakIsNextAfterThis | (Flags & MTRF_LineBreakFollows);
576 if (Flags & (MTRF_JumpTarget | MTRF_CommaFollows))
577 UseLineComment = false;
578
579 if (Flags & MTRF_Comment)
580 OS << (UseLineComment ? "// " : "/*");
581
582 OS << EmitStr;
583 if (Flags & MTRF_Label)
584 OS << ": @" << Table.getLabelIndex(LabelID);
585
586 if (Flags & MTRF_Comment && !UseLineComment)
587 OS << "*/";
588
589 if (Flags & MTRF_JumpTarget) {
590 if (Flags & MTRF_Comment)
591 OS << " ";
592 OS << Table.getLabelIndex(LabelID);
593 }
594
595 if (Flags & MTRF_CommaFollows) {
596 OS << ",";
597 if (!LineBreakIsNextAfterThis && !(Flags & MTRF_LineBreakFollows))
598 OS << " ";
599 }
600
601 if (Flags & MTRF_LineBreakFollows)
602 OS << "\n";
603}
604
605MatchTable &operator<<(MatchTable &Table, const MatchTableRecord &Value) {
606 Table.push_back(Value);
607 return Table;
608}
609
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000610//===- Matchers -----------------------------------------------------------===//
611
Daniel Sandersbee57392017-04-04 13:25:23 +0000612class OperandMatcher;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000613class MatchAction;
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000614class PredicateMatcher;
615class RuleMatcher;
616
617class Matcher {
618public:
619 virtual ~Matcher() = default;
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000620 virtual void optimize() {}
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000621 virtual void emit(MatchTable &Table) = 0;
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000622
623 virtual bool hasFirstCondition() const = 0;
624 virtual const PredicateMatcher &getFirstCondition() const = 0;
625 virtual std::unique_ptr<PredicateMatcher> popFirstCondition() = 0;
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000626};
627
Roman Tereshinbeb39312018-05-02 20:15:11 +0000628MatchTable MatchTable::buildTable(ArrayRef<Matcher *> Rules,
629 bool WithCoverage) {
630 MatchTable Table(WithCoverage);
Roman Tereshin2d6d3762018-05-02 20:08:14 +0000631 for (Matcher *Rule : Rules)
632 Rule->emit(Table);
633
634 return Table << MatchTable::Opcode("GIM_Reject") << MatchTable::LineBreak;
635}
636
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000637class GroupMatcher final : public Matcher {
638 /// Conditions that form a common prefix of all the matchers contained.
639 SmallVector<std::unique_ptr<PredicateMatcher>, 1> Conditions;
640
641 /// All the nested matchers, sharing a common prefix.
642 std::vector<Matcher *> Matchers;
643
644 /// An owning collection for any auxiliary matchers created while optimizing
645 /// nested matchers contained.
646 std::vector<std::unique_ptr<Matcher>> MatcherStorage;
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000647
648public:
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000649 /// Add a matcher to the collection of nested matchers if it meets the
650 /// requirements, and return true. If it doesn't, do nothing and return false.
651 ///
652 /// Expected to preserve its argument, so it could be moved out later on.
653 bool addMatcher(Matcher &Candidate);
654
655 /// Mark the matcher as fully-built and ensure any invariants expected by both
656 /// optimize() and emit(...) methods. Generally, both sequences of calls
657 /// are expected to lead to a sensible result:
658 ///
659 /// addMatcher(...)*; finalize(); optimize(); emit(...); and
660 /// addMatcher(...)*; finalize(); emit(...);
661 ///
662 /// or generally
663 ///
664 /// addMatcher(...)*; finalize(); { optimize()*; emit(...); }*
665 ///
666 /// Multiple calls to optimize() are expected to be handled gracefully, though
667 /// optimize() is not expected to be idempotent. Multiple calls to finalize()
668 /// aren't generally supported. emit(...) is expected to be non-mutating and
669 /// producing the exact same results upon repeated calls.
670 ///
671 /// addMatcher() calls after the finalize() call are not supported.
672 ///
673 /// finalize() and optimize() are both allowed to mutate the contained
674 /// matchers, so moving them out after finalize() is not supported.
675 void finalize();
Roman Tereshinfedae332018-05-23 02:04:19 +0000676 void optimize() override;
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000677 void emit(MatchTable &Table) override;
Quentin Colombet34688b92017-12-18 21:25:53 +0000678
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000679 /// Could be used to move out the matchers added previously, unless finalize()
680 /// has been already called. If any of the matchers are moved out, the group
681 /// becomes safe to destroy, but not safe to re-use for anything else.
682 iterator_range<std::vector<Matcher *>::iterator> matchers() {
683 return make_range(Matchers.begin(), Matchers.end());
Quentin Colombet34688b92017-12-18 21:25:53 +0000684 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000685 size_t size() const { return Matchers.size(); }
686 bool empty() const { return Matchers.empty(); }
687
688 std::unique_ptr<PredicateMatcher> popFirstCondition() override {
689 assert(!Conditions.empty() &&
690 "Trying to pop a condition from a condition-less group");
691 std::unique_ptr<PredicateMatcher> P = std::move(Conditions.front());
692 Conditions.erase(Conditions.begin());
693 return P;
694 }
695 const PredicateMatcher &getFirstCondition() const override {
696 assert(!Conditions.empty() &&
697 "Trying to get a condition from a condition-less group");
698 return *Conditions.front();
699 }
700 bool hasFirstCondition() const override { return !Conditions.empty(); }
701
702private:
703 /// See if a candidate matcher could be added to this group solely by
704 /// analyzing its first condition.
705 bool candidateConditionMatches(const PredicateMatcher &Predicate) const;
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000706};
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000707
Roman Tereshin0ee082f2018-05-22 19:37:59 +0000708class SwitchMatcher : public Matcher {
709 /// All the nested matchers, representing distinct switch-cases. The first
710 /// conditions (as Matcher::getFirstCondition() reports) of all the nested
711 /// matchers must share the same type and path to a value they check, in other
712 /// words, be isIdenticalDownToValue, but have different values they check
713 /// against.
714 std::vector<Matcher *> Matchers;
715
716 /// The representative condition, with a type and a path (InsnVarID and OpIdx
717 /// in most cases) shared by all the matchers contained.
718 std::unique_ptr<PredicateMatcher> Condition = nullptr;
719
720 /// Temporary set used to check that the case values don't repeat within the
721 /// same switch.
722 std::set<MatchTableRecord> Values;
723
724 /// An owning collection for any auxiliary matchers created while optimizing
725 /// nested matchers contained.
726 std::vector<std::unique_ptr<Matcher>> MatcherStorage;
727
728public:
729 bool addMatcher(Matcher &Candidate);
730
731 void finalize();
732 void emit(MatchTable &Table) override;
733
734 iterator_range<std::vector<Matcher *>::iterator> matchers() {
735 return make_range(Matchers.begin(), Matchers.end());
736 }
737 size_t size() const { return Matchers.size(); }
738 bool empty() const { return Matchers.empty(); }
739
740 std::unique_ptr<PredicateMatcher> popFirstCondition() override {
741 // SwitchMatcher doesn't have a common first condition for its cases, as all
742 // the cases only share a kind of a value (a type and a path to it) they
743 // match, but deliberately differ in the actual value they match.
744 llvm_unreachable("Trying to pop a condition from a condition-less group");
745 }
746 const PredicateMatcher &getFirstCondition() const override {
747 llvm_unreachable("Trying to pop a condition from a condition-less group");
748 }
749 bool hasFirstCondition() const override { return false; }
750
751private:
752 /// See if the predicate type has a Switch-implementation for it.
753 static bool isSupportedPredicateType(const PredicateMatcher &Predicate);
754
755 bool candidateConditionMatches(const PredicateMatcher &Predicate) const;
756
757 /// emit()-helper
758 static void emitPredicateSpecificOpcodes(const PredicateMatcher &P,
759 MatchTable &Table);
760};
761
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000762/// Generates code to check that a match rule matches.
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000763class RuleMatcher : public Matcher {
Daniel Sanders7438b262017-10-31 23:03:18 +0000764public:
Daniel Sanders08464522018-01-29 21:09:12 +0000765 using ActionList = std::list<std::unique_ptr<MatchAction>>;
766 using action_iterator = ActionList::iterator;
Daniel Sanders7438b262017-10-31 23:03:18 +0000767
768protected:
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000769 /// A list of matchers that all need to succeed for the current rule to match.
770 /// FIXME: This currently supports a single match position but could be
771 /// extended to support multiple positions to support div/rem fusion or
772 /// load-multiple instructions.
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000773 using MatchersTy = std::vector<std::unique_ptr<InstructionMatcher>> ;
774 MatchersTy Matchers;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000775
776 /// A list of actions that need to be taken when all predicates in this rule
777 /// have succeeded.
Daniel Sanders08464522018-01-29 21:09:12 +0000778 ActionList Actions;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000779
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000780 using DefinedInsnVariablesMap = std::map<InstructionMatcher *, unsigned>;
Daniel Sandersa7b75262017-10-31 18:50:24 +0000781
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000782 /// A map of instruction matchers to the local variables
Daniel Sanders078572b2017-08-02 11:03:36 +0000783 DefinedInsnVariablesMap InsnVariableIDs;
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000784
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000785 using MutatableInsnSet = SmallPtrSet<InstructionMatcher *, 4>;
Daniel Sandersa7b75262017-10-31 18:50:24 +0000786
787 // The set of instruction matchers that have not yet been claimed for mutation
788 // by a BuildMI.
789 MutatableInsnSet MutatableInsns;
790
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000791 /// A map of named operands defined by the matchers that may be referenced by
792 /// the renderers.
793 StringMap<OperandMatcher *> DefinedOperands;
794
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000795 /// ID for the next instruction variable defined with implicitlyDefineInsnVar()
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000796 unsigned NextInsnVarID;
797
Daniel Sanders198447a2017-11-01 00:29:47 +0000798 /// ID for the next output instruction allocated with allocateOutputInsnID()
799 unsigned NextOutputInsnID;
800
Daniel Sanders9cbe7c72017-11-01 19:57:57 +0000801 /// ID for the next temporary register ID allocated with allocateTempRegID()
802 unsigned NextTempRegID;
803
Daniel Sanderse7b0d662017-04-21 15:59:56 +0000804 std::vector<Record *> RequiredFeatures;
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000805 std::vector<std::unique_ptr<PredicateMatcher>> EpilogueMatchers;
Daniel Sanderse7b0d662017-04-21 15:59:56 +0000806
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000807 ArrayRef<SMLoc> SrcLoc;
808
Daniel Sandersdf39cba2017-10-15 18:22:54 +0000809 typedef std::tuple<Record *, unsigned, unsigned>
810 DefinedComplexPatternSubOperand;
811 typedef StringMap<DefinedComplexPatternSubOperand>
812 DefinedComplexPatternSubOperandMap;
813 /// A map of Symbolic Names to ComplexPattern sub-operands.
814 DefinedComplexPatternSubOperandMap ComplexSubOperands;
815
Daniel Sandersf76f3152017-11-16 00:46:35 +0000816 uint64_t RuleID;
817 static uint64_t NextRuleID;
818
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000819public:
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000820 RuleMatcher(ArrayRef<SMLoc> SrcLoc)
Daniel Sandersa7b75262017-10-31 18:50:24 +0000821 : Matchers(), Actions(), InsnVariableIDs(), MutatableInsns(),
Daniel Sanders198447a2017-11-01 00:29:47 +0000822 DefinedOperands(), NextInsnVarID(0), NextOutputInsnID(0),
Daniel Sandersf76f3152017-11-16 00:46:35 +0000823 NextTempRegID(0), SrcLoc(SrcLoc), ComplexSubOperands(),
824 RuleID(NextRuleID++) {}
Zachary Turnerb7dbd872017-03-20 19:56:52 +0000825 RuleMatcher(RuleMatcher &&Other) = default;
826 RuleMatcher &operator=(RuleMatcher &&Other) = default;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000827
Daniel Sandersf76f3152017-11-16 00:46:35 +0000828 uint64_t getRuleID() const { return RuleID; }
829
Daniel Sanders05540042017-08-08 10:44:31 +0000830 InstructionMatcher &addInstructionMatcher(StringRef SymbolicName);
Daniel Sanderse7b0d662017-04-21 15:59:56 +0000831 void addRequiredFeature(Record *Feature);
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000832 const std::vector<Record *> &getRequiredFeatures() const;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000833
834 template <class Kind, class... Args> Kind &addAction(Args &&... args);
Daniel Sanders7438b262017-10-31 23:03:18 +0000835 template <class Kind, class... Args>
836 action_iterator insertAction(action_iterator InsertPt, Args &&... args);
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000837
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000838 /// Define an instruction without emitting any code to do so.
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000839 unsigned implicitlyDefineInsnVar(InstructionMatcher &Matcher);
840
841 unsigned getInsnVarID(InstructionMatcher &InsnMatcher) const;
Daniel Sanders078572b2017-08-02 11:03:36 +0000842 DefinedInsnVariablesMap::const_iterator defined_insn_vars_begin() const {
843 return InsnVariableIDs.begin();
844 }
845 DefinedInsnVariablesMap::const_iterator defined_insn_vars_end() const {
846 return InsnVariableIDs.end();
847 }
848 iterator_range<typename DefinedInsnVariablesMap::const_iterator>
849 defined_insn_vars() const {
850 return make_range(defined_insn_vars_begin(), defined_insn_vars_end());
851 }
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000852
Daniel Sandersa7b75262017-10-31 18:50:24 +0000853 MutatableInsnSet::const_iterator mutatable_insns_begin() const {
854 return MutatableInsns.begin();
855 }
856 MutatableInsnSet::const_iterator mutatable_insns_end() const {
857 return MutatableInsns.end();
858 }
859 iterator_range<typename MutatableInsnSet::const_iterator>
860 mutatable_insns() const {
861 return make_range(mutatable_insns_begin(), mutatable_insns_end());
862 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000863 void reserveInsnMatcherForMutation(InstructionMatcher *InsnMatcher) {
Daniel Sandersa7b75262017-10-31 18:50:24 +0000864 bool R = MutatableInsns.erase(InsnMatcher);
865 assert(R && "Reserving a mutatable insn that isn't available");
866 (void)R;
867 }
868
Daniel Sanders7438b262017-10-31 23:03:18 +0000869 action_iterator actions_begin() { return Actions.begin(); }
870 action_iterator actions_end() { return Actions.end(); }
871 iterator_range<action_iterator> actions() {
872 return make_range(actions_begin(), actions_end());
873 }
874
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000875 void defineOperand(StringRef SymbolicName, OperandMatcher &OM);
876
Daniel Sandersdf39cba2017-10-15 18:22:54 +0000877 void defineComplexSubOperand(StringRef SymbolicName, Record *ComplexPattern,
878 unsigned RendererID, unsigned SubOperandID) {
879 assert(ComplexSubOperands.count(SymbolicName) == 0 && "Already defined");
880 ComplexSubOperands[SymbolicName] =
881 std::make_tuple(ComplexPattern, RendererID, SubOperandID);
882 }
883 Optional<DefinedComplexPatternSubOperand>
884 getComplexSubOperand(StringRef SymbolicName) const {
885 const auto &I = ComplexSubOperands.find(SymbolicName);
886 if (I == ComplexSubOperands.end())
887 return None;
888 return I->second;
889 }
890
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000891 InstructionMatcher &getInstructionMatcher(StringRef SymbolicName) const;
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000892 const OperandMatcher &getOperandMatcher(StringRef Name) const;
Daniel Sanders05540042017-08-08 10:44:31 +0000893
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000894 void optimize() override;
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000895 void emit(MatchTable &Table) override;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000896
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000897 /// Compare the priority of this object and B.
898 ///
899 /// Returns true if this object is more important than B.
900 bool isHigherPriorityThan(const RuleMatcher &B) const;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000901
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000902 /// Report the maximum number of temporary operands needed by the rule
903 /// matcher.
904 unsigned countRendererFns() const;
Daniel Sanders2deea182017-04-22 15:11:04 +0000905
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000906 std::unique_ptr<PredicateMatcher> popFirstCondition() override;
907 const PredicateMatcher &getFirstCondition() const override;
Roman Tereshin9a9fa492018-05-23 21:30:16 +0000908 LLTCodeGen getFirstConditionAsRootType();
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000909 bool hasFirstCondition() const override;
910 unsigned getNumOperands() const;
Roman Tereshin19da6672018-05-22 04:31:50 +0000911 StringRef getOpcode() const;
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000912
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000913 // FIXME: Remove this as soon as possible
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000914 InstructionMatcher &insnmatchers_front() const { return *Matchers.front(); }
Daniel Sanders198447a2017-11-01 00:29:47 +0000915
916 unsigned allocateOutputInsnID() { return NextOutputInsnID++; }
Daniel Sanders9cbe7c72017-11-01 19:57:57 +0000917 unsigned allocateTempRegID() { return NextTempRegID++; }
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000918
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000919 iterator_range<MatchersTy::iterator> insnmatchers() {
920 return make_range(Matchers.begin(), Matchers.end());
921 }
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000922 bool insnmatchers_empty() const { return Matchers.empty(); }
923 void insnmatchers_pop_front() { Matchers.erase(Matchers.begin()); }
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000924};
925
Daniel Sandersf76f3152017-11-16 00:46:35 +0000926uint64_t RuleMatcher::NextRuleID = 0;
927
Daniel Sanders7438b262017-10-31 23:03:18 +0000928using action_iterator = RuleMatcher::action_iterator;
929
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000930template <class PredicateTy> class PredicateListMatcher {
931private:
Daniel Sanders2c269f62017-08-24 09:11:20 +0000932 /// Template instantiations should specialize this to return a string to use
933 /// for the comment emitted when there are no predicates.
934 std::string getNoPredicateComment() const;
935
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000936protected:
937 using PredicatesTy = std::deque<std::unique_ptr<PredicateTy>>;
938 PredicatesTy Predicates;
Roman Tereshinf0dc9fa2018-05-21 22:04:39 +0000939
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000940 /// Track if the list of predicates was manipulated by one of the optimization
941 /// methods.
942 bool Optimized = false;
943
944public:
945 /// Construct a new predicate and add it to the matcher.
946 template <class Kind, class... Args>
947 Optional<Kind *> addPredicate(Args &&... args);
948
949 typename PredicatesTy::iterator predicates_begin() {
Daniel Sanders32291982017-06-28 13:50:04 +0000950 return Predicates.begin();
951 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000952 typename PredicatesTy::iterator predicates_end() {
Daniel Sanders32291982017-06-28 13:50:04 +0000953 return Predicates.end();
954 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000955 iterator_range<typename PredicatesTy::iterator> predicates() {
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000956 return make_range(predicates_begin(), predicates_end());
957 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000958 typename PredicatesTy::size_type predicates_size() const {
Daniel Sanders32291982017-06-28 13:50:04 +0000959 return Predicates.size();
960 }
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000961 bool predicates_empty() const { return Predicates.empty(); }
962
963 std::unique_ptr<PredicateTy> predicates_pop_front() {
964 std::unique_ptr<PredicateTy> Front = std::move(Predicates.front());
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000965 Predicates.pop_front();
966 Optimized = true;
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000967 return Front;
968 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000969
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000970 void prependPredicate(std::unique_ptr<PredicateTy> &&Predicate) {
971 Predicates.push_front(std::move(Predicate));
972 }
973
974 void eraseNullPredicates() {
975 const auto NewEnd =
976 std::stable_partition(Predicates.begin(), Predicates.end(),
977 std::logical_not<std::unique_ptr<PredicateTy>>());
978 if (NewEnd != Predicates.begin()) {
979 Predicates.erase(Predicates.begin(), NewEnd);
980 Optimized = true;
981 }
982 }
983
Daniel Sanders9d662d22017-07-06 10:06:12 +0000984 /// Emit MatchTable opcodes that tests whether all the predicates are met.
Ahmed Bougachab67a3ce2017-01-26 22:07:37 +0000985 template <class... Args>
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000986 void emitPredicateListOpcodes(MatchTable &Table, Args &&... args) {
987 if (Predicates.empty() && !Optimized) {
Daniel Sanders2c269f62017-08-24 09:11:20 +0000988 Table << MatchTable::Comment(getNoPredicateComment())
989 << MatchTable::LineBreak;
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000990 return;
991 }
992
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000993 for (const auto &Predicate : predicates())
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000994 Predicate->emitPredicateOpcodes(Table, std::forward<Args>(args)...);
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000995 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000996};
997
Quentin Colombet063d7982017-12-14 23:44:07 +0000998class PredicateMatcher {
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000999public:
Daniel Sanders759ff412017-02-24 13:58:11 +00001000 /// This enum is used for RTTI and also defines the priority that is given to
1001 /// the predicate when generating the matcher code. Kinds with higher priority
1002 /// must be tested first.
1003 ///
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001004 /// The relative priority of OPM_LLT, OPM_RegBank, and OPM_MBB do not matter
1005 /// but OPM_Int must have priority over OPM_RegBank since constant integers
1006 /// are represented by a virtual register defined by a G_CONSTANT instruction.
Quentin Colombet063d7982017-12-14 23:44:07 +00001007 ///
1008 /// Note: The relative priority between IPM_ and OPM_ does not matter, they
1009 /// are currently not compared between each other.
Daniel Sanders759ff412017-02-24 13:58:11 +00001010 enum PredicateKind {
Quentin Colombet063d7982017-12-14 23:44:07 +00001011 IPM_Opcode,
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001012 IPM_NumOperands,
Quentin Colombet063d7982017-12-14 23:44:07 +00001013 IPM_ImmPredicate,
1014 IPM_AtomicOrderingMMO,
Daniel Sandersf84bc372018-05-05 20:53:24 +00001015 IPM_MemoryLLTSize,
1016 IPM_MemoryVsLLTSize,
Daniel Sanders1e4569f2017-10-20 20:55:29 +00001017 OPM_SameOperand,
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001018 OPM_ComplexPattern,
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00001019 OPM_IntrinsicID,
Daniel Sanders05540042017-08-08 10:44:31 +00001020 OPM_Instruction,
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001021 OPM_Int,
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001022 OPM_LiteralInt,
Daniel Sanders759ff412017-02-24 13:58:11 +00001023 OPM_LLT,
Daniel Sandersa71f4542017-10-16 00:56:30 +00001024 OPM_PointerToAny,
Daniel Sanders759ff412017-02-24 13:58:11 +00001025 OPM_RegBank,
1026 OPM_MBB,
1027 };
1028
1029protected:
1030 PredicateKind Kind;
Quentin Colombetaad20be2017-12-15 23:07:42 +00001031 unsigned InsnVarID;
1032 unsigned OpIdx;
Daniel Sanders759ff412017-02-24 13:58:11 +00001033
1034public:
Quentin Colombetaad20be2017-12-15 23:07:42 +00001035 PredicateMatcher(PredicateKind Kind, unsigned InsnVarID, unsigned OpIdx = ~0)
1036 : Kind(Kind), InsnVarID(InsnVarID), OpIdx(OpIdx) {}
Quentin Colombet063d7982017-12-14 23:44:07 +00001037
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001038 unsigned getInsnVarID() const { return InsnVarID; }
Quentin Colombetaad20be2017-12-15 23:07:42 +00001039 unsigned getOpIdx() const { return OpIdx; }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001040
Quentin Colombet063d7982017-12-14 23:44:07 +00001041 virtual ~PredicateMatcher() = default;
1042 /// Emit MatchTable opcodes that check the predicate for the given operand.
Quentin Colombetaad20be2017-12-15 23:07:42 +00001043 virtual void emitPredicateOpcodes(MatchTable &Table,
1044 RuleMatcher &Rule) const = 0;
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001045
Daniel Sanders759ff412017-02-24 13:58:11 +00001046 PredicateKind getKind() const { return Kind; }
Quentin Colombet893e0f12017-12-15 23:24:39 +00001047
1048 virtual bool isIdentical(const PredicateMatcher &B) const {
Quentin Colombet893e0f12017-12-15 23:24:39 +00001049 return B.getKind() == getKind() && InsnVarID == B.InsnVarID &&
1050 OpIdx == B.OpIdx;
1051 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001052
1053 virtual bool isIdenticalDownToValue(const PredicateMatcher &B) const {
1054 return hasValue() && PredicateMatcher::isIdentical(B);
1055 }
1056
1057 virtual MatchTableRecord getValue() const {
1058 assert(hasValue() && "Can not get a value of a value-less predicate!");
1059 llvm_unreachable("Not implemented yet");
1060 }
1061 virtual bool hasValue() const { return false; }
1062
1063 /// Report the maximum number of temporary operands needed by the predicate
1064 /// matcher.
1065 virtual unsigned countRendererFns() const { return 0; }
Quentin Colombet063d7982017-12-14 23:44:07 +00001066};
1067
1068/// Generates code to check a predicate of an operand.
1069///
1070/// Typical predicates include:
1071/// * Operand is a particular register.
1072/// * Operand is assigned a particular register bank.
1073/// * Operand is an MBB.
1074class OperandPredicateMatcher : public PredicateMatcher {
1075public:
Quentin Colombetaad20be2017-12-15 23:07:42 +00001076 OperandPredicateMatcher(PredicateKind Kind, unsigned InsnVarID,
1077 unsigned OpIdx)
1078 : PredicateMatcher(Kind, InsnVarID, OpIdx) {}
Quentin Colombet063d7982017-12-14 23:44:07 +00001079 virtual ~OperandPredicateMatcher() {}
Daniel Sanders759ff412017-02-24 13:58:11 +00001080
Daniel Sanders759ff412017-02-24 13:58:11 +00001081 /// Compare the priority of this object and B.
1082 ///
1083 /// Returns true if this object is more important than B.
Daniel Sanders05540042017-08-08 10:44:31 +00001084 virtual bool isHigherPriorityThan(const OperandPredicateMatcher &B) const;
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001085};
1086
Daniel Sanders2c269f62017-08-24 09:11:20 +00001087template <>
1088std::string
1089PredicateListMatcher<OperandPredicateMatcher>::getNoPredicateComment() const {
1090 return "No operand predicates";
1091}
1092
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001093/// Generates code to check that a register operand is defined by the same exact
1094/// one as another.
1095class SameOperandMatcher : public OperandPredicateMatcher {
Daniel Sanders1e4569f2017-10-20 20:55:29 +00001096 std::string MatchingName;
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001097
1098public:
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001099 SameOperandMatcher(unsigned InsnVarID, unsigned OpIdx, StringRef MatchingName)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001100 : OperandPredicateMatcher(OPM_SameOperand, InsnVarID, OpIdx),
1101 MatchingName(MatchingName) {}
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001102
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001103 static bool classof(const PredicateMatcher *P) {
Daniel Sanders1e4569f2017-10-20 20:55:29 +00001104 return P->getKind() == OPM_SameOperand;
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001105 }
1106
Quentin Colombetaad20be2017-12-15 23:07:42 +00001107 void emitPredicateOpcodes(MatchTable &Table,
1108 RuleMatcher &Rule) const override;
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001109
1110 bool isIdentical(const PredicateMatcher &B) const override {
1111 return OperandPredicateMatcher::isIdentical(B) &&
1112 MatchingName == cast<SameOperandMatcher>(&B)->MatchingName;
1113 }
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001114};
1115
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001116/// Generates code to check that an operand is a particular LLT.
1117class LLTOperandMatcher : public OperandPredicateMatcher {
1118protected:
Daniel Sanders52b4ce72017-03-07 23:20:35 +00001119 LLTCodeGen Ty;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001120
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001121public:
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001122 static std::map<LLTCodeGen, unsigned> TypeIDValues;
1123
1124 static void initTypeIDValuesMap() {
1125 TypeIDValues.clear();
1126
1127 unsigned ID = 0;
1128 for (const LLTCodeGen LLTy : KnownTypes)
1129 TypeIDValues[LLTy] = ID++;
1130 }
1131
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001132 LLTOperandMatcher(unsigned InsnVarID, unsigned OpIdx, const LLTCodeGen &Ty)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001133 : OperandPredicateMatcher(OPM_LLT, InsnVarID, OpIdx), Ty(Ty) {
Daniel Sanders032e7f22017-08-17 13:18:35 +00001134 KnownTypes.insert(Ty);
1135 }
Daniel Sanders759ff412017-02-24 13:58:11 +00001136
Quentin Colombet063d7982017-12-14 23:44:07 +00001137 static bool classof(const PredicateMatcher *P) {
Daniel Sanders759ff412017-02-24 13:58:11 +00001138 return P->getKind() == OPM_LLT;
1139 }
Quentin Colombet893e0f12017-12-15 23:24:39 +00001140 bool isIdentical(const PredicateMatcher &B) const override {
1141 return OperandPredicateMatcher::isIdentical(B) &&
1142 Ty == cast<LLTOperandMatcher>(&B)->Ty;
1143 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001144 MatchTableRecord getValue() const override {
1145 const auto VI = TypeIDValues.find(Ty);
1146 if (VI == TypeIDValues.end())
1147 return MatchTable::NamedValue(getTy().getCxxEnumValue());
1148 return MatchTable::NamedValue(getTy().getCxxEnumValue(), VI->second);
1149 }
1150 bool hasValue() const override {
1151 if (TypeIDValues.size() != KnownTypes.size())
1152 initTypeIDValuesMap();
1153 return TypeIDValues.count(Ty);
1154 }
1155
1156 LLTCodeGen getTy() const { return Ty; }
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001157
Quentin Colombetaad20be2017-12-15 23:07:42 +00001158 void emitPredicateOpcodes(MatchTable &Table,
1159 RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001160 Table << MatchTable::Opcode("GIM_CheckType") << MatchTable::Comment("MI")
1161 << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Op")
1162 << MatchTable::IntValue(OpIdx) << MatchTable::Comment("Type")
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001163 << getValue() << MatchTable::LineBreak;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001164 }
1165};
1166
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001167std::map<LLTCodeGen, unsigned> LLTOperandMatcher::TypeIDValues;
1168
Daniel Sandersa71f4542017-10-16 00:56:30 +00001169/// Generates code to check that an operand is a pointer to any address space.
1170///
1171/// In SelectionDAG, the types did not describe pointers or address spaces. As a
1172/// result, iN is used to describe a pointer of N bits to any address space and
1173/// PatFrag predicates are typically used to constrain the address space. There's
1174/// no reliable means to derive the missing type information from the pattern so
1175/// imported rules must test the components of a pointer separately.
1176///
Daniel Sandersea8711b2017-10-16 03:36:29 +00001177/// If SizeInBits is zero, then the pointer size will be obtained from the
1178/// subtarget.
Daniel Sandersa71f4542017-10-16 00:56:30 +00001179class PointerToAnyOperandMatcher : public OperandPredicateMatcher {
1180protected:
1181 unsigned SizeInBits;
1182
1183public:
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001184 PointerToAnyOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
1185 unsigned SizeInBits)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001186 : OperandPredicateMatcher(OPM_PointerToAny, InsnVarID, OpIdx),
1187 SizeInBits(SizeInBits) {}
Daniel Sandersa71f4542017-10-16 00:56:30 +00001188
1189 static bool classof(const OperandPredicateMatcher *P) {
1190 return P->getKind() == OPM_PointerToAny;
1191 }
1192
Quentin Colombetaad20be2017-12-15 23:07:42 +00001193 void emitPredicateOpcodes(MatchTable &Table,
1194 RuleMatcher &Rule) const override {
1195 Table << MatchTable::Opcode("GIM_CheckPointerToAny")
1196 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1197 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1198 << MatchTable::Comment("SizeInBits")
Daniel Sandersa71f4542017-10-16 00:56:30 +00001199 << MatchTable::IntValue(SizeInBits) << MatchTable::LineBreak;
1200 }
1201};
1202
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001203/// Generates code to check that an operand is a particular target constant.
1204class ComplexPatternOperandMatcher : public OperandPredicateMatcher {
1205protected:
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001206 const OperandMatcher &Operand;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001207 const Record &TheDef;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001208
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001209 unsigned getAllocatedTemporariesBaseID() const;
1210
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001211public:
Quentin Colombet893e0f12017-12-15 23:24:39 +00001212 bool isIdentical(const PredicateMatcher &B) const override { return false; }
1213
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001214 ComplexPatternOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
1215 const OperandMatcher &Operand,
1216 const Record &TheDef)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001217 : OperandPredicateMatcher(OPM_ComplexPattern, InsnVarID, OpIdx),
1218 Operand(Operand), TheDef(TheDef) {}
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001219
Quentin Colombet063d7982017-12-14 23:44:07 +00001220 static bool classof(const PredicateMatcher *P) {
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001221 return P->getKind() == OPM_ComplexPattern;
1222 }
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001223
Quentin Colombetaad20be2017-12-15 23:07:42 +00001224 void emitPredicateOpcodes(MatchTable &Table,
1225 RuleMatcher &Rule) const override {
Daniel Sanders2deea182017-04-22 15:11:04 +00001226 unsigned ID = getAllocatedTemporariesBaseID();
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001227 Table << MatchTable::Opcode("GIM_CheckComplexPattern")
1228 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1229 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1230 << MatchTable::Comment("Renderer") << MatchTable::IntValue(ID)
1231 << MatchTable::NamedValue(("GICP_" + TheDef.getName()).str())
1232 << MatchTable::LineBreak;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001233 }
1234
Daniel Sanders2deea182017-04-22 15:11:04 +00001235 unsigned countRendererFns() const override {
1236 return 1;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001237 }
1238};
1239
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001240/// Generates code to check that an operand is in a particular register bank.
1241class RegisterBankOperandMatcher : public OperandPredicateMatcher {
1242protected:
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001243 const CodeGenRegisterClass &RC;
1244
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001245public:
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001246 RegisterBankOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
1247 const CodeGenRegisterClass &RC)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001248 : OperandPredicateMatcher(OPM_RegBank, InsnVarID, OpIdx), RC(RC) {}
Daniel Sanders759ff412017-02-24 13:58:11 +00001249
Quentin Colombet893e0f12017-12-15 23:24:39 +00001250 bool isIdentical(const PredicateMatcher &B) const override {
1251 return OperandPredicateMatcher::isIdentical(B) &&
1252 RC.getDef() == cast<RegisterBankOperandMatcher>(&B)->RC.getDef();
1253 }
1254
Quentin Colombet063d7982017-12-14 23:44:07 +00001255 static bool classof(const PredicateMatcher *P) {
Daniel Sanders759ff412017-02-24 13:58:11 +00001256 return P->getKind() == OPM_RegBank;
1257 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001258
Quentin Colombetaad20be2017-12-15 23:07:42 +00001259 void emitPredicateOpcodes(MatchTable &Table,
1260 RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001261 Table << MatchTable::Opcode("GIM_CheckRegBankForClass")
1262 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1263 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1264 << MatchTable::Comment("RC")
1265 << MatchTable::NamedValue(RC.getQualifiedName() + "RegClassID")
1266 << MatchTable::LineBreak;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001267 }
1268};
1269
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001270/// Generates code to check that an operand is a basic block.
1271class MBBOperandMatcher : public OperandPredicateMatcher {
1272public:
Quentin Colombetaad20be2017-12-15 23:07:42 +00001273 MBBOperandMatcher(unsigned InsnVarID, unsigned OpIdx)
1274 : OperandPredicateMatcher(OPM_MBB, InsnVarID, OpIdx) {}
Daniel Sanders759ff412017-02-24 13:58:11 +00001275
Quentin Colombet063d7982017-12-14 23:44:07 +00001276 static bool classof(const PredicateMatcher *P) {
Daniel Sanders759ff412017-02-24 13:58:11 +00001277 return P->getKind() == OPM_MBB;
1278 }
1279
Quentin Colombetaad20be2017-12-15 23:07:42 +00001280 void emitPredicateOpcodes(MatchTable &Table,
1281 RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001282 Table << MatchTable::Opcode("GIM_CheckIsMBB") << MatchTable::Comment("MI")
1283 << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Op")
1284 << MatchTable::IntValue(OpIdx) << MatchTable::LineBreak;
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001285 }
1286};
1287
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001288/// Generates code to check that an operand is a G_CONSTANT with a particular
1289/// int.
1290class ConstantIntOperandMatcher : public OperandPredicateMatcher {
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001291protected:
1292 int64_t Value;
1293
1294public:
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001295 ConstantIntOperandMatcher(unsigned InsnVarID, unsigned OpIdx, int64_t Value)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001296 : OperandPredicateMatcher(OPM_Int, InsnVarID, OpIdx), Value(Value) {}
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001297
Quentin Colombet893e0f12017-12-15 23:24:39 +00001298 bool isIdentical(const PredicateMatcher &B) const override {
1299 return OperandPredicateMatcher::isIdentical(B) &&
1300 Value == cast<ConstantIntOperandMatcher>(&B)->Value;
1301 }
1302
Quentin Colombet063d7982017-12-14 23:44:07 +00001303 static bool classof(const PredicateMatcher *P) {
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001304 return P->getKind() == OPM_Int;
1305 }
1306
Quentin Colombetaad20be2017-12-15 23:07:42 +00001307 void emitPredicateOpcodes(MatchTable &Table,
1308 RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001309 Table << MatchTable::Opcode("GIM_CheckConstantInt")
1310 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1311 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1312 << MatchTable::IntValue(Value) << MatchTable::LineBreak;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001313 }
1314};
1315
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001316/// Generates code to check that an operand is a raw int (where MO.isImm() or
1317/// MO.isCImm() is true).
1318class LiteralIntOperandMatcher : public OperandPredicateMatcher {
1319protected:
1320 int64_t Value;
1321
1322public:
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001323 LiteralIntOperandMatcher(unsigned InsnVarID, unsigned OpIdx, int64_t Value)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001324 : OperandPredicateMatcher(OPM_LiteralInt, InsnVarID, OpIdx),
1325 Value(Value) {}
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001326
Quentin Colombet893e0f12017-12-15 23:24:39 +00001327 bool isIdentical(const PredicateMatcher &B) const override {
1328 return OperandPredicateMatcher::isIdentical(B) &&
1329 Value == cast<LiteralIntOperandMatcher>(&B)->Value;
1330 }
1331
Quentin Colombet063d7982017-12-14 23:44:07 +00001332 static bool classof(const PredicateMatcher *P) {
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001333 return P->getKind() == OPM_LiteralInt;
1334 }
1335
Quentin Colombetaad20be2017-12-15 23:07:42 +00001336 void emitPredicateOpcodes(MatchTable &Table,
1337 RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001338 Table << MatchTable::Opcode("GIM_CheckLiteralInt")
1339 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1340 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1341 << MatchTable::IntValue(Value) << MatchTable::LineBreak;
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001342 }
1343};
1344
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00001345/// Generates code to check that an operand is an intrinsic ID.
1346class IntrinsicIDOperandMatcher : public OperandPredicateMatcher {
1347protected:
1348 const CodeGenIntrinsic *II;
1349
1350public:
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001351 IntrinsicIDOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
1352 const CodeGenIntrinsic *II)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001353 : OperandPredicateMatcher(OPM_IntrinsicID, InsnVarID, OpIdx), II(II) {}
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00001354
Quentin Colombet893e0f12017-12-15 23:24:39 +00001355 bool isIdentical(const PredicateMatcher &B) const override {
1356 return OperandPredicateMatcher::isIdentical(B) &&
1357 II == cast<IntrinsicIDOperandMatcher>(&B)->II;
1358 }
1359
Quentin Colombet063d7982017-12-14 23:44:07 +00001360 static bool classof(const PredicateMatcher *P) {
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00001361 return P->getKind() == OPM_IntrinsicID;
1362 }
1363
Quentin Colombetaad20be2017-12-15 23:07:42 +00001364 void emitPredicateOpcodes(MatchTable &Table,
1365 RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001366 Table << MatchTable::Opcode("GIM_CheckIntrinsicID")
1367 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1368 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1369 << MatchTable::NamedValue("Intrinsic::" + II->EnumName)
1370 << MatchTable::LineBreak;
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00001371 }
1372};
1373
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001374/// Generates code to check that a set of predicates match for a particular
1375/// operand.
1376class OperandMatcher : public PredicateListMatcher<OperandPredicateMatcher> {
1377protected:
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001378 InstructionMatcher &Insn;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001379 unsigned OpIdx;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001380 std::string SymbolicName;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001381
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001382 /// The index of the first temporary variable allocated to this operand. The
1383 /// number of allocated temporaries can be found with
Daniel Sanders2deea182017-04-22 15:11:04 +00001384 /// countRendererFns().
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001385 unsigned AllocatedTemporariesBaseID;
1386
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001387public:
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001388 OperandMatcher(InstructionMatcher &Insn, unsigned OpIdx,
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001389 const std::string &SymbolicName,
1390 unsigned AllocatedTemporariesBaseID)
1391 : Insn(Insn), OpIdx(OpIdx), SymbolicName(SymbolicName),
1392 AllocatedTemporariesBaseID(AllocatedTemporariesBaseID) {}
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001393
1394 bool hasSymbolicName() const { return !SymbolicName.empty(); }
1395 const StringRef getSymbolicName() const { return SymbolicName; }
Daniel Sandersffc7d582017-03-29 15:37:18 +00001396 void setSymbolicName(StringRef Name) {
1397 assert(SymbolicName.empty() && "Operand already has a symbolic name");
1398 SymbolicName = Name;
1399 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001400
1401 /// Construct a new operand predicate and add it to the matcher.
1402 template <class Kind, class... Args>
1403 Optional<Kind *> addPredicate(Args &&... args) {
1404 if (isSameAsAnotherOperand())
1405 return None;
1406 Predicates.emplace_back(llvm::make_unique<Kind>(
1407 getInsnVarID(), getOpIdx(), std::forward<Args>(args)...));
1408 return static_cast<Kind *>(Predicates.back().get());
1409 }
1410
1411 unsigned getOpIdx() const { return OpIdx; }
Quentin Colombetaad20be2017-12-15 23:07:42 +00001412 unsigned getInsnVarID() const;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001413
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001414 std::string getOperandExpr(unsigned InsnVarID) const {
1415 return "State.MIs[" + llvm::to_string(InsnVarID) + "]->getOperand(" +
1416 llvm::to_string(OpIdx) + ")";
Daniel Sanderse604ef52017-02-20 15:30:43 +00001417 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001418
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001419 InstructionMatcher &getInstructionMatcher() const { return Insn; }
1420
Daniel Sandersa71f4542017-10-16 00:56:30 +00001421 Error addTypeCheckPredicate(const TypeSetByHwMode &VTy,
Reid Klecknercfdd4a22017-10-16 20:31:16 +00001422 bool OperandIsAPointer);
Daniel Sandersa71f4542017-10-16 00:56:30 +00001423
Daniel Sanders9d662d22017-07-06 10:06:12 +00001424 /// Emit MatchTable opcodes that test whether the instruction named in
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001425 /// InsnVarID matches all the predicates and all the operands.
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001426 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule) {
1427 if (!Optimized) {
1428 std::string Comment;
1429 raw_string_ostream CommentOS(Comment);
1430 CommentOS << "MIs[" << getInsnVarID() << "] ";
1431 if (SymbolicName.empty())
1432 CommentOS << "Operand " << OpIdx;
1433 else
1434 CommentOS << SymbolicName;
1435 Table << MatchTable::Comment(CommentOS.str()) << MatchTable::LineBreak;
1436 }
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001437
Quentin Colombetaad20be2017-12-15 23:07:42 +00001438 emitPredicateListOpcodes(Table, Rule);
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001439 }
Daniel Sanders759ff412017-02-24 13:58:11 +00001440
1441 /// Compare the priority of this object and B.
1442 ///
1443 /// Returns true if this object is more important than B.
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001444 bool isHigherPriorityThan(OperandMatcher &B) {
Daniel Sanders759ff412017-02-24 13:58:11 +00001445 // Operand matchers involving more predicates have higher priority.
1446 if (predicates_size() > B.predicates_size())
1447 return true;
1448 if (predicates_size() < B.predicates_size())
1449 return false;
1450
1451 // This assumes that predicates are added in a consistent order.
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001452 for (auto &&Predicate : zip(predicates(), B.predicates())) {
Daniel Sanders759ff412017-02-24 13:58:11 +00001453 if (std::get<0>(Predicate)->isHigherPriorityThan(*std::get<1>(Predicate)))
1454 return true;
1455 if (std::get<1>(Predicate)->isHigherPriorityThan(*std::get<0>(Predicate)))
1456 return false;
1457 }
1458
1459 return false;
1460 };
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001461
1462 /// Report the maximum number of temporary operands needed by the operand
1463 /// matcher.
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001464 unsigned countRendererFns() {
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001465 return std::accumulate(
1466 predicates().begin(), predicates().end(), 0,
1467 [](unsigned A,
1468 const std::unique_ptr<OperandPredicateMatcher> &Predicate) {
Daniel Sanders2deea182017-04-22 15:11:04 +00001469 return A + Predicate->countRendererFns();
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001470 });
1471 }
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001472
1473 unsigned getAllocatedTemporariesBaseID() const {
1474 return AllocatedTemporariesBaseID;
1475 }
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001476
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001477 bool isSameAsAnotherOperand() {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001478 for (const auto &Predicate : predicates())
1479 if (isa<SameOperandMatcher>(Predicate))
1480 return true;
1481 return false;
1482 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001483};
1484
Reid Klecknercfdd4a22017-10-16 20:31:16 +00001485Error OperandMatcher::addTypeCheckPredicate(const TypeSetByHwMode &VTy,
Quentin Colombetaad20be2017-12-15 23:07:42 +00001486 bool OperandIsAPointer) {
Reid Klecknercfdd4a22017-10-16 20:31:16 +00001487 if (!VTy.isMachineValueType())
1488 return failedImport("unsupported typeset");
1489
1490 if (VTy.getMachineValueType() == MVT::iPTR && OperandIsAPointer) {
1491 addPredicate<PointerToAnyOperandMatcher>(0);
1492 return Error::success();
1493 }
1494
1495 auto OpTyOrNone = MVTToLLT(VTy.getMachineValueType().SimpleTy);
1496 if (!OpTyOrNone)
1497 return failedImport("unsupported type");
1498
1499 if (OperandIsAPointer)
1500 addPredicate<PointerToAnyOperandMatcher>(OpTyOrNone->get().getSizeInBits());
1501 else
1502 addPredicate<LLTOperandMatcher>(*OpTyOrNone);
1503 return Error::success();
1504}
1505
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001506unsigned ComplexPatternOperandMatcher::getAllocatedTemporariesBaseID() const {
1507 return Operand.getAllocatedTemporariesBaseID();
1508}
1509
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001510/// Generates code to check a predicate on an instruction.
1511///
1512/// Typical predicates include:
1513/// * The opcode of the instruction is a particular value.
1514/// * The nsw/nuw flag is/isn't set.
Quentin Colombet063d7982017-12-14 23:44:07 +00001515class InstructionPredicateMatcher : public PredicateMatcher {
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001516public:
Quentin Colombetaad20be2017-12-15 23:07:42 +00001517 InstructionPredicateMatcher(PredicateKind Kind, unsigned InsnVarID)
1518 : PredicateMatcher(Kind, InsnVarID) {}
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001519 virtual ~InstructionPredicateMatcher() {}
1520
Daniel Sanders759ff412017-02-24 13:58:11 +00001521 /// Compare the priority of this object and B.
1522 ///
1523 /// Returns true if this object is more important than B.
Daniel Sanders32291982017-06-28 13:50:04 +00001524 virtual bool
1525 isHigherPriorityThan(const InstructionPredicateMatcher &B) const {
Daniel Sanders759ff412017-02-24 13:58:11 +00001526 return Kind < B.Kind;
1527 };
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001528};
1529
Daniel Sanders2c269f62017-08-24 09:11:20 +00001530template <>
1531std::string
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001532PredicateListMatcher<PredicateMatcher>::getNoPredicateComment() const {
Daniel Sanders2c269f62017-08-24 09:11:20 +00001533 return "No instruction predicates";
1534}
1535
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001536/// Generates code to check the opcode of an instruction.
1537class InstructionOpcodeMatcher : public InstructionPredicateMatcher {
1538protected:
1539 const CodeGenInstruction *I;
1540
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001541 static DenseMap<const CodeGenInstruction *, unsigned> OpcodeValues;
1542
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001543public:
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001544 static void initOpcodeValuesMap(const CodeGenTarget &Target) {
1545 OpcodeValues.clear();
1546
1547 unsigned OpcodeValue = 0;
1548 for (const CodeGenInstruction *I : Target.getInstructionsByEnumValue())
1549 OpcodeValues[I] = OpcodeValue++;
1550 }
1551
Quentin Colombetaad20be2017-12-15 23:07:42 +00001552 InstructionOpcodeMatcher(unsigned InsnVarID, const CodeGenInstruction *I)
1553 : InstructionPredicateMatcher(IPM_Opcode, InsnVarID), I(I) {}
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001554
Quentin Colombet063d7982017-12-14 23:44:07 +00001555 static bool classof(const PredicateMatcher *P) {
Daniel Sanders759ff412017-02-24 13:58:11 +00001556 return P->getKind() == IPM_Opcode;
1557 }
1558
Quentin Colombet893e0f12017-12-15 23:24:39 +00001559 bool isIdentical(const PredicateMatcher &B) const override {
1560 return InstructionPredicateMatcher::isIdentical(B) &&
1561 I == cast<InstructionOpcodeMatcher>(&B)->I;
1562 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001563 MatchTableRecord getValue() const override {
1564 const auto VI = OpcodeValues.find(I);
1565 if (VI != OpcodeValues.end())
1566 return MatchTable::NamedValue(I->Namespace, I->TheDef->getName(),
1567 VI->second);
1568 return MatchTable::NamedValue(I->Namespace, I->TheDef->getName());
1569 }
1570 bool hasValue() const override { return OpcodeValues.count(I); }
Quentin Colombet893e0f12017-12-15 23:24:39 +00001571
Quentin Colombetaad20be2017-12-15 23:07:42 +00001572 void emitPredicateOpcodes(MatchTable &Table,
1573 RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001574 Table << MatchTable::Opcode("GIM_CheckOpcode") << MatchTable::Comment("MI")
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001575 << MatchTable::IntValue(InsnVarID) << getValue()
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001576 << MatchTable::LineBreak;
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001577 }
Daniel Sanders759ff412017-02-24 13:58:11 +00001578
1579 /// Compare the priority of this object and B.
1580 ///
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001581 /// Returns true if this object is more important than B.
Daniel Sanders32291982017-06-28 13:50:04 +00001582 bool
1583 isHigherPriorityThan(const InstructionPredicateMatcher &B) const override {
Daniel Sanders759ff412017-02-24 13:58:11 +00001584 if (InstructionPredicateMatcher::isHigherPriorityThan(B))
1585 return true;
1586 if (B.InstructionPredicateMatcher::isHigherPriorityThan(*this))
1587 return false;
1588
1589 // Prioritize opcodes for cosmetic reasons in the generated source. Although
1590 // this is cosmetic at the moment, we may want to drive a similar ordering
1591 // using instruction frequency information to improve compile time.
1592 if (const InstructionOpcodeMatcher *BO =
1593 dyn_cast<InstructionOpcodeMatcher>(&B))
1594 return I->TheDef->getName() < BO->I->TheDef->getName();
1595
1596 return false;
1597 };
Daniel Sanders05540042017-08-08 10:44:31 +00001598
1599 bool isConstantInstruction() const {
1600 return I->TheDef->getName() == "G_CONSTANT";
1601 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001602
Roman Tereshin19da6672018-05-22 04:31:50 +00001603 StringRef getOpcode() const { return I->TheDef->getName(); }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001604 unsigned getNumOperands() const { return I->Operands.size(); }
1605
1606 StringRef getOperandType(unsigned OpIdx) const {
1607 return I->Operands[OpIdx].OperandType;
1608 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001609};
1610
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001611DenseMap<const CodeGenInstruction *, unsigned>
1612 InstructionOpcodeMatcher::OpcodeValues;
1613
Roman Tereshin19da6672018-05-22 04:31:50 +00001614class InstructionNumOperandsMatcher final : public InstructionPredicateMatcher {
1615 unsigned NumOperands = 0;
1616
1617public:
1618 InstructionNumOperandsMatcher(unsigned InsnVarID, unsigned NumOperands)
1619 : InstructionPredicateMatcher(IPM_NumOperands, InsnVarID),
1620 NumOperands(NumOperands) {}
1621
1622 static bool classof(const PredicateMatcher *P) {
1623 return P->getKind() == IPM_NumOperands;
1624 }
1625
1626 bool isIdentical(const PredicateMatcher &B) const override {
1627 return InstructionPredicateMatcher::isIdentical(B) &&
1628 NumOperands == cast<InstructionNumOperandsMatcher>(&B)->NumOperands;
1629 }
1630
1631 void emitPredicateOpcodes(MatchTable &Table,
1632 RuleMatcher &Rule) const override {
1633 Table << MatchTable::Opcode("GIM_CheckNumOperands")
1634 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1635 << MatchTable::Comment("Expected")
1636 << MatchTable::IntValue(NumOperands) << MatchTable::LineBreak;
1637 }
1638};
1639
Daniel Sanders2c269f62017-08-24 09:11:20 +00001640/// Generates code to check that this instruction is a constant whose value
1641/// meets an immediate predicate.
1642///
1643/// Immediates are slightly odd since they are typically used like an operand
1644/// but are represented as an operator internally. We typically write simm8:$src
1645/// in a tablegen pattern, but this is just syntactic sugar for
1646/// (imm:i32)<<P:Predicate_simm8>>:$imm which more directly describes the nodes
1647/// that will be matched and the predicate (which is attached to the imm
1648/// operator) that will be tested. In SelectionDAG this describes a
1649/// ConstantSDNode whose internal value will be tested using the simm8 predicate.
1650///
1651/// The corresponding GlobalISel representation is %1 = G_CONSTANT iN Value. In
1652/// this representation, the immediate could be tested with an
1653/// InstructionMatcher, InstructionOpcodeMatcher, OperandMatcher, and a
1654/// OperandPredicateMatcher-subclass to check the Value meets the predicate but
1655/// there are two implementation issues with producing that matcher
1656/// configuration from the SelectionDAG pattern:
1657/// * ImmLeaf is a PatFrag whose root is an InstructionMatcher. This means that
1658/// were we to sink the immediate predicate to the operand we would have to
1659/// have two partial implementations of PatFrag support, one for immediates
1660/// and one for non-immediates.
1661/// * At the point we handle the predicate, the OperandMatcher hasn't been
1662/// created yet. If we were to sink the predicate to the OperandMatcher we
1663/// would also have to complicate (or duplicate) the code that descends and
1664/// creates matchers for the subtree.
1665/// Overall, it's simpler to handle it in the place it was found.
1666class InstructionImmPredicateMatcher : public InstructionPredicateMatcher {
1667protected:
1668 TreePredicateFn Predicate;
1669
1670public:
Quentin Colombetaad20be2017-12-15 23:07:42 +00001671 InstructionImmPredicateMatcher(unsigned InsnVarID,
1672 const TreePredicateFn &Predicate)
1673 : InstructionPredicateMatcher(IPM_ImmPredicate, InsnVarID),
1674 Predicate(Predicate) {}
Daniel Sanders2c269f62017-08-24 09:11:20 +00001675
Quentin Colombet893e0f12017-12-15 23:24:39 +00001676 bool isIdentical(const PredicateMatcher &B) const override {
1677 return InstructionPredicateMatcher::isIdentical(B) &&
1678 Predicate.getOrigPatFragRecord() ==
1679 cast<InstructionImmPredicateMatcher>(&B)
1680 ->Predicate.getOrigPatFragRecord();
1681 }
1682
Quentin Colombet063d7982017-12-14 23:44:07 +00001683 static bool classof(const PredicateMatcher *P) {
Daniel Sanders2c269f62017-08-24 09:11:20 +00001684 return P->getKind() == IPM_ImmPredicate;
1685 }
1686
Quentin Colombetaad20be2017-12-15 23:07:42 +00001687 void emitPredicateOpcodes(MatchTable &Table,
1688 RuleMatcher &Rule) const override {
Daniel Sanders11300ce2017-10-13 21:28:03 +00001689 Table << MatchTable::Opcode(getMatchOpcodeForPredicate(Predicate))
Daniel Sanders2c269f62017-08-24 09:11:20 +00001690 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1691 << MatchTable::Comment("Predicate")
Daniel Sanders11300ce2017-10-13 21:28:03 +00001692 << MatchTable::NamedValue(getEnumNameForPredicate(Predicate))
Daniel Sanders2c269f62017-08-24 09:11:20 +00001693 << MatchTable::LineBreak;
1694 }
1695};
1696
Daniel Sanders76664652017-11-28 22:07:05 +00001697/// Generates code to check that a memory instruction has a atomic ordering
1698/// MachineMemoryOperand.
1699class AtomicOrderingMMOPredicateMatcher : public InstructionPredicateMatcher {
Daniel Sanders0c43b3a2017-11-30 21:05:59 +00001700public:
1701 enum AOComparator {
1702 AO_Exactly,
1703 AO_OrStronger,
1704 AO_WeakerThan,
1705 };
1706
1707protected:
Daniel Sanders76664652017-11-28 22:07:05 +00001708 StringRef Order;
Daniel Sanders0c43b3a2017-11-30 21:05:59 +00001709 AOComparator Comparator;
Daniel Sanders76664652017-11-28 22:07:05 +00001710
Daniel Sanders39690bd2017-10-15 02:41:12 +00001711public:
Quentin Colombetaad20be2017-12-15 23:07:42 +00001712 AtomicOrderingMMOPredicateMatcher(unsigned InsnVarID, StringRef Order,
Daniel Sanders0c43b3a2017-11-30 21:05:59 +00001713 AOComparator Comparator = AO_Exactly)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001714 : InstructionPredicateMatcher(IPM_AtomicOrderingMMO, InsnVarID),
1715 Order(Order), Comparator(Comparator) {}
Daniel Sanders39690bd2017-10-15 02:41:12 +00001716
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001717 static bool classof(const PredicateMatcher *P) {
Daniel Sanders76664652017-11-28 22:07:05 +00001718 return P->getKind() == IPM_AtomicOrderingMMO;
Daniel Sanders39690bd2017-10-15 02:41:12 +00001719 }
1720
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001721 bool isIdentical(const PredicateMatcher &B) const override {
1722 if (!InstructionPredicateMatcher::isIdentical(B))
1723 return false;
1724 const auto &R = *cast<AtomicOrderingMMOPredicateMatcher>(&B);
1725 return Order == R.Order && Comparator == R.Comparator;
1726 }
1727
Quentin Colombetaad20be2017-12-15 23:07:42 +00001728 void emitPredicateOpcodes(MatchTable &Table,
1729 RuleMatcher &Rule) const override {
Daniel Sanders0c43b3a2017-11-30 21:05:59 +00001730 StringRef Opcode = "GIM_CheckAtomicOrdering";
1731
1732 if (Comparator == AO_OrStronger)
1733 Opcode = "GIM_CheckAtomicOrderingOrStrongerThan";
1734 if (Comparator == AO_WeakerThan)
1735 Opcode = "GIM_CheckAtomicOrderingWeakerThan";
1736
1737 Table << MatchTable::Opcode(Opcode) << MatchTable::Comment("MI")
1738 << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Order")
Daniel Sanders76664652017-11-28 22:07:05 +00001739 << MatchTable::NamedValue(("(int64_t)AtomicOrdering::" + Order).str())
Daniel Sanders39690bd2017-10-15 02:41:12 +00001740 << MatchTable::LineBreak;
1741 }
1742};
1743
Daniel Sandersf84bc372018-05-05 20:53:24 +00001744/// Generates code to check that the size of an MMO is exactly N bytes.
1745class MemorySizePredicateMatcher : public InstructionPredicateMatcher {
1746protected:
1747 unsigned MMOIdx;
1748 uint64_t Size;
1749
1750public:
1751 MemorySizePredicateMatcher(unsigned InsnVarID, unsigned MMOIdx, unsigned Size)
1752 : InstructionPredicateMatcher(IPM_MemoryLLTSize, InsnVarID),
1753 MMOIdx(MMOIdx), Size(Size) {}
1754
1755 static bool classof(const PredicateMatcher *P) {
1756 return P->getKind() == IPM_MemoryLLTSize;
1757 }
1758 bool isIdentical(const PredicateMatcher &B) const override {
1759 return InstructionPredicateMatcher::isIdentical(B) &&
1760 MMOIdx == cast<MemorySizePredicateMatcher>(&B)->MMOIdx &&
1761 Size == cast<MemorySizePredicateMatcher>(&B)->Size;
1762 }
1763
1764 void emitPredicateOpcodes(MatchTable &Table,
1765 RuleMatcher &Rule) const override {
1766 Table << MatchTable::Opcode("GIM_CheckMemorySizeEqualTo")
1767 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1768 << MatchTable::Comment("MMO") << MatchTable::IntValue(MMOIdx)
1769 << MatchTable::Comment("Size") << MatchTable::IntValue(Size)
1770 << MatchTable::LineBreak;
1771 }
1772};
1773
1774/// Generates code to check that the size of an MMO is less-than, equal-to, or
1775/// greater than a given LLT.
1776class MemoryVsLLTSizePredicateMatcher : public InstructionPredicateMatcher {
1777public:
1778 enum RelationKind {
1779 GreaterThan,
1780 EqualTo,
1781 LessThan,
1782 };
1783
1784protected:
1785 unsigned MMOIdx;
1786 RelationKind Relation;
1787 unsigned OpIdx;
1788
1789public:
1790 MemoryVsLLTSizePredicateMatcher(unsigned InsnVarID, unsigned MMOIdx,
1791 enum RelationKind Relation,
1792 unsigned OpIdx)
1793 : InstructionPredicateMatcher(IPM_MemoryVsLLTSize, InsnVarID),
1794 MMOIdx(MMOIdx), Relation(Relation), OpIdx(OpIdx) {}
1795
1796 static bool classof(const PredicateMatcher *P) {
1797 return P->getKind() == IPM_MemoryVsLLTSize;
1798 }
1799 bool isIdentical(const PredicateMatcher &B) const override {
1800 return InstructionPredicateMatcher::isIdentical(B) &&
1801 MMOIdx == cast<MemoryVsLLTSizePredicateMatcher>(&B)->MMOIdx &&
1802 Relation == cast<MemoryVsLLTSizePredicateMatcher>(&B)->Relation &&
1803 OpIdx == cast<MemoryVsLLTSizePredicateMatcher>(&B)->OpIdx;
1804 }
1805
1806 void emitPredicateOpcodes(MatchTable &Table,
1807 RuleMatcher &Rule) const override {
1808 Table << MatchTable::Opcode(Relation == EqualTo
1809 ? "GIM_CheckMemorySizeEqualToLLT"
1810 : Relation == GreaterThan
1811 ? "GIM_CheckMemorySizeGreaterThanLLT"
1812 : "GIM_CheckMemorySizeLessThanLLT")
1813 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1814 << MatchTable::Comment("MMO") << MatchTable::IntValue(MMOIdx)
1815 << MatchTable::Comment("OpIdx") << MatchTable::IntValue(OpIdx)
1816 << MatchTable::LineBreak;
1817 }
1818};
1819
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001820/// Generates code to check that a set of predicates and operands match for a
1821/// particular instruction.
1822///
1823/// Typical predicates include:
1824/// * Has a specific opcode.
1825/// * Has an nsw/nuw flag or doesn't.
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001826class InstructionMatcher final : public PredicateListMatcher<PredicateMatcher> {
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001827protected:
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001828 typedef std::vector<std::unique_ptr<OperandMatcher>> OperandVec;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001829
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001830 RuleMatcher &Rule;
1831
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001832 /// The operands to match. All rendered operands must be present even if the
1833 /// condition is always true.
1834 OperandVec Operands;
Roman Tereshin19da6672018-05-22 04:31:50 +00001835 bool NumOperandsCheck = true;
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001836
Daniel Sanders05540042017-08-08 10:44:31 +00001837 std::string SymbolicName;
Quentin Colombetaad20be2017-12-15 23:07:42 +00001838 unsigned InsnVarID;
Daniel Sanders05540042017-08-08 10:44:31 +00001839
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001840public:
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001841 InstructionMatcher(RuleMatcher &Rule, StringRef SymbolicName)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001842 : Rule(Rule), SymbolicName(SymbolicName) {
1843 // We create a new instruction matcher.
1844 // Get a new ID for that instruction.
1845 InsnVarID = Rule.implicitlyDefineInsnVar(*this);
1846 }
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001847
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001848 /// Construct a new instruction predicate and add it to the matcher.
1849 template <class Kind, class... Args>
1850 Optional<Kind *> addPredicate(Args &&... args) {
1851 Predicates.emplace_back(
1852 llvm::make_unique<Kind>(getInsnVarID(), std::forward<Args>(args)...));
1853 return static_cast<Kind *>(Predicates.back().get());
1854 }
1855
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001856 RuleMatcher &getRuleMatcher() const { return Rule; }
Daniel Sanders05540042017-08-08 10:44:31 +00001857
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001858 unsigned getInsnVarID() const { return InsnVarID; }
Quentin Colombetaad20be2017-12-15 23:07:42 +00001859
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001860 /// Add an operand to the matcher.
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001861 OperandMatcher &addOperand(unsigned OpIdx, const std::string &SymbolicName,
1862 unsigned AllocatedTemporariesBaseID) {
1863 Operands.emplace_back(new OperandMatcher(*this, OpIdx, SymbolicName,
1864 AllocatedTemporariesBaseID));
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001865 if (!SymbolicName.empty())
1866 Rule.defineOperand(SymbolicName, *Operands.back());
1867
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001868 return *Operands.back();
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001869 }
1870
Daniel Sandersffc7d582017-03-29 15:37:18 +00001871 OperandMatcher &getOperand(unsigned OpIdx) {
1872 auto I = std::find_if(Operands.begin(), Operands.end(),
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001873 [&OpIdx](const std::unique_ptr<OperandMatcher> &X) {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001874 return X->getOpIdx() == OpIdx;
Daniel Sandersffc7d582017-03-29 15:37:18 +00001875 });
1876 if (I != Operands.end())
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001877 return **I;
Daniel Sandersffc7d582017-03-29 15:37:18 +00001878 llvm_unreachable("Failed to lookup operand");
1879 }
1880
Daniel Sanders05540042017-08-08 10:44:31 +00001881 StringRef getSymbolicName() const { return SymbolicName; }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001882 unsigned getNumOperands() const { return Operands.size(); }
Daniel Sandersbee57392017-04-04 13:25:23 +00001883 OperandVec::iterator operands_begin() { return Operands.begin(); }
1884 OperandVec::iterator operands_end() { return Operands.end(); }
1885 iterator_range<OperandVec::iterator> operands() {
1886 return make_range(operands_begin(), operands_end());
1887 }
Daniel Sandersffc7d582017-03-29 15:37:18 +00001888 OperandVec::const_iterator operands_begin() const { return Operands.begin(); }
1889 OperandVec::const_iterator operands_end() const { return Operands.end(); }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001890 iterator_range<OperandVec::const_iterator> operands() const {
1891 return make_range(operands_begin(), operands_end());
1892 }
Quentin Colombetec76d9c2017-12-18 19:47:41 +00001893 bool operands_empty() const { return Operands.empty(); }
1894
1895 void pop_front() { Operands.erase(Operands.begin()); }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001896
Roman Tereshin19da6672018-05-22 04:31:50 +00001897 void optimize();
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001898
1899 /// Emit MatchTable opcodes that test whether the instruction named in
1900 /// InsnVarName matches all the predicates and all the operands.
1901 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule) {
Roman Tereshin19da6672018-05-22 04:31:50 +00001902 if (NumOperandsCheck)
1903 InstructionNumOperandsMatcher(InsnVarID, getNumOperands())
1904 .emitPredicateOpcodes(Table, Rule);
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001905
Quentin Colombetaad20be2017-12-15 23:07:42 +00001906 emitPredicateListOpcodes(Table, Rule);
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001907
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001908 for (const auto &Operand : Operands)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001909 Operand->emitPredicateOpcodes(Table, Rule);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001910 }
Daniel Sanders759ff412017-02-24 13:58:11 +00001911
1912 /// Compare the priority of this object and B.
1913 ///
1914 /// Returns true if this object is more important than B.
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001915 bool isHigherPriorityThan(InstructionMatcher &B) {
Daniel Sanders759ff412017-02-24 13:58:11 +00001916 // Instruction matchers involving more operands have higher priority.
1917 if (Operands.size() > B.Operands.size())
1918 return true;
1919 if (Operands.size() < B.Operands.size())
1920 return false;
1921
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001922 for (auto &&P : zip(predicates(), B.predicates())) {
1923 auto L = static_cast<InstructionPredicateMatcher *>(std::get<0>(P).get());
1924 auto R = static_cast<InstructionPredicateMatcher *>(std::get<1>(P).get());
1925 if (L->isHigherPriorityThan(*R))
Daniel Sanders759ff412017-02-24 13:58:11 +00001926 return true;
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001927 if (R->isHigherPriorityThan(*L))
Daniel Sanders759ff412017-02-24 13:58:11 +00001928 return false;
1929 }
1930
1931 for (const auto &Operand : zip(Operands, B.Operands)) {
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001932 if (std::get<0>(Operand)->isHigherPriorityThan(*std::get<1>(Operand)))
Daniel Sanders759ff412017-02-24 13:58:11 +00001933 return true;
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001934 if (std::get<1>(Operand)->isHigherPriorityThan(*std::get<0>(Operand)))
Daniel Sanders759ff412017-02-24 13:58:11 +00001935 return false;
1936 }
1937
1938 return false;
1939 };
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001940
1941 /// Report the maximum number of temporary operands needed by the instruction
1942 /// matcher.
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001943 unsigned countRendererFns() {
1944 return std::accumulate(
1945 predicates().begin(), predicates().end(), 0,
1946 [](unsigned A,
1947 const std::unique_ptr<PredicateMatcher> &Predicate) {
1948 return A + Predicate->countRendererFns();
1949 }) +
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001950 std::accumulate(
1951 Operands.begin(), Operands.end(), 0,
1952 [](unsigned A, const std::unique_ptr<OperandMatcher> &Operand) {
Daniel Sanders2deea182017-04-22 15:11:04 +00001953 return A + Operand->countRendererFns();
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001954 });
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001955 }
Daniel Sanders05540042017-08-08 10:44:31 +00001956
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001957 InstructionOpcodeMatcher &getOpcodeMatcher() {
1958 for (auto &P : predicates())
1959 if (auto *OpMatcher = dyn_cast<InstructionOpcodeMatcher>(P.get()))
1960 return *OpMatcher;
1961 llvm_unreachable("Didn't find an opcode matcher");
1962 }
1963
1964 bool isConstantInstruction() {
1965 return getOpcodeMatcher().isConstantInstruction();
Daniel Sanders05540042017-08-08 10:44:31 +00001966 }
Roman Tereshin19da6672018-05-22 04:31:50 +00001967
1968 StringRef getOpcode() { return getOpcodeMatcher().getOpcode(); }
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001969};
1970
Roman Tereshin19da6672018-05-22 04:31:50 +00001971StringRef RuleMatcher::getOpcode() const {
1972 return Matchers.front()->getOpcode();
1973}
1974
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001975unsigned RuleMatcher::getNumOperands() const {
1976 return Matchers.front()->getNumOperands();
1977}
1978
Roman Tereshin9a9fa492018-05-23 21:30:16 +00001979LLTCodeGen RuleMatcher::getFirstConditionAsRootType() {
1980 InstructionMatcher &InsnMatcher = *Matchers.front();
1981 if (!InsnMatcher.predicates_empty())
1982 if (const auto *TM =
1983 dyn_cast<LLTOperandMatcher>(&**InsnMatcher.predicates_begin()))
1984 if (TM->getInsnVarID() == 0 && TM->getOpIdx() == 0)
1985 return TM->getTy();
1986 return {};
1987}
1988
Daniel Sandersbee57392017-04-04 13:25:23 +00001989/// Generates code to check that the operand is a register defined by an
1990/// instruction that matches the given instruction matcher.
1991///
1992/// For example, the pattern:
1993/// (set $dst, (G_MUL (G_ADD $src1, $src2), $src3))
1994/// would use an InstructionOperandMatcher for operand 1 of the G_MUL to match
1995/// the:
1996/// (G_ADD $src1, $src2)
1997/// subpattern.
1998class InstructionOperandMatcher : public OperandPredicateMatcher {
1999protected:
2000 std::unique_ptr<InstructionMatcher> InsnMatcher;
2001
2002public:
Quentin Colombeteba10cb2017-12-18 22:12:13 +00002003 InstructionOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
2004 RuleMatcher &Rule, StringRef SymbolicName)
Quentin Colombetaad20be2017-12-15 23:07:42 +00002005 : OperandPredicateMatcher(OPM_Instruction, InsnVarID, OpIdx),
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002006 InsnMatcher(new InstructionMatcher(Rule, SymbolicName)) {}
Daniel Sandersbee57392017-04-04 13:25:23 +00002007
Quentin Colombet063d7982017-12-14 23:44:07 +00002008 static bool classof(const PredicateMatcher *P) {
Daniel Sandersbee57392017-04-04 13:25:23 +00002009 return P->getKind() == OPM_Instruction;
2010 }
2011
2012 InstructionMatcher &getInsnMatcher() const { return *InsnMatcher; }
2013
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002014 void emitCaptureOpcodes(MatchTable &Table, RuleMatcher &Rule) const {
2015 const unsigned NewInsnVarID = InsnMatcher->getInsnVarID();
2016 Table << MatchTable::Opcode("GIM_RecordInsn")
2017 << MatchTable::Comment("DefineMI")
2018 << MatchTable::IntValue(NewInsnVarID) << MatchTable::Comment("MI")
2019 << MatchTable::IntValue(getInsnVarID())
2020 << MatchTable::Comment("OpIdx") << MatchTable::IntValue(getOpIdx())
2021 << MatchTable::Comment("MIs[" + llvm::to_string(NewInsnVarID) + "]")
2022 << MatchTable::LineBreak;
Daniel Sandersbee57392017-04-04 13:25:23 +00002023 }
2024
Quentin Colombetaad20be2017-12-15 23:07:42 +00002025 void emitPredicateOpcodes(MatchTable &Table,
2026 RuleMatcher &Rule) const override {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002027 emitCaptureOpcodes(Table, Rule);
Quentin Colombetaad20be2017-12-15 23:07:42 +00002028 InsnMatcher->emitPredicateOpcodes(Table, Rule);
Daniel Sandersbee57392017-04-04 13:25:23 +00002029 }
Daniel Sanders12e6e702018-01-17 20:34:29 +00002030
2031 bool isHigherPriorityThan(const OperandPredicateMatcher &B) const override {
2032 if (OperandPredicateMatcher::isHigherPriorityThan(B))
2033 return true;
2034 if (B.OperandPredicateMatcher::isHigherPriorityThan(*this))
2035 return false;
2036
2037 if (const InstructionOperandMatcher *BP =
2038 dyn_cast<InstructionOperandMatcher>(&B))
2039 if (InsnMatcher->isHigherPriorityThan(*BP->InsnMatcher))
2040 return true;
2041 return false;
2042 }
Daniel Sandersbee57392017-04-04 13:25:23 +00002043};
2044
Roman Tereshin19da6672018-05-22 04:31:50 +00002045void InstructionMatcher::optimize() {
2046 SmallVector<std::unique_ptr<PredicateMatcher>, 8> Stash;
2047 const auto &OpcMatcher = getOpcodeMatcher();
2048
2049 Stash.push_back(predicates_pop_front());
2050 if (Stash.back().get() == &OpcMatcher) {
2051 if (NumOperandsCheck && OpcMatcher.getNumOperands() < getNumOperands())
2052 Stash.emplace_back(
2053 new InstructionNumOperandsMatcher(InsnVarID, getNumOperands()));
2054 NumOperandsCheck = false;
Roman Tereshinfedae332018-05-23 02:04:19 +00002055
2056 for (auto &OM : Operands)
2057 for (auto &OP : OM->predicates())
2058 if (isa<IntrinsicIDOperandMatcher>(OP)) {
2059 Stash.push_back(std::move(OP));
2060 OM->eraseNullPredicates();
2061 break;
2062 }
Roman Tereshin19da6672018-05-22 04:31:50 +00002063 }
2064
2065 if (InsnVarID > 0) {
2066 assert(!Operands.empty() && "Nested instruction is expected to def a vreg");
2067 for (auto &OP : Operands[0]->predicates())
2068 OP.reset();
2069 Operands[0]->eraseNullPredicates();
2070 }
Roman Tereshinb1ba1272018-05-23 19:16:59 +00002071 for (auto &OM : Operands) {
2072 for (auto &OP : OM->predicates())
2073 if (isa<LLTOperandMatcher>(OP))
2074 Stash.push_back(std::move(OP));
2075 OM->eraseNullPredicates();
2076 }
Roman Tereshin19da6672018-05-22 04:31:50 +00002077 while (!Stash.empty())
2078 prependPredicate(Stash.pop_back_val());
2079}
2080
Daniel Sanders43c882c2017-02-01 10:53:10 +00002081//===- Actions ------------------------------------------------------------===//
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002082class OperandRenderer {
2083public:
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002084 enum RendererKind {
2085 OR_Copy,
Daniel Sandersd66e0902017-10-23 18:19:24 +00002086 OR_CopyOrAddZeroReg,
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002087 OR_CopySubReg,
Daniel Sanders05540042017-08-08 10:44:31 +00002088 OR_CopyConstantAsImm,
Daniel Sanders11300ce2017-10-13 21:28:03 +00002089 OR_CopyFConstantAsFPImm,
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002090 OR_Imm,
2091 OR_Register,
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002092 OR_TempRegister,
Volkan Kelesf7f25682018-01-16 18:44:05 +00002093 OR_ComplexPattern,
2094 OR_Custom
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002095 };
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002096
2097protected:
2098 RendererKind Kind;
2099
2100public:
2101 OperandRenderer(RendererKind Kind) : Kind(Kind) {}
2102 virtual ~OperandRenderer() {}
2103
2104 RendererKind getKind() const { return Kind; }
2105
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002106 virtual void emitRenderOpcodes(MatchTable &Table,
2107 RuleMatcher &Rule) const = 0;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002108};
2109
2110/// A CopyRenderer emits code to copy a single operand from an existing
2111/// instruction to the one being built.
2112class CopyRenderer : public OperandRenderer {
2113protected:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002114 unsigned NewInsnID;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002115 /// The name of the operand.
2116 const StringRef SymbolicName;
2117
2118public:
Daniel Sandersbd83ad42017-10-24 01:48:34 +00002119 CopyRenderer(unsigned NewInsnID, StringRef SymbolicName)
2120 : OperandRenderer(OR_Copy), NewInsnID(NewInsnID),
Daniel Sanders05540042017-08-08 10:44:31 +00002121 SymbolicName(SymbolicName) {
2122 assert(!SymbolicName.empty() && "Cannot copy from an unspecified source");
2123 }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002124
2125 static bool classof(const OperandRenderer *R) {
2126 return R->getKind() == OR_Copy;
2127 }
2128
2129 const StringRef getSymbolicName() const { return SymbolicName; }
2130
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002131 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002132 const OperandMatcher &Operand = Rule.getOperandMatcher(SymbolicName);
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002133 unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002134 Table << MatchTable::Opcode("GIR_Copy") << MatchTable::Comment("NewInsnID")
2135 << MatchTable::IntValue(NewInsnID) << MatchTable::Comment("OldInsnID")
2136 << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002137 << MatchTable::IntValue(Operand.getOpIdx())
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002138 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002139 }
2140};
2141
Daniel Sandersd66e0902017-10-23 18:19:24 +00002142/// A CopyOrAddZeroRegRenderer emits code to copy a single operand from an
2143/// existing instruction to the one being built. If the operand turns out to be
2144/// a 'G_CONSTANT 0' then it replaces the operand with a zero register.
2145class CopyOrAddZeroRegRenderer : public OperandRenderer {
2146protected:
2147 unsigned NewInsnID;
2148 /// The name of the operand.
2149 const StringRef SymbolicName;
2150 const Record *ZeroRegisterDef;
2151
2152public:
2153 CopyOrAddZeroRegRenderer(unsigned NewInsnID,
Daniel Sandersd66e0902017-10-23 18:19:24 +00002154 StringRef SymbolicName, Record *ZeroRegisterDef)
2155 : OperandRenderer(OR_CopyOrAddZeroReg), NewInsnID(NewInsnID),
2156 SymbolicName(SymbolicName), ZeroRegisterDef(ZeroRegisterDef) {
2157 assert(!SymbolicName.empty() && "Cannot copy from an unspecified source");
2158 }
2159
2160 static bool classof(const OperandRenderer *R) {
2161 return R->getKind() == OR_CopyOrAddZeroReg;
2162 }
2163
2164 const StringRef getSymbolicName() const { return SymbolicName; }
2165
2166 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2167 const OperandMatcher &Operand = Rule.getOperandMatcher(SymbolicName);
2168 unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
2169 Table << MatchTable::Opcode("GIR_CopyOrAddZeroReg")
2170 << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
2171 << MatchTable::Comment("OldInsnID")
2172 << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002173 << MatchTable::IntValue(Operand.getOpIdx())
Daniel Sandersd66e0902017-10-23 18:19:24 +00002174 << MatchTable::NamedValue(
2175 (ZeroRegisterDef->getValue("Namespace")
2176 ? ZeroRegisterDef->getValueAsString("Namespace")
2177 : ""),
2178 ZeroRegisterDef->getName())
2179 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2180 }
2181};
2182
Daniel Sanders05540042017-08-08 10:44:31 +00002183/// A CopyConstantAsImmRenderer emits code to render a G_CONSTANT instruction to
2184/// an extended immediate operand.
2185class CopyConstantAsImmRenderer : public OperandRenderer {
2186protected:
2187 unsigned NewInsnID;
2188 /// The name of the operand.
2189 const std::string SymbolicName;
2190 bool Signed;
2191
2192public:
2193 CopyConstantAsImmRenderer(unsigned NewInsnID, StringRef SymbolicName)
2194 : OperandRenderer(OR_CopyConstantAsImm), NewInsnID(NewInsnID),
2195 SymbolicName(SymbolicName), Signed(true) {}
2196
2197 static bool classof(const OperandRenderer *R) {
2198 return R->getKind() == OR_CopyConstantAsImm;
2199 }
2200
2201 const StringRef getSymbolicName() const { return SymbolicName; }
2202
2203 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002204 InstructionMatcher &InsnMatcher = Rule.getInstructionMatcher(SymbolicName);
Daniel Sanders05540042017-08-08 10:44:31 +00002205 unsigned OldInsnVarID = Rule.getInsnVarID(InsnMatcher);
2206 Table << MatchTable::Opcode(Signed ? "GIR_CopyConstantAsSImm"
2207 : "GIR_CopyConstantAsUImm")
2208 << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
2209 << MatchTable::Comment("OldInsnID")
2210 << MatchTable::IntValue(OldInsnVarID)
2211 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2212 }
2213};
2214
Daniel Sanders11300ce2017-10-13 21:28:03 +00002215/// A CopyFConstantAsFPImmRenderer emits code to render a G_FCONSTANT
2216/// instruction to an extended immediate operand.
2217class CopyFConstantAsFPImmRenderer : public OperandRenderer {
2218protected:
2219 unsigned NewInsnID;
2220 /// The name of the operand.
2221 const std::string SymbolicName;
2222
2223public:
2224 CopyFConstantAsFPImmRenderer(unsigned NewInsnID, StringRef SymbolicName)
2225 : OperandRenderer(OR_CopyFConstantAsFPImm), NewInsnID(NewInsnID),
2226 SymbolicName(SymbolicName) {}
2227
2228 static bool classof(const OperandRenderer *R) {
2229 return R->getKind() == OR_CopyFConstantAsFPImm;
2230 }
2231
2232 const StringRef getSymbolicName() const { return SymbolicName; }
2233
2234 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002235 InstructionMatcher &InsnMatcher = Rule.getInstructionMatcher(SymbolicName);
Daniel Sanders11300ce2017-10-13 21:28:03 +00002236 unsigned OldInsnVarID = Rule.getInsnVarID(InsnMatcher);
2237 Table << MatchTable::Opcode("GIR_CopyFConstantAsFPImm")
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 Sanderscc36dbf2017-06-27 10:11:39 +00002245/// A CopySubRegRenderer emits code to copy a single register operand from an
2246/// existing instruction to the one being built and indicate that only a
2247/// subregister should be copied.
2248class CopySubRegRenderer : public OperandRenderer {
2249protected:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002250 unsigned NewInsnID;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002251 /// The name of the operand.
2252 const StringRef SymbolicName;
2253 /// The subregister to extract.
2254 const CodeGenSubRegIndex *SubReg;
2255
2256public:
Daniel Sandersbd83ad42017-10-24 01:48:34 +00002257 CopySubRegRenderer(unsigned NewInsnID, StringRef SymbolicName,
2258 const CodeGenSubRegIndex *SubReg)
2259 : OperandRenderer(OR_CopySubReg), NewInsnID(NewInsnID),
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002260 SymbolicName(SymbolicName), SubReg(SubReg) {}
2261
2262 static bool classof(const OperandRenderer *R) {
2263 return R->getKind() == OR_CopySubReg;
2264 }
2265
2266 const StringRef getSymbolicName() const { return SymbolicName; }
2267
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002268 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002269 const OperandMatcher &Operand = Rule.getOperandMatcher(SymbolicName);
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002270 unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002271 Table << MatchTable::Opcode("GIR_CopySubReg")
2272 << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
2273 << MatchTable::Comment("OldInsnID")
2274 << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002275 << MatchTable::IntValue(Operand.getOpIdx())
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002276 << MatchTable::Comment("SubRegIdx")
2277 << MatchTable::IntValue(SubReg->EnumValue)
2278 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002279 }
2280};
2281
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002282/// Adds a specific physical register to the instruction being built.
2283/// This is typically useful for WZR/XZR on AArch64.
2284class AddRegisterRenderer : public OperandRenderer {
2285protected:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002286 unsigned InsnID;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002287 const Record *RegisterDef;
2288
2289public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002290 AddRegisterRenderer(unsigned InsnID, const Record *RegisterDef)
2291 : OperandRenderer(OR_Register), InsnID(InsnID), RegisterDef(RegisterDef) {
2292 }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002293
2294 static bool classof(const OperandRenderer *R) {
2295 return R->getKind() == OR_Register;
2296 }
2297
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002298 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2299 Table << MatchTable::Opcode("GIR_AddRegister")
2300 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2301 << MatchTable::NamedValue(
2302 (RegisterDef->getValue("Namespace")
2303 ? RegisterDef->getValueAsString("Namespace")
2304 : ""),
2305 RegisterDef->getName())
2306 << MatchTable::LineBreak;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002307 }
2308};
2309
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002310/// Adds a specific temporary virtual register to the instruction being built.
2311/// This is used to chain instructions together when emitting multiple
2312/// instructions.
2313class TempRegRenderer : public OperandRenderer {
2314protected:
2315 unsigned InsnID;
2316 unsigned TempRegID;
2317 bool IsDef;
2318
2319public:
2320 TempRegRenderer(unsigned InsnID, unsigned TempRegID, bool IsDef = false)
2321 : OperandRenderer(OR_Register), InsnID(InsnID), TempRegID(TempRegID),
2322 IsDef(IsDef) {}
2323
2324 static bool classof(const OperandRenderer *R) {
2325 return R->getKind() == OR_TempRegister;
2326 }
2327
2328 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2329 Table << MatchTable::Opcode("GIR_AddTempRegister")
2330 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2331 << MatchTable::Comment("TempRegID") << MatchTable::IntValue(TempRegID)
2332 << MatchTable::Comment("TempRegFlags");
2333 if (IsDef)
2334 Table << MatchTable::NamedValue("RegState::Define");
2335 else
2336 Table << MatchTable::IntValue(0);
2337 Table << MatchTable::LineBreak;
2338 }
2339};
2340
Daniel Sanders0ed28822017-04-12 08:23:08 +00002341/// Adds a specific immediate to the instruction being built.
2342class ImmRenderer : public OperandRenderer {
2343protected:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002344 unsigned InsnID;
Daniel Sanders0ed28822017-04-12 08:23:08 +00002345 int64_t Imm;
2346
2347public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002348 ImmRenderer(unsigned InsnID, int64_t Imm)
2349 : OperandRenderer(OR_Imm), InsnID(InsnID), Imm(Imm) {}
Daniel Sanders0ed28822017-04-12 08:23:08 +00002350
2351 static bool classof(const OperandRenderer *R) {
2352 return R->getKind() == OR_Imm;
2353 }
2354
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002355 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2356 Table << MatchTable::Opcode("GIR_AddImm") << MatchTable::Comment("InsnID")
2357 << MatchTable::IntValue(InsnID) << MatchTable::Comment("Imm")
2358 << MatchTable::IntValue(Imm) << MatchTable::LineBreak;
Daniel Sanders0ed28822017-04-12 08:23:08 +00002359 }
2360};
2361
Daniel Sanders2deea182017-04-22 15:11:04 +00002362/// Adds operands by calling a renderer function supplied by the ComplexPattern
2363/// matcher function.
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002364class RenderComplexPatternOperand : public OperandRenderer {
2365private:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002366 unsigned InsnID;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002367 const Record &TheDef;
Daniel Sanders2deea182017-04-22 15:11:04 +00002368 /// The name of the operand.
2369 const StringRef SymbolicName;
2370 /// The renderer number. This must be unique within a rule since it's used to
2371 /// identify a temporary variable to hold the renderer function.
2372 unsigned RendererID;
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002373 /// When provided, this is the suboperand of the ComplexPattern operand to
2374 /// render. Otherwise all the suboperands will be rendered.
2375 Optional<unsigned> SubOperand;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002376
2377 unsigned getNumOperands() const {
2378 return TheDef.getValueAsDag("Operands")->getNumArgs();
2379 }
2380
2381public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002382 RenderComplexPatternOperand(unsigned InsnID, const Record &TheDef,
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002383 StringRef SymbolicName, unsigned RendererID,
2384 Optional<unsigned> SubOperand = None)
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002385 : OperandRenderer(OR_ComplexPattern), InsnID(InsnID), TheDef(TheDef),
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002386 SymbolicName(SymbolicName), RendererID(RendererID),
2387 SubOperand(SubOperand) {}
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002388
2389 static bool classof(const OperandRenderer *R) {
2390 return R->getKind() == OR_ComplexPattern;
2391 }
2392
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002393 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002394 Table << MatchTable::Opcode(SubOperand.hasValue() ? "GIR_ComplexSubOperandRenderer"
2395 : "GIR_ComplexRenderer")
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002396 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2397 << MatchTable::Comment("RendererID")
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002398 << MatchTable::IntValue(RendererID);
2399 if (SubOperand.hasValue())
2400 Table << MatchTable::Comment("SubOperand")
2401 << MatchTable::IntValue(SubOperand.getValue());
2402 Table << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002403 }
2404};
2405
Volkan Kelesf7f25682018-01-16 18:44:05 +00002406class CustomRenderer : public OperandRenderer {
2407protected:
2408 unsigned InsnID;
2409 const Record &Renderer;
2410 /// The name of the operand.
2411 const std::string SymbolicName;
2412
2413public:
2414 CustomRenderer(unsigned InsnID, const Record &Renderer,
2415 StringRef SymbolicName)
2416 : OperandRenderer(OR_Custom), InsnID(InsnID), Renderer(Renderer),
2417 SymbolicName(SymbolicName) {}
2418
2419 static bool classof(const OperandRenderer *R) {
2420 return R->getKind() == OR_Custom;
2421 }
2422
2423 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002424 InstructionMatcher &InsnMatcher = Rule.getInstructionMatcher(SymbolicName);
Volkan Kelesf7f25682018-01-16 18:44:05 +00002425 unsigned OldInsnVarID = Rule.getInsnVarID(InsnMatcher);
2426 Table << MatchTable::Opcode("GIR_CustomRenderer")
2427 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2428 << MatchTable::Comment("OldInsnID")
2429 << MatchTable::IntValue(OldInsnVarID)
2430 << MatchTable::Comment("Renderer")
2431 << MatchTable::NamedValue(
2432 "GICR_" + Renderer.getValueAsString("RendererFn").str())
2433 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2434 }
2435};
2436
Ahmed Bougacha56ca3a92017-02-04 00:47:10 +00002437/// An action taken when all Matcher predicates succeeded for a parent rule.
2438///
2439/// Typical actions include:
2440/// * Changing the opcode of an instruction.
2441/// * Adding an operand to an instruction.
Daniel Sanders43c882c2017-02-01 10:53:10 +00002442class MatchAction {
2443public:
2444 virtual ~MatchAction() {}
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002445
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002446 /// Emit the MatchTable opcodes to implement the action.
Daniel Sandersa7b75262017-10-31 18:50:24 +00002447 virtual void emitActionOpcodes(MatchTable &Table,
2448 RuleMatcher &Rule) const = 0;
Daniel Sanders43c882c2017-02-01 10:53:10 +00002449};
2450
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +00002451/// Generates a comment describing the matched rule being acted upon.
2452class DebugCommentAction : public MatchAction {
2453private:
Daniel Sanders6ea17ed2017-10-31 18:07:03 +00002454 std::string S;
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +00002455
2456public:
Daniel Sanders6ea17ed2017-10-31 18:07:03 +00002457 DebugCommentAction(StringRef S) : S(S) {}
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +00002458
Daniel Sandersa7b75262017-10-31 18:50:24 +00002459 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sanders6ea17ed2017-10-31 18:07:03 +00002460 Table << MatchTable::Comment(S) << MatchTable::LineBreak;
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +00002461 }
2462};
2463
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002464/// Generates code to build an instruction or mutate an existing instruction
2465/// into the desired instruction when this is possible.
2466class BuildMIAction : public MatchAction {
Daniel Sanders43c882c2017-02-01 10:53:10 +00002467private:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002468 unsigned InsnID;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002469 const CodeGenInstruction *I;
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002470 InstructionMatcher *Matched;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002471 std::vector<std::unique_ptr<OperandRenderer>> OperandRenderers;
2472
2473 /// True if the instruction can be built solely by mutating the opcode.
Daniel Sandersa7b75262017-10-31 18:50:24 +00002474 bool canMutate(RuleMatcher &Rule, const InstructionMatcher *Insn) const {
2475 if (!Insn)
Daniel Sandersab1d1192017-10-24 18:11:54 +00002476 return false;
2477
Daniel Sandersa7b75262017-10-31 18:50:24 +00002478 if (OperandRenderers.size() != Insn->getNumOperands())
Daniel Sanderse9fdba32017-04-29 17:30:09 +00002479 return false;
2480
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002481 for (const auto &Renderer : enumerate(OperandRenderers)) {
Zachary Turner309a0882017-03-13 16:24:10 +00002482 if (const auto *Copy = dyn_cast<CopyRenderer>(&*Renderer.value())) {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002483 const OperandMatcher &OM = Rule.getOperandMatcher(Copy->getSymbolicName());
Daniel Sandersa7b75262017-10-31 18:50:24 +00002484 if (Insn != &OM.getInstructionMatcher() ||
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002485 OM.getOpIdx() != Renderer.index())
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002486 return false;
2487 } else
2488 return false;
2489 }
2490
2491 return true;
2492 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002493
Daniel Sanders43c882c2017-02-01 10:53:10 +00002494public:
Daniel Sandersa7b75262017-10-31 18:50:24 +00002495 BuildMIAction(unsigned InsnID, const CodeGenInstruction *I)
2496 : InsnID(InsnID), I(I), Matched(nullptr) {}
2497
Daniel Sanders08464522018-01-29 21:09:12 +00002498 unsigned getInsnID() const { return InsnID; }
Daniel Sandersdf258e32017-10-31 19:09:29 +00002499 const CodeGenInstruction *getCGI() const { return I; }
2500
Daniel Sandersa7b75262017-10-31 18:50:24 +00002501 void chooseInsnToMutate(RuleMatcher &Rule) {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002502 for (auto *MutateCandidate : Rule.mutatable_insns()) {
Daniel Sandersa7b75262017-10-31 18:50:24 +00002503 if (canMutate(Rule, MutateCandidate)) {
2504 // Take the first one we're offered that we're able to mutate.
2505 Rule.reserveInsnMatcherForMutation(MutateCandidate);
2506 Matched = MutateCandidate;
2507 return;
2508 }
2509 }
2510 }
Daniel Sanders43c882c2017-02-01 10:53:10 +00002511
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002512 template <class Kind, class... Args>
2513 Kind &addRenderer(Args&&... args) {
2514 OperandRenderers.emplace_back(
Daniel Sanders198447a2017-11-01 00:29:47 +00002515 llvm::make_unique<Kind>(InsnID, std::forward<Args>(args)...));
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002516 return *static_cast<Kind *>(OperandRenderers.back().get());
2517 }
2518
Daniel Sandersa7b75262017-10-31 18:50:24 +00002519 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2520 if (Matched) {
2521 assert(canMutate(Rule, Matched) &&
2522 "Arranged to mutate an insn that isn't mutatable");
2523
2524 unsigned RecycleInsnID = Rule.getInsnVarID(*Matched);
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002525 Table << MatchTable::Opcode("GIR_MutateOpcode")
2526 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2527 << MatchTable::Comment("RecycleInsnID")
2528 << MatchTable::IntValue(RecycleInsnID)
2529 << MatchTable::Comment("Opcode")
2530 << MatchTable::NamedValue(I->Namespace, I->TheDef->getName())
2531 << MatchTable::LineBreak;
Tim Northover4340d642017-03-20 21:58:23 +00002532
2533 if (!I->ImplicitDefs.empty() || !I->ImplicitUses.empty()) {
Tim Northover4340d642017-03-20 21:58:23 +00002534 for (auto Def : I->ImplicitDefs) {
Diana Picus8abcbbb2017-05-02 09:40:49 +00002535 auto Namespace = Def->getValue("Namespace")
2536 ? Def->getValueAsString("Namespace")
2537 : "";
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002538 Table << MatchTable::Opcode("GIR_AddImplicitDef")
2539 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2540 << MatchTable::NamedValue(Namespace, Def->getName())
2541 << MatchTable::LineBreak;
Tim Northover4340d642017-03-20 21:58:23 +00002542 }
2543 for (auto Use : I->ImplicitUses) {
Diana Picus8abcbbb2017-05-02 09:40:49 +00002544 auto Namespace = Use->getValue("Namespace")
2545 ? Use->getValueAsString("Namespace")
2546 : "";
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002547 Table << MatchTable::Opcode("GIR_AddImplicitUse")
2548 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2549 << MatchTable::NamedValue(Namespace, Use->getName())
2550 << MatchTable::LineBreak;
Tim Northover4340d642017-03-20 21:58:23 +00002551 }
2552 }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002553 return;
2554 }
2555
2556 // TODO: Simple permutation looks like it could be almost as common as
2557 // mutation due to commutative operations.
2558
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002559 Table << MatchTable::Opcode("GIR_BuildMI") << MatchTable::Comment("InsnID")
2560 << MatchTable::IntValue(InsnID) << MatchTable::Comment("Opcode")
2561 << MatchTable::NamedValue(I->Namespace, I->TheDef->getName())
2562 << MatchTable::LineBreak;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002563 for (const auto &Renderer : OperandRenderers)
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002564 Renderer->emitRenderOpcodes(Table, Rule);
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002565
Florian Hahn3bc3ec62017-08-03 14:48:22 +00002566 if (I->mayLoad || I->mayStore) {
2567 Table << MatchTable::Opcode("GIR_MergeMemOperands")
2568 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2569 << MatchTable::Comment("MergeInsnID's");
2570 // Emit the ID's for all the instructions that are matched by this rule.
2571 // TODO: Limit this to matched instructions that mayLoad/mayStore or have
2572 // some other means of having a memoperand. Also limit this to
2573 // emitted instructions that expect to have a memoperand too. For
2574 // example, (G_SEXT (G_LOAD x)) that results in separate load and
2575 // sign-extend instructions shouldn't put the memoperand on the
2576 // sign-extend since it has no effect there.
2577 std::vector<unsigned> MergeInsnIDs;
2578 for (const auto &IDMatcherPair : Rule.defined_insn_vars())
2579 MergeInsnIDs.push_back(IDMatcherPair.second);
Mandeep Singh Grang1b0e2f22018-04-06 20:18:05 +00002580 llvm::sort(MergeInsnIDs.begin(), MergeInsnIDs.end());
Florian Hahn3bc3ec62017-08-03 14:48:22 +00002581 for (const auto &MergeInsnID : MergeInsnIDs)
2582 Table << MatchTable::IntValue(MergeInsnID);
Daniel Sanders05540042017-08-08 10:44:31 +00002583 Table << MatchTable::NamedValue("GIU_MergeMemOperands_EndOfList")
2584 << MatchTable::LineBreak;
Florian Hahn3bc3ec62017-08-03 14:48:22 +00002585 }
2586
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002587 // FIXME: This is a hack but it's sufficient for ISel. We'll need to do
2588 // better for combines. Particularly when there are multiple match
2589 // roots.
2590 if (InsnID == 0)
2591 Table << MatchTable::Opcode("GIR_EraseFromParent")
2592 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2593 << MatchTable::LineBreak;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002594 }
2595};
2596
2597/// Generates code to constrain the operands of an output instruction to the
2598/// register classes specified by the definition of that instruction.
2599class ConstrainOperandsToDefinitionAction : public MatchAction {
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002600 unsigned InsnID;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002601
2602public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002603 ConstrainOperandsToDefinitionAction(unsigned InsnID) : InsnID(InsnID) {}
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002604
Daniel Sandersa7b75262017-10-31 18:50:24 +00002605 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002606 Table << MatchTable::Opcode("GIR_ConstrainSelectedInstOperands")
2607 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2608 << MatchTable::LineBreak;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002609 }
2610};
2611
2612/// Generates code to constrain the specified operand of an output instruction
2613/// to the specified register class.
2614class ConstrainOperandToRegClassAction : public MatchAction {
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002615 unsigned InsnID;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002616 unsigned OpIdx;
2617 const CodeGenRegisterClass &RC;
2618
2619public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002620 ConstrainOperandToRegClassAction(unsigned InsnID, unsigned OpIdx,
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002621 const CodeGenRegisterClass &RC)
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002622 : InsnID(InsnID), OpIdx(OpIdx), RC(RC) {}
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002623
Daniel Sandersa7b75262017-10-31 18:50:24 +00002624 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002625 Table << MatchTable::Opcode("GIR_ConstrainOperandRC")
2626 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2627 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
2628 << MatchTable::Comment("RC " + RC.getName())
2629 << MatchTable::IntValue(RC.EnumValue) << MatchTable::LineBreak;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002630 }
2631};
2632
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002633/// Generates code to create a temporary register which can be used to chain
2634/// instructions together.
2635class MakeTempRegisterAction : public MatchAction {
2636private:
2637 LLTCodeGen Ty;
2638 unsigned TempRegID;
2639
2640public:
2641 MakeTempRegisterAction(const LLTCodeGen &Ty, unsigned TempRegID)
2642 : Ty(Ty), TempRegID(TempRegID) {}
2643
2644 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2645 Table << MatchTable::Opcode("GIR_MakeTempReg")
2646 << MatchTable::Comment("TempRegID") << MatchTable::IntValue(TempRegID)
2647 << MatchTable::Comment("TypeID")
2648 << MatchTable::NamedValue(Ty.getCxxEnumValue())
2649 << MatchTable::LineBreak;
2650 }
2651};
2652
Daniel Sanders05540042017-08-08 10:44:31 +00002653InstructionMatcher &RuleMatcher::addInstructionMatcher(StringRef SymbolicName) {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002654 Matchers.emplace_back(new InstructionMatcher(*this, SymbolicName));
Daniel Sandersa7b75262017-10-31 18:50:24 +00002655 MutatableInsns.insert(Matchers.back().get());
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002656 return *Matchers.back();
2657}
Ahmed Bougacha56ca3a92017-02-04 00:47:10 +00002658
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002659void RuleMatcher::addRequiredFeature(Record *Feature) {
2660 RequiredFeatures.push_back(Feature);
2661}
2662
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002663const std::vector<Record *> &RuleMatcher::getRequiredFeatures() const {
2664 return RequiredFeatures;
2665}
2666
Daniel Sanders7438b262017-10-31 23:03:18 +00002667// Emplaces an action of the specified Kind at the end of the action list.
2668//
2669// Returns a reference to the newly created action.
2670//
2671// Like std::vector::emplace_back(), may invalidate all iterators if the new
2672// size exceeds the capacity. Otherwise, only invalidates the past-the-end
2673// iterator.
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002674template <class Kind, class... Args>
2675Kind &RuleMatcher::addAction(Args &&... args) {
2676 Actions.emplace_back(llvm::make_unique<Kind>(std::forward<Args>(args)...));
2677 return *static_cast<Kind *>(Actions.back().get());
2678}
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002679
Daniel Sanders7438b262017-10-31 23:03:18 +00002680// Emplaces an action of the specified Kind before the given insertion point.
2681//
2682// Returns an iterator pointing at the newly created instruction.
2683//
2684// Like std::vector::insert(), may invalidate all iterators if the new size
2685// exceeds the capacity. Otherwise, only invalidates the iterators from the
2686// insertion point onwards.
2687template <class Kind, class... Args>
2688action_iterator RuleMatcher::insertAction(action_iterator InsertPt,
2689 Args &&... args) {
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002690 return Actions.emplace(InsertPt,
2691 llvm::make_unique<Kind>(std::forward<Args>(args)...));
Daniel Sanders7438b262017-10-31 23:03:18 +00002692}
Daniel Sandersdc662ff2017-01-26 11:10:14 +00002693
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002694unsigned RuleMatcher::implicitlyDefineInsnVar(InstructionMatcher &Matcher) {
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002695 unsigned NewInsnVarID = NextInsnVarID++;
2696 InsnVariableIDs[&Matcher] = NewInsnVarID;
2697 return NewInsnVarID;
Daniel Sandersb96f40d2017-03-20 15:20:42 +00002698}
2699
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002700unsigned RuleMatcher::getInsnVarID(InstructionMatcher &InsnMatcher) const {
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002701 const auto &I = InsnVariableIDs.find(&InsnMatcher);
2702 if (I != InsnVariableIDs.end())
Daniel Sandersb96f40d2017-03-20 15:20:42 +00002703 return I->second;
2704 llvm_unreachable("Matched Insn was not captured in a local variable");
2705}
2706
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002707void RuleMatcher::defineOperand(StringRef SymbolicName, OperandMatcher &OM) {
2708 if (DefinedOperands.find(SymbolicName) == DefinedOperands.end()) {
2709 DefinedOperands[SymbolicName] = &OM;
2710 return;
2711 }
2712
2713 // If the operand is already defined, then we must ensure both references in
2714 // the matcher have the exact same node.
2715 OM.addPredicate<SameOperandMatcher>(OM.getSymbolicName());
2716}
2717
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002718InstructionMatcher &
Daniel Sanders05540042017-08-08 10:44:31 +00002719RuleMatcher::getInstructionMatcher(StringRef SymbolicName) const {
2720 for (const auto &I : InsnVariableIDs)
2721 if (I.first->getSymbolicName() == SymbolicName)
2722 return *I.first;
2723 llvm_unreachable(
2724 ("Failed to lookup instruction " + SymbolicName).str().c_str());
2725}
2726
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002727const OperandMatcher &
2728RuleMatcher::getOperandMatcher(StringRef Name) const {
2729 const auto &I = DefinedOperands.find(Name);
2730
2731 if (I == DefinedOperands.end())
2732 PrintFatalError(SrcLoc, "Operand " + Name + " was not declared in matcher");
2733
2734 return *I->second;
2735}
2736
Daniel Sanders8e82af22017-07-27 11:03:45 +00002737void RuleMatcher::emit(MatchTable &Table) {
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002738 if (Matchers.empty())
2739 llvm_unreachable("Unexpected empty matcher!");
Daniel Sandersdc662ff2017-01-26 11:10:14 +00002740
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002741 // The representation supports rules that require multiple roots such as:
2742 // %ptr(p0) = ...
2743 // %elt0(s32) = G_LOAD %ptr
2744 // %1(p0) = G_ADD %ptr, 4
2745 // %elt1(s32) = G_LOAD p0 %1
2746 // which could be usefully folded into:
2747 // %ptr(p0) = ...
2748 // %elt0(s32), %elt1(s32) = TGT_LOAD_PAIR %ptr
2749 // on some targets but we don't need to make use of that yet.
2750 assert(Matchers.size() == 1 && "Cannot handle multi-root matchers yet");
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002751
Daniel Sanders8e82af22017-07-27 11:03:45 +00002752 unsigned LabelID = Table.allocateLabelID();
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002753 Table << MatchTable::Opcode("GIM_Try", +1)
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002754 << MatchTable::Comment("On fail goto")
2755 << MatchTable::JumpTarget(LabelID)
2756 << MatchTable::Comment(("Rule ID " + Twine(RuleID) + " //").str())
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002757 << MatchTable::LineBreak;
2758
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002759 if (!RequiredFeatures.empty()) {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002760 Table << MatchTable::Opcode("GIM_CheckFeatures")
2761 << MatchTable::NamedValue(getNameForFeatureBitset(RequiredFeatures))
2762 << MatchTable::LineBreak;
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002763 }
Daniel Sandersb96f40d2017-03-20 15:20:42 +00002764
Quentin Colombetaad20be2017-12-15 23:07:42 +00002765 Matchers.front()->emitPredicateOpcodes(Table, *this);
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002766
Daniel Sandersbee57392017-04-04 13:25:23 +00002767 // We must also check if it's safe to fold the matched instructions.
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002768 if (InsnVariableIDs.size() >= 2) {
Galina Kistanova1754fee2017-05-25 01:51:53 +00002769 // Invert the map to create stable ordering (by var names)
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002770 SmallVector<unsigned, 2> InsnIDs;
2771 for (const auto &Pair : InsnVariableIDs) {
Daniel Sandersbee57392017-04-04 13:25:23 +00002772 // Skip the root node since it isn't moving anywhere. Everything else is
2773 // sinking to meet it.
2774 if (Pair.first == Matchers.front().get())
2775 continue;
2776
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002777 InsnIDs.push_back(Pair.second);
Galina Kistanova1754fee2017-05-25 01:51:53 +00002778 }
Mandeep Singh Grang1b0e2f22018-04-06 20:18:05 +00002779 llvm::sort(InsnIDs.begin(), InsnIDs.end());
Galina Kistanova1754fee2017-05-25 01:51:53 +00002780
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002781 for (const auto &InsnID : InsnIDs) {
Daniel Sandersbee57392017-04-04 13:25:23 +00002782 // Reject the difficult cases until we have a more accurate check.
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002783 Table << MatchTable::Opcode("GIM_CheckIsSafeToFold")
2784 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2785 << MatchTable::LineBreak;
Daniel Sandersbee57392017-04-04 13:25:23 +00002786
2787 // FIXME: Emit checks to determine it's _actually_ safe to fold and/or
2788 // account for unsafe cases.
2789 //
2790 // Example:
2791 // MI1--> %0 = ...
2792 // %1 = ... %0
2793 // MI0--> %2 = ... %0
2794 // It's not safe to erase MI1. We currently handle this by not
2795 // erasing %0 (even when it's dead).
2796 //
2797 // Example:
2798 // MI1--> %0 = load volatile @a
2799 // %1 = load volatile @a
2800 // MI0--> %2 = ... %0
2801 // It's not safe to sink %0's def past %1. We currently handle
2802 // this by rejecting all loads.
2803 //
2804 // Example:
2805 // MI1--> %0 = load @a
2806 // %1 = store @a
2807 // MI0--> %2 = ... %0
2808 // It's not safe to sink %0's def past %1. We currently handle
2809 // this by rejecting all loads.
2810 //
2811 // Example:
2812 // G_CONDBR %cond, @BB1
2813 // BB0:
2814 // MI1--> %0 = load @a
2815 // G_BR @BB1
2816 // BB1:
2817 // MI0--> %2 = ... %0
2818 // It's not always safe to sink %0 across control flow. In this
2819 // case it may introduce a memory fault. We currentl handle this
2820 // by rejecting all loads.
2821 }
2822 }
2823
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002824 for (const auto &PM : EpilogueMatchers)
2825 PM->emitPredicateOpcodes(Table, *this);
2826
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002827 for (const auto &MA : Actions)
Daniel Sandersa7b75262017-10-31 18:50:24 +00002828 MA->emitActionOpcodes(Table, *this);
Daniel Sandersf76f3152017-11-16 00:46:35 +00002829
Roman Tereshinbeb39312018-05-02 20:15:11 +00002830 if (Table.isWithCoverage())
Daniel Sandersf76f3152017-11-16 00:46:35 +00002831 Table << MatchTable::Opcode("GIR_Coverage") << MatchTable::IntValue(RuleID)
2832 << MatchTable::LineBreak;
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002833 else
2834 Table << MatchTable::Comment(("GIR_Coverage, " + Twine(RuleID) + ",").str())
2835 << MatchTable::LineBreak;
Daniel Sandersf76f3152017-11-16 00:46:35 +00002836
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002837 Table << MatchTable::Opcode("GIR_Done", -1) << MatchTable::LineBreak
Daniel Sanders8e82af22017-07-27 11:03:45 +00002838 << MatchTable::Label(LabelID);
Volkan Keles4f3fa792018-01-25 00:18:52 +00002839 ++NumPatternEmitted;
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002840}
Daniel Sanders43c882c2017-02-01 10:53:10 +00002841
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002842bool RuleMatcher::isHigherPriorityThan(const RuleMatcher &B) const {
2843 // Rules involving more match roots have higher priority.
2844 if (Matchers.size() > B.Matchers.size())
2845 return true;
2846 if (Matchers.size() < B.Matchers.size())
Daniel Sanders759ff412017-02-24 13:58:11 +00002847 return false;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002848
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002849 for (const auto &Matcher : zip(Matchers, B.Matchers)) {
2850 if (std::get<0>(Matcher)->isHigherPriorityThan(*std::get<1>(Matcher)))
2851 return true;
2852 if (std::get<1>(Matcher)->isHigherPriorityThan(*std::get<0>(Matcher)))
2853 return false;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002854 }
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002855
2856 return false;
Simon Pilgrima7d1da82017-03-15 22:50:47 +00002857}
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002858
Daniel Sanders2deea182017-04-22 15:11:04 +00002859unsigned RuleMatcher::countRendererFns() const {
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002860 return std::accumulate(
2861 Matchers.begin(), Matchers.end(), 0,
2862 [](unsigned A, const std::unique_ptr<InstructionMatcher> &Matcher) {
Daniel Sanders2deea182017-04-22 15:11:04 +00002863 return A + Matcher->countRendererFns();
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002864 });
2865}
2866
Daniel Sanders05540042017-08-08 10:44:31 +00002867bool OperandPredicateMatcher::isHigherPriorityThan(
2868 const OperandPredicateMatcher &B) const {
2869 // Generally speaking, an instruction is more important than an Int or a
2870 // LiteralInt because it can cover more nodes but theres an exception to
2871 // this. G_CONSTANT's are less important than either of those two because they
2872 // are more permissive.
Daniel Sandersedd07842017-08-17 09:26:14 +00002873
2874 const InstructionOperandMatcher *AOM =
2875 dyn_cast<InstructionOperandMatcher>(this);
2876 const InstructionOperandMatcher *BOM =
2877 dyn_cast<InstructionOperandMatcher>(&B);
2878 bool AIsConstantInsn = AOM && AOM->getInsnMatcher().isConstantInstruction();
2879 bool BIsConstantInsn = BOM && BOM->getInsnMatcher().isConstantInstruction();
2880
2881 if (AOM && BOM) {
2882 // The relative priorities between a G_CONSTANT and any other instruction
2883 // don't actually matter but this code is needed to ensure a strict weak
2884 // ordering. This is particularly important on Windows where the rules will
2885 // be incorrectly sorted without it.
2886 if (AIsConstantInsn != BIsConstantInsn)
2887 return AIsConstantInsn < BIsConstantInsn;
2888 return false;
Daniel Sanders05540042017-08-08 10:44:31 +00002889 }
Daniel Sandersedd07842017-08-17 09:26:14 +00002890
2891 if (AOM && AIsConstantInsn && (B.Kind == OPM_Int || B.Kind == OPM_LiteralInt))
2892 return false;
2893 if (BOM && BIsConstantInsn && (Kind == OPM_Int || Kind == OPM_LiteralInt))
2894 return true;
Daniel Sanders05540042017-08-08 10:44:31 +00002895
2896 return Kind < B.Kind;
Daniel Sanders75b84fc2017-08-08 13:21:26 +00002897}
Daniel Sanders05540042017-08-08 10:44:31 +00002898
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002899void SameOperandMatcher::emitPredicateOpcodes(MatchTable &Table,
Quentin Colombetaad20be2017-12-15 23:07:42 +00002900 RuleMatcher &Rule) const {
Daniel Sanders1e4569f2017-10-20 20:55:29 +00002901 const OperandMatcher &OtherOM = Rule.getOperandMatcher(MatchingName);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002902 unsigned OtherInsnVarID = Rule.getInsnVarID(OtherOM.getInstructionMatcher());
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002903 assert(OtherInsnVarID == OtherOM.getInstructionMatcher().getInsnVarID());
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002904
2905 Table << MatchTable::Opcode("GIM_CheckIsSameOperand")
2906 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
2907 << MatchTable::Comment("OpIdx") << MatchTable::IntValue(OpIdx)
2908 << MatchTable::Comment("OtherMI")
2909 << MatchTable::IntValue(OtherInsnVarID)
2910 << MatchTable::Comment("OtherOpIdx")
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002911 << MatchTable::IntValue(OtherOM.getOpIdx())
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002912 << MatchTable::LineBreak;
2913}
2914
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002915//===- GlobalISelEmitter class --------------------------------------------===//
2916
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002917class GlobalISelEmitter {
2918public:
2919 explicit GlobalISelEmitter(RecordKeeper &RK);
2920 void run(raw_ostream &OS);
2921
2922private:
2923 const RecordKeeper &RK;
2924 const CodeGenDAGPatterns CGP;
2925 const CodeGenTarget &Target;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002926 CodeGenRegBank CGRegs;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002927
Daniel Sanders39690bd2017-10-15 02:41:12 +00002928 /// Keep track of the equivalence between SDNodes and Instruction by mapping
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00002929 /// SDNodes to the GINodeEquiv mapping. We need to map to the GINodeEquiv to
2930 /// check for attributes on the relation such as CheckMMOIsNonAtomic.
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002931 /// This is defined using 'GINodeEquiv' in the target description.
Daniel Sanders39690bd2017-10-15 02:41:12 +00002932 DenseMap<Record *, Record *> NodeEquivs;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002933
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002934 /// Keep track of the equivalence between ComplexPattern's and
2935 /// GIComplexOperandMatcher. Map entries are specified by subclassing
2936 /// GIComplexPatternEquiv.
2937 DenseMap<const Record *, const Record *> ComplexPatternEquivs;
2938
Volkan Kelesf7f25682018-01-16 18:44:05 +00002939 /// Keep track of the equivalence between SDNodeXForm's and
2940 /// GICustomOperandRenderer. Map entries are specified by subclassing
2941 /// GISDNodeXFormEquiv.
2942 DenseMap<const Record *, const Record *> SDNodeXFormEquivs;
2943
Aditya Nandakumarb63e7632018-02-16 22:37:15 +00002944 /// Keep track of Scores of PatternsToMatch similar to how the DAG does.
2945 /// This adds compatibility for RuleMatchers to use this for ordering rules.
2946 DenseMap<uint64_t, int> RuleMatcherScores;
2947
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002948 // Map of predicates to their subtarget features.
Daniel Sanderse9fdba32017-04-29 17:30:09 +00002949 SubtargetFeatureInfoMap SubtargetFeatures;
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002950
Daniel Sandersf76f3152017-11-16 00:46:35 +00002951 // Rule coverage information.
2952 Optional<CodeGenCoverage> RuleCoverage;
2953
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002954 void gatherOpcodeValues();
2955 void gatherTypeIDValues();
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002956 void gatherNodeEquivs();
Daniel Sanders39690bd2017-10-15 02:41:12 +00002957 Record *findNodeEquiv(Record *N) const;
Daniel Sandersf84bc372018-05-05 20:53:24 +00002958 const CodeGenInstruction *getEquivNode(Record &Equiv,
2959 const TreePatternNode *N) const;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002960
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002961 Error importRulePredicates(RuleMatcher &M, ArrayRef<Predicate> Predicates);
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002962 Expected<InstructionMatcher &> createAndImportSelDAGMatcher(
2963 RuleMatcher &Rule, InstructionMatcher &InsnMatcher,
2964 const TreePatternNode *Src, unsigned &TempOpIdx) const;
2965 Error importComplexPatternOperandMatcher(OperandMatcher &OM, Record *R,
2966 unsigned &TempOpIdx) const;
2967 Error importChildMatcher(RuleMatcher &Rule, InstructionMatcher &InsnMatcher,
Daniel Sandersa71f4542017-10-16 00:56:30 +00002968 const TreePatternNode *SrcChild,
2969 bool OperandIsAPointer, unsigned OpIdx,
Daniel Sandersc270c502017-03-30 09:36:33 +00002970 unsigned &TempOpIdx) const;
Daniel Sandersdf258e32017-10-31 19:09:29 +00002971
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002972 Expected<BuildMIAction &>
Daniel Sandersa7b75262017-10-31 18:50:24 +00002973 createAndImportInstructionRenderer(RuleMatcher &M,
2974 const TreePatternNode *Dst);
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002975 Expected<action_iterator> createAndImportSubInstructionRenderer(
2976 action_iterator InsertPt, RuleMatcher &M, const TreePatternNode *Dst,
2977 unsigned TempReg);
Daniel Sanders7438b262017-10-31 23:03:18 +00002978 Expected<action_iterator>
2979 createInstructionRenderer(action_iterator InsertPt, RuleMatcher &M,
2980 const TreePatternNode *Dst);
Daniel Sandersdf258e32017-10-31 19:09:29 +00002981 void importExplicitDefRenderers(BuildMIAction &DstMIBuilder);
Daniel Sanders7438b262017-10-31 23:03:18 +00002982 Expected<action_iterator>
2983 importExplicitUseRenderers(action_iterator InsertPt, RuleMatcher &M,
2984 BuildMIAction &DstMIBuilder,
Daniel Sandersdf258e32017-10-31 19:09:29 +00002985 const llvm::TreePatternNode *Dst);
Daniel Sanders7438b262017-10-31 23:03:18 +00002986 Expected<action_iterator>
2987 importExplicitUseRenderer(action_iterator InsertPt, RuleMatcher &Rule,
2988 BuildMIAction &DstMIBuilder,
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002989 TreePatternNode *DstChild);
Diana Picus382602f2017-05-17 08:57:28 +00002990 Error importDefaultOperandRenderers(BuildMIAction &DstMIBuilder,
2991 DagInit *DefaultOps) const;
Daniel Sandersc270c502017-03-30 09:36:33 +00002992 Error
Daniel Sandersffc7d582017-03-29 15:37:18 +00002993 importImplicitDefRenderers(BuildMIAction &DstMIBuilder,
2994 const std::vector<Record *> &ImplicitDefs) const;
2995
Daniel Sanders11300ce2017-10-13 21:28:03 +00002996 void emitImmPredicates(raw_ostream &OS, StringRef TypeIdentifier,
2997 StringRef Type,
Daniel Sanders649c5852017-10-13 20:42:18 +00002998 std::function<bool(const Record *R)> Filter);
2999
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003000 /// Analyze pattern \p P, returning a matcher for it if possible.
3001 /// Otherwise, return an Error explaining why we don't support it.
3002 Expected<RuleMatcher> runOnPattern(const PatternToMatch &P);
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003003
3004 void declareSubtargetFeature(Record *Predicate);
Daniel Sanders7e523672017-11-11 03:23:44 +00003005
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003006 MatchTable buildMatchTable(MutableArrayRef<RuleMatcher> Rules, bool Optimize,
3007 bool WithCoverage);
3008
3009public:
Quentin Colombetec76d9c2017-12-18 19:47:41 +00003010 /// Takes a sequence of \p Rules and group them based on the predicates
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003011 /// they share. \p MatcherStorage is used as a memory container
Hiroshi Inoue501931b2018-01-24 05:04:35 +00003012 /// for the group that are created as part of this process.
Quentin Colombetec76d9c2017-12-18 19:47:41 +00003013 ///
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003014 /// What this optimization does looks like if GroupT = GroupMatcher:
Quentin Colombetec76d9c2017-12-18 19:47:41 +00003015 /// Output without optimization:
3016 /// \verbatim
3017 /// # R1
3018 /// # predicate A
3019 /// # predicate B
3020 /// ...
3021 /// # R2
3022 /// # predicate A // <-- effectively this is going to be checked twice.
3023 /// // Once in R1 and once in R2.
3024 /// # predicate C
3025 /// \endverbatim
3026 /// Output with optimization:
3027 /// \verbatim
3028 /// # Group1_2
3029 /// # predicate A // <-- Check is now shared.
3030 /// # R1
3031 /// # predicate B
3032 /// # R2
3033 /// # predicate C
3034 /// \endverbatim
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003035 template <class GroupT>
3036 static std::vector<Matcher *> optimizeRules(
Roman Tereshin2d6d3762018-05-02 20:08:14 +00003037 ArrayRef<Matcher *> Rules,
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003038 std::vector<std::unique_ptr<Matcher>> &MatcherStorage);
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003039};
3040
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003041void GlobalISelEmitter::gatherOpcodeValues() {
3042 InstructionOpcodeMatcher::initOpcodeValuesMap(Target);
3043}
3044
3045void GlobalISelEmitter::gatherTypeIDValues() {
3046 LLTOperandMatcher::initTypeIDValuesMap();
3047}
3048
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003049void GlobalISelEmitter::gatherNodeEquivs() {
3050 assert(NodeEquivs.empty());
3051 for (Record *Equiv : RK.getAllDerivedDefinitions("GINodeEquiv"))
Daniel Sanders39690bd2017-10-15 02:41:12 +00003052 NodeEquivs[Equiv->getValueAsDef("Node")] = Equiv;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00003053
3054 assert(ComplexPatternEquivs.empty());
3055 for (Record *Equiv : RK.getAllDerivedDefinitions("GIComplexPatternEquiv")) {
3056 Record *SelDAGEquiv = Equiv->getValueAsDef("SelDAGEquivalent");
3057 if (!SelDAGEquiv)
3058 continue;
3059 ComplexPatternEquivs[SelDAGEquiv] = Equiv;
3060 }
Volkan Kelesf7f25682018-01-16 18:44:05 +00003061
3062 assert(SDNodeXFormEquivs.empty());
3063 for (Record *Equiv : RK.getAllDerivedDefinitions("GISDNodeXFormEquiv")) {
3064 Record *SelDAGEquiv = Equiv->getValueAsDef("SelDAGEquivalent");
3065 if (!SelDAGEquiv)
3066 continue;
3067 SDNodeXFormEquivs[SelDAGEquiv] = Equiv;
3068 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003069}
3070
Daniel Sanders39690bd2017-10-15 02:41:12 +00003071Record *GlobalISelEmitter::findNodeEquiv(Record *N) const {
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003072 return NodeEquivs.lookup(N);
3073}
3074
Daniel Sandersf84bc372018-05-05 20:53:24 +00003075const CodeGenInstruction *
3076GlobalISelEmitter::getEquivNode(Record &Equiv, const TreePatternNode *N) const {
3077 for (const auto &Predicate : N->getPredicateFns()) {
3078 if (!Equiv.isValueUnset("IfSignExtend") && Predicate.isLoad() &&
3079 Predicate.isSignExtLoad())
3080 return &Target.getInstruction(Equiv.getValueAsDef("IfSignExtend"));
3081 if (!Equiv.isValueUnset("IfZeroExtend") && Predicate.isLoad() &&
3082 Predicate.isZeroExtLoad())
3083 return &Target.getInstruction(Equiv.getValueAsDef("IfZeroExtend"));
3084 }
3085 return &Target.getInstruction(Equiv.getValueAsDef("I"));
3086}
3087
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003088GlobalISelEmitter::GlobalISelEmitter(RecordKeeper &RK)
Daniel Sandersf84bc372018-05-05 20:53:24 +00003089 : RK(RK), CGP(RK), Target(CGP.getTargetInfo()),
3090 CGRegs(RK, Target.getHwModes()) {}
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003091
3092//===- Emitter ------------------------------------------------------------===//
3093
Daniel Sandersc270c502017-03-30 09:36:33 +00003094Error
Daniel Sandersffc7d582017-03-29 15:37:18 +00003095GlobalISelEmitter::importRulePredicates(RuleMatcher &M,
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003096 ArrayRef<Predicate> Predicates) {
3097 for (const Predicate &P : Predicates) {
3098 if (!P.Def)
3099 continue;
3100 declareSubtargetFeature(P.Def);
3101 M.addRequiredFeature(P.Def);
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003102 }
3103
Daniel Sandersc270c502017-03-30 09:36:33 +00003104 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00003105}
Daniel Sanders8a4bae92017-03-14 21:32:08 +00003106
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003107Expected<InstructionMatcher &> GlobalISelEmitter::createAndImportSelDAGMatcher(
3108 RuleMatcher &Rule, InstructionMatcher &InsnMatcher,
3109 const TreePatternNode *Src, unsigned &TempOpIdx) const {
3110 Record *SrcGIEquivOrNull = nullptr;
3111 const CodeGenInstruction *SrcGIOrNull = nullptr;
3112
3113 // Start with the defined operands (i.e., the results of the root operator).
3114 if (Src->getExtTypes().size() > 1)
3115 return failedImport("Src pattern has multiple results");
3116
3117 if (Src->isLeaf()) {
3118 Init *SrcInit = Src->getLeafValue();
3119 if (isa<IntInit>(SrcInit)) {
3120 InsnMatcher.addPredicate<InstructionOpcodeMatcher>(
3121 &Target.getInstruction(RK.getDef("G_CONSTANT")));
3122 } else
3123 return failedImport(
3124 "Unable to deduce gMIR opcode to handle Src (which is a leaf)");
3125 } else {
3126 SrcGIEquivOrNull = findNodeEquiv(Src->getOperator());
3127 if (!SrcGIEquivOrNull)
3128 return failedImport("Pattern operator lacks an equivalent Instruction" +
3129 explainOperator(Src->getOperator()));
Daniel Sandersf84bc372018-05-05 20:53:24 +00003130 SrcGIOrNull = getEquivNode(*SrcGIEquivOrNull, Src);
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003131
3132 // The operators look good: match the opcode
3133 InsnMatcher.addPredicate<InstructionOpcodeMatcher>(SrcGIOrNull);
3134 }
3135
3136 unsigned OpIdx = 0;
3137 for (const TypeSetByHwMode &VTy : Src->getExtTypes()) {
3138 // Results don't have a name unless they are the root node. The caller will
3139 // set the name if appropriate.
3140 OperandMatcher &OM = InsnMatcher.addOperand(OpIdx++, "", TempOpIdx);
3141 if (auto Error = OM.addTypeCheckPredicate(VTy, false /* OperandIsAPointer */))
3142 return failedImport(toString(std::move(Error)) +
3143 " for result of Src pattern operator");
3144 }
3145
Daniel Sanders2c269f62017-08-24 09:11:20 +00003146 for (const auto &Predicate : Src->getPredicateFns()) {
3147 if (Predicate.isAlwaysTrue())
3148 continue;
3149
3150 if (Predicate.isImmediatePattern()) {
3151 InsnMatcher.addPredicate<InstructionImmPredicateMatcher>(Predicate);
3152 continue;
3153 }
3154
Daniel Sandersf84bc372018-05-05 20:53:24 +00003155 // G_LOAD is used for both non-extending and any-extending loads.
3156 if (Predicate.isLoad() && Predicate.isNonExtLoad()) {
3157 InsnMatcher.addPredicate<MemoryVsLLTSizePredicateMatcher>(
3158 0, MemoryVsLLTSizePredicateMatcher::EqualTo, 0);
3159 continue;
3160 }
3161 if (Predicate.isLoad() && Predicate.isAnyExtLoad()) {
3162 InsnMatcher.addPredicate<MemoryVsLLTSizePredicateMatcher>(
3163 0, MemoryVsLLTSizePredicateMatcher::LessThan, 0);
3164 continue;
3165 }
3166
3167 // No check required. We already did it by swapping the opcode.
3168 if (!SrcGIEquivOrNull->isValueUnset("IfSignExtend") &&
3169 Predicate.isSignExtLoad())
3170 continue;
3171
3172 // No check required. We already did it by swapping the opcode.
3173 if (!SrcGIEquivOrNull->isValueUnset("IfZeroExtend") &&
3174 Predicate.isZeroExtLoad())
Daniel Sandersa71f4542017-10-16 00:56:30 +00003175 continue;
3176
Daniel Sandersd66e0902017-10-23 18:19:24 +00003177 // No check required. G_STORE by itself is a non-extending store.
3178 if (Predicate.isNonTruncStore())
3179 continue;
3180
Daniel Sanders76664652017-11-28 22:07:05 +00003181 if (Predicate.isLoad() || Predicate.isStore() || Predicate.isAtomic()) {
3182 if (Predicate.getMemoryVT() != nullptr) {
3183 Optional<LLTCodeGen> MemTyOrNone =
3184 MVTToLLT(getValueType(Predicate.getMemoryVT()));
Daniel Sandersd66e0902017-10-23 18:19:24 +00003185
Daniel Sanders76664652017-11-28 22:07:05 +00003186 if (!MemTyOrNone)
3187 return failedImport("MemVT could not be converted to LLT");
Daniel Sandersd66e0902017-10-23 18:19:24 +00003188
Daniel Sandersf84bc372018-05-05 20:53:24 +00003189 // MMO's work in bytes so we must take care of unusual types like i1
3190 // don't round down.
3191 unsigned MemSizeInBits =
3192 llvm::alignTo(MemTyOrNone->get().getSizeInBits(), 8);
3193
3194 InsnMatcher.addPredicate<MemorySizePredicateMatcher>(
3195 0, MemSizeInBits / 8);
Daniel Sanders76664652017-11-28 22:07:05 +00003196 continue;
3197 }
3198 }
3199
3200 if (Predicate.isLoad() || Predicate.isStore()) {
3201 // No check required. A G_LOAD/G_STORE is an unindexed load.
3202 if (Predicate.isUnindexed())
3203 continue;
3204 }
3205
3206 if (Predicate.isAtomic()) {
3207 if (Predicate.isAtomicOrderingMonotonic()) {
3208 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3209 "Monotonic");
3210 continue;
3211 }
3212 if (Predicate.isAtomicOrderingAcquire()) {
3213 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>("Acquire");
3214 continue;
3215 }
3216 if (Predicate.isAtomicOrderingRelease()) {
3217 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>("Release");
3218 continue;
3219 }
3220 if (Predicate.isAtomicOrderingAcquireRelease()) {
3221 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3222 "AcquireRelease");
3223 continue;
3224 }
3225 if (Predicate.isAtomicOrderingSequentiallyConsistent()) {
3226 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3227 "SequentiallyConsistent");
3228 continue;
3229 }
Daniel Sanders0c43b3a2017-11-30 21:05:59 +00003230
3231 if (Predicate.isAtomicOrderingAcquireOrStronger()) {
3232 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3233 "Acquire", AtomicOrderingMMOPredicateMatcher::AO_OrStronger);
3234 continue;
3235 }
3236 if (Predicate.isAtomicOrderingWeakerThanAcquire()) {
3237 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3238 "Acquire", AtomicOrderingMMOPredicateMatcher::AO_WeakerThan);
3239 continue;
3240 }
3241
3242 if (Predicate.isAtomicOrderingReleaseOrStronger()) {
3243 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3244 "Release", AtomicOrderingMMOPredicateMatcher::AO_OrStronger);
3245 continue;
3246 }
3247 if (Predicate.isAtomicOrderingWeakerThanRelease()) {
3248 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3249 "Release", AtomicOrderingMMOPredicateMatcher::AO_WeakerThan);
3250 continue;
3251 }
Daniel Sandersd66e0902017-10-23 18:19:24 +00003252 }
3253
Daniel Sanders2c269f62017-08-24 09:11:20 +00003254 return failedImport("Src pattern child has predicate (" +
3255 explainPredicates(Src) + ")");
3256 }
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003257 if (SrcGIEquivOrNull && SrcGIEquivOrNull->getValueAsBit("CheckMMOIsNonAtomic"))
3258 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>("NotAtomic");
Daniel Sanders2c269f62017-08-24 09:11:20 +00003259
Daniel Sanders452c8ae2017-05-23 19:33:16 +00003260 if (Src->isLeaf()) {
3261 Init *SrcInit = Src->getLeafValue();
3262 if (IntInit *SrcIntInit = dyn_cast<IntInit>(SrcInit)) {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003263 OperandMatcher &OM =
3264 InsnMatcher.addOperand(OpIdx++, Src->getName(), TempOpIdx);
Daniel Sanders452c8ae2017-05-23 19:33:16 +00003265 OM.addPredicate<LiteralIntOperandMatcher>(SrcIntInit->getValue());
3266 } else
Daniel Sanders32291982017-06-28 13:50:04 +00003267 return failedImport(
3268 "Unable to deduce gMIR opcode to handle Src (which is a leaf)");
Daniel Sanders452c8ae2017-05-23 19:33:16 +00003269 } else {
Daniel Sanders85ffd362017-07-06 08:12:20 +00003270 assert(SrcGIOrNull &&
3271 "Expected to have already found an equivalent Instruction");
Daniel Sanders11300ce2017-10-13 21:28:03 +00003272 if (SrcGIOrNull->TheDef->getName() == "G_CONSTANT" ||
3273 SrcGIOrNull->TheDef->getName() == "G_FCONSTANT") {
3274 // imm/fpimm still have operands but we don't need to do anything with it
Daniel Sanders05540042017-08-08 10:44:31 +00003275 // here since we don't support ImmLeaf predicates yet. However, we still
3276 // need to note the hidden operand to get GIM_CheckNumOperands correct.
3277 InsnMatcher.addOperand(OpIdx++, "", TempOpIdx);
3278 return InsnMatcher;
3279 }
3280
Daniel Sanders452c8ae2017-05-23 19:33:16 +00003281 // Match the used operands (i.e. the children of the operator).
3282 for (unsigned i = 0, e = Src->getNumChildren(); i != e; ++i) {
Daniel Sanders85ffd362017-07-06 08:12:20 +00003283 TreePatternNode *SrcChild = Src->getChild(i);
3284
Daniel Sandersa71f4542017-10-16 00:56:30 +00003285 // SelectionDAG allows pointers to be represented with iN since it doesn't
3286 // distinguish between pointers and integers but they are different types in GlobalISel.
3287 // Coerce integers to pointers to address space 0 if the context indicates a pointer.
Daniel Sandersc54aa9c2017-11-18 00:16:44 +00003288 bool OperandIsAPointer = SrcGIOrNull->isOperandAPointer(i);
Daniel Sandersa71f4542017-10-16 00:56:30 +00003289
Daniel Sanders28887fe2017-09-19 12:56:36 +00003290 // For G_INTRINSIC/G_INTRINSIC_W_SIDE_EFFECTS, the operand immediately
3291 // following the defs is an intrinsic ID.
3292 if ((SrcGIOrNull->TheDef->getName() == "G_INTRINSIC" ||
3293 SrcGIOrNull->TheDef->getName() == "G_INTRINSIC_W_SIDE_EFFECTS") &&
3294 i == 0) {
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00003295 if (const CodeGenIntrinsic *II = Src->getIntrinsicInfo(CGP)) {
Daniel Sanders85ffd362017-07-06 08:12:20 +00003296 OperandMatcher &OM =
3297 InsnMatcher.addOperand(OpIdx++, SrcChild->getName(), TempOpIdx);
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00003298 OM.addPredicate<IntrinsicIDOperandMatcher>(II);
Daniel Sanders85ffd362017-07-06 08:12:20 +00003299 continue;
3300 }
3301
3302 return failedImport("Expected IntInit containing instrinsic ID)");
3303 }
3304
Daniel Sandersa71f4542017-10-16 00:56:30 +00003305 if (auto Error =
3306 importChildMatcher(Rule, InsnMatcher, SrcChild, OperandIsAPointer,
3307 OpIdx++, TempOpIdx))
Daniel Sanders452c8ae2017-05-23 19:33:16 +00003308 return std::move(Error);
3309 }
Daniel Sandersffc7d582017-03-29 15:37:18 +00003310 }
3311
3312 return InsnMatcher;
3313}
3314
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003315Error GlobalISelEmitter::importComplexPatternOperandMatcher(
3316 OperandMatcher &OM, Record *R, unsigned &TempOpIdx) const {
3317 const auto &ComplexPattern = ComplexPatternEquivs.find(R);
3318 if (ComplexPattern == ComplexPatternEquivs.end())
3319 return failedImport("SelectionDAG ComplexPattern (" + R->getName() +
3320 ") not mapped to GlobalISel");
3321
3322 OM.addPredicate<ComplexPatternOperandMatcher>(OM, *ComplexPattern->second);
3323 TempOpIdx++;
3324 return Error::success();
3325}
3326
3327Error GlobalISelEmitter::importChildMatcher(RuleMatcher &Rule,
3328 InstructionMatcher &InsnMatcher,
Daniel Sanders452c8ae2017-05-23 19:33:16 +00003329 const TreePatternNode *SrcChild,
Daniel Sandersa71f4542017-10-16 00:56:30 +00003330 bool OperandIsAPointer,
Daniel Sandersc270c502017-03-30 09:36:33 +00003331 unsigned OpIdx,
3332 unsigned &TempOpIdx) const {
Daniel Sanders4f3eb242017-04-05 13:14:03 +00003333 OperandMatcher &OM =
3334 InsnMatcher.addOperand(OpIdx, SrcChild->getName(), TempOpIdx);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003335 if (OM.isSameAsAnotherOperand())
3336 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00003337
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003338 ArrayRef<TypeSetByHwMode> ChildTypes = SrcChild->getExtTypes();
Daniel Sandersffc7d582017-03-29 15:37:18 +00003339 if (ChildTypes.size() != 1)
3340 return failedImport("Src pattern child has multiple results");
3341
3342 // Check MBB's before the type check since they are not a known type.
3343 if (!SrcChild->isLeaf()) {
3344 if (SrcChild->getOperator()->isSubClassOf("SDNode")) {
3345 auto &ChildSDNI = CGP.getSDNodeInfo(SrcChild->getOperator());
3346 if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") {
3347 OM.addPredicate<MBBOperandMatcher>();
Daniel Sandersc270c502017-03-30 09:36:33 +00003348 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00003349 }
3350 }
Daniel Sandersffc7d582017-03-29 15:37:18 +00003351 }
3352
Daniel Sandersa71f4542017-10-16 00:56:30 +00003353 if (auto Error =
3354 OM.addTypeCheckPredicate(ChildTypes.front(), OperandIsAPointer))
3355 return failedImport(toString(std::move(Error)) + " for Src operand (" +
3356 to_string(*SrcChild) + ")");
Daniel Sandersffc7d582017-03-29 15:37:18 +00003357
Daniel Sandersbee57392017-04-04 13:25:23 +00003358 // Check for nested instructions.
3359 if (!SrcChild->isLeaf()) {
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003360 if (SrcChild->getOperator()->isSubClassOf("ComplexPattern")) {
3361 // When a ComplexPattern is used as an operator, it should do the same
3362 // thing as when used as a leaf. However, the children of the operator
3363 // name the sub-operands that make up the complex operand and we must
3364 // prepare to reference them in the renderer too.
3365 unsigned RendererID = TempOpIdx;
3366 if (auto Error = importComplexPatternOperandMatcher(
3367 OM, SrcChild->getOperator(), TempOpIdx))
3368 return Error;
3369
3370 for (unsigned i = 0, e = SrcChild->getNumChildren(); i != e; ++i) {
3371 auto *SubOperand = SrcChild->getChild(i);
3372 if (!SubOperand->getName().empty())
3373 Rule.defineComplexSubOperand(SubOperand->getName(),
3374 SrcChild->getOperator(), RendererID, i);
3375 }
3376
3377 return Error::success();
3378 }
3379
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003380 auto MaybeInsnOperand = OM.addPredicate<InstructionOperandMatcher>(
3381 InsnMatcher.getRuleMatcher(), SrcChild->getName());
3382 if (!MaybeInsnOperand.hasValue()) {
3383 // This isn't strictly true. If the user were to provide exactly the same
3384 // matchers as the original operand then we could allow it. However, it's
3385 // simpler to not permit the redundant specification.
3386 return failedImport("Nested instruction cannot be the same as another operand");
3387 }
3388
Daniel Sandersbee57392017-04-04 13:25:23 +00003389 // Map the node to a gMIR instruction.
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003390 InstructionOperandMatcher &InsnOperand = **MaybeInsnOperand;
Daniel Sanders57938df2017-07-11 10:40:18 +00003391 auto InsnMatcherOrError = createAndImportSelDAGMatcher(
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003392 Rule, InsnOperand.getInsnMatcher(), SrcChild, TempOpIdx);
Daniel Sandersbee57392017-04-04 13:25:23 +00003393 if (auto Error = InsnMatcherOrError.takeError())
3394 return Error;
3395
3396 return Error::success();
3397 }
3398
Diana Picusd1b61812017-11-03 10:30:19 +00003399 if (SrcChild->hasAnyPredicate())
3400 return failedImport("Src pattern child has unsupported predicate");
3401
Daniel Sandersffc7d582017-03-29 15:37:18 +00003402 // Check for constant immediates.
3403 if (auto *ChildInt = dyn_cast<IntInit>(SrcChild->getLeafValue())) {
Daniel Sanders452c8ae2017-05-23 19:33:16 +00003404 OM.addPredicate<ConstantIntOperandMatcher>(ChildInt->getValue());
Daniel Sandersc270c502017-03-30 09:36:33 +00003405 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00003406 }
3407
3408 // Check for def's like register classes or ComplexPattern's.
3409 if (auto *ChildDefInit = dyn_cast<DefInit>(SrcChild->getLeafValue())) {
3410 auto *ChildRec = ChildDefInit->getDef();
3411
3412 // Check for register classes.
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003413 if (ChildRec->isSubClassOf("RegisterClass") ||
3414 ChildRec->isSubClassOf("RegisterOperand")) {
Daniel Sandersffc7d582017-03-29 15:37:18 +00003415 OM.addPredicate<RegisterBankOperandMatcher>(
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003416 Target.getRegisterClass(getInitValueAsRegClass(ChildDefInit)));
Daniel Sanders658541f2017-04-22 15:53:21 +00003417 return Error::success();
3418 }
3419
Daniel Sanders4d4e7652017-10-09 18:14:53 +00003420 // Check for ValueType.
3421 if (ChildRec->isSubClassOf("ValueType")) {
3422 // We already added a type check as standard practice so this doesn't need
3423 // to do anything.
3424 return Error::success();
3425 }
3426
Daniel Sandersffc7d582017-03-29 15:37:18 +00003427 // Check for ComplexPattern's.
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003428 if (ChildRec->isSubClassOf("ComplexPattern"))
3429 return importComplexPatternOperandMatcher(OM, ChildRec, TempOpIdx);
Daniel Sandersffc7d582017-03-29 15:37:18 +00003430
Daniel Sandersd0656a32017-04-13 09:45:37 +00003431 if (ChildRec->isSubClassOf("ImmLeaf")) {
3432 return failedImport(
3433 "Src pattern child def is an unsupported tablegen class (ImmLeaf)");
3434 }
3435
Daniel Sandersffc7d582017-03-29 15:37:18 +00003436 return failedImport(
3437 "Src pattern child def is an unsupported tablegen class");
3438 }
3439
3440 return failedImport("Src pattern child is an unsupported kind");
3441}
3442
Daniel Sanders7438b262017-10-31 23:03:18 +00003443Expected<action_iterator> GlobalISelEmitter::importExplicitUseRenderer(
3444 action_iterator InsertPt, RuleMatcher &Rule, BuildMIAction &DstMIBuilder,
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003445 TreePatternNode *DstChild) {
Daniel Sanders2c269f62017-08-24 09:11:20 +00003446
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003447 const auto &SubOperand = Rule.getComplexSubOperand(DstChild->getName());
3448 if (SubOperand.hasValue()) {
3449 DstMIBuilder.addRenderer<RenderComplexPatternOperand>(
Daniel Sanders198447a2017-11-01 00:29:47 +00003450 *std::get<0>(*SubOperand), DstChild->getName(),
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003451 std::get<1>(*SubOperand), std::get<2>(*SubOperand));
Daniel Sanders7438b262017-10-31 23:03:18 +00003452 return InsertPt;
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003453 }
3454
Daniel Sandersffc7d582017-03-29 15:37:18 +00003455 if (!DstChild->isLeaf()) {
Volkan Kelesf7f25682018-01-16 18:44:05 +00003456
3457 if (DstChild->getOperator()->isSubClassOf("SDNodeXForm")) {
3458 auto Child = DstChild->getChild(0);
3459 auto I = SDNodeXFormEquivs.find(DstChild->getOperator());
3460 if (I != SDNodeXFormEquivs.end()) {
3461 DstMIBuilder.addRenderer<CustomRenderer>(*I->second, Child->getName());
3462 return InsertPt;
3463 }
3464 return failedImport("SDNodeXForm " + Child->getName() +
3465 " has no custom renderer");
3466 }
3467
Daniel Sanders05540042017-08-08 10:44:31 +00003468 // We accept 'bb' here. It's an operator because BasicBlockSDNode isn't
3469 // inline, but in MI it's just another operand.
Daniel Sandersffc7d582017-03-29 15:37:18 +00003470 if (DstChild->getOperator()->isSubClassOf("SDNode")) {
3471 auto &ChildSDNI = CGP.getSDNodeInfo(DstChild->getOperator());
3472 if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") {
Daniel Sanders198447a2017-11-01 00:29:47 +00003473 DstMIBuilder.addRenderer<CopyRenderer>(DstChild->getName());
Daniel Sanders7438b262017-10-31 23:03:18 +00003474 return InsertPt;
Daniel Sandersffc7d582017-03-29 15:37:18 +00003475 }
3476 }
Daniel Sanders05540042017-08-08 10:44:31 +00003477
3478 // Similarly, imm is an operator in TreePatternNode's view but must be
3479 // rendered as operands.
3480 // FIXME: The target should be able to choose sign-extended when appropriate
3481 // (e.g. on Mips).
3482 if (DstChild->getOperator()->getName() == "imm") {
Daniel Sanders198447a2017-11-01 00:29:47 +00003483 DstMIBuilder.addRenderer<CopyConstantAsImmRenderer>(DstChild->getName());
Daniel Sanders7438b262017-10-31 23:03:18 +00003484 return InsertPt;
Daniel Sanders11300ce2017-10-13 21:28:03 +00003485 } else if (DstChild->getOperator()->getName() == "fpimm") {
3486 DstMIBuilder.addRenderer<CopyFConstantAsFPImmRenderer>(
Daniel Sanders198447a2017-11-01 00:29:47 +00003487 DstChild->getName());
Daniel Sanders7438b262017-10-31 23:03:18 +00003488 return InsertPt;
Daniel Sanders05540042017-08-08 10:44:31 +00003489 }
3490
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003491 if (DstChild->getOperator()->isSubClassOf("Instruction")) {
3492 ArrayRef<TypeSetByHwMode> ChildTypes = DstChild->getExtTypes();
3493 if (ChildTypes.size() != 1)
3494 return failedImport("Dst pattern child has multiple results");
3495
3496 Optional<LLTCodeGen> OpTyOrNone = None;
3497 if (ChildTypes.front().isMachineValueType())
3498 OpTyOrNone =
3499 MVTToLLT(ChildTypes.front().getMachineValueType().SimpleTy);
3500 if (!OpTyOrNone)
3501 return failedImport("Dst operand has an unsupported type");
3502
3503 unsigned TempRegID = Rule.allocateTempRegID();
3504 InsertPt = Rule.insertAction<MakeTempRegisterAction>(
3505 InsertPt, OpTyOrNone.getValue(), TempRegID);
3506 DstMIBuilder.addRenderer<TempRegRenderer>(TempRegID);
3507
3508 auto InsertPtOrError = createAndImportSubInstructionRenderer(
3509 ++InsertPt, Rule, DstChild, TempRegID);
3510 if (auto Error = InsertPtOrError.takeError())
3511 return std::move(Error);
3512 return InsertPtOrError.get();
3513 }
3514
Daniel Sanders2c269f62017-08-24 09:11:20 +00003515 return failedImport("Dst pattern child isn't a leaf node or an MBB" + llvm::to_string(*DstChild));
Daniel Sandersffc7d582017-03-29 15:37:18 +00003516 }
3517
Daniel Sandersf499b2b2017-11-30 18:48:35 +00003518 // It could be a specific immediate in which case we should just check for
3519 // that immediate.
3520 if (const IntInit *ChildIntInit =
3521 dyn_cast<IntInit>(DstChild->getLeafValue())) {
3522 DstMIBuilder.addRenderer<ImmRenderer>(ChildIntInit->getValue());
3523 return InsertPt;
3524 }
3525
Daniel Sandersffc7d582017-03-29 15:37:18 +00003526 // Otherwise, we're looking for a bog-standard RegisterClass operand.
Daniel Sandersffc7d582017-03-29 15:37:18 +00003527 if (auto *ChildDefInit = dyn_cast<DefInit>(DstChild->getLeafValue())) {
3528 auto *ChildRec = ChildDefInit->getDef();
3529
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003530 ArrayRef<TypeSetByHwMode> ChildTypes = DstChild->getExtTypes();
Daniel Sandersffc7d582017-03-29 15:37:18 +00003531 if (ChildTypes.size() != 1)
3532 return failedImport("Dst pattern child has multiple results");
3533
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003534 Optional<LLTCodeGen> OpTyOrNone = None;
3535 if (ChildTypes.front().isMachineValueType())
3536 OpTyOrNone = MVTToLLT(ChildTypes.front().getMachineValueType().SimpleTy);
Daniel Sandersffc7d582017-03-29 15:37:18 +00003537 if (!OpTyOrNone)
3538 return failedImport("Dst operand has an unsupported type");
3539
3540 if (ChildRec->isSubClassOf("Register")) {
Daniel Sanders198447a2017-11-01 00:29:47 +00003541 DstMIBuilder.addRenderer<AddRegisterRenderer>(ChildRec);
Daniel Sanders7438b262017-10-31 23:03:18 +00003542 return InsertPt;
Daniel Sandersffc7d582017-03-29 15:37:18 +00003543 }
3544
Daniel Sanders658541f2017-04-22 15:53:21 +00003545 if (ChildRec->isSubClassOf("RegisterClass") ||
Daniel Sanders4d4e7652017-10-09 18:14:53 +00003546 ChildRec->isSubClassOf("RegisterOperand") ||
3547 ChildRec->isSubClassOf("ValueType")) {
Daniel Sandersd66e0902017-10-23 18:19:24 +00003548 if (ChildRec->isSubClassOf("RegisterOperand") &&
3549 !ChildRec->isValueUnset("GIZeroRegister")) {
3550 DstMIBuilder.addRenderer<CopyOrAddZeroRegRenderer>(
Daniel Sanders198447a2017-11-01 00:29:47 +00003551 DstChild->getName(), ChildRec->getValueAsDef("GIZeroRegister"));
Daniel Sanders7438b262017-10-31 23:03:18 +00003552 return InsertPt;
Daniel Sandersd66e0902017-10-23 18:19:24 +00003553 }
3554
Daniel Sanders198447a2017-11-01 00:29:47 +00003555 DstMIBuilder.addRenderer<CopyRenderer>(DstChild->getName());
Daniel Sanders7438b262017-10-31 23:03:18 +00003556 return InsertPt;
Daniel Sandersffc7d582017-03-29 15:37:18 +00003557 }
3558
3559 if (ChildRec->isSubClassOf("ComplexPattern")) {
3560 const auto &ComplexPattern = ComplexPatternEquivs.find(ChildRec);
3561 if (ComplexPattern == ComplexPatternEquivs.end())
3562 return failedImport(
3563 "SelectionDAG ComplexPattern not mapped to GlobalISel");
3564
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003565 const OperandMatcher &OM = Rule.getOperandMatcher(DstChild->getName());
Daniel Sandersffc7d582017-03-29 15:37:18 +00003566 DstMIBuilder.addRenderer<RenderComplexPatternOperand>(
Daniel Sanders198447a2017-11-01 00:29:47 +00003567 *ComplexPattern->second, DstChild->getName(),
Daniel Sanders2deea182017-04-22 15:11:04 +00003568 OM.getAllocatedTemporariesBaseID());
Daniel Sanders7438b262017-10-31 23:03:18 +00003569 return InsertPt;
Daniel Sandersffc7d582017-03-29 15:37:18 +00003570 }
3571
3572 return failedImport(
3573 "Dst pattern child def is an unsupported tablegen class");
3574 }
3575
3576 return failedImport("Dst pattern child is an unsupported kind");
3577}
3578
Daniel Sandersc270c502017-03-30 09:36:33 +00003579Expected<BuildMIAction &> GlobalISelEmitter::createAndImportInstructionRenderer(
Daniel Sandersa7b75262017-10-31 18:50:24 +00003580 RuleMatcher &M, const TreePatternNode *Dst) {
Daniel Sanders7438b262017-10-31 23:03:18 +00003581 auto InsertPtOrError = createInstructionRenderer(M.actions_end(), M, Dst);
3582 if (auto Error = InsertPtOrError.takeError())
Daniel Sandersdf258e32017-10-31 19:09:29 +00003583 return std::move(Error);
3584
Daniel Sanders7438b262017-10-31 23:03:18 +00003585 action_iterator InsertPt = InsertPtOrError.get();
3586 BuildMIAction &DstMIBuilder = *static_cast<BuildMIAction *>(InsertPt->get());
Daniel Sandersdf258e32017-10-31 19:09:29 +00003587
3588 importExplicitDefRenderers(DstMIBuilder);
3589
Daniel Sanders7438b262017-10-31 23:03:18 +00003590 if (auto Error = importExplicitUseRenderers(InsertPt, M, DstMIBuilder, Dst)
3591 .takeError())
Daniel Sandersdf258e32017-10-31 19:09:29 +00003592 return std::move(Error);
3593
3594 return DstMIBuilder;
3595}
3596
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003597Expected<action_iterator>
3598GlobalISelEmitter::createAndImportSubInstructionRenderer(
Daniel Sanders08464522018-01-29 21:09:12 +00003599 const action_iterator InsertPt, RuleMatcher &M, const TreePatternNode *Dst,
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003600 unsigned TempRegID) {
3601 auto InsertPtOrError = createInstructionRenderer(InsertPt, M, Dst);
3602
3603 // TODO: Assert there's exactly one result.
3604
3605 if (auto Error = InsertPtOrError.takeError())
3606 return std::move(Error);
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003607
3608 BuildMIAction &DstMIBuilder =
3609 *static_cast<BuildMIAction *>(InsertPtOrError.get()->get());
3610
3611 // Assign the result to TempReg.
3612 DstMIBuilder.addRenderer<TempRegRenderer>(TempRegID, true);
3613
Daniel Sanders08464522018-01-29 21:09:12 +00003614 InsertPtOrError =
3615 importExplicitUseRenderers(InsertPtOrError.get(), M, DstMIBuilder, Dst);
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003616 if (auto Error = InsertPtOrError.takeError())
3617 return std::move(Error);
3618
Daniel Sanders08464522018-01-29 21:09:12 +00003619 M.insertAction<ConstrainOperandsToDefinitionAction>(InsertPt,
3620 DstMIBuilder.getInsnID());
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003621 return InsertPtOrError.get();
3622}
3623
Daniel Sanders7438b262017-10-31 23:03:18 +00003624Expected<action_iterator> GlobalISelEmitter::createInstructionRenderer(
3625 action_iterator InsertPt, RuleMatcher &M, const TreePatternNode *Dst) {
Daniel Sandersffc7d582017-03-29 15:37:18 +00003626 Record *DstOp = Dst->getOperator();
Daniel Sandersd0656a32017-04-13 09:45:37 +00003627 if (!DstOp->isSubClassOf("Instruction")) {
3628 if (DstOp->isSubClassOf("ValueType"))
3629 return failedImport(
3630 "Pattern operator isn't an instruction (it's a ValueType)");
Daniel Sandersffc7d582017-03-29 15:37:18 +00003631 return failedImport("Pattern operator isn't an instruction");
Daniel Sandersd0656a32017-04-13 09:45:37 +00003632 }
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003633 CodeGenInstruction *DstI = &Target.getInstruction(DstOp);
Daniel Sandersffc7d582017-03-29 15:37:18 +00003634
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003635 // COPY_TO_REGCLASS is just a copy with a ConstrainOperandToRegClassAction
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00003636 // attached. Similarly for EXTRACT_SUBREG except that's a subregister copy.
Daniel Sandersdf258e32017-10-31 19:09:29 +00003637 if (DstI->TheDef->getName() == "COPY_TO_REGCLASS")
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003638 DstI = &Target.getInstruction(RK.getDef("COPY"));
Daniel Sandersdf258e32017-10-31 19:09:29 +00003639 else if (DstI->TheDef->getName() == "EXTRACT_SUBREG")
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00003640 DstI = &Target.getInstruction(RK.getDef("COPY"));
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003641 else if (DstI->TheDef->getName() == "REG_SEQUENCE")
3642 return failedImport("Unable to emit REG_SEQUENCE");
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003643
Daniel Sanders198447a2017-11-01 00:29:47 +00003644 return M.insertAction<BuildMIAction>(InsertPt, M.allocateOutputInsnID(),
3645 DstI);
Daniel Sandersdf258e32017-10-31 19:09:29 +00003646}
3647
3648void GlobalISelEmitter::importExplicitDefRenderers(
3649 BuildMIAction &DstMIBuilder) {
3650 const CodeGenInstruction *DstI = DstMIBuilder.getCGI();
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003651 for (unsigned I = 0; I < DstI->Operands.NumDefs; ++I) {
3652 const CGIOperandList::OperandInfo &DstIOperand = DstI->Operands[I];
Daniel Sanders198447a2017-11-01 00:29:47 +00003653 DstMIBuilder.addRenderer<CopyRenderer>(DstIOperand.Name);
Daniel Sandersffc7d582017-03-29 15:37:18 +00003654 }
Daniel Sandersdf258e32017-10-31 19:09:29 +00003655}
3656
Daniel Sanders7438b262017-10-31 23:03:18 +00003657Expected<action_iterator> GlobalISelEmitter::importExplicitUseRenderers(
3658 action_iterator InsertPt, RuleMatcher &M, BuildMIAction &DstMIBuilder,
Daniel Sandersdf258e32017-10-31 19:09:29 +00003659 const llvm::TreePatternNode *Dst) {
3660 const CodeGenInstruction *DstI = DstMIBuilder.getCGI();
3661 CodeGenInstruction *OrigDstI = &Target.getInstruction(Dst->getOperator());
Daniel Sandersffc7d582017-03-29 15:37:18 +00003662
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00003663 // EXTRACT_SUBREG needs to use a subregister COPY.
Daniel Sandersdf258e32017-10-31 19:09:29 +00003664 if (OrigDstI->TheDef->getName() == "EXTRACT_SUBREG") {
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00003665 if (!Dst->getChild(0)->isLeaf())
3666 return failedImport("EXTRACT_SUBREG child #1 is not a leaf");
3667
Daniel Sanders32291982017-06-28 13:50:04 +00003668 if (DefInit *SubRegInit =
3669 dyn_cast<DefInit>(Dst->getChild(1)->getLeafValue())) {
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003670 Record *RCDef = getInitValueAsRegClass(Dst->getChild(0)->getLeafValue());
3671 if (!RCDef)
3672 return failedImport("EXTRACT_SUBREG child #0 could not "
3673 "be coerced to a register class");
3674
3675 CodeGenRegisterClass *RC = CGRegs.getRegClass(RCDef);
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00003676 CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef());
3677
3678 const auto &SrcRCDstRCPair =
3679 RC->getMatchingSubClassWithSubRegs(CGRegs, SubIdx);
3680 if (SrcRCDstRCPair.hasValue()) {
3681 assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
3682 if (SrcRCDstRCPair->first != RC)
3683 return failedImport("EXTRACT_SUBREG requires an additional COPY");
3684 }
3685
Daniel Sanders198447a2017-11-01 00:29:47 +00003686 DstMIBuilder.addRenderer<CopySubRegRenderer>(Dst->getChild(0)->getName(),
3687 SubIdx);
Daniel Sanders7438b262017-10-31 23:03:18 +00003688 return InsertPt;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00003689 }
3690
3691 return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
3692 }
3693
Daniel Sandersffc7d582017-03-29 15:37:18 +00003694 // Render the explicit uses.
Daniel Sandersdf258e32017-10-31 19:09:29 +00003695 unsigned DstINumUses = OrigDstI->Operands.size() - OrigDstI->Operands.NumDefs;
3696 unsigned ExpectedDstINumUses = Dst->getNumChildren();
3697 if (OrigDstI->TheDef->getName() == "COPY_TO_REGCLASS") {
3698 DstINumUses--; // Ignore the class constraint.
3699 ExpectedDstINumUses--;
3700 }
3701
Daniel Sanders0ed28822017-04-12 08:23:08 +00003702 unsigned Child = 0;
Diana Picus382602f2017-05-17 08:57:28 +00003703 unsigned NumDefaultOps = 0;
Daniel Sanders0ed28822017-04-12 08:23:08 +00003704 for (unsigned I = 0; I != DstINumUses; ++I) {
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003705 const CGIOperandList::OperandInfo &DstIOperand =
3706 DstI->Operands[DstI->Operands.NumDefs + I];
Daniel Sanders0ed28822017-04-12 08:23:08 +00003707
Diana Picus382602f2017-05-17 08:57:28 +00003708 // If the operand has default values, introduce them now.
3709 // FIXME: Until we have a decent test case that dictates we should do
3710 // otherwise, we're going to assume that operands with default values cannot
3711 // be specified in the patterns. Therefore, adding them will not cause us to
3712 // end up with too many rendered operands.
3713 if (DstIOperand.Rec->isSubClassOf("OperandWithDefaultOps")) {
Daniel Sanders0ed28822017-04-12 08:23:08 +00003714 DagInit *DefaultOps = DstIOperand.Rec->getValueAsDag("DefaultOps");
Diana Picus382602f2017-05-17 08:57:28 +00003715 if (auto Error = importDefaultOperandRenderers(DstMIBuilder, DefaultOps))
3716 return std::move(Error);
3717 ++NumDefaultOps;
Daniel Sanders0ed28822017-04-12 08:23:08 +00003718 continue;
3719 }
3720
Daniel Sanders7438b262017-10-31 23:03:18 +00003721 auto InsertPtOrError = importExplicitUseRenderer(InsertPt, M, DstMIBuilder,
3722 Dst->getChild(Child));
3723 if (auto Error = InsertPtOrError.takeError())
Daniel Sandersffc7d582017-03-29 15:37:18 +00003724 return std::move(Error);
Daniel Sanders7438b262017-10-31 23:03:18 +00003725 InsertPt = InsertPtOrError.get();
Daniel Sanders0ed28822017-04-12 08:23:08 +00003726 ++Child;
Daniel Sandersffc7d582017-03-29 15:37:18 +00003727 }
3728
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003729 if (NumDefaultOps + ExpectedDstINumUses != DstINumUses)
Diana Picuseb2057c2017-05-17 09:25:08 +00003730 return failedImport("Expected " + llvm::to_string(DstINumUses) +
Diana Picus382602f2017-05-17 08:57:28 +00003731 " used operands but found " +
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003732 llvm::to_string(ExpectedDstINumUses) +
Diana Picuseb2057c2017-05-17 09:25:08 +00003733 " explicit ones and " + llvm::to_string(NumDefaultOps) +
Diana Picus382602f2017-05-17 08:57:28 +00003734 " default ones");
3735
Daniel Sanders7438b262017-10-31 23:03:18 +00003736 return InsertPt;
Daniel Sandersffc7d582017-03-29 15:37:18 +00003737}
3738
Diana Picus382602f2017-05-17 08:57:28 +00003739Error GlobalISelEmitter::importDefaultOperandRenderers(
3740 BuildMIAction &DstMIBuilder, DagInit *DefaultOps) const {
Craig Topper481ff702017-05-29 21:49:34 +00003741 for (const auto *DefaultOp : DefaultOps->getArgs()) {
Diana Picus382602f2017-05-17 08:57:28 +00003742 // Look through ValueType operators.
3743 if (const DagInit *DefaultDagOp = dyn_cast<DagInit>(DefaultOp)) {
3744 if (const DefInit *DefaultDagOperator =
3745 dyn_cast<DefInit>(DefaultDagOp->getOperator())) {
3746 if (DefaultDagOperator->getDef()->isSubClassOf("ValueType"))
3747 DefaultOp = DefaultDagOp->getArg(0);
3748 }
3749 }
3750
3751 if (const DefInit *DefaultDefOp = dyn_cast<DefInit>(DefaultOp)) {
Daniel Sanders198447a2017-11-01 00:29:47 +00003752 DstMIBuilder.addRenderer<AddRegisterRenderer>(DefaultDefOp->getDef());
Diana Picus382602f2017-05-17 08:57:28 +00003753 continue;
3754 }
3755
3756 if (const IntInit *DefaultIntOp = dyn_cast<IntInit>(DefaultOp)) {
Daniel Sanders198447a2017-11-01 00:29:47 +00003757 DstMIBuilder.addRenderer<ImmRenderer>(DefaultIntOp->getValue());
Diana Picus382602f2017-05-17 08:57:28 +00003758 continue;
3759 }
3760
3761 return failedImport("Could not add default op");
3762 }
3763
3764 return Error::success();
3765}
3766
Daniel Sandersc270c502017-03-30 09:36:33 +00003767Error GlobalISelEmitter::importImplicitDefRenderers(
Daniel Sandersffc7d582017-03-29 15:37:18 +00003768 BuildMIAction &DstMIBuilder,
3769 const std::vector<Record *> &ImplicitDefs) const {
3770 if (!ImplicitDefs.empty())
3771 return failedImport("Pattern defines a physical register");
Daniel Sandersc270c502017-03-30 09:36:33 +00003772 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00003773}
3774
3775Expected<RuleMatcher> GlobalISelEmitter::runOnPattern(const PatternToMatch &P) {
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003776 // Keep track of the matchers and actions to emit.
Aditya Nandakumarb63e7632018-02-16 22:37:15 +00003777 int Score = P.getPatternComplexity(CGP);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003778 RuleMatcher M(P.getSrcRecord()->getLoc());
Aditya Nandakumarb63e7632018-02-16 22:37:15 +00003779 RuleMatcherScores[M.getRuleID()] = Score;
Daniel Sanders6ea17ed2017-10-31 18:07:03 +00003780 M.addAction<DebugCommentAction>(llvm::to_string(*P.getSrcPattern()) +
3781 " => " +
3782 llvm::to_string(*P.getDstPattern()));
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003783
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003784 if (auto Error = importRulePredicates(M, P.getPredicates()))
Daniel Sandersffc7d582017-03-29 15:37:18 +00003785 return std::move(Error);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003786
3787 // Next, analyze the pattern operators.
3788 TreePatternNode *Src = P.getSrcPattern();
3789 TreePatternNode *Dst = P.getDstPattern();
3790
3791 // If the root of either pattern isn't a simple operator, ignore it.
Daniel Sandersd0656a32017-04-13 09:45:37 +00003792 if (auto Err = isTrivialOperatorNode(Dst))
3793 return failedImport("Dst pattern root isn't a trivial operator (" +
3794 toString(std::move(Err)) + ")");
3795 if (auto Err = isTrivialOperatorNode(Src))
3796 return failedImport("Src pattern root isn't a trivial operator (" +
3797 toString(std::move(Err)) + ")");
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003798
Quentin Colombetaad20be2017-12-15 23:07:42 +00003799 // The different predicates and matchers created during
3800 // addInstructionMatcher use the RuleMatcher M to set up their
3801 // instruction ID (InsnVarID) that are going to be used when
3802 // M is going to be emitted.
3803 // However, the code doing the emission still relies on the IDs
3804 // returned during that process by the RuleMatcher when issuing
3805 // the recordInsn opcodes.
3806 // Because of that:
3807 // 1. The order in which we created the predicates
3808 // and such must be the same as the order in which we emit them,
3809 // and
3810 // 2. We need to reset the generation of the IDs in M somewhere between
3811 // addInstructionMatcher and emit
3812 //
3813 // FIXME: Long term, we don't want to have to rely on this implicit
3814 // naming being the same. One possible solution would be to have
3815 // explicit operator for operation capture and reference those.
3816 // The plus side is that it would expose opportunities to share
3817 // the capture accross rules. The downside is that it would
3818 // introduce a dependency between predicates (captures must happen
3819 // before their first use.)
Daniel Sandersedd07842017-08-17 09:26:14 +00003820 InstructionMatcher &InsnMatcherTemp = M.addInstructionMatcher(Src->getName());
3821 unsigned TempOpIdx = 0;
3822 auto InsnMatcherOrError =
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003823 createAndImportSelDAGMatcher(M, InsnMatcherTemp, Src, TempOpIdx);
Daniel Sandersedd07842017-08-17 09:26:14 +00003824 if (auto Error = InsnMatcherOrError.takeError())
3825 return std::move(Error);
3826 InstructionMatcher &InsnMatcher = InsnMatcherOrError.get();
3827
3828 if (Dst->isLeaf()) {
3829 Record *RCDef = getInitValueAsRegClass(Dst->getLeafValue());
3830
3831 const CodeGenRegisterClass &RC = Target.getRegisterClass(RCDef);
3832 if (RCDef) {
3833 // We need to replace the def and all its uses with the specified
3834 // operand. However, we must also insert COPY's wherever needed.
3835 // For now, emit a copy and let the register allocator clean up.
3836 auto &DstI = Target.getInstruction(RK.getDef("COPY"));
3837 const auto &DstIOperand = DstI.Operands[0];
3838
3839 OperandMatcher &OM0 = InsnMatcher.getOperand(0);
3840 OM0.setSymbolicName(DstIOperand.Name);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003841 M.defineOperand(OM0.getSymbolicName(), OM0);
Daniel Sandersedd07842017-08-17 09:26:14 +00003842 OM0.addPredicate<RegisterBankOperandMatcher>(RC);
3843
Daniel Sanders198447a2017-11-01 00:29:47 +00003844 auto &DstMIBuilder =
3845 M.addAction<BuildMIAction>(M.allocateOutputInsnID(), &DstI);
3846 DstMIBuilder.addRenderer<CopyRenderer>(DstIOperand.Name);
3847 DstMIBuilder.addRenderer<CopyRenderer>(Dst->getName());
Daniel Sandersedd07842017-08-17 09:26:14 +00003848 M.addAction<ConstrainOperandToRegClassAction>(0, 0, RC);
3849
3850 // We're done with this pattern! It's eligible for GISel emission; return
3851 // it.
3852 ++NumPatternImported;
3853 return std::move(M);
3854 }
3855
Daniel Sanders452c8ae2017-05-23 19:33:16 +00003856 return failedImport("Dst pattern root isn't a known leaf");
Daniel Sandersedd07842017-08-17 09:26:14 +00003857 }
Daniel Sanders452c8ae2017-05-23 19:33:16 +00003858
Daniel Sandersbee57392017-04-04 13:25:23 +00003859 // Start with the defined operands (i.e., the results of the root operator).
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003860 Record *DstOp = Dst->getOperator();
3861 if (!DstOp->isSubClassOf("Instruction"))
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003862 return failedImport("Pattern operator isn't an instruction");
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003863
3864 auto &DstI = Target.getInstruction(DstOp);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003865 if (DstI.Operands.NumDefs != Src->getExtTypes().size())
Daniel Sandersd0656a32017-04-13 09:45:37 +00003866 return failedImport("Src pattern results and dst MI defs are different (" +
3867 to_string(Src->getExtTypes().size()) + " def(s) vs " +
3868 to_string(DstI.Operands.NumDefs) + " def(s))");
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003869
Daniel Sandersffc7d582017-03-29 15:37:18 +00003870 // The root of the match also has constraints on the register bank so that it
3871 // matches the result instruction.
3872 unsigned OpIdx = 0;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003873 for (const TypeSetByHwMode &VTy : Src->getExtTypes()) {
3874 (void)VTy;
Daniel Sandersffc7d582017-03-29 15:37:18 +00003875
Daniel Sanders066ebbf2017-02-24 15:43:30 +00003876 const auto &DstIOperand = DstI.Operands[OpIdx];
3877 Record *DstIOpRec = DstIOperand.Rec;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003878 if (DstI.TheDef->getName() == "COPY_TO_REGCLASS") {
3879 DstIOpRec = getInitValueAsRegClass(Dst->getChild(1)->getLeafValue());
3880
3881 if (DstIOpRec == nullptr)
3882 return failedImport(
3883 "COPY_TO_REGCLASS operand #1 isn't a register class");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00003884 } else if (DstI.TheDef->getName() == "EXTRACT_SUBREG") {
3885 if (!Dst->getChild(0)->isLeaf())
3886 return failedImport("EXTRACT_SUBREG operand #0 isn't a leaf");
3887
Daniel Sanders32291982017-06-28 13:50:04 +00003888 // We can assume that a subregister is in the same bank as it's super
3889 // register.
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00003890 DstIOpRec = getInitValueAsRegClass(Dst->getChild(0)->getLeafValue());
3891
3892 if (DstIOpRec == nullptr)
3893 return failedImport(
3894 "EXTRACT_SUBREG operand #0 isn't a register class");
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003895 } else if (DstIOpRec->isSubClassOf("RegisterOperand"))
Daniel Sanders658541f2017-04-22 15:53:21 +00003896 DstIOpRec = DstIOpRec->getValueAsDef("RegClass");
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003897 else if (!DstIOpRec->isSubClassOf("RegisterClass"))
Daniel Sanders32291982017-06-28 13:50:04 +00003898 return failedImport("Dst MI def isn't a register class" +
3899 to_string(*Dst));
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003900
Daniel Sandersffc7d582017-03-29 15:37:18 +00003901 OperandMatcher &OM = InsnMatcher.getOperand(OpIdx);
3902 OM.setSymbolicName(DstIOperand.Name);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003903 M.defineOperand(OM.getSymbolicName(), OM);
Daniel Sandersdc662ff2017-01-26 11:10:14 +00003904 OM.addPredicate<RegisterBankOperandMatcher>(
3905 Target.getRegisterClass(DstIOpRec));
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003906 ++OpIdx;
3907 }
3908
Daniel Sandersa7b75262017-10-31 18:50:24 +00003909 auto DstMIBuilderOrError = createAndImportInstructionRenderer(M, Dst);
Daniel Sandersffc7d582017-03-29 15:37:18 +00003910 if (auto Error = DstMIBuilderOrError.takeError())
3911 return std::move(Error);
3912 BuildMIAction &DstMIBuilder = DstMIBuilderOrError.get();
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003913
Daniel Sandersffc7d582017-03-29 15:37:18 +00003914 // Render the implicit defs.
3915 // These are only added to the root of the result.
Daniel Sandersc270c502017-03-30 09:36:33 +00003916 if (auto Error = importImplicitDefRenderers(DstMIBuilder, P.getDstRegs()))
Daniel Sandersffc7d582017-03-29 15:37:18 +00003917 return std::move(Error);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003918
Daniel Sandersa7b75262017-10-31 18:50:24 +00003919 DstMIBuilder.chooseInsnToMutate(M);
3920
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003921 // Constrain the registers to classes. This is normally derived from the
3922 // emitted instruction but a few instructions require special handling.
3923 if (DstI.TheDef->getName() == "COPY_TO_REGCLASS") {
3924 // COPY_TO_REGCLASS does not provide operand constraints itself but the
3925 // result is constrained to the class given by the second child.
3926 Record *DstIOpRec =
3927 getInitValueAsRegClass(Dst->getChild(1)->getLeafValue());
3928
3929 if (DstIOpRec == nullptr)
3930 return failedImport("COPY_TO_REGCLASS operand #1 isn't a register class");
3931
3932 M.addAction<ConstrainOperandToRegClassAction>(
Daniel Sandersd93a35a2017-07-05 09:39:33 +00003933 0, 0, Target.getRegisterClass(DstIOpRec));
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00003934
3935 // We're done with this pattern! It's eligible for GISel emission; return
3936 // it.
3937 ++NumPatternImported;
3938 return std::move(M);
3939 }
3940
3941 if (DstI.TheDef->getName() == "EXTRACT_SUBREG") {
3942 // EXTRACT_SUBREG selects into a subregister COPY but unlike most
3943 // instructions, the result register class is controlled by the
3944 // subregisters of the operand. As a result, we must constrain the result
3945 // class rather than check that it's already the right one.
3946 if (!Dst->getChild(0)->isLeaf())
3947 return failedImport("EXTRACT_SUBREG child #1 is not a leaf");
3948
Daniel Sanders320390b2017-06-28 15:16:03 +00003949 DefInit *SubRegInit = dyn_cast<DefInit>(Dst->getChild(1)->getLeafValue());
3950 if (!SubRegInit)
3951 return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00003952
Daniel Sanders320390b2017-06-28 15:16:03 +00003953 // Constrain the result to the same register bank as the operand.
3954 Record *DstIOpRec =
3955 getInitValueAsRegClass(Dst->getChild(0)->getLeafValue());
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00003956
Daniel Sanders320390b2017-06-28 15:16:03 +00003957 if (DstIOpRec == nullptr)
3958 return failedImport("EXTRACT_SUBREG operand #1 isn't a register class");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00003959
Daniel Sanders320390b2017-06-28 15:16:03 +00003960 CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef());
Daniel Sandersd93a35a2017-07-05 09:39:33 +00003961 CodeGenRegisterClass *SrcRC = CGRegs.getRegClass(DstIOpRec);
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00003962
Daniel Sanders320390b2017-06-28 15:16:03 +00003963 // It would be nice to leave this constraint implicit but we're required
3964 // to pick a register class so constrain the result to a register class
3965 // that can hold the correct MVT.
3966 //
3967 // FIXME: This may introduce an extra copy if the chosen class doesn't
3968 // actually contain the subregisters.
3969 assert(Src->getExtTypes().size() == 1 &&
3970 "Expected Src of EXTRACT_SUBREG to have one result type");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00003971
Daniel Sanders320390b2017-06-28 15:16:03 +00003972 const auto &SrcRCDstRCPair =
3973 SrcRC->getMatchingSubClassWithSubRegs(CGRegs, SubIdx);
3974 assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
Daniel Sandersd93a35a2017-07-05 09:39:33 +00003975 M.addAction<ConstrainOperandToRegClassAction>(0, 0, *SrcRCDstRCPair->second);
3976 M.addAction<ConstrainOperandToRegClassAction>(0, 1, *SrcRCDstRCPair->first);
3977
3978 // We're done with this pattern! It's eligible for GISel emission; return
3979 // it.
3980 ++NumPatternImported;
3981 return std::move(M);
3982 }
3983
3984 M.addAction<ConstrainOperandsToDefinitionAction>(0);
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003985
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003986 // We're done with this pattern! It's eligible for GISel emission; return it.
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00003987 ++NumPatternImported;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003988 return std::move(M);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003989}
3990
Daniel Sanders649c5852017-10-13 20:42:18 +00003991// Emit imm predicate table and an enum to reference them with.
3992// The 'Predicate_' part of the name is redundant but eliminating it is more
3993// trouble than it's worth.
3994void GlobalISelEmitter::emitImmPredicates(
Daniel Sanders11300ce2017-10-13 21:28:03 +00003995 raw_ostream &OS, StringRef TypeIdentifier, StringRef Type,
3996 std::function<bool(const Record *R)> Filter) {
Daniel Sanders649c5852017-10-13 20:42:18 +00003997 std::vector<const Record *> MatchedRecords;
3998 const auto &Defs = RK.getAllDerivedDefinitions("PatFrag");
3999 std::copy_if(Defs.begin(), Defs.end(), std::back_inserter(MatchedRecords),
4000 [&](Record *Record) {
4001 return !Record->getValueAsString("ImmediateCode").empty() &&
4002 Filter(Record);
4003 });
4004
Daniel Sanders11300ce2017-10-13 21:28:03 +00004005 if (!MatchedRecords.empty()) {
4006 OS << "// PatFrag predicates.\n"
4007 << "enum {\n";
Daniel Sanders2fed4ff2017-10-13 21:51:20 +00004008 std::string EnumeratorSeparator =
Daniel Sanders11300ce2017-10-13 21:28:03 +00004009 (" = GIPFP_" + TypeIdentifier + "_Invalid + 1,\n").str();
4010 for (const auto *Record : MatchedRecords) {
4011 OS << " GIPFP_" << TypeIdentifier << "_Predicate_" << Record->getName()
4012 << EnumeratorSeparator;
4013 EnumeratorSeparator = ",\n";
4014 }
4015 OS << "};\n";
Daniel Sanders649c5852017-10-13 20:42:18 +00004016 }
Daniel Sanders11300ce2017-10-13 21:28:03 +00004017
Daniel Sanders32de8bb2017-12-20 14:41:51 +00004018 OS << "bool " << Target.getName() << "InstructionSelector::testImmPredicate_"
Aaron Ballman82e17f52017-12-20 20:09:30 +00004019 << TypeIdentifier << "(unsigned PredicateID, " << Type
4020 << " Imm) const {\n";
4021 if (!MatchedRecords.empty())
4022 OS << " switch (PredicateID) {\n";
Daniel Sanders32de8bb2017-12-20 14:41:51 +00004023 for (const auto *Record : MatchedRecords) {
4024 OS << " case GIPFP_" << TypeIdentifier << "_Predicate_"
4025 << Record->getName() << ": {\n"
4026 << " " << Record->getValueAsString("ImmediateCode") << "\n"
4027 << " llvm_unreachable(\"ImmediateCode should have returned\");\n"
4028 << " return false;\n"
4029 << " }\n";
4030 }
Aaron Ballman82e17f52017-12-20 20:09:30 +00004031 if (!MatchedRecords.empty())
4032 OS << " }\n";
4033 OS << " llvm_unreachable(\"Unknown predicate\");\n"
Daniel Sanders32de8bb2017-12-20 14:41:51 +00004034 << " return false;\n"
4035 << "}\n";
Daniel Sanders649c5852017-10-13 20:42:18 +00004036}
4037
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004038template <class GroupT>
Quentin Colombetec76d9c2017-12-18 19:47:41 +00004039std::vector<Matcher *> GlobalISelEmitter::optimizeRules(
Roman Tereshin2d6d3762018-05-02 20:08:14 +00004040 ArrayRef<Matcher *> Rules,
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004041 std::vector<std::unique_ptr<Matcher>> &MatcherStorage) {
4042
Quentin Colombetec76d9c2017-12-18 19:47:41 +00004043 std::vector<Matcher *> OptRules;
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004044 std::unique_ptr<GroupT> CurrentGroup = make_unique<GroupT>();
4045 assert(CurrentGroup->empty() && "Newly created group isn't empty!");
4046 unsigned NumGroups = 0;
4047
4048 auto ProcessCurrentGroup = [&]() {
4049 if (CurrentGroup->empty())
4050 // An empty group is good to be reused:
4051 return;
4052
4053 // If the group isn't large enough to provide any benefit, move all the
4054 // added rules out of it and make sure to re-create the group to properly
4055 // re-initialize it:
4056 if (CurrentGroup->size() < 2)
4057 for (Matcher *M : CurrentGroup->matchers())
4058 OptRules.push_back(M);
4059 else {
4060 CurrentGroup->finalize();
Roman Tereshin8bdf7be2018-05-21 22:21:24 +00004061 OptRules.push_back(CurrentGroup.get());
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004062 MatcherStorage.emplace_back(std::move(CurrentGroup));
4063 ++NumGroups;
Roman Tereshin8bdf7be2018-05-21 22:21:24 +00004064 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004065 CurrentGroup = make_unique<GroupT>();
4066 };
4067 for (Matcher *Rule : Rules) {
4068 // Greedily add as many matchers as possible to the current group:
4069 if (CurrentGroup->addMatcher(*Rule))
4070 continue;
4071
4072 ProcessCurrentGroup();
4073 assert(CurrentGroup->empty() && "A group wasn't properly re-initialized");
4074
4075 // Try to add the pending matcher to a newly created empty group:
4076 if (!CurrentGroup->addMatcher(*Rule))
4077 // If we couldn't add the matcher to an empty group, that group type
4078 // doesn't support that kind of matchers at all, so just skip it:
4079 OptRules.push_back(Rule);
Quentin Colombetec76d9c2017-12-18 19:47:41 +00004080 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004081 ProcessCurrentGroup();
4082
Nicola Zaghen03d0b912018-05-23 15:09:29 +00004083 LLVM_DEBUG(dbgs() << "NumGroups: " << NumGroups << "\n");
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004084 assert(CurrentGroup->empty() && "The last group wasn't properly processed");
Quentin Colombetec76d9c2017-12-18 19:47:41 +00004085 return OptRules;
4086}
4087
Roman Tereshin2d6d3762018-05-02 20:08:14 +00004088MatchTable
4089GlobalISelEmitter::buildMatchTable(MutableArrayRef<RuleMatcher> Rules,
Roman Tereshinbeb39312018-05-02 20:15:11 +00004090 bool Optimize, bool WithCoverage) {
Roman Tereshin2d6d3762018-05-02 20:08:14 +00004091 std::vector<Matcher *> InputRules;
4092 for (Matcher &Rule : Rules)
4093 InputRules.push_back(&Rule);
4094
4095 if (!Optimize)
Roman Tereshinbeb39312018-05-02 20:15:11 +00004096 return MatchTable::buildTable(InputRules, WithCoverage);
Roman Tereshin2d6d3762018-05-02 20:08:14 +00004097
Roman Tereshin77013602018-05-22 16:54:27 +00004098 unsigned CurrentOrdering = 0;
4099 StringMap<unsigned> OpcodeOrder;
4100 for (RuleMatcher &Rule : Rules) {
4101 const StringRef Opcode = Rule.getOpcode();
4102 assert(!Opcode.empty() && "Didn't expect an undefined opcode");
4103 if (OpcodeOrder.count(Opcode) == 0)
4104 OpcodeOrder[Opcode] = CurrentOrdering++;
4105 }
4106
4107 std::stable_sort(InputRules.begin(), InputRules.end(),
4108 [&OpcodeOrder](const Matcher *A, const Matcher *B) {
4109 auto *L = static_cast<const RuleMatcher *>(A);
4110 auto *R = static_cast<const RuleMatcher *>(B);
4111 return std::make_tuple(OpcodeOrder[L->getOpcode()],
4112 L->getNumOperands()) <
4113 std::make_tuple(OpcodeOrder[R->getOpcode()],
4114 R->getNumOperands());
4115 });
4116
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004117 for (Matcher *Rule : InputRules)
4118 Rule->optimize();
4119
4120 std::vector<std::unique_ptr<Matcher>> MatcherStorage;
Roman Tereshin2d6d3762018-05-02 20:08:14 +00004121 std::vector<Matcher *> OptRules =
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004122 optimizeRules<GroupMatcher>(InputRules, MatcherStorage);
4123
4124 for (Matcher *Rule : OptRules)
4125 Rule->optimize();
Roman Tereshin2d6d3762018-05-02 20:08:14 +00004126
Roman Tereshin0ee082f2018-05-22 19:37:59 +00004127 OptRules = optimizeRules<SwitchMatcher>(OptRules, MatcherStorage);
4128
Roman Tereshinbeb39312018-05-02 20:15:11 +00004129 return MatchTable::buildTable(OptRules, WithCoverage);
Roman Tereshin2d6d3762018-05-02 20:08:14 +00004130}
4131
Roman Tereshinfedae332018-05-23 02:04:19 +00004132void GroupMatcher::optimize() {
Roman Tereshin9a9fa492018-05-23 21:30:16 +00004133 // Make sure we only sort by a specific predicate within a range of rules that
4134 // all have that predicate checked against a specific value (not a wildcard):
4135 auto F = Matchers.begin();
4136 auto T = F;
4137 auto E = Matchers.end();
4138 while (T != E) {
4139 while (T != E) {
4140 auto *R = static_cast<RuleMatcher *>(*T);
4141 if (!R->getFirstConditionAsRootType().get().isValid())
4142 break;
4143 ++T;
4144 }
4145 std::stable_sort(F, T, [](Matcher *A, Matcher *B) {
4146 auto *L = static_cast<RuleMatcher *>(A);
4147 auto *R = static_cast<RuleMatcher *>(B);
4148 return L->getFirstConditionAsRootType() <
4149 R->getFirstConditionAsRootType();
4150 });
4151 if (T != E)
4152 F = ++T;
4153 }
Roman Tereshinfedae332018-05-23 02:04:19 +00004154 GlobalISelEmitter::optimizeRules<GroupMatcher>(Matchers, MatcherStorage)
4155 .swap(Matchers);
Roman Tereshina4c410d2018-05-24 00:24:15 +00004156 GlobalISelEmitter::optimizeRules<SwitchMatcher>(Matchers, MatcherStorage)
4157 .swap(Matchers);
Roman Tereshinfedae332018-05-23 02:04:19 +00004158}
4159
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004160void GlobalISelEmitter::run(raw_ostream &OS) {
Daniel Sandersf76f3152017-11-16 00:46:35 +00004161 if (!UseCoverageFile.empty()) {
4162 RuleCoverage = CodeGenCoverage();
4163 auto RuleCoverageBufOrErr = MemoryBuffer::getFile(UseCoverageFile);
4164 if (!RuleCoverageBufOrErr) {
4165 PrintWarning(SMLoc(), "Missing rule coverage data");
4166 RuleCoverage = None;
4167 } else {
4168 if (!RuleCoverage->parse(*RuleCoverageBufOrErr.get(), Target.getName())) {
4169 PrintWarning(SMLoc(), "Ignoring invalid or missing rule coverage data");
4170 RuleCoverage = None;
4171 }
4172 }
4173 }
4174
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004175 // Track the run-time opcode values
4176 gatherOpcodeValues();
4177 // Track the run-time LLT ID values
4178 gatherTypeIDValues();
4179
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004180 // Track the GINodeEquiv definitions.
4181 gatherNodeEquivs();
4182
4183 emitSourceFileHeader(("Global Instruction Selector for the " +
4184 Target.getName() + " target").str(), OS);
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00004185 std::vector<RuleMatcher> Rules;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004186 // Look through the SelectionDAG patterns we found, possibly emitting some.
4187 for (const PatternToMatch &Pat : CGP.ptms()) {
4188 ++NumPatternTotal;
Daniel Sanders7e523672017-11-11 03:23:44 +00004189
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00004190 auto MatcherOrErr = runOnPattern(Pat);
4191
4192 // The pattern analysis can fail, indicating an unsupported pattern.
4193 // Report that if we've been asked to do so.
4194 if (auto Err = MatcherOrErr.takeError()) {
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004195 if (WarnOnSkippedPatterns) {
4196 PrintWarning(Pat.getSrcRecord()->getLoc(),
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00004197 "Skipped pattern: " + toString(std::move(Err)));
4198 } else {
4199 consumeError(std::move(Err));
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004200 }
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00004201 ++NumPatternImportsSkipped;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00004202 continue;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004203 }
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00004204
Daniel Sandersf76f3152017-11-16 00:46:35 +00004205 if (RuleCoverage) {
4206 if (RuleCoverage->isCovered(MatcherOrErr->getRuleID()))
4207 ++NumPatternsTested;
4208 else
4209 PrintWarning(Pat.getSrcRecord()->getLoc(),
4210 "Pattern is not covered by a test");
4211 }
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00004212 Rules.push_back(std::move(MatcherOrErr.get()));
4213 }
4214
Volkan Kelesf7f25682018-01-16 18:44:05 +00004215 // Comparison function to order records by name.
4216 auto orderByName = [](const Record *A, const Record *B) {
4217 return A->getName() < B->getName();
4218 };
4219
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00004220 std::vector<Record *> ComplexPredicates =
4221 RK.getAllDerivedDefinitions("GIComplexOperandMatcher");
Mandeep Singh Grang1b0e2f22018-04-06 20:18:05 +00004222 llvm::sort(ComplexPredicates.begin(), ComplexPredicates.end(), orderByName);
Volkan Kelesf7f25682018-01-16 18:44:05 +00004223
4224 std::vector<Record *> CustomRendererFns =
4225 RK.getAllDerivedDefinitions("GICustomOperandRenderer");
Mandeep Singh Grang1b0e2f22018-04-06 20:18:05 +00004226 llvm::sort(CustomRendererFns.begin(), CustomRendererFns.end(), orderByName);
Volkan Kelesf7f25682018-01-16 18:44:05 +00004227
Daniel Sanders8a4bae92017-03-14 21:32:08 +00004228 unsigned MaxTemporaries = 0;
4229 for (const auto &Rule : Rules)
Daniel Sanders2deea182017-04-22 15:11:04 +00004230 MaxTemporaries = std::max(MaxTemporaries, Rule.countRendererFns());
Daniel Sanders8a4bae92017-03-14 21:32:08 +00004231
Daniel Sanderse7b0d662017-04-21 15:59:56 +00004232 OS << "#ifdef GET_GLOBALISEL_PREDICATE_BITSET\n"
4233 << "const unsigned MAX_SUBTARGET_PREDICATES = " << SubtargetFeatures.size()
4234 << ";\n"
4235 << "using PredicateBitset = "
4236 "llvm::PredicateBitsetImpl<MAX_SUBTARGET_PREDICATES>;\n"
4237 << "#endif // ifdef GET_GLOBALISEL_PREDICATE_BITSET\n\n";
4238
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00004239 OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n"
4240 << " mutable MatcherState State;\n"
4241 << " typedef "
Daniel Sanders1e4569f2017-10-20 20:55:29 +00004242 "ComplexRendererFns("
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00004243 << Target.getName()
4244 << "InstructionSelector::*ComplexMatcherMemFn)(MachineOperand &) const;\n"
Volkan Kelesf7f25682018-01-16 18:44:05 +00004245
4246 << " typedef void(" << Target.getName()
4247 << "InstructionSelector::*CustomRendererFn)(MachineInstrBuilder &, const "
4248 "MachineInstr&) "
4249 "const;\n"
4250 << " const ISelInfoTy<PredicateBitset, ComplexMatcherMemFn, "
4251 "CustomRendererFn> "
4252 "ISelInfo;\n";
4253 OS << " static " << Target.getName()
Daniel Sandersea8711b2017-10-16 03:36:29 +00004254 << "InstructionSelector::ComplexMatcherMemFn ComplexPredicateFns[];\n"
Volkan Kelesf7f25682018-01-16 18:44:05 +00004255 << " static " << Target.getName()
4256 << "InstructionSelector::CustomRendererFn CustomRenderers[];\n"
Roman Tereshin2df4c222018-05-02 20:07:15 +00004257 << " bool testImmPredicate_I64(unsigned PredicateID, int64_t Imm) const "
Daniel Sanders32de8bb2017-12-20 14:41:51 +00004258 "override;\n"
Roman Tereshin2df4c222018-05-02 20:07:15 +00004259 << " bool testImmPredicate_APInt(unsigned PredicateID, const APInt &Imm) "
Daniel Sanders32de8bb2017-12-20 14:41:51 +00004260 "const override;\n"
Roman Tereshin2df4c222018-05-02 20:07:15 +00004261 << " bool testImmPredicate_APFloat(unsigned PredicateID, const APFloat "
Daniel Sanders32de8bb2017-12-20 14:41:51 +00004262 "&Imm) const override;\n"
Roman Tereshin2df4c222018-05-02 20:07:15 +00004263 << " const int64_t *getMatchTable() const override;\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00004264 << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n\n";
Daniel Sanders8a4bae92017-03-14 21:32:08 +00004265
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00004266 OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n"
4267 << ", State(" << MaxTemporaries << "),\n"
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004268 << "ISelInfo(TypeObjects, NumTypeObjects, FeatureBitsets"
4269 << ", ComplexPredicateFns, CustomRenderers)\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00004270 << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n\n";
Daniel Sanders8a4bae92017-03-14 21:32:08 +00004271
Daniel Sanderse7b0d662017-04-21 15:59:56 +00004272 OS << "#ifdef GET_GLOBALISEL_IMPL\n";
4273 SubtargetFeatureInfo::emitSubtargetFeatureBitEnumeration(SubtargetFeatures,
4274 OS);
Daniel Sanderse9fdba32017-04-29 17:30:09 +00004275
4276 // Separate subtarget features by how often they must be recomputed.
4277 SubtargetFeatureInfoMap ModuleFeatures;
4278 std::copy_if(SubtargetFeatures.begin(), SubtargetFeatures.end(),
4279 std::inserter(ModuleFeatures, ModuleFeatures.end()),
4280 [](const SubtargetFeatureInfoMap::value_type &X) {
4281 return !X.second.mustRecomputePerFunction();
4282 });
4283 SubtargetFeatureInfoMap FunctionFeatures;
4284 std::copy_if(SubtargetFeatures.begin(), SubtargetFeatures.end(),
4285 std::inserter(FunctionFeatures, FunctionFeatures.end()),
4286 [](const SubtargetFeatureInfoMap::value_type &X) {
4287 return X.second.mustRecomputePerFunction();
4288 });
4289
Daniel Sanderse7b0d662017-04-21 15:59:56 +00004290 SubtargetFeatureInfo::emitComputeAvailableFeatures(
Daniel Sanderse9fdba32017-04-29 17:30:09 +00004291 Target.getName(), "InstructionSelector", "computeAvailableModuleFeatures",
4292 ModuleFeatures, OS);
4293 SubtargetFeatureInfo::emitComputeAvailableFeatures(
4294 Target.getName(), "InstructionSelector",
4295 "computeAvailableFunctionFeatures", FunctionFeatures, OS,
4296 "const MachineFunction *MF");
Daniel Sanderse7b0d662017-04-21 15:59:56 +00004297
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00004298 // Emit a table containing the LLT objects needed by the matcher and an enum
4299 // for the matcher to reference them with.
Daniel Sanders032e7f22017-08-17 13:18:35 +00004300 std::vector<LLTCodeGen> TypeObjects;
Daniel Sandersf84bc372018-05-05 20:53:24 +00004301 for (const auto &Ty : KnownTypes)
Daniel Sanders032e7f22017-08-17 13:18:35 +00004302 TypeObjects.push_back(Ty);
Mandeep Singh Grang1b0e2f22018-04-06 20:18:05 +00004303 llvm::sort(TypeObjects.begin(), TypeObjects.end());
Daniel Sanders49980702017-08-23 10:09:25 +00004304 OS << "// LLT Objects.\n"
4305 << "enum {\n";
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00004306 for (const auto &TypeObject : TypeObjects) {
4307 OS << " ";
4308 TypeObject.emitCxxEnumValue(OS);
4309 OS << ",\n";
4310 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004311 OS << "};\n";
4312 OS << "const static size_t NumTypeObjects = " << TypeObjects.size() << ";\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00004313 << "const static LLT TypeObjects[] = {\n";
4314 for (const auto &TypeObject : TypeObjects) {
4315 OS << " ";
4316 TypeObject.emitCxxConstructorCall(OS);
4317 OS << ",\n";
4318 }
4319 OS << "};\n\n";
4320
4321 // Emit a table containing the PredicateBitsets objects needed by the matcher
4322 // and an enum for the matcher to reference them with.
4323 std::vector<std::vector<Record *>> FeatureBitsets;
4324 for (auto &Rule : Rules)
4325 FeatureBitsets.push_back(Rule.getRequiredFeatures());
Mandeep Singh Grang1b0e2f22018-04-06 20:18:05 +00004326 llvm::sort(
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00004327 FeatureBitsets.begin(), FeatureBitsets.end(),
4328 [&](const std::vector<Record *> &A, const std::vector<Record *> &B) {
4329 if (A.size() < B.size())
4330 return true;
4331 if (A.size() > B.size())
4332 return false;
4333 for (const auto &Pair : zip(A, B)) {
4334 if (std::get<0>(Pair)->getName() < std::get<1>(Pair)->getName())
4335 return true;
4336 if (std::get<0>(Pair)->getName() > std::get<1>(Pair)->getName())
4337 return false;
4338 }
4339 return false;
4340 });
4341 FeatureBitsets.erase(
4342 std::unique(FeatureBitsets.begin(), FeatureBitsets.end()),
4343 FeatureBitsets.end());
Daniel Sanders49980702017-08-23 10:09:25 +00004344 OS << "// Feature bitsets.\n"
4345 << "enum {\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00004346 << " GIFBS_Invalid,\n";
4347 for (const auto &FeatureBitset : FeatureBitsets) {
4348 if (FeatureBitset.empty())
4349 continue;
4350 OS << " " << getNameForFeatureBitset(FeatureBitset) << ",\n";
4351 }
4352 OS << "};\n"
4353 << "const static PredicateBitset FeatureBitsets[] {\n"
4354 << " {}, // GIFBS_Invalid\n";
4355 for (const auto &FeatureBitset : FeatureBitsets) {
4356 if (FeatureBitset.empty())
4357 continue;
4358 OS << " {";
4359 for (const auto &Feature : FeatureBitset) {
4360 const auto &I = SubtargetFeatures.find(Feature);
4361 assert(I != SubtargetFeatures.end() && "Didn't import predicate?");
4362 OS << I->second.getEnumBitName() << ", ";
4363 }
4364 OS << "},\n";
4365 }
4366 OS << "};\n\n";
4367
4368 // Emit complex predicate table and an enum to reference them with.
Daniel Sanders49980702017-08-23 10:09:25 +00004369 OS << "// ComplexPattern predicates.\n"
4370 << "enum {\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00004371 << " GICP_Invalid,\n";
4372 for (const auto &Record : ComplexPredicates)
4373 OS << " GICP_" << Record->getName() << ",\n";
4374 OS << "};\n"
4375 << "// See constructor for table contents\n\n";
4376
Daniel Sanders11300ce2017-10-13 21:28:03 +00004377 emitImmPredicates(OS, "I64", "int64_t", [](const Record *R) {
Daniel Sanders649c5852017-10-13 20:42:18 +00004378 bool Unset;
4379 return !R->getValueAsBitOrUnset("IsAPFloat", Unset) &&
4380 !R->getValueAsBit("IsAPInt");
4381 });
Daniel Sanders11300ce2017-10-13 21:28:03 +00004382 emitImmPredicates(OS, "APFloat", "const APFloat &", [](const Record *R) {
4383 bool Unset;
4384 return R->getValueAsBitOrUnset("IsAPFloat", Unset);
4385 });
4386 emitImmPredicates(OS, "APInt", "const APInt &", [](const Record *R) {
4387 return R->getValueAsBit("IsAPInt");
4388 });
Daniel Sandersea8711b2017-10-16 03:36:29 +00004389 OS << "\n";
4390
4391 OS << Target.getName() << "InstructionSelector::ComplexMatcherMemFn\n"
4392 << Target.getName() << "InstructionSelector::ComplexPredicateFns[] = {\n"
4393 << " nullptr, // GICP_Invalid\n";
4394 for (const auto &Record : ComplexPredicates)
4395 OS << " &" << Target.getName()
4396 << "InstructionSelector::" << Record->getValueAsString("MatcherFn")
4397 << ", // " << Record->getName() << "\n";
4398 OS << "};\n\n";
Daniel Sanders2c269f62017-08-24 09:11:20 +00004399
Volkan Kelesf7f25682018-01-16 18:44:05 +00004400 OS << "// Custom renderers.\n"
4401 << "enum {\n"
4402 << " GICR_Invalid,\n";
4403 for (const auto &Record : CustomRendererFns)
4404 OS << " GICR_" << Record->getValueAsString("RendererFn") << ", \n";
4405 OS << "};\n";
4406
4407 OS << Target.getName() << "InstructionSelector::CustomRendererFn\n"
4408 << Target.getName() << "InstructionSelector::CustomRenderers[] = {\n"
4409 << " nullptr, // GICP_Invalid\n";
4410 for (const auto &Record : CustomRendererFns)
4411 OS << " &" << Target.getName()
4412 << "InstructionSelector::" << Record->getValueAsString("RendererFn")
4413 << ", // " << Record->getName() << "\n";
4414 OS << "};\n\n";
4415
Quentin Colombetec76d9c2017-12-18 19:47:41 +00004416 std::stable_sort(Rules.begin(), Rules.end(), [&](const RuleMatcher &A,
4417 const RuleMatcher &B) {
Aditya Nandakumarb63e7632018-02-16 22:37:15 +00004418 int ScoreA = RuleMatcherScores[A.getRuleID()];
4419 int ScoreB = RuleMatcherScores[B.getRuleID()];
4420 if (ScoreA > ScoreB)
4421 return true;
4422 if (ScoreB > ScoreA)
4423 return false;
Quentin Colombetec76d9c2017-12-18 19:47:41 +00004424 if (A.isHigherPriorityThan(B)) {
4425 assert(!B.isHigherPriorityThan(A) && "Cannot be more important "
4426 "and less important at "
4427 "the same time");
4428 return true;
4429 }
4430 return false;
4431 });
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004432
Roman Tereshin2df4c222018-05-02 20:07:15 +00004433 OS << "bool " << Target.getName()
4434 << "InstructionSelector::selectImpl(MachineInstr &I, CodeGenCoverage "
4435 "&CoverageInfo) const {\n"
4436 << " MachineFunction &MF = *I.getParent()->getParent();\n"
4437 << " MachineRegisterInfo &MRI = MF.getRegInfo();\n"
4438 << " // FIXME: This should be computed on a per-function basis rather "
4439 "than per-insn.\n"
4440 << " AvailableFunctionFeatures = computeAvailableFunctionFeatures(&STI, "
4441 "&MF);\n"
4442 << " const PredicateBitset AvailableFeatures = getAvailableFeatures();\n"
4443 << " NewMIVector OutMIs;\n"
4444 << " State.MIs.clear();\n"
4445 << " State.MIs.push_back(&I);\n\n"
4446 << " if (executeMatchTable(*this, OutMIs, State, ISelInfo"
4447 << ", getMatchTable(), TII, MRI, TRI, RBI, AvailableFeatures"
4448 << ", CoverageInfo)) {\n"
4449 << " return true;\n"
4450 << " }\n\n"
4451 << " return false;\n"
4452 << "}\n\n";
4453
Roman Tereshinbeb39312018-05-02 20:15:11 +00004454 const MatchTable Table =
4455 buildMatchTable(Rules, OptimizeMatchTable, GenerateCoverage);
Roman Tereshin2df4c222018-05-02 20:07:15 +00004456 OS << "const int64_t *" << Target.getName()
4457 << "InstructionSelector::getMatchTable() const {\n";
4458 Table.emitDeclaration(OS);
4459 OS << " return ";
4460 Table.emitUse(OS);
4461 OS << ";\n}\n";
4462 OS << "#endif // ifdef GET_GLOBALISEL_IMPL\n";
Daniel Sanderse9fdba32017-04-29 17:30:09 +00004463
4464 OS << "#ifdef GET_GLOBALISEL_PREDICATES_DECL\n"
4465 << "PredicateBitset AvailableModuleFeatures;\n"
4466 << "mutable PredicateBitset AvailableFunctionFeatures;\n"
4467 << "PredicateBitset getAvailableFeatures() const {\n"
4468 << " return AvailableModuleFeatures | AvailableFunctionFeatures;\n"
4469 << "}\n"
4470 << "PredicateBitset\n"
4471 << "computeAvailableModuleFeatures(const " << Target.getName()
4472 << "Subtarget *Subtarget) const;\n"
4473 << "PredicateBitset\n"
4474 << "computeAvailableFunctionFeatures(const " << Target.getName()
4475 << "Subtarget *Subtarget,\n"
4476 << " const MachineFunction *MF) const;\n"
4477 << "#endif // ifdef GET_GLOBALISEL_PREDICATES_DECL\n";
4478
4479 OS << "#ifdef GET_GLOBALISEL_PREDICATES_INIT\n"
4480 << "AvailableModuleFeatures(computeAvailableModuleFeatures(&STI)),\n"
4481 << "AvailableFunctionFeatures()\n"
4482 << "#endif // ifdef GET_GLOBALISEL_PREDICATES_INIT\n";
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004483}
4484
Daniel Sanderse7b0d662017-04-21 15:59:56 +00004485void GlobalISelEmitter::declareSubtargetFeature(Record *Predicate) {
4486 if (SubtargetFeatures.count(Predicate) == 0)
4487 SubtargetFeatures.emplace(
4488 Predicate, SubtargetFeatureInfo(Predicate, SubtargetFeatures.size()));
4489}
4490
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004491void RuleMatcher::optimize() {
4492 for (auto &Item : InsnVariableIDs) {
4493 InstructionMatcher &InsnMatcher = *Item.first;
4494 for (auto &OM : InsnMatcher.operands()) {
Roman Tereshin5f5e5502018-05-23 23:58:10 +00004495 // Complex Patterns are usually expensive and they relatively rarely fail
4496 // on their own: more often we end up throwing away all the work done by a
4497 // matching part of a complex pattern because some other part of the
4498 // enclosing pattern didn't match. All of this makes it beneficial to
4499 // delay complex patterns until the very end of the rule matching,
4500 // especially for targets having lots of complex patterns.
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004501 for (auto &OP : OM->predicates())
Roman Tereshin5f5e5502018-05-23 23:58:10 +00004502 if (isa<ComplexPatternOperandMatcher>(OP))
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004503 EpilogueMatchers.emplace_back(std::move(OP));
4504 OM->eraseNullPredicates();
4505 }
4506 InsnMatcher.optimize();
Quentin Colombetec76d9c2017-12-18 19:47:41 +00004507 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004508 llvm::sort(
4509 EpilogueMatchers.begin(), EpilogueMatchers.end(),
4510 [](const std::unique_ptr<PredicateMatcher> &L,
4511 const std::unique_ptr<PredicateMatcher> &R) {
4512 return std::make_tuple(L->getKind(), L->getInsnVarID(), L->getOpIdx()) <
4513 std::make_tuple(R->getKind(), R->getInsnVarID(), R->getOpIdx());
4514 });
Quentin Colombetec76d9c2017-12-18 19:47:41 +00004515}
4516
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004517bool RuleMatcher::hasFirstCondition() const {
4518 if (insnmatchers_empty())
4519 return false;
4520 InstructionMatcher &Matcher = insnmatchers_front();
4521 if (!Matcher.predicates_empty())
4522 return true;
4523 for (auto &OM : Matcher.operands())
4524 for (auto &OP : OM->predicates())
4525 if (!isa<InstructionOperandMatcher>(OP))
4526 return true;
4527 return false;
4528}
4529
4530const PredicateMatcher &RuleMatcher::getFirstCondition() const {
4531 assert(!insnmatchers_empty() &&
4532 "Trying to get a condition from an empty RuleMatcher");
4533
4534 InstructionMatcher &Matcher = insnmatchers_front();
4535 if (!Matcher.predicates_empty())
4536 return **Matcher.predicates_begin();
4537 // If there is no more predicate on the instruction itself, look at its
4538 // operands.
4539 for (auto &OM : Matcher.operands())
4540 for (auto &OP : OM->predicates())
4541 if (!isa<InstructionOperandMatcher>(OP))
4542 return *OP;
4543
4544 llvm_unreachable("Trying to get a condition from an InstructionMatcher with "
4545 "no conditions");
4546}
4547
4548std::unique_ptr<PredicateMatcher> RuleMatcher::popFirstCondition() {
4549 assert(!insnmatchers_empty() &&
4550 "Trying to pop a condition from an empty RuleMatcher");
4551
4552 InstructionMatcher &Matcher = insnmatchers_front();
4553 if (!Matcher.predicates_empty())
4554 return Matcher.predicates_pop_front();
4555 // If there is no more predicate on the instruction itself, look at its
4556 // operands.
4557 for (auto &OM : Matcher.operands())
4558 for (auto &OP : OM->predicates())
4559 if (!isa<InstructionOperandMatcher>(OP)) {
4560 std::unique_ptr<PredicateMatcher> Result = std::move(OP);
4561 OM->eraseNullPredicates();
4562 return Result;
4563 }
4564
4565 llvm_unreachable("Trying to pop a condition from an InstructionMatcher with "
4566 "no conditions");
4567}
4568
4569bool GroupMatcher::candidateConditionMatches(
Quentin Colombetec76d9c2017-12-18 19:47:41 +00004570 const PredicateMatcher &Predicate) const {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004571
4572 if (empty()) {
4573 // Sharing predicates for nested instructions is not supported yet as we
4574 // currently don't hoist the GIM_RecordInsn's properly, therefore we can
4575 // only work on the original root instruction (InsnVarID == 0):
4576 if (Predicate.getInsnVarID() != 0)
4577 return false;
4578 // ... otherwise an empty group can handle any predicate with no specific
4579 // requirements:
4580 return true;
4581 }
4582
4583 const Matcher &Representative = **Matchers.begin();
4584 const auto &RepresentativeCondition = Representative.getFirstCondition();
4585 // ... if not empty, the group can only accomodate matchers with the exact
4586 // same first condition:
4587 return Predicate.isIdentical(RepresentativeCondition);
4588}
4589
4590bool GroupMatcher::addMatcher(Matcher &Candidate) {
4591 if (!Candidate.hasFirstCondition())
4592 return false;
4593
4594 const PredicateMatcher &Predicate = Candidate.getFirstCondition();
4595 if (!candidateConditionMatches(Predicate))
4596 return false;
4597
4598 Matchers.push_back(&Candidate);
4599 return true;
4600}
4601
4602void GroupMatcher::finalize() {
4603 assert(Conditions.empty() && "Already finalized?");
4604 if (empty())
4605 return;
4606
4607 Matcher &FirstRule = **Matchers.begin();
Roman Tereshin152fc162018-05-23 22:50:53 +00004608 for (;;) {
4609 // All the checks are expected to succeed during the first iteration:
4610 for (const auto &Rule : Matchers)
4611 if (!Rule->hasFirstCondition())
4612 return;
4613 const auto &FirstCondition = FirstRule.getFirstCondition();
4614 for (unsigned I = 1, E = Matchers.size(); I < E; ++I)
4615 if (!Matchers[I]->getFirstCondition().isIdentical(FirstCondition))
4616 return;
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004617
Roman Tereshin152fc162018-05-23 22:50:53 +00004618 Conditions.push_back(FirstRule.popFirstCondition());
4619 for (unsigned I = 1, E = Matchers.size(); I < E; ++I)
4620 Matchers[I]->popFirstCondition();
4621 }
Quentin Colombetec76d9c2017-12-18 19:47:41 +00004622}
4623
4624void GroupMatcher::emit(MatchTable &Table) {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004625 unsigned LabelID = ~0U;
4626 if (!Conditions.empty()) {
4627 LabelID = Table.allocateLabelID();
Quentin Colombetec76d9c2017-12-18 19:47:41 +00004628 Table << MatchTable::Opcode("GIM_Try", +1)
4629 << MatchTable::Comment("On fail goto")
4630 << MatchTable::JumpTarget(LabelID) << MatchTable::LineBreak;
Quentin Colombetec76d9c2017-12-18 19:47:41 +00004631 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004632 for (auto &Condition : Conditions)
4633 Condition->emitPredicateOpcodes(
4634 Table, *static_cast<RuleMatcher *>(*Matchers.begin()));
4635
4636 for (const auto &M : Matchers)
4637 M->emit(Table);
4638
4639 // Exit the group
4640 if (!Conditions.empty())
4641 Table << MatchTable::Opcode("GIM_Reject", -1) << MatchTable::LineBreak
Quentin Colombetec76d9c2017-12-18 19:47:41 +00004642 << MatchTable::Label(LabelID);
Quentin Colombetec76d9c2017-12-18 19:47:41 +00004643}
4644
Roman Tereshin0ee082f2018-05-22 19:37:59 +00004645bool SwitchMatcher::isSupportedPredicateType(const PredicateMatcher &P) {
Roman Tereshina4c410d2018-05-24 00:24:15 +00004646 return isa<InstructionOpcodeMatcher>(P) || isa<LLTOperandMatcher>(P);
Roman Tereshin0ee082f2018-05-22 19:37:59 +00004647}
4648
4649bool SwitchMatcher::candidateConditionMatches(
4650 const PredicateMatcher &Predicate) const {
4651
4652 if (empty()) {
4653 // Sharing predicates for nested instructions is not supported yet as we
4654 // currently don't hoist the GIM_RecordInsn's properly, therefore we can
4655 // only work on the original root instruction (InsnVarID == 0):
4656 if (Predicate.getInsnVarID() != 0)
4657 return false;
4658 // ... while an attempt to add even a root matcher to an empty SwitchMatcher
4659 // could fail as not all the types of conditions are supported:
4660 if (!isSupportedPredicateType(Predicate))
4661 return false;
4662 // ... or the condition might not have a proper implementation of
4663 // getValue() / isIdenticalDownToValue() yet:
4664 if (!Predicate.hasValue())
4665 return false;
4666 // ... otherwise an empty Switch can accomodate the condition with no
4667 // further requirements:
4668 return true;
4669 }
4670
4671 const Matcher &CaseRepresentative = **Matchers.begin();
4672 const auto &RepresentativeCondition = CaseRepresentative.getFirstCondition();
4673 // Switch-cases must share the same kind of condition and path to the value it
4674 // checks:
4675 if (!Predicate.isIdenticalDownToValue(RepresentativeCondition))
4676 return false;
4677
4678 const auto Value = Predicate.getValue();
4679 // ... but be unique with respect to the actual value they check:
4680 return Values.count(Value) == 0;
4681}
4682
4683bool SwitchMatcher::addMatcher(Matcher &Candidate) {
4684 if (!Candidate.hasFirstCondition())
4685 return false;
4686
4687 const PredicateMatcher &Predicate = Candidate.getFirstCondition();
4688 if (!candidateConditionMatches(Predicate))
4689 return false;
4690 const auto Value = Predicate.getValue();
4691 Values.insert(Value);
4692
4693 Matchers.push_back(&Candidate);
4694 return true;
4695}
4696
4697void SwitchMatcher::finalize() {
4698 assert(Condition == nullptr && "Already finalized");
4699 assert(Values.size() == Matchers.size() && "Broken SwitchMatcher");
4700 if (empty())
4701 return;
4702
4703 std::stable_sort(Matchers.begin(), Matchers.end(),
4704 [](const Matcher *L, const Matcher *R) {
4705 return L->getFirstCondition().getValue() <
4706 R->getFirstCondition().getValue();
4707 });
4708 Condition = Matchers[0]->popFirstCondition();
4709 for (unsigned I = 1, E = Values.size(); I < E; ++I)
4710 Matchers[I]->popFirstCondition();
4711}
4712
4713void SwitchMatcher::emitPredicateSpecificOpcodes(const PredicateMatcher &P,
4714 MatchTable &Table) {
4715 assert(isSupportedPredicateType(P) && "Predicate type is not supported");
4716
4717 if (const auto *Condition = dyn_cast<InstructionOpcodeMatcher>(&P)) {
4718 Table << MatchTable::Opcode("GIM_SwitchOpcode") << MatchTable::Comment("MI")
4719 << MatchTable::IntValue(Condition->getInsnVarID());
4720 return;
4721 }
Roman Tereshina4c410d2018-05-24 00:24:15 +00004722 if (const auto *Condition = dyn_cast<LLTOperandMatcher>(&P)) {
4723 Table << MatchTable::Opcode("GIM_SwitchType") << MatchTable::Comment("MI")
4724 << MatchTable::IntValue(Condition->getInsnVarID())
4725 << MatchTable::Comment("Op")
4726 << MatchTable::IntValue(Condition->getOpIdx());
4727 return;
4728 }
Roman Tereshin0ee082f2018-05-22 19:37:59 +00004729
4730 llvm_unreachable("emitPredicateSpecificOpcodes is broken: can not handle a "
4731 "predicate type that is claimed to be supported");
4732}
4733
4734void SwitchMatcher::emit(MatchTable &Table) {
4735 assert(Values.size() == Matchers.size() && "Broken SwitchMatcher");
4736 if (empty())
4737 return;
4738 assert(Condition != nullptr &&
4739 "Broken SwitchMatcher, hasn't been finalized?");
4740
4741 std::vector<unsigned> LabelIDs(Values.size());
4742 std::generate(LabelIDs.begin(), LabelIDs.end(),
4743 [&Table]() { return Table.allocateLabelID(); });
4744 const unsigned Default = Table.allocateLabelID();
4745
4746 const int64_t LowerBound = Values.begin()->getRawValue();
4747 const int64_t UpperBound = Values.rbegin()->getRawValue() + 1;
4748
4749 emitPredicateSpecificOpcodes(*Condition, Table);
4750
4751 Table << MatchTable::Comment("[") << MatchTable::IntValue(LowerBound)
4752 << MatchTable::IntValue(UpperBound) << MatchTable::Comment(")")
4753 << MatchTable::Comment("default:") << MatchTable::JumpTarget(Default);
4754
4755 int64_t J = LowerBound;
4756 auto VI = Values.begin();
4757 for (unsigned I = 0, E = Values.size(); I < E; ++I) {
4758 auto V = *VI++;
4759 while (J++ < V.getRawValue())
4760 Table << MatchTable::IntValue(0);
4761 V.turnIntoComment();
4762 Table << MatchTable::LineBreak << V << MatchTable::JumpTarget(LabelIDs[I]);
4763 }
4764 Table << MatchTable::LineBreak;
4765
4766 for (unsigned I = 0, E = Values.size(); I < E; ++I) {
4767 Table << MatchTable::Label(LabelIDs[I]);
4768 Matchers[I]->emit(Table);
4769 Table << MatchTable::Opcode("GIM_Reject") << MatchTable::LineBreak;
4770 }
4771 Table << MatchTable::Label(Default);
4772}
4773
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004774unsigned OperandMatcher::getInsnVarID() const { return Insn.getInsnVarID(); }
Quentin Colombetaad20be2017-12-15 23:07:42 +00004775
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00004776} // end anonymous namespace
4777
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004778//===----------------------------------------------------------------------===//
4779
4780namespace llvm {
4781void EmitGlobalISel(RecordKeeper &RK, raw_ostream &OS) {
4782 GlobalISelEmitter(RK).run(OS);
4783}
4784} // End llvm namespace