blob: 40c8fa94f44e577a8af343f694a485c036512385 [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:
103 LLTCodeGen(const LLT &Ty) : Ty(Ty) {}
104
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000105 std::string getCxxEnumValue() const {
106 std::string Str;
107 raw_string_ostream OS(Str);
108
109 emitCxxEnumValue(OS);
110 return OS.str();
111 }
112
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000113 void emitCxxEnumValue(raw_ostream &OS) const {
114 if (Ty.isScalar()) {
115 OS << "GILLT_s" << Ty.getSizeInBits();
116 return;
117 }
118 if (Ty.isVector()) {
119 OS << "GILLT_v" << Ty.getNumElements() << "s" << Ty.getScalarSizeInBits();
120 return;
121 }
Daniel Sandersa71f4542017-10-16 00:56:30 +0000122 if (Ty.isPointer()) {
123 OS << "GILLT_p" << Ty.getAddressSpace();
124 if (Ty.getSizeInBits() > 0)
125 OS << "s" << Ty.getSizeInBits();
126 return;
127 }
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000128 llvm_unreachable("Unhandled LLT");
129 }
130
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000131 void emitCxxConstructorCall(raw_ostream &OS) const {
132 if (Ty.isScalar()) {
133 OS << "LLT::scalar(" << Ty.getSizeInBits() << ")";
134 return;
135 }
136 if (Ty.isVector()) {
Daniel Sanders32291982017-06-28 13:50:04 +0000137 OS << "LLT::vector(" << Ty.getNumElements() << ", "
138 << Ty.getScalarSizeInBits() << ")";
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000139 return;
140 }
Daniel Sandersa71f4542017-10-16 00:56:30 +0000141 if (Ty.isPointer() && Ty.getSizeInBits() > 0) {
142 OS << "LLT::pointer(" << Ty.getAddressSpace() << ", "
143 << Ty.getSizeInBits() << ")";
144 return;
145 }
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000146 llvm_unreachable("Unhandled LLT");
147 }
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000148
149 const LLT &get() const { return Ty; }
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000150
Mandeep Singh Grang1b0e2f22018-04-06 20:18:05 +0000151 /// This ordering is used for std::unique() and llvm::sort(). There's no
Daniel Sanders032e7f22017-08-17 13:18:35 +0000152 /// particular logic behind the order but either A < B or B < A must be
153 /// true if A != B.
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000154 bool operator<(const LLTCodeGen &Other) const {
Daniel Sanders032e7f22017-08-17 13:18:35 +0000155 if (Ty.isValid() != Other.Ty.isValid())
156 return Ty.isValid() < Other.Ty.isValid();
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000157 if (!Ty.isValid())
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000158 return false;
Daniel Sanders032e7f22017-08-17 13:18:35 +0000159
160 if (Ty.isVector() != Other.Ty.isVector())
161 return Ty.isVector() < Other.Ty.isVector();
162 if (Ty.isScalar() != Other.Ty.isScalar())
163 return Ty.isScalar() < Other.Ty.isScalar();
164 if (Ty.isPointer() != Other.Ty.isPointer())
165 return Ty.isPointer() < Other.Ty.isPointer();
166
167 if (Ty.isPointer() && Ty.getAddressSpace() != Other.Ty.getAddressSpace())
168 return Ty.getAddressSpace() < Other.Ty.getAddressSpace();
169
170 if (Ty.isVector() && Ty.getNumElements() != Other.Ty.getNumElements())
171 return Ty.getNumElements() < Other.Ty.getNumElements();
172
173 return Ty.getSizeInBits() < Other.Ty.getSizeInBits();
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000174 }
Quentin Colombet893e0f12017-12-15 23:24:39 +0000175
176 bool operator==(const LLTCodeGen &B) const { return Ty == B.Ty; }
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000177};
178
Daniel Sandersf84bc372018-05-05 20:53:24 +0000179// Track all types that are used so we can emit the corresponding enum.
180std::set<LLTCodeGen> KnownTypes;
181
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000182class InstructionMatcher;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000183/// Convert an MVT to an equivalent LLT if possible, or the invalid LLT() for
184/// MVTs that don't map cleanly to an LLT (e.g., iPTR, *any, ...).
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000185static Optional<LLTCodeGen> MVTToLLT(MVT::SimpleValueType SVT) {
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000186 MVT VT(SVT);
Daniel Sandersa71f4542017-10-16 00:56:30 +0000187
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000188 if (VT.isVector() && VT.getVectorNumElements() != 1)
Daniel Sanders32291982017-06-28 13:50:04 +0000189 return LLTCodeGen(
190 LLT::vector(VT.getVectorNumElements(), VT.getScalarSizeInBits()));
Daniel Sandersa71f4542017-10-16 00:56:30 +0000191
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000192 if (VT.isInteger() || VT.isFloatingPoint())
193 return LLTCodeGen(LLT::scalar(VT.getSizeInBits()));
194 return None;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000195}
196
Daniel Sandersd0656a32017-04-13 09:45:37 +0000197static std::string explainPredicates(const TreePatternNode *N) {
198 std::string Explanation = "";
199 StringRef Separator = "";
200 for (const auto &P : N->getPredicateFns()) {
201 Explanation +=
202 (Separator + P.getOrigPatFragRecord()->getRecord()->getName()).str();
Daniel Sanders76664652017-11-28 22:07:05 +0000203 Separator = ", ";
204
Daniel Sandersd0656a32017-04-13 09:45:37 +0000205 if (P.isAlwaysTrue())
206 Explanation += " always-true";
207 if (P.isImmediatePattern())
208 Explanation += " immediate";
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000209
210 if (P.isUnindexed())
211 Explanation += " unindexed";
212
213 if (P.isNonExtLoad())
214 Explanation += " non-extload";
215 if (P.isAnyExtLoad())
216 Explanation += " extload";
217 if (P.isSignExtLoad())
218 Explanation += " sextload";
219 if (P.isZeroExtLoad())
220 Explanation += " zextload";
221
222 if (P.isNonTruncStore())
223 Explanation += " non-truncstore";
224 if (P.isTruncStore())
225 Explanation += " truncstore";
226
227 if (Record *VT = P.getMemoryVT())
228 Explanation += (" MemVT=" + VT->getName()).str();
229 if (Record *VT = P.getScalarMemoryVT())
230 Explanation += (" ScalarVT(MemVT)=" + VT->getName()).str();
Daniel Sanders76664652017-11-28 22:07:05 +0000231
232 if (P.isAtomicOrderingMonotonic())
233 Explanation += " monotonic";
234 if (P.isAtomicOrderingAcquire())
235 Explanation += " acquire";
236 if (P.isAtomicOrderingRelease())
237 Explanation += " release";
238 if (P.isAtomicOrderingAcquireRelease())
239 Explanation += " acq_rel";
240 if (P.isAtomicOrderingSequentiallyConsistent())
241 Explanation += " seq_cst";
Daniel Sanders0c43b3a2017-11-30 21:05:59 +0000242 if (P.isAtomicOrderingAcquireOrStronger())
243 Explanation += " >=acquire";
244 if (P.isAtomicOrderingWeakerThanAcquire())
245 Explanation += " <acquire";
246 if (P.isAtomicOrderingReleaseOrStronger())
247 Explanation += " >=release";
248 if (P.isAtomicOrderingWeakerThanRelease())
249 Explanation += " <release";
Daniel Sandersd0656a32017-04-13 09:45:37 +0000250 }
251 return Explanation;
252}
253
Daniel Sandersd0656a32017-04-13 09:45:37 +0000254std::string explainOperator(Record *Operator) {
255 if (Operator->isSubClassOf("SDNode"))
Craig Topper2b8419a2017-05-31 19:01:11 +0000256 return (" (" + Operator->getValueAsString("Opcode") + ")").str();
Daniel Sandersd0656a32017-04-13 09:45:37 +0000257
258 if (Operator->isSubClassOf("Intrinsic"))
259 return (" (Operator is an Intrinsic, " + Operator->getName() + ")").str();
260
Daniel Sandersdf39cba2017-10-15 18:22:54 +0000261 if (Operator->isSubClassOf("ComplexPattern"))
262 return (" (Operator is an unmapped ComplexPattern, " + Operator->getName() +
263 ")")
264 .str();
265
Volkan Kelesf7f25682018-01-16 18:44:05 +0000266 if (Operator->isSubClassOf("SDNodeXForm"))
267 return (" (Operator is an unmapped SDNodeXForm, " + Operator->getName() +
268 ")")
269 .str();
270
Daniel Sandersdf39cba2017-10-15 18:22:54 +0000271 return (" (Operator " + Operator->getName() + " not understood)").str();
Daniel Sandersd0656a32017-04-13 09:45:37 +0000272}
273
274/// Helper function to let the emitter report skip reason error messages.
275static Error failedImport(const Twine &Reason) {
276 return make_error<StringError>(Reason, inconvertibleErrorCode());
277}
278
279static Error isTrivialOperatorNode(const TreePatternNode *N) {
280 std::string Explanation = "";
281 std::string Separator = "";
Daniel Sanders2c269f62017-08-24 09:11:20 +0000282
283 bool HasUnsupportedPredicate = false;
284 for (const auto &Predicate : N->getPredicateFns()) {
285 if (Predicate.isAlwaysTrue())
286 continue;
287
288 if (Predicate.isImmediatePattern())
289 continue;
290
Daniel Sandersf84bc372018-05-05 20:53:24 +0000291 if (Predicate.isNonExtLoad() || Predicate.isAnyExtLoad() ||
292 Predicate.isSignExtLoad() || Predicate.isZeroExtLoad())
Daniel Sandersa71f4542017-10-16 00:56:30 +0000293 continue;
Daniel Sandersd66e0902017-10-23 18:19:24 +0000294
Daniel Sanders76664652017-11-28 22:07:05 +0000295 if (Predicate.isNonTruncStore())
Daniel Sandersd66e0902017-10-23 18:19:24 +0000296 continue;
297
Daniel Sandersf84bc372018-05-05 20:53:24 +0000298 if (Predicate.isLoad() && Predicate.getMemoryVT())
299 continue;
300
Daniel Sanders76664652017-11-28 22:07:05 +0000301 if (Predicate.isLoad() || Predicate.isStore()) {
302 if (Predicate.isUnindexed())
303 continue;
304 }
305
306 if (Predicate.isAtomic() && Predicate.getMemoryVT())
307 continue;
308
309 if (Predicate.isAtomic() &&
310 (Predicate.isAtomicOrderingMonotonic() ||
311 Predicate.isAtomicOrderingAcquire() ||
312 Predicate.isAtomicOrderingRelease() ||
313 Predicate.isAtomicOrderingAcquireRelease() ||
Daniel Sanders0c43b3a2017-11-30 21:05:59 +0000314 Predicate.isAtomicOrderingSequentiallyConsistent() ||
315 Predicate.isAtomicOrderingAcquireOrStronger() ||
316 Predicate.isAtomicOrderingWeakerThanAcquire() ||
317 Predicate.isAtomicOrderingReleaseOrStronger() ||
318 Predicate.isAtomicOrderingWeakerThanRelease()))
Daniel Sandersd66e0902017-10-23 18:19:24 +0000319 continue;
320
Daniel Sanders2c269f62017-08-24 09:11:20 +0000321 HasUnsupportedPredicate = true;
Daniel Sandersd0656a32017-04-13 09:45:37 +0000322 Explanation = Separator + "Has a predicate (" + explainPredicates(N) + ")";
323 Separator = ", ";
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000324 Explanation += (Separator + "first-failing:" +
325 Predicate.getOrigPatFragRecord()->getRecord()->getName())
326 .str();
Daniel Sanders2c269f62017-08-24 09:11:20 +0000327 break;
Daniel Sandersd0656a32017-04-13 09:45:37 +0000328 }
329
Volkan Kelesf7f25682018-01-16 18:44:05 +0000330 if (!HasUnsupportedPredicate)
Daniel Sandersd0656a32017-04-13 09:45:37 +0000331 return Error::success();
332
333 return failedImport(Explanation);
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000334}
335
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +0000336static Record *getInitValueAsRegClass(Init *V) {
337 if (DefInit *VDefInit = dyn_cast<DefInit>(V)) {
338 if (VDefInit->getDef()->isSubClassOf("RegisterOperand"))
339 return VDefInit->getDef()->getValueAsDef("RegClass");
340 if (VDefInit->getDef()->isSubClassOf("RegisterClass"))
341 return VDefInit->getDef();
342 }
343 return nullptr;
344}
345
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000346std::string
347getNameForFeatureBitset(const std::vector<Record *> &FeatureBitset) {
348 std::string Name = "GIFBS";
349 for (const auto &Feature : FeatureBitset)
350 Name += ("_" + Feature->getName()).str();
351 return Name;
352}
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000353
354//===- MatchTable Helpers -------------------------------------------------===//
355
356class MatchTable;
357
358/// A record to be stored in a MatchTable.
359///
360/// This class represents any and all output that may be required to emit the
361/// MatchTable. Instances are most often configured to represent an opcode or
362/// value that will be emitted to the table with some formatting but it can also
363/// represent commas, comments, and other formatting instructions.
364struct MatchTableRecord {
365 enum RecordFlagsBits {
366 MTRF_None = 0x0,
367 /// Causes EmitStr to be formatted as comment when emitted.
368 MTRF_Comment = 0x1,
369 /// Causes the record value to be followed by a comma when emitted.
370 MTRF_CommaFollows = 0x2,
371 /// Causes the record value to be followed by a line break when emitted.
372 MTRF_LineBreakFollows = 0x4,
373 /// Indicates that the record defines a label and causes an additional
374 /// comment to be emitted containing the index of the label.
375 MTRF_Label = 0x8,
376 /// Causes the record to be emitted as the index of the label specified by
377 /// LabelID along with a comment indicating where that label is.
378 MTRF_JumpTarget = 0x10,
379 /// Causes the formatter to add a level of indentation before emitting the
380 /// record.
381 MTRF_Indent = 0x20,
382 /// Causes the formatter to remove a level of indentation after emitting the
383 /// record.
384 MTRF_Outdent = 0x40,
385 };
386
387 /// When MTRF_Label or MTRF_JumpTarget is used, indicates a label id to
388 /// reference or define.
389 unsigned LabelID;
390 /// The string to emit. Depending on the MTRF_* flags it may be a comment, a
391 /// value, a label name.
392 std::string EmitStr;
393
394private:
395 /// The number of MatchTable elements described by this record. Comments are 0
396 /// while values are typically 1. Values >1 may occur when we need to emit
397 /// values that exceed the size of a MatchTable element.
398 unsigned NumElements;
399
400public:
401 /// A bitfield of RecordFlagsBits flags.
402 unsigned Flags;
403
404 MatchTableRecord(Optional<unsigned> LabelID_, StringRef EmitStr,
405 unsigned NumElements, unsigned Flags)
406 : LabelID(LabelID_.hasValue() ? LabelID_.getValue() : ~0u),
407 EmitStr(EmitStr), NumElements(NumElements), Flags(Flags) {
408 assert((!LabelID_.hasValue() || LabelID != ~0u) &&
409 "This value is reserved for non-labels");
410 }
411
412 void emit(raw_ostream &OS, bool LineBreakNextAfterThis,
413 const MatchTable &Table) const;
414 unsigned size() const { return NumElements; }
415};
416
Roman Tereshin2d6d3762018-05-02 20:08:14 +0000417class Matcher;
418
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000419/// Holds the contents of a generated MatchTable to enable formatting and the
420/// necessary index tracking needed to support GIM_Try.
421class MatchTable {
422 /// An unique identifier for the table. The generated table will be named
423 /// MatchTable${ID}.
424 unsigned ID;
425 /// The records that make up the table. Also includes comments describing the
426 /// values being emitted and line breaks to format it.
427 std::vector<MatchTableRecord> Contents;
428 /// The currently defined labels.
429 DenseMap<unsigned, unsigned> LabelMap;
430 /// Tracks the sum of MatchTableRecord::NumElements as the table is built.
Roman Tereshin2d6d3762018-05-02 20:08:14 +0000431 unsigned CurrentSize = 0;
Daniel Sanders8e82af22017-07-27 11:03:45 +0000432 /// A unique identifier for a MatchTable label.
Roman Tereshin2d6d3762018-05-02 20:08:14 +0000433 unsigned CurrentLabelID = 0;
Roman Tereshinbeb39312018-05-02 20:15:11 +0000434 /// Determines if the table should be instrumented for rule coverage tracking.
435 bool IsWithCoverage;
Daniel Sanders8e82af22017-07-27 11:03:45 +0000436
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000437public:
438 static MatchTableRecord LineBreak;
439 static MatchTableRecord Comment(StringRef Comment) {
440 return MatchTableRecord(None, Comment, 0, MatchTableRecord::MTRF_Comment);
441 }
442 static MatchTableRecord Opcode(StringRef Opcode, int IndentAdjust = 0) {
443 unsigned ExtraFlags = 0;
444 if (IndentAdjust > 0)
445 ExtraFlags |= MatchTableRecord::MTRF_Indent;
446 if (IndentAdjust < 0)
447 ExtraFlags |= MatchTableRecord::MTRF_Outdent;
448
449 return MatchTableRecord(None, Opcode, 1,
450 MatchTableRecord::MTRF_CommaFollows | ExtraFlags);
451 }
452 static MatchTableRecord NamedValue(StringRef NamedValue) {
453 return MatchTableRecord(None, NamedValue, 1,
454 MatchTableRecord::MTRF_CommaFollows);
455 }
456 static MatchTableRecord NamedValue(StringRef Namespace,
457 StringRef NamedValue) {
458 return MatchTableRecord(None, (Namespace + "::" + NamedValue).str(), 1,
459 MatchTableRecord::MTRF_CommaFollows);
460 }
461 static MatchTableRecord IntValue(int64_t IntValue) {
462 return MatchTableRecord(None, llvm::to_string(IntValue), 1,
463 MatchTableRecord::MTRF_CommaFollows);
464 }
465 static MatchTableRecord Label(unsigned LabelID) {
466 return MatchTableRecord(LabelID, "Label " + llvm::to_string(LabelID), 0,
467 MatchTableRecord::MTRF_Label |
468 MatchTableRecord::MTRF_Comment |
469 MatchTableRecord::MTRF_LineBreakFollows);
470 }
471 static MatchTableRecord JumpTarget(unsigned LabelID) {
Daniel Sanders8e82af22017-07-27 11:03:45 +0000472 return MatchTableRecord(LabelID, "Label " + llvm::to_string(LabelID), 1,
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000473 MatchTableRecord::MTRF_JumpTarget |
474 MatchTableRecord::MTRF_Comment |
475 MatchTableRecord::MTRF_CommaFollows);
476 }
477
Roman Tereshinbeb39312018-05-02 20:15:11 +0000478 static MatchTable buildTable(ArrayRef<Matcher *> Rules, bool WithCoverage);
Roman Tereshin2d6d3762018-05-02 20:08:14 +0000479
Roman Tereshinbeb39312018-05-02 20:15:11 +0000480 MatchTable(bool WithCoverage, unsigned ID = 0)
481 : ID(ID), IsWithCoverage(WithCoverage) {}
482
483 bool isWithCoverage() const { return IsWithCoverage; }
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000484
485 void push_back(const MatchTableRecord &Value) {
486 if (Value.Flags & MatchTableRecord::MTRF_Label)
487 defineLabel(Value.LabelID);
488 Contents.push_back(Value);
489 CurrentSize += Value.size();
490 }
491
Roman Tereshin2d6d3762018-05-02 20:08:14 +0000492 unsigned allocateLabelID() { return CurrentLabelID++; }
Daniel Sanders8e82af22017-07-27 11:03:45 +0000493
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000494 void defineLabel(unsigned LabelID) {
Daniel Sanders8e82af22017-07-27 11:03:45 +0000495 LabelMap.insert(std::make_pair(LabelID, CurrentSize));
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000496 }
497
498 unsigned getLabelIndex(unsigned LabelID) const {
499 const auto I = LabelMap.find(LabelID);
500 assert(I != LabelMap.end() && "Use of undeclared label");
501 return I->second;
502 }
503
Daniel Sanders8e82af22017-07-27 11:03:45 +0000504 void emitUse(raw_ostream &OS) const { OS << "MatchTable" << ID; }
505
506 void emitDeclaration(raw_ostream &OS) const {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000507 unsigned Indentation = 4;
Daniel Sanderscbbbfe42017-07-27 12:47:31 +0000508 OS << " constexpr static int64_t MatchTable" << ID << "[] = {";
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000509 LineBreak.emit(OS, true, *this);
510 OS << std::string(Indentation, ' ');
511
512 for (auto I = Contents.begin(), E = Contents.end(); I != E;
513 ++I) {
514 bool LineBreakIsNext = false;
515 const auto &NextI = std::next(I);
516
517 if (NextI != E) {
518 if (NextI->EmitStr == "" &&
519 NextI->Flags == MatchTableRecord::MTRF_LineBreakFollows)
520 LineBreakIsNext = true;
521 }
522
523 if (I->Flags & MatchTableRecord::MTRF_Indent)
524 Indentation += 2;
525
526 I->emit(OS, LineBreakIsNext, *this);
527 if (I->Flags & MatchTableRecord::MTRF_LineBreakFollows)
528 OS << std::string(Indentation, ' ');
529
530 if (I->Flags & MatchTableRecord::MTRF_Outdent)
531 Indentation -= 2;
532 }
533 OS << "};\n";
534 }
535};
536
537MatchTableRecord MatchTable::LineBreak = {
538 None, "" /* Emit String */, 0 /* Elements */,
539 MatchTableRecord::MTRF_LineBreakFollows};
540
541void MatchTableRecord::emit(raw_ostream &OS, bool LineBreakIsNextAfterThis,
542 const MatchTable &Table) const {
543 bool UseLineComment =
544 LineBreakIsNextAfterThis | (Flags & MTRF_LineBreakFollows);
545 if (Flags & (MTRF_JumpTarget | MTRF_CommaFollows))
546 UseLineComment = false;
547
548 if (Flags & MTRF_Comment)
549 OS << (UseLineComment ? "// " : "/*");
550
551 OS << EmitStr;
552 if (Flags & MTRF_Label)
553 OS << ": @" << Table.getLabelIndex(LabelID);
554
555 if (Flags & MTRF_Comment && !UseLineComment)
556 OS << "*/";
557
558 if (Flags & MTRF_JumpTarget) {
559 if (Flags & MTRF_Comment)
560 OS << " ";
561 OS << Table.getLabelIndex(LabelID);
562 }
563
564 if (Flags & MTRF_CommaFollows) {
565 OS << ",";
566 if (!LineBreakIsNextAfterThis && !(Flags & MTRF_LineBreakFollows))
567 OS << " ";
568 }
569
570 if (Flags & MTRF_LineBreakFollows)
571 OS << "\n";
572}
573
574MatchTable &operator<<(MatchTable &Table, const MatchTableRecord &Value) {
575 Table.push_back(Value);
576 return Table;
577}
578
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000579//===- Matchers -----------------------------------------------------------===//
580
Daniel Sandersbee57392017-04-04 13:25:23 +0000581class OperandMatcher;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000582class MatchAction;
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000583class PredicateMatcher;
584class RuleMatcher;
585
586class Matcher {
587public:
588 virtual ~Matcher() = default;
589 virtual void emit(MatchTable &Table) = 0;
Quentin Colombet34688b92017-12-18 21:25:53 +0000590 virtual std::unique_ptr<PredicateMatcher> forgetFirstCondition() = 0;
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000591};
592
Roman Tereshinbeb39312018-05-02 20:15:11 +0000593MatchTable MatchTable::buildTable(ArrayRef<Matcher *> Rules,
594 bool WithCoverage) {
595 MatchTable Table(WithCoverage);
Roman Tereshin2d6d3762018-05-02 20:08:14 +0000596 for (Matcher *Rule : Rules)
597 Rule->emit(Table);
598
599 return Table << MatchTable::Opcode("GIM_Reject") << MatchTable::LineBreak;
600}
601
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000602class GroupMatcher : public Matcher {
603 SmallVector<std::unique_ptr<PredicateMatcher>, 8> Conditions;
604 SmallVector<Matcher *, 8> Rules;
605
606public:
607 void addCondition(std::unique_ptr<PredicateMatcher> &&Predicate) {
608 Conditions.emplace_back(std::move(Predicate));
609 }
610 void addRule(Matcher &Rule) { Rules.push_back(&Rule); }
611 const std::unique_ptr<PredicateMatcher> &conditions_back() const {
612 return Conditions.back();
613 }
614 bool lastConditionMatches(const PredicateMatcher &Predicate) const;
615 bool conditions_empty() const { return Conditions.empty(); }
616 void clear() {
617 Conditions.clear();
618 Rules.clear();
619 }
620 void emit(MatchTable &Table) override;
Quentin Colombet34688b92017-12-18 21:25:53 +0000621
622 std::unique_ptr<PredicateMatcher> forgetFirstCondition() override {
623 // We shouldn't need to mess up with groups, since we
624 // should have merged everything shareable upfront.
625 // If we start to look into reordering predicates,
626 // we may want to reconsider this.
627 assert(0 && "Groups should be formed maximal for now");
628 llvm_unreachable("No need for this for now");
629 }
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000630};
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000631
632/// Generates code to check that a match rule matches.
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000633class RuleMatcher : public Matcher {
Daniel Sanders7438b262017-10-31 23:03:18 +0000634public:
Daniel Sanders08464522018-01-29 21:09:12 +0000635 using ActionList = std::list<std::unique_ptr<MatchAction>>;
636 using action_iterator = ActionList::iterator;
Daniel Sanders7438b262017-10-31 23:03:18 +0000637
638protected:
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000639 /// A list of matchers that all need to succeed for the current rule to match.
640 /// FIXME: This currently supports a single match position but could be
641 /// extended to support multiple positions to support div/rem fusion or
642 /// load-multiple instructions.
643 std::vector<std::unique_ptr<InstructionMatcher>> Matchers;
644
645 /// A list of actions that need to be taken when all predicates in this rule
646 /// have succeeded.
Daniel Sanders08464522018-01-29 21:09:12 +0000647 ActionList Actions;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000648
Daniel Sandersa7b75262017-10-31 18:50:24 +0000649 using DefinedInsnVariablesMap =
650 std::map<const InstructionMatcher *, unsigned>;
651
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000652 /// A map of instruction matchers to the local variables created by
Daniel Sanders9d662d22017-07-06 10:06:12 +0000653 /// emitCaptureOpcodes().
Daniel Sanders078572b2017-08-02 11:03:36 +0000654 DefinedInsnVariablesMap InsnVariableIDs;
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000655
Daniel Sandersa7b75262017-10-31 18:50:24 +0000656 using MutatableInsnSet = SmallPtrSet<const InstructionMatcher *, 4>;
657
658 // The set of instruction matchers that have not yet been claimed for mutation
659 // by a BuildMI.
660 MutatableInsnSet MutatableInsns;
661
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000662 /// A map of named operands defined by the matchers that may be referenced by
663 /// the renderers.
664 StringMap<OperandMatcher *> DefinedOperands;
665
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000666 /// ID for the next instruction variable defined with defineInsnVar()
667 unsigned NextInsnVarID;
668
Daniel Sanders198447a2017-11-01 00:29:47 +0000669 /// ID for the next output instruction allocated with allocateOutputInsnID()
670 unsigned NextOutputInsnID;
671
Daniel Sanders9cbe7c72017-11-01 19:57:57 +0000672 /// ID for the next temporary register ID allocated with allocateTempRegID()
673 unsigned NextTempRegID;
674
Daniel Sanderse7b0d662017-04-21 15:59:56 +0000675 std::vector<Record *> RequiredFeatures;
676
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000677 ArrayRef<SMLoc> SrcLoc;
678
Daniel Sandersdf39cba2017-10-15 18:22:54 +0000679 typedef std::tuple<Record *, unsigned, unsigned>
680 DefinedComplexPatternSubOperand;
681 typedef StringMap<DefinedComplexPatternSubOperand>
682 DefinedComplexPatternSubOperandMap;
683 /// A map of Symbolic Names to ComplexPattern sub-operands.
684 DefinedComplexPatternSubOperandMap ComplexSubOperands;
685
Daniel Sandersf76f3152017-11-16 00:46:35 +0000686 uint64_t RuleID;
687 static uint64_t NextRuleID;
688
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000689public:
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000690 RuleMatcher(ArrayRef<SMLoc> SrcLoc)
Daniel Sandersa7b75262017-10-31 18:50:24 +0000691 : Matchers(), Actions(), InsnVariableIDs(), MutatableInsns(),
Daniel Sanders198447a2017-11-01 00:29:47 +0000692 DefinedOperands(), NextInsnVarID(0), NextOutputInsnID(0),
Daniel Sandersf76f3152017-11-16 00:46:35 +0000693 NextTempRegID(0), SrcLoc(SrcLoc), ComplexSubOperands(),
694 RuleID(NextRuleID++) {}
Zachary Turnerb7dbd872017-03-20 19:56:52 +0000695 RuleMatcher(RuleMatcher &&Other) = default;
696 RuleMatcher &operator=(RuleMatcher &&Other) = default;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000697
Daniel Sandersf76f3152017-11-16 00:46:35 +0000698 uint64_t getRuleID() const { return RuleID; }
699
Daniel Sanders05540042017-08-08 10:44:31 +0000700 InstructionMatcher &addInstructionMatcher(StringRef SymbolicName);
Daniel Sanderse7b0d662017-04-21 15:59:56 +0000701 void addRequiredFeature(Record *Feature);
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000702 const std::vector<Record *> &getRequiredFeatures() const;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000703
704 template <class Kind, class... Args> Kind &addAction(Args &&... args);
Daniel Sanders7438b262017-10-31 23:03:18 +0000705 template <class Kind, class... Args>
706 action_iterator insertAction(action_iterator InsertPt, Args &&... args);
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000707
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000708 /// Define an instruction without emitting any code to do so.
709 /// This is used for the root of the match.
710 unsigned implicitlyDefineInsnVar(const InstructionMatcher &Matcher);
Quentin Colombetaad20be2017-12-15 23:07:42 +0000711 void clearImplicitMap() {
712 NextInsnVarID = 0;
713 InsnVariableIDs.clear();
714 };
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000715 /// Define an instruction and emit corresponding state-machine opcodes.
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000716 unsigned defineInsnVar(MatchTable &Table, const InstructionMatcher &Matcher,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000717 unsigned InsnVarID, unsigned OpIdx);
718 unsigned getInsnVarID(const InstructionMatcher &InsnMatcher) const;
Daniel Sanders078572b2017-08-02 11:03:36 +0000719 DefinedInsnVariablesMap::const_iterator defined_insn_vars_begin() const {
720 return InsnVariableIDs.begin();
721 }
722 DefinedInsnVariablesMap::const_iterator defined_insn_vars_end() const {
723 return InsnVariableIDs.end();
724 }
725 iterator_range<typename DefinedInsnVariablesMap::const_iterator>
726 defined_insn_vars() const {
727 return make_range(defined_insn_vars_begin(), defined_insn_vars_end());
728 }
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000729
Daniel Sandersa7b75262017-10-31 18:50:24 +0000730 MutatableInsnSet::const_iterator mutatable_insns_begin() const {
731 return MutatableInsns.begin();
732 }
733 MutatableInsnSet::const_iterator mutatable_insns_end() const {
734 return MutatableInsns.end();
735 }
736 iterator_range<typename MutatableInsnSet::const_iterator>
737 mutatable_insns() const {
738 return make_range(mutatable_insns_begin(), mutatable_insns_end());
739 }
740 void reserveInsnMatcherForMutation(const InstructionMatcher *InsnMatcher) {
741 bool R = MutatableInsns.erase(InsnMatcher);
742 assert(R && "Reserving a mutatable insn that isn't available");
743 (void)R;
744 }
745
Daniel Sanders7438b262017-10-31 23:03:18 +0000746 action_iterator actions_begin() { return Actions.begin(); }
747 action_iterator actions_end() { return Actions.end(); }
748 iterator_range<action_iterator> actions() {
749 return make_range(actions_begin(), actions_end());
750 }
751
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000752 void defineOperand(StringRef SymbolicName, OperandMatcher &OM);
753
Daniel Sandersdf39cba2017-10-15 18:22:54 +0000754 void defineComplexSubOperand(StringRef SymbolicName, Record *ComplexPattern,
755 unsigned RendererID, unsigned SubOperandID) {
756 assert(ComplexSubOperands.count(SymbolicName) == 0 && "Already defined");
757 ComplexSubOperands[SymbolicName] =
758 std::make_tuple(ComplexPattern, RendererID, SubOperandID);
759 }
760 Optional<DefinedComplexPatternSubOperand>
761 getComplexSubOperand(StringRef SymbolicName) const {
762 const auto &I = ComplexSubOperands.find(SymbolicName);
763 if (I == ComplexSubOperands.end())
764 return None;
765 return I->second;
766 }
767
Daniel Sanders05540042017-08-08 10:44:31 +0000768 const InstructionMatcher &getInstructionMatcher(StringRef SymbolicName) const;
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000769 const OperandMatcher &getOperandMatcher(StringRef Name) const;
Daniel Sanders05540042017-08-08 10:44:31 +0000770
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000771 void emitCaptureOpcodes(MatchTable &Table);
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000772
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000773 void emit(MatchTable &Table) override;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000774
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000775 /// Compare the priority of this object and B.
776 ///
777 /// Returns true if this object is more important than B.
778 bool isHigherPriorityThan(const RuleMatcher &B) const;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000779
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000780 /// Report the maximum number of temporary operands needed by the rule
781 /// matcher.
782 unsigned countRendererFns() const;
Daniel Sanders2deea182017-04-22 15:11:04 +0000783
Quentin Colombet34688b92017-12-18 21:25:53 +0000784 std::unique_ptr<PredicateMatcher> forgetFirstCondition() override;
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000785
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000786 // FIXME: Remove this as soon as possible
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000787 InstructionMatcher &insnmatchers_front() const { return *Matchers.front(); }
Daniel Sanders198447a2017-11-01 00:29:47 +0000788
789 unsigned allocateOutputInsnID() { return NextOutputInsnID++; }
Daniel Sanders9cbe7c72017-11-01 19:57:57 +0000790 unsigned allocateTempRegID() { return NextTempRegID++; }
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000791
792 bool insnmatchers_empty() const { return Matchers.empty(); }
793 void insnmatchers_pop_front() { Matchers.erase(Matchers.begin()); }
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000794};
795
Daniel Sandersf76f3152017-11-16 00:46:35 +0000796uint64_t RuleMatcher::NextRuleID = 0;
797
Daniel Sanders7438b262017-10-31 23:03:18 +0000798using action_iterator = RuleMatcher::action_iterator;
799
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000800template <class PredicateTy> class PredicateListMatcher {
801private:
802 typedef std::vector<std::unique_ptr<PredicateTy>> PredicateVec;
803 PredicateVec Predicates;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000804
Daniel Sanders2c269f62017-08-24 09:11:20 +0000805 /// Template instantiations should specialize this to return a string to use
806 /// for the comment emitted when there are no predicates.
807 std::string getNoPredicateComment() const;
808
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000809public:
810 /// Construct a new operand predicate and add it to the matcher.
811 template <class Kind, class... Args>
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000812 Optional<Kind *> addPredicate(Args&&... args) {
Ahmed Bougachab67a3ce2017-01-26 22:07:37 +0000813 Predicates.emplace_back(
814 llvm::make_unique<Kind>(std::forward<Args>(args)...));
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000815 return static_cast<Kind *>(Predicates.back().get());
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000816 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000817
Daniel Sanders32291982017-06-28 13:50:04 +0000818 typename PredicateVec::const_iterator predicates_begin() const {
819 return Predicates.begin();
820 }
821 typename PredicateVec::const_iterator predicates_end() const {
822 return Predicates.end();
823 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000824 iterator_range<typename PredicateVec::const_iterator> predicates() const {
825 return make_range(predicates_begin(), predicates_end());
826 }
Daniel Sanders32291982017-06-28 13:50:04 +0000827 typename PredicateVec::size_type predicates_size() const {
828 return Predicates.size();
829 }
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000830 bool predicates_empty() const { return Predicates.empty(); }
831
832 std::unique_ptr<PredicateTy> predicates_pop_front() {
833 std::unique_ptr<PredicateTy> Front = std::move(Predicates.front());
834 Predicates.erase(Predicates.begin());
835 return Front;
836 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000837
Daniel Sanders9d662d22017-07-06 10:06:12 +0000838 /// Emit MatchTable opcodes that tests whether all the predicates are met.
Ahmed Bougachab67a3ce2017-01-26 22:07:37 +0000839 template <class... Args>
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000840 void emitPredicateListOpcodes(MatchTable &Table, Args &&... args) const {
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000841 if (Predicates.empty()) {
Daniel Sanders2c269f62017-08-24 09:11:20 +0000842 Table << MatchTable::Comment(getNoPredicateComment())
843 << MatchTable::LineBreak;
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000844 return;
845 }
846
Quentin Colombetaad20be2017-12-15 23:07:42 +0000847 unsigned OpIdx = (*predicates_begin())->getOpIdx();
848 (void)OpIdx;
849 for (const auto &Predicate : predicates()) {
850 assert(Predicate->getOpIdx() == OpIdx &&
851 "Checks touch different operands?");
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000852 Predicate->emitPredicateOpcodes(Table, std::forward<Args>(args)...);
Quentin Colombetaad20be2017-12-15 23:07:42 +0000853 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000854 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000855};
856
Quentin Colombet063d7982017-12-14 23:44:07 +0000857class PredicateMatcher {
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000858public:
Daniel Sanders759ff412017-02-24 13:58:11 +0000859 /// This enum is used for RTTI and also defines the priority that is given to
860 /// the predicate when generating the matcher code. Kinds with higher priority
861 /// must be tested first.
862 ///
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000863 /// The relative priority of OPM_LLT, OPM_RegBank, and OPM_MBB do not matter
864 /// but OPM_Int must have priority over OPM_RegBank since constant integers
865 /// are represented by a virtual register defined by a G_CONSTANT instruction.
Quentin Colombet063d7982017-12-14 23:44:07 +0000866 ///
867 /// Note: The relative priority between IPM_ and OPM_ does not matter, they
868 /// are currently not compared between each other.
Daniel Sanders759ff412017-02-24 13:58:11 +0000869 enum PredicateKind {
Quentin Colombet063d7982017-12-14 23:44:07 +0000870 IPM_Opcode,
871 IPM_ImmPredicate,
872 IPM_AtomicOrderingMMO,
Daniel Sandersf84bc372018-05-05 20:53:24 +0000873 IPM_MemoryLLTSize,
874 IPM_MemoryVsLLTSize,
Daniel Sanders1e4569f2017-10-20 20:55:29 +0000875 OPM_SameOperand,
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000876 OPM_ComplexPattern,
Daniel Sandersfe12c0f2017-07-11 08:57:29 +0000877 OPM_IntrinsicID,
Daniel Sanders05540042017-08-08 10:44:31 +0000878 OPM_Instruction,
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000879 OPM_Int,
Daniel Sanders452c8ae2017-05-23 19:33:16 +0000880 OPM_LiteralInt,
Daniel Sanders759ff412017-02-24 13:58:11 +0000881 OPM_LLT,
Daniel Sandersa71f4542017-10-16 00:56:30 +0000882 OPM_PointerToAny,
Daniel Sanders759ff412017-02-24 13:58:11 +0000883 OPM_RegBank,
884 OPM_MBB,
885 };
886
887protected:
888 PredicateKind Kind;
Quentin Colombetaad20be2017-12-15 23:07:42 +0000889 unsigned InsnVarID;
890 unsigned OpIdx;
Daniel Sanders759ff412017-02-24 13:58:11 +0000891
892public:
Quentin Colombetaad20be2017-12-15 23:07:42 +0000893 PredicateMatcher(PredicateKind Kind, unsigned InsnVarID, unsigned OpIdx = ~0)
894 : Kind(Kind), InsnVarID(InsnVarID), OpIdx(OpIdx) {}
Quentin Colombet063d7982017-12-14 23:44:07 +0000895
Quentin Colombetaad20be2017-12-15 23:07:42 +0000896 unsigned getOpIdx() const { return OpIdx; }
Quentin Colombet063d7982017-12-14 23:44:07 +0000897 virtual ~PredicateMatcher() = default;
898 /// Emit MatchTable opcodes that check the predicate for the given operand.
Quentin Colombetaad20be2017-12-15 23:07:42 +0000899 virtual void emitPredicateOpcodes(MatchTable &Table,
900 RuleMatcher &Rule) const = 0;
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000901
Daniel Sanders759ff412017-02-24 13:58:11 +0000902 PredicateKind getKind() const { return Kind; }
Quentin Colombet893e0f12017-12-15 23:24:39 +0000903
904 virtual bool isIdentical(const PredicateMatcher &B) const {
905 if (InsnVarID != 0 || OpIdx != (unsigned)~0) {
906 // We currently don't hoist the record of instruction properly.
907 // Therefore we can only work on the orig instruction (InsnVarID
908 // == 0).
909 DEBUG(dbgs() << "Non-zero instr ID not supported yet\n");
910 return false;
911 }
912 return B.getKind() == getKind() && InsnVarID == B.InsnVarID &&
913 OpIdx == B.OpIdx;
914 }
Quentin Colombet063d7982017-12-14 23:44:07 +0000915};
916
917/// Generates code to check a predicate of an operand.
918///
919/// Typical predicates include:
920/// * Operand is a particular register.
921/// * Operand is assigned a particular register bank.
922/// * Operand is an MBB.
923class OperandPredicateMatcher : public PredicateMatcher {
924public:
Quentin Colombetaad20be2017-12-15 23:07:42 +0000925 OperandPredicateMatcher(PredicateKind Kind, unsigned InsnVarID,
926 unsigned OpIdx)
927 : PredicateMatcher(Kind, InsnVarID, OpIdx) {}
Quentin Colombet063d7982017-12-14 23:44:07 +0000928 virtual ~OperandPredicateMatcher() {}
Daniel Sanders759ff412017-02-24 13:58:11 +0000929
Daniel Sanders9d662d22017-07-06 10:06:12 +0000930 /// Emit MatchTable opcodes to capture instructions into the MIs table.
Daniel Sandersbee57392017-04-04 13:25:23 +0000931 ///
Daniel Sanders9d662d22017-07-06 10:06:12 +0000932 /// Only InstructionOperandMatcher needs to do anything for this method the
933 /// rest just walk the tree.
Quentin Colombetaad20be2017-12-15 23:07:42 +0000934 virtual void emitCaptureOpcodes(MatchTable &Table, RuleMatcher &Rule) const {}
Daniel Sandersbee57392017-04-04 13:25:23 +0000935
Daniel Sanders759ff412017-02-24 13:58:11 +0000936 /// Compare the priority of this object and B.
937 ///
938 /// Returns true if this object is more important than B.
Daniel Sanders05540042017-08-08 10:44:31 +0000939 virtual bool isHigherPriorityThan(const OperandPredicateMatcher &B) const;
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000940
941 /// Report the maximum number of temporary operands needed by the predicate
942 /// matcher.
Daniel Sanders2deea182017-04-22 15:11:04 +0000943 virtual unsigned countRendererFns() const { return 0; }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000944};
945
Daniel Sanders2c269f62017-08-24 09:11:20 +0000946template <>
947std::string
948PredicateListMatcher<OperandPredicateMatcher>::getNoPredicateComment() const {
949 return "No operand predicates";
950}
951
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000952/// Generates code to check that a register operand is defined by the same exact
953/// one as another.
954class SameOperandMatcher : public OperandPredicateMatcher {
Daniel Sanders1e4569f2017-10-20 20:55:29 +0000955 std::string MatchingName;
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000956
957public:
Quentin Colombeteba10cb2017-12-18 22:12:13 +0000958 SameOperandMatcher(unsigned InsnVarID, unsigned OpIdx, StringRef MatchingName)
Quentin Colombetaad20be2017-12-15 23:07:42 +0000959 : OperandPredicateMatcher(OPM_SameOperand, InsnVarID, OpIdx),
960 MatchingName(MatchingName) {}
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000961
962 static bool classof(const OperandPredicateMatcher *P) {
Daniel Sanders1e4569f2017-10-20 20:55:29 +0000963 return P->getKind() == OPM_SameOperand;
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000964 }
965
Quentin Colombetaad20be2017-12-15 23:07:42 +0000966 void emitPredicateOpcodes(MatchTable &Table,
967 RuleMatcher &Rule) const override;
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000968};
969
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000970/// Generates code to check that an operand is a particular LLT.
971class LLTOperandMatcher : public OperandPredicateMatcher {
972protected:
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000973 LLTCodeGen Ty;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000974
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000975public:
Quentin Colombeteba10cb2017-12-18 22:12:13 +0000976 LLTOperandMatcher(unsigned InsnVarID, unsigned OpIdx, const LLTCodeGen &Ty)
Quentin Colombetaad20be2017-12-15 23:07:42 +0000977 : OperandPredicateMatcher(OPM_LLT, InsnVarID, OpIdx), Ty(Ty) {
Daniel Sanders032e7f22017-08-17 13:18:35 +0000978 KnownTypes.insert(Ty);
979 }
Daniel Sanders759ff412017-02-24 13:58:11 +0000980
Quentin Colombet063d7982017-12-14 23:44:07 +0000981 static bool classof(const PredicateMatcher *P) {
Daniel Sanders759ff412017-02-24 13:58:11 +0000982 return P->getKind() == OPM_LLT;
983 }
Quentin Colombet893e0f12017-12-15 23:24:39 +0000984 bool isIdentical(const PredicateMatcher &B) const override {
985 return OperandPredicateMatcher::isIdentical(B) &&
986 Ty == cast<LLTOperandMatcher>(&B)->Ty;
987 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000988
Quentin Colombetaad20be2017-12-15 23:07:42 +0000989 void emitPredicateOpcodes(MatchTable &Table,
990 RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000991 Table << MatchTable::Opcode("GIM_CheckType") << MatchTable::Comment("MI")
992 << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Op")
993 << MatchTable::IntValue(OpIdx) << MatchTable::Comment("Type")
994 << MatchTable::NamedValue(Ty.getCxxEnumValue())
995 << MatchTable::LineBreak;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000996 }
997};
998
Daniel Sandersa71f4542017-10-16 00:56:30 +0000999/// Generates code to check that an operand is a pointer to any address space.
1000///
1001/// In SelectionDAG, the types did not describe pointers or address spaces. As a
1002/// result, iN is used to describe a pointer of N bits to any address space and
1003/// PatFrag predicates are typically used to constrain the address space. There's
1004/// no reliable means to derive the missing type information from the pattern so
1005/// imported rules must test the components of a pointer separately.
1006///
Daniel Sandersea8711b2017-10-16 03:36:29 +00001007/// If SizeInBits is zero, then the pointer size will be obtained from the
1008/// subtarget.
Daniel Sandersa71f4542017-10-16 00:56:30 +00001009class PointerToAnyOperandMatcher : public OperandPredicateMatcher {
1010protected:
1011 unsigned SizeInBits;
1012
1013public:
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001014 PointerToAnyOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
1015 unsigned SizeInBits)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001016 : OperandPredicateMatcher(OPM_PointerToAny, InsnVarID, OpIdx),
1017 SizeInBits(SizeInBits) {}
Daniel Sandersa71f4542017-10-16 00:56:30 +00001018
1019 static bool classof(const OperandPredicateMatcher *P) {
1020 return P->getKind() == OPM_PointerToAny;
1021 }
1022
Quentin Colombetaad20be2017-12-15 23:07:42 +00001023 void emitPredicateOpcodes(MatchTable &Table,
1024 RuleMatcher &Rule) const override {
1025 Table << MatchTable::Opcode("GIM_CheckPointerToAny")
1026 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1027 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1028 << MatchTable::Comment("SizeInBits")
Daniel Sandersa71f4542017-10-16 00:56:30 +00001029 << MatchTable::IntValue(SizeInBits) << MatchTable::LineBreak;
1030 }
1031};
1032
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001033/// Generates code to check that an operand is a particular target constant.
1034class ComplexPatternOperandMatcher : public OperandPredicateMatcher {
1035protected:
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001036 const OperandMatcher &Operand;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001037 const Record &TheDef;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001038
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001039 unsigned getAllocatedTemporariesBaseID() const;
1040
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001041public:
Quentin Colombet893e0f12017-12-15 23:24:39 +00001042 bool isIdentical(const PredicateMatcher &B) const override { return false; }
1043
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001044 ComplexPatternOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
1045 const OperandMatcher &Operand,
1046 const Record &TheDef)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001047 : OperandPredicateMatcher(OPM_ComplexPattern, InsnVarID, OpIdx),
1048 Operand(Operand), TheDef(TheDef) {}
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001049
Quentin Colombet063d7982017-12-14 23:44:07 +00001050 static bool classof(const PredicateMatcher *P) {
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001051 return P->getKind() == OPM_ComplexPattern;
1052 }
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001053
Quentin Colombetaad20be2017-12-15 23:07:42 +00001054 void emitPredicateOpcodes(MatchTable &Table,
1055 RuleMatcher &Rule) const override {
Daniel Sanders2deea182017-04-22 15:11:04 +00001056 unsigned ID = getAllocatedTemporariesBaseID();
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001057 Table << MatchTable::Opcode("GIM_CheckComplexPattern")
1058 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1059 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1060 << MatchTable::Comment("Renderer") << MatchTable::IntValue(ID)
1061 << MatchTable::NamedValue(("GICP_" + TheDef.getName()).str())
1062 << MatchTable::LineBreak;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001063 }
1064
Daniel Sanders2deea182017-04-22 15:11:04 +00001065 unsigned countRendererFns() const override {
1066 return 1;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001067 }
1068};
1069
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001070/// Generates code to check that an operand is in a particular register bank.
1071class RegisterBankOperandMatcher : public OperandPredicateMatcher {
1072protected:
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001073 const CodeGenRegisterClass &RC;
1074
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001075public:
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001076 RegisterBankOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
1077 const CodeGenRegisterClass &RC)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001078 : OperandPredicateMatcher(OPM_RegBank, InsnVarID, OpIdx), RC(RC) {}
Daniel Sanders759ff412017-02-24 13:58:11 +00001079
Quentin Colombet893e0f12017-12-15 23:24:39 +00001080 bool isIdentical(const PredicateMatcher &B) const override {
1081 return OperandPredicateMatcher::isIdentical(B) &&
1082 RC.getDef() == cast<RegisterBankOperandMatcher>(&B)->RC.getDef();
1083 }
1084
Quentin Colombet063d7982017-12-14 23:44:07 +00001085 static bool classof(const PredicateMatcher *P) {
Daniel Sanders759ff412017-02-24 13:58:11 +00001086 return P->getKind() == OPM_RegBank;
1087 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001088
Quentin Colombetaad20be2017-12-15 23:07:42 +00001089 void emitPredicateOpcodes(MatchTable &Table,
1090 RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001091 Table << MatchTable::Opcode("GIM_CheckRegBankForClass")
1092 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1093 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1094 << MatchTable::Comment("RC")
1095 << MatchTable::NamedValue(RC.getQualifiedName() + "RegClassID")
1096 << MatchTable::LineBreak;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001097 }
1098};
1099
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001100/// Generates code to check that an operand is a basic block.
1101class MBBOperandMatcher : public OperandPredicateMatcher {
1102public:
Quentin Colombetaad20be2017-12-15 23:07:42 +00001103 MBBOperandMatcher(unsigned InsnVarID, unsigned OpIdx)
1104 : OperandPredicateMatcher(OPM_MBB, InsnVarID, OpIdx) {}
Daniel Sanders759ff412017-02-24 13:58:11 +00001105
Quentin Colombet063d7982017-12-14 23:44:07 +00001106 static bool classof(const PredicateMatcher *P) {
Daniel Sanders759ff412017-02-24 13:58:11 +00001107 return P->getKind() == OPM_MBB;
1108 }
1109
Quentin Colombetaad20be2017-12-15 23:07:42 +00001110 void emitPredicateOpcodes(MatchTable &Table,
1111 RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001112 Table << MatchTable::Opcode("GIM_CheckIsMBB") << MatchTable::Comment("MI")
1113 << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Op")
1114 << MatchTable::IntValue(OpIdx) << MatchTable::LineBreak;
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001115 }
1116};
1117
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001118/// Generates code to check that an operand is a G_CONSTANT with a particular
1119/// int.
1120class ConstantIntOperandMatcher : public OperandPredicateMatcher {
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001121protected:
1122 int64_t Value;
1123
1124public:
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001125 ConstantIntOperandMatcher(unsigned InsnVarID, unsigned OpIdx, int64_t Value)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001126 : OperandPredicateMatcher(OPM_Int, InsnVarID, OpIdx), Value(Value) {}
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001127
Quentin Colombet893e0f12017-12-15 23:24:39 +00001128 bool isIdentical(const PredicateMatcher &B) const override {
1129 return OperandPredicateMatcher::isIdentical(B) &&
1130 Value == cast<ConstantIntOperandMatcher>(&B)->Value;
1131 }
1132
Quentin Colombet063d7982017-12-14 23:44:07 +00001133 static bool classof(const PredicateMatcher *P) {
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001134 return P->getKind() == OPM_Int;
1135 }
1136
Quentin Colombetaad20be2017-12-15 23:07:42 +00001137 void emitPredicateOpcodes(MatchTable &Table,
1138 RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001139 Table << MatchTable::Opcode("GIM_CheckConstantInt")
1140 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1141 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1142 << MatchTable::IntValue(Value) << MatchTable::LineBreak;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001143 }
1144};
1145
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001146/// Generates code to check that an operand is a raw int (where MO.isImm() or
1147/// MO.isCImm() is true).
1148class LiteralIntOperandMatcher : public OperandPredicateMatcher {
1149protected:
1150 int64_t Value;
1151
1152public:
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001153 LiteralIntOperandMatcher(unsigned InsnVarID, unsigned OpIdx, int64_t Value)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001154 : OperandPredicateMatcher(OPM_LiteralInt, InsnVarID, OpIdx),
1155 Value(Value) {}
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001156
Quentin Colombet893e0f12017-12-15 23:24:39 +00001157 bool isIdentical(const PredicateMatcher &B) const override {
1158 return OperandPredicateMatcher::isIdentical(B) &&
1159 Value == cast<LiteralIntOperandMatcher>(&B)->Value;
1160 }
1161
Quentin Colombet063d7982017-12-14 23:44:07 +00001162 static bool classof(const PredicateMatcher *P) {
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001163 return P->getKind() == OPM_LiteralInt;
1164 }
1165
Quentin Colombetaad20be2017-12-15 23:07:42 +00001166 void emitPredicateOpcodes(MatchTable &Table,
1167 RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001168 Table << MatchTable::Opcode("GIM_CheckLiteralInt")
1169 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1170 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1171 << MatchTable::IntValue(Value) << MatchTable::LineBreak;
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001172 }
1173};
1174
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00001175/// Generates code to check that an operand is an intrinsic ID.
1176class IntrinsicIDOperandMatcher : public OperandPredicateMatcher {
1177protected:
1178 const CodeGenIntrinsic *II;
1179
1180public:
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001181 IntrinsicIDOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
1182 const CodeGenIntrinsic *II)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001183 : OperandPredicateMatcher(OPM_IntrinsicID, InsnVarID, OpIdx), II(II) {}
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00001184
Quentin Colombet893e0f12017-12-15 23:24:39 +00001185 bool isIdentical(const PredicateMatcher &B) const override {
1186 return OperandPredicateMatcher::isIdentical(B) &&
1187 II == cast<IntrinsicIDOperandMatcher>(&B)->II;
1188 }
1189
Quentin Colombet063d7982017-12-14 23:44:07 +00001190 static bool classof(const PredicateMatcher *P) {
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00001191 return P->getKind() == OPM_IntrinsicID;
1192 }
1193
Quentin Colombetaad20be2017-12-15 23:07:42 +00001194 void emitPredicateOpcodes(MatchTable &Table,
1195 RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001196 Table << MatchTable::Opcode("GIM_CheckIntrinsicID")
1197 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1198 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1199 << MatchTable::NamedValue("Intrinsic::" + II->EnumName)
1200 << MatchTable::LineBreak;
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00001201 }
1202};
1203
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001204/// Generates code to check that a set of predicates match for a particular
1205/// operand.
1206class OperandMatcher : public PredicateListMatcher<OperandPredicateMatcher> {
1207protected:
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001208 InstructionMatcher &Insn;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001209 unsigned OpIdx;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001210 std::string SymbolicName;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001211
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001212 /// The index of the first temporary variable allocated to this operand. The
1213 /// number of allocated temporaries can be found with
Daniel Sanders2deea182017-04-22 15:11:04 +00001214 /// countRendererFns().
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001215 unsigned AllocatedTemporariesBaseID;
1216
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001217public:
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001218 OperandMatcher(InstructionMatcher &Insn, unsigned OpIdx,
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001219 const std::string &SymbolicName,
1220 unsigned AllocatedTemporariesBaseID)
1221 : Insn(Insn), OpIdx(OpIdx), SymbolicName(SymbolicName),
1222 AllocatedTemporariesBaseID(AllocatedTemporariesBaseID) {}
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001223
1224 bool hasSymbolicName() const { return !SymbolicName.empty(); }
1225 const StringRef getSymbolicName() const { return SymbolicName; }
Daniel Sandersffc7d582017-03-29 15:37:18 +00001226 void setSymbolicName(StringRef Name) {
1227 assert(SymbolicName.empty() && "Operand already has a symbolic name");
1228 SymbolicName = Name;
1229 }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001230 unsigned getOperandIndex() const { return OpIdx; }
Quentin Colombetaad20be2017-12-15 23:07:42 +00001231 unsigned getInsnVarID() const;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001232
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001233 std::string getOperandExpr(unsigned InsnVarID) const {
1234 return "State.MIs[" + llvm::to_string(InsnVarID) + "]->getOperand(" +
1235 llvm::to_string(OpIdx) + ")";
Daniel Sanderse604ef52017-02-20 15:30:43 +00001236 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001237
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001238 InstructionMatcher &getInstructionMatcher() const { return Insn; }
1239
Daniel Sandersa71f4542017-10-16 00:56:30 +00001240 Error addTypeCheckPredicate(const TypeSetByHwMode &VTy,
Reid Klecknercfdd4a22017-10-16 20:31:16 +00001241 bool OperandIsAPointer);
Daniel Sandersa71f4542017-10-16 00:56:30 +00001242
Daniel Sanders9d662d22017-07-06 10:06:12 +00001243 /// Emit MatchTable opcodes to capture instructions into the MIs table.
Quentin Colombetaad20be2017-12-15 23:07:42 +00001244 void emitCaptureOpcodes(MatchTable &Table, RuleMatcher &Rule) const {
Daniel Sandersbee57392017-04-04 13:25:23 +00001245 for (const auto &Predicate : predicates())
Quentin Colombetaad20be2017-12-15 23:07:42 +00001246 Predicate->emitCaptureOpcodes(Table, Rule);
Daniel Sandersbee57392017-04-04 13:25:23 +00001247 }
1248
Daniel Sanders9d662d22017-07-06 10:06:12 +00001249 /// Emit MatchTable opcodes that test whether the instruction named in
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001250 /// InsnVarID matches all the predicates and all the operands.
Quentin Colombetaad20be2017-12-15 23:07:42 +00001251 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule) const {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001252 std::string Comment;
1253 raw_string_ostream CommentOS(Comment);
Quentin Colombetaad20be2017-12-15 23:07:42 +00001254 CommentOS << "MIs[" << getInsnVarID() << "] ";
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001255 if (SymbolicName.empty())
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001256 CommentOS << "Operand " << OpIdx;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001257 else
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001258 CommentOS << SymbolicName;
1259 Table << MatchTable::Comment(CommentOS.str()) << MatchTable::LineBreak;
1260
Quentin Colombetaad20be2017-12-15 23:07:42 +00001261 emitPredicateListOpcodes(Table, Rule);
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001262 }
Daniel Sanders759ff412017-02-24 13:58:11 +00001263
1264 /// Compare the priority of this object and B.
1265 ///
1266 /// Returns true if this object is more important than B.
1267 bool isHigherPriorityThan(const OperandMatcher &B) const {
1268 // Operand matchers involving more predicates have higher priority.
1269 if (predicates_size() > B.predicates_size())
1270 return true;
1271 if (predicates_size() < B.predicates_size())
1272 return false;
1273
1274 // This assumes that predicates are added in a consistent order.
1275 for (const auto &Predicate : zip(predicates(), B.predicates())) {
1276 if (std::get<0>(Predicate)->isHigherPriorityThan(*std::get<1>(Predicate)))
1277 return true;
1278 if (std::get<1>(Predicate)->isHigherPriorityThan(*std::get<0>(Predicate)))
1279 return false;
1280 }
1281
1282 return false;
1283 };
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001284
1285 /// Report the maximum number of temporary operands needed by the operand
1286 /// matcher.
Daniel Sanders2deea182017-04-22 15:11:04 +00001287 unsigned countRendererFns() const {
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001288 return std::accumulate(
1289 predicates().begin(), predicates().end(), 0,
1290 [](unsigned A,
1291 const std::unique_ptr<OperandPredicateMatcher> &Predicate) {
Daniel Sanders2deea182017-04-22 15:11:04 +00001292 return A + Predicate->countRendererFns();
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001293 });
1294 }
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001295
1296 unsigned getAllocatedTemporariesBaseID() const {
1297 return AllocatedTemporariesBaseID;
1298 }
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001299
1300 bool isSameAsAnotherOperand() const {
1301 for (const auto &Predicate : predicates())
1302 if (isa<SameOperandMatcher>(Predicate))
1303 return true;
1304 return false;
1305 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001306};
1307
Reid Klecknercfdd4a22017-10-16 20:31:16 +00001308// Specialize OperandMatcher::addPredicate() to refrain from adding redundant
1309// predicates.
1310template <>
1311template <class Kind, class... Args>
1312Optional<Kind *>
1313PredicateListMatcher<OperandPredicateMatcher>::addPredicate(Args &&... args) {
Quentin Colombetaad20be2017-12-15 23:07:42 +00001314 auto *OpMatcher = static_cast<OperandMatcher *>(this);
Reid Klecknercfdd4a22017-10-16 20:31:16 +00001315 if (static_cast<OperandMatcher *>(this)->isSameAsAnotherOperand())
1316 return None;
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001317 Predicates.emplace_back(llvm::make_unique<Kind>(OpMatcher->getInsnVarID(),
1318 OpMatcher->getOperandIndex(),
1319 std::forward<Args>(args)...));
Reid Klecknercfdd4a22017-10-16 20:31:16 +00001320 return static_cast<Kind *>(Predicates.back().get());
1321}
1322
1323Error OperandMatcher::addTypeCheckPredicate(const TypeSetByHwMode &VTy,
Quentin Colombetaad20be2017-12-15 23:07:42 +00001324 bool OperandIsAPointer) {
Reid Klecknercfdd4a22017-10-16 20:31:16 +00001325 if (!VTy.isMachineValueType())
1326 return failedImport("unsupported typeset");
1327
1328 if (VTy.getMachineValueType() == MVT::iPTR && OperandIsAPointer) {
1329 addPredicate<PointerToAnyOperandMatcher>(0);
1330 return Error::success();
1331 }
1332
1333 auto OpTyOrNone = MVTToLLT(VTy.getMachineValueType().SimpleTy);
1334 if (!OpTyOrNone)
1335 return failedImport("unsupported type");
1336
1337 if (OperandIsAPointer)
1338 addPredicate<PointerToAnyOperandMatcher>(OpTyOrNone->get().getSizeInBits());
1339 else
1340 addPredicate<LLTOperandMatcher>(*OpTyOrNone);
1341 return Error::success();
1342}
1343
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001344unsigned ComplexPatternOperandMatcher::getAllocatedTemporariesBaseID() const {
1345 return Operand.getAllocatedTemporariesBaseID();
1346}
1347
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001348/// Generates code to check a predicate on an instruction.
1349///
1350/// Typical predicates include:
1351/// * The opcode of the instruction is a particular value.
1352/// * The nsw/nuw flag is/isn't set.
Quentin Colombet063d7982017-12-14 23:44:07 +00001353class InstructionPredicateMatcher : public PredicateMatcher {
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001354public:
Quentin Colombetaad20be2017-12-15 23:07:42 +00001355 InstructionPredicateMatcher(PredicateKind Kind, unsigned InsnVarID)
1356 : PredicateMatcher(Kind, InsnVarID) {}
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001357 virtual ~InstructionPredicateMatcher() {}
1358
Daniel Sanders759ff412017-02-24 13:58:11 +00001359 /// Compare the priority of this object and B.
1360 ///
1361 /// Returns true if this object is more important than B.
Daniel Sanders32291982017-06-28 13:50:04 +00001362 virtual bool
1363 isHigherPriorityThan(const InstructionPredicateMatcher &B) const {
Daniel Sanders759ff412017-02-24 13:58:11 +00001364 return Kind < B.Kind;
1365 };
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001366
1367 /// Report the maximum number of temporary operands needed by the predicate
1368 /// matcher.
Daniel Sanders2deea182017-04-22 15:11:04 +00001369 virtual unsigned countRendererFns() const { return 0; }
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001370};
1371
Daniel Sanders2c269f62017-08-24 09:11:20 +00001372template <>
1373std::string
1374PredicateListMatcher<InstructionPredicateMatcher>::getNoPredicateComment() const {
1375 return "No instruction predicates";
1376}
1377
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001378/// Generates code to check the opcode of an instruction.
1379class InstructionOpcodeMatcher : public InstructionPredicateMatcher {
1380protected:
1381 const CodeGenInstruction *I;
1382
1383public:
Quentin Colombetaad20be2017-12-15 23:07:42 +00001384 InstructionOpcodeMatcher(unsigned InsnVarID, const CodeGenInstruction *I)
1385 : InstructionPredicateMatcher(IPM_Opcode, InsnVarID), I(I) {}
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001386
Quentin Colombet063d7982017-12-14 23:44:07 +00001387 static bool classof(const PredicateMatcher *P) {
Daniel Sanders759ff412017-02-24 13:58:11 +00001388 return P->getKind() == IPM_Opcode;
1389 }
1390
Quentin Colombet893e0f12017-12-15 23:24:39 +00001391 bool isIdentical(const PredicateMatcher &B) const override {
1392 return InstructionPredicateMatcher::isIdentical(B) &&
1393 I == cast<InstructionOpcodeMatcher>(&B)->I;
1394 }
1395
Quentin Colombetaad20be2017-12-15 23:07:42 +00001396 void emitPredicateOpcodes(MatchTable &Table,
1397 RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001398 Table << MatchTable::Opcode("GIM_CheckOpcode") << MatchTable::Comment("MI")
1399 << MatchTable::IntValue(InsnVarID)
1400 << MatchTable::NamedValue(I->Namespace, I->TheDef->getName())
1401 << MatchTable::LineBreak;
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001402 }
Daniel Sanders759ff412017-02-24 13:58:11 +00001403
1404 /// Compare the priority of this object and B.
1405 ///
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001406 /// Returns true if this object is more important than B.
Daniel Sanders32291982017-06-28 13:50:04 +00001407 bool
1408 isHigherPriorityThan(const InstructionPredicateMatcher &B) const override {
Daniel Sanders759ff412017-02-24 13:58:11 +00001409 if (InstructionPredicateMatcher::isHigherPriorityThan(B))
1410 return true;
1411 if (B.InstructionPredicateMatcher::isHigherPriorityThan(*this))
1412 return false;
1413
1414 // Prioritize opcodes for cosmetic reasons in the generated source. Although
1415 // this is cosmetic at the moment, we may want to drive a similar ordering
1416 // using instruction frequency information to improve compile time.
1417 if (const InstructionOpcodeMatcher *BO =
1418 dyn_cast<InstructionOpcodeMatcher>(&B))
1419 return I->TheDef->getName() < BO->I->TheDef->getName();
1420
1421 return false;
1422 };
Daniel Sanders05540042017-08-08 10:44:31 +00001423
1424 bool isConstantInstruction() const {
1425 return I->TheDef->getName() == "G_CONSTANT";
1426 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001427};
1428
Daniel Sanders2c269f62017-08-24 09:11:20 +00001429/// Generates code to check that this instruction is a constant whose value
1430/// meets an immediate predicate.
1431///
1432/// Immediates are slightly odd since they are typically used like an operand
1433/// but are represented as an operator internally. We typically write simm8:$src
1434/// in a tablegen pattern, but this is just syntactic sugar for
1435/// (imm:i32)<<P:Predicate_simm8>>:$imm which more directly describes the nodes
1436/// that will be matched and the predicate (which is attached to the imm
1437/// operator) that will be tested. In SelectionDAG this describes a
1438/// ConstantSDNode whose internal value will be tested using the simm8 predicate.
1439///
1440/// The corresponding GlobalISel representation is %1 = G_CONSTANT iN Value. In
1441/// this representation, the immediate could be tested with an
1442/// InstructionMatcher, InstructionOpcodeMatcher, OperandMatcher, and a
1443/// OperandPredicateMatcher-subclass to check the Value meets the predicate but
1444/// there are two implementation issues with producing that matcher
1445/// configuration from the SelectionDAG pattern:
1446/// * ImmLeaf is a PatFrag whose root is an InstructionMatcher. This means that
1447/// were we to sink the immediate predicate to the operand we would have to
1448/// have two partial implementations of PatFrag support, one for immediates
1449/// and one for non-immediates.
1450/// * At the point we handle the predicate, the OperandMatcher hasn't been
1451/// created yet. If we were to sink the predicate to the OperandMatcher we
1452/// would also have to complicate (or duplicate) the code that descends and
1453/// creates matchers for the subtree.
1454/// Overall, it's simpler to handle it in the place it was found.
1455class InstructionImmPredicateMatcher : public InstructionPredicateMatcher {
1456protected:
1457 TreePredicateFn Predicate;
1458
1459public:
Quentin Colombetaad20be2017-12-15 23:07:42 +00001460 InstructionImmPredicateMatcher(unsigned InsnVarID,
1461 const TreePredicateFn &Predicate)
1462 : InstructionPredicateMatcher(IPM_ImmPredicate, InsnVarID),
1463 Predicate(Predicate) {}
Daniel Sanders2c269f62017-08-24 09:11:20 +00001464
Quentin Colombet893e0f12017-12-15 23:24:39 +00001465 bool isIdentical(const PredicateMatcher &B) const override {
1466 return InstructionPredicateMatcher::isIdentical(B) &&
1467 Predicate.getOrigPatFragRecord() ==
1468 cast<InstructionImmPredicateMatcher>(&B)
1469 ->Predicate.getOrigPatFragRecord();
1470 }
1471
Quentin Colombet063d7982017-12-14 23:44:07 +00001472 static bool classof(const PredicateMatcher *P) {
Daniel Sanders2c269f62017-08-24 09:11:20 +00001473 return P->getKind() == IPM_ImmPredicate;
1474 }
1475
Quentin Colombetaad20be2017-12-15 23:07:42 +00001476 void emitPredicateOpcodes(MatchTable &Table,
1477 RuleMatcher &Rule) const override {
Daniel Sanders11300ce2017-10-13 21:28:03 +00001478 Table << MatchTable::Opcode(getMatchOpcodeForPredicate(Predicate))
Daniel Sanders2c269f62017-08-24 09:11:20 +00001479 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1480 << MatchTable::Comment("Predicate")
Daniel Sanders11300ce2017-10-13 21:28:03 +00001481 << MatchTable::NamedValue(getEnumNameForPredicate(Predicate))
Daniel Sanders2c269f62017-08-24 09:11:20 +00001482 << MatchTable::LineBreak;
1483 }
1484};
1485
Daniel Sanders76664652017-11-28 22:07:05 +00001486/// Generates code to check that a memory instruction has a atomic ordering
1487/// MachineMemoryOperand.
1488class AtomicOrderingMMOPredicateMatcher : public InstructionPredicateMatcher {
Daniel Sanders0c43b3a2017-11-30 21:05:59 +00001489public:
1490 enum AOComparator {
1491 AO_Exactly,
1492 AO_OrStronger,
1493 AO_WeakerThan,
1494 };
1495
1496protected:
Daniel Sanders76664652017-11-28 22:07:05 +00001497 StringRef Order;
Daniel Sanders0c43b3a2017-11-30 21:05:59 +00001498 AOComparator Comparator;
Daniel Sanders76664652017-11-28 22:07:05 +00001499
Daniel Sanders39690bd2017-10-15 02:41:12 +00001500public:
Quentin Colombetaad20be2017-12-15 23:07:42 +00001501 AtomicOrderingMMOPredicateMatcher(unsigned InsnVarID, StringRef Order,
Daniel Sanders0c43b3a2017-11-30 21:05:59 +00001502 AOComparator Comparator = AO_Exactly)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001503 : InstructionPredicateMatcher(IPM_AtomicOrderingMMO, InsnVarID),
1504 Order(Order), Comparator(Comparator) {}
Daniel Sanders39690bd2017-10-15 02:41:12 +00001505
1506 static bool classof(const InstructionPredicateMatcher *P) {
Daniel Sanders76664652017-11-28 22:07:05 +00001507 return P->getKind() == IPM_AtomicOrderingMMO;
Daniel Sanders39690bd2017-10-15 02:41:12 +00001508 }
1509
Quentin Colombetaad20be2017-12-15 23:07:42 +00001510 void emitPredicateOpcodes(MatchTable &Table,
1511 RuleMatcher &Rule) const override {
Daniel Sanders0c43b3a2017-11-30 21:05:59 +00001512 StringRef Opcode = "GIM_CheckAtomicOrdering";
1513
1514 if (Comparator == AO_OrStronger)
1515 Opcode = "GIM_CheckAtomicOrderingOrStrongerThan";
1516 if (Comparator == AO_WeakerThan)
1517 Opcode = "GIM_CheckAtomicOrderingWeakerThan";
1518
1519 Table << MatchTable::Opcode(Opcode) << MatchTable::Comment("MI")
1520 << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Order")
Daniel Sanders76664652017-11-28 22:07:05 +00001521 << MatchTable::NamedValue(("(int64_t)AtomicOrdering::" + Order).str())
Daniel Sanders39690bd2017-10-15 02:41:12 +00001522 << MatchTable::LineBreak;
1523 }
1524};
1525
Daniel Sandersf84bc372018-05-05 20:53:24 +00001526/// Generates code to check that the size of an MMO is exactly N bytes.
1527class MemorySizePredicateMatcher : public InstructionPredicateMatcher {
1528protected:
1529 unsigned MMOIdx;
1530 uint64_t Size;
1531
1532public:
1533 MemorySizePredicateMatcher(unsigned InsnVarID, unsigned MMOIdx, unsigned Size)
1534 : InstructionPredicateMatcher(IPM_MemoryLLTSize, InsnVarID),
1535 MMOIdx(MMOIdx), Size(Size) {}
1536
1537 static bool classof(const PredicateMatcher *P) {
1538 return P->getKind() == IPM_MemoryLLTSize;
1539 }
1540 bool isIdentical(const PredicateMatcher &B) const override {
1541 return InstructionPredicateMatcher::isIdentical(B) &&
1542 MMOIdx == cast<MemorySizePredicateMatcher>(&B)->MMOIdx &&
1543 Size == cast<MemorySizePredicateMatcher>(&B)->Size;
1544 }
1545
1546 void emitPredicateOpcodes(MatchTable &Table,
1547 RuleMatcher &Rule) const override {
1548 Table << MatchTable::Opcode("GIM_CheckMemorySizeEqualTo")
1549 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1550 << MatchTable::Comment("MMO") << MatchTable::IntValue(MMOIdx)
1551 << MatchTable::Comment("Size") << MatchTable::IntValue(Size)
1552 << MatchTable::LineBreak;
1553 }
1554};
1555
1556/// Generates code to check that the size of an MMO is less-than, equal-to, or
1557/// greater than a given LLT.
1558class MemoryVsLLTSizePredicateMatcher : public InstructionPredicateMatcher {
1559public:
1560 enum RelationKind {
1561 GreaterThan,
1562 EqualTo,
1563 LessThan,
1564 };
1565
1566protected:
1567 unsigned MMOIdx;
1568 RelationKind Relation;
1569 unsigned OpIdx;
1570
1571public:
1572 MemoryVsLLTSizePredicateMatcher(unsigned InsnVarID, unsigned MMOIdx,
1573 enum RelationKind Relation,
1574 unsigned OpIdx)
1575 : InstructionPredicateMatcher(IPM_MemoryVsLLTSize, InsnVarID),
1576 MMOIdx(MMOIdx), Relation(Relation), OpIdx(OpIdx) {}
1577
1578 static bool classof(const PredicateMatcher *P) {
1579 return P->getKind() == IPM_MemoryVsLLTSize;
1580 }
1581 bool isIdentical(const PredicateMatcher &B) const override {
1582 return InstructionPredicateMatcher::isIdentical(B) &&
1583 MMOIdx == cast<MemoryVsLLTSizePredicateMatcher>(&B)->MMOIdx &&
1584 Relation == cast<MemoryVsLLTSizePredicateMatcher>(&B)->Relation &&
1585 OpIdx == cast<MemoryVsLLTSizePredicateMatcher>(&B)->OpIdx;
1586 }
1587
1588 void emitPredicateOpcodes(MatchTable &Table,
1589 RuleMatcher &Rule) const override {
1590 Table << MatchTable::Opcode(Relation == EqualTo
1591 ? "GIM_CheckMemorySizeEqualToLLT"
1592 : Relation == GreaterThan
1593 ? "GIM_CheckMemorySizeGreaterThanLLT"
1594 : "GIM_CheckMemorySizeLessThanLLT")
1595 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1596 << MatchTable::Comment("MMO") << MatchTable::IntValue(MMOIdx)
1597 << MatchTable::Comment("OpIdx") << MatchTable::IntValue(OpIdx)
1598 << MatchTable::LineBreak;
1599 }
1600};
1601
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001602/// Generates code to check that a set of predicates and operands match for a
1603/// particular instruction.
1604///
1605/// Typical predicates include:
1606/// * Has a specific opcode.
1607/// * Has an nsw/nuw flag or doesn't.
1608class InstructionMatcher
1609 : public PredicateListMatcher<InstructionPredicateMatcher> {
1610protected:
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001611 typedef std::vector<std::unique_ptr<OperandMatcher>> OperandVec;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001612
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001613 RuleMatcher &Rule;
1614
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001615 /// The operands to match. All rendered operands must be present even if the
1616 /// condition is always true.
1617 OperandVec Operands;
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001618
Daniel Sanders05540042017-08-08 10:44:31 +00001619 std::string SymbolicName;
Quentin Colombetaad20be2017-12-15 23:07:42 +00001620 unsigned InsnVarID;
Daniel Sanders05540042017-08-08 10:44:31 +00001621
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001622public:
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001623 InstructionMatcher(RuleMatcher &Rule, StringRef SymbolicName)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001624 : Rule(Rule), SymbolicName(SymbolicName) {
1625 // We create a new instruction matcher.
1626 // Get a new ID for that instruction.
1627 InsnVarID = Rule.implicitlyDefineInsnVar(*this);
1628 }
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001629
1630 RuleMatcher &getRuleMatcher() const { return Rule; }
Daniel Sanders05540042017-08-08 10:44:31 +00001631
Quentin Colombetaad20be2017-12-15 23:07:42 +00001632 unsigned getVarID() const { return InsnVarID; }
1633
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001634 /// Add an operand to the matcher.
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001635 OperandMatcher &addOperand(unsigned OpIdx, const std::string &SymbolicName,
1636 unsigned AllocatedTemporariesBaseID) {
1637 Operands.emplace_back(new OperandMatcher(*this, OpIdx, SymbolicName,
1638 AllocatedTemporariesBaseID));
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001639 if (!SymbolicName.empty())
1640 Rule.defineOperand(SymbolicName, *Operands.back());
1641
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001642 return *Operands.back();
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001643 }
1644
Daniel Sandersffc7d582017-03-29 15:37:18 +00001645 OperandMatcher &getOperand(unsigned OpIdx) {
1646 auto I = std::find_if(Operands.begin(), Operands.end(),
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001647 [&OpIdx](const std::unique_ptr<OperandMatcher> &X) {
1648 return X->getOperandIndex() == OpIdx;
Daniel Sandersffc7d582017-03-29 15:37:18 +00001649 });
1650 if (I != Operands.end())
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001651 return **I;
Daniel Sandersffc7d582017-03-29 15:37:18 +00001652 llvm_unreachable("Failed to lookup operand");
1653 }
1654
Daniel Sanders05540042017-08-08 10:44:31 +00001655 StringRef getSymbolicName() const { return SymbolicName; }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001656 unsigned getNumOperands() const { return Operands.size(); }
Daniel Sandersbee57392017-04-04 13:25:23 +00001657 OperandVec::iterator operands_begin() { return Operands.begin(); }
1658 OperandVec::iterator operands_end() { return Operands.end(); }
1659 iterator_range<OperandVec::iterator> operands() {
1660 return make_range(operands_begin(), operands_end());
1661 }
Daniel Sandersffc7d582017-03-29 15:37:18 +00001662 OperandVec::const_iterator operands_begin() const { return Operands.begin(); }
1663 OperandVec::const_iterator operands_end() const { return Operands.end(); }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001664 iterator_range<OperandVec::const_iterator> operands() const {
1665 return make_range(operands_begin(), operands_end());
1666 }
Quentin Colombetec76d9c2017-12-18 19:47:41 +00001667 bool operands_empty() const { return Operands.empty(); }
1668
1669 void pop_front() { Operands.erase(Operands.begin()); }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001670
Daniel Sanders9d662d22017-07-06 10:06:12 +00001671 /// Emit MatchTable opcodes to check the shape of the match and capture
1672 /// instructions into the MIs table.
Quentin Colombetaad20be2017-12-15 23:07:42 +00001673 void emitCaptureOpcodes(MatchTable &Table, RuleMatcher &Rule) {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001674 Table << MatchTable::Opcode("GIM_CheckNumOperands")
Quentin Colombetaad20be2017-12-15 23:07:42 +00001675 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001676 << MatchTable::Comment("Expected")
1677 << MatchTable::IntValue(getNumOperands()) << MatchTable::LineBreak;
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001678 for (const auto &Operand : Operands)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001679 Operand->emitCaptureOpcodes(Table, Rule);
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001680 }
1681
Daniel Sanders9d662d22017-07-06 10:06:12 +00001682 /// Emit MatchTable opcodes that test whether the instruction named in
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001683 /// InsnVarName matches all the predicates and all the operands.
Quentin Colombetaad20be2017-12-15 23:07:42 +00001684 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule) const {
1685 emitPredicateListOpcodes(Table, Rule);
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001686 for (const auto &Operand : Operands)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001687 Operand->emitPredicateOpcodes(Table, Rule);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001688 }
Daniel Sanders759ff412017-02-24 13:58:11 +00001689
1690 /// Compare the priority of this object and B.
1691 ///
1692 /// Returns true if this object is more important than B.
1693 bool isHigherPriorityThan(const InstructionMatcher &B) const {
1694 // Instruction matchers involving more operands have higher priority.
1695 if (Operands.size() > B.Operands.size())
1696 return true;
1697 if (Operands.size() < B.Operands.size())
1698 return false;
1699
1700 for (const auto &Predicate : zip(predicates(), B.predicates())) {
1701 if (std::get<0>(Predicate)->isHigherPriorityThan(*std::get<1>(Predicate)))
1702 return true;
1703 if (std::get<1>(Predicate)->isHigherPriorityThan(*std::get<0>(Predicate)))
1704 return false;
1705 }
1706
1707 for (const auto &Operand : zip(Operands, B.Operands)) {
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001708 if (std::get<0>(Operand)->isHigherPriorityThan(*std::get<1>(Operand)))
Daniel Sanders759ff412017-02-24 13:58:11 +00001709 return true;
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001710 if (std::get<1>(Operand)->isHigherPriorityThan(*std::get<0>(Operand)))
Daniel Sanders759ff412017-02-24 13:58:11 +00001711 return false;
1712 }
1713
1714 return false;
1715 };
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001716
1717 /// Report the maximum number of temporary operands needed by the instruction
1718 /// matcher.
Daniel Sanders2deea182017-04-22 15:11:04 +00001719 unsigned countRendererFns() const {
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001720 return std::accumulate(predicates().begin(), predicates().end(), 0,
1721 [](unsigned A,
1722 const std::unique_ptr<InstructionPredicateMatcher>
1723 &Predicate) {
Daniel Sanders2deea182017-04-22 15:11:04 +00001724 return A + Predicate->countRendererFns();
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001725 }) +
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001726 std::accumulate(
1727 Operands.begin(), Operands.end(), 0,
1728 [](unsigned A, const std::unique_ptr<OperandMatcher> &Operand) {
Daniel Sanders2deea182017-04-22 15:11:04 +00001729 return A + Operand->countRendererFns();
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001730 });
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001731 }
Daniel Sanders05540042017-08-08 10:44:31 +00001732
1733 bool isConstantInstruction() const {
1734 for (const auto &P : predicates())
1735 if (const InstructionOpcodeMatcher *Opcode =
1736 dyn_cast<InstructionOpcodeMatcher>(P.get()))
1737 return Opcode->isConstantInstruction();
1738 return false;
1739 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001740};
1741
Quentin Colombetaad20be2017-12-15 23:07:42 +00001742template <>
1743template <class Kind, class... Args>
1744Optional<Kind *>
1745PredicateListMatcher<InstructionPredicateMatcher>::addPredicate(
1746 Args &&... args) {
1747 InstructionMatcher *InstMatcher = static_cast<InstructionMatcher *>(this);
1748 Predicates.emplace_back(llvm::make_unique<Kind>(InstMatcher->getVarID(),
1749 std::forward<Args>(args)...));
1750 return static_cast<Kind *>(Predicates.back().get());
1751}
1752
Daniel Sandersbee57392017-04-04 13:25:23 +00001753/// Generates code to check that the operand is a register defined by an
1754/// instruction that matches the given instruction matcher.
1755///
1756/// For example, the pattern:
1757/// (set $dst, (G_MUL (G_ADD $src1, $src2), $src3))
1758/// would use an InstructionOperandMatcher for operand 1 of the G_MUL to match
1759/// the:
1760/// (G_ADD $src1, $src2)
1761/// subpattern.
1762class InstructionOperandMatcher : public OperandPredicateMatcher {
1763protected:
1764 std::unique_ptr<InstructionMatcher> InsnMatcher;
1765
1766public:
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001767 InstructionOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
1768 RuleMatcher &Rule, StringRef SymbolicName)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001769 : OperandPredicateMatcher(OPM_Instruction, InsnVarID, OpIdx),
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001770 InsnMatcher(new InstructionMatcher(Rule, SymbolicName)) {}
Daniel Sandersbee57392017-04-04 13:25:23 +00001771
Quentin Colombet063d7982017-12-14 23:44:07 +00001772 static bool classof(const PredicateMatcher *P) {
Daniel Sandersbee57392017-04-04 13:25:23 +00001773 return P->getKind() == OPM_Instruction;
1774 }
1775
1776 InstructionMatcher &getInsnMatcher() const { return *InsnMatcher; }
1777
Quentin Colombetaad20be2017-12-15 23:07:42 +00001778 void emitCaptureOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
1779 unsigned InsnID =
1780 Rule.defineInsnVar(Table, *InsnMatcher, InsnVarID, getOpIdx());
1781 (void)InsnID;
1782 assert(InsnMatcher->getVarID() == InsnID &&
1783 "Mismatch between build and emit");
1784 InsnMatcher->emitCaptureOpcodes(Table, Rule);
Daniel Sandersbee57392017-04-04 13:25:23 +00001785 }
1786
Quentin Colombetaad20be2017-12-15 23:07:42 +00001787 void emitPredicateOpcodes(MatchTable &Table,
1788 RuleMatcher &Rule) const override {
1789 InsnMatcher->emitPredicateOpcodes(Table, Rule);
Daniel Sandersbee57392017-04-04 13:25:23 +00001790 }
Daniel Sanders12e6e702018-01-17 20:34:29 +00001791
1792 bool isHigherPriorityThan(const OperandPredicateMatcher &B) const override {
1793 if (OperandPredicateMatcher::isHigherPriorityThan(B))
1794 return true;
1795 if (B.OperandPredicateMatcher::isHigherPriorityThan(*this))
1796 return false;
1797
1798 if (const InstructionOperandMatcher *BP =
1799 dyn_cast<InstructionOperandMatcher>(&B))
1800 if (InsnMatcher->isHigherPriorityThan(*BP->InsnMatcher))
1801 return true;
1802 return false;
1803 }
Daniel Sandersbee57392017-04-04 13:25:23 +00001804};
1805
Daniel Sanders43c882c2017-02-01 10:53:10 +00001806//===- Actions ------------------------------------------------------------===//
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001807class OperandRenderer {
1808public:
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00001809 enum RendererKind {
1810 OR_Copy,
Daniel Sandersd66e0902017-10-23 18:19:24 +00001811 OR_CopyOrAddZeroReg,
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00001812 OR_CopySubReg,
Daniel Sanders05540042017-08-08 10:44:31 +00001813 OR_CopyConstantAsImm,
Daniel Sanders11300ce2017-10-13 21:28:03 +00001814 OR_CopyFConstantAsFPImm,
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00001815 OR_Imm,
1816 OR_Register,
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00001817 OR_TempRegister,
Volkan Kelesf7f25682018-01-16 18:44:05 +00001818 OR_ComplexPattern,
1819 OR_Custom
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00001820 };
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001821
1822protected:
1823 RendererKind Kind;
1824
1825public:
1826 OperandRenderer(RendererKind Kind) : Kind(Kind) {}
1827 virtual ~OperandRenderer() {}
1828
1829 RendererKind getKind() const { return Kind; }
1830
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001831 virtual void emitRenderOpcodes(MatchTable &Table,
1832 RuleMatcher &Rule) const = 0;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001833};
1834
1835/// A CopyRenderer emits code to copy a single operand from an existing
1836/// instruction to the one being built.
1837class CopyRenderer : public OperandRenderer {
1838protected:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001839 unsigned NewInsnID;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001840 /// The name of the operand.
1841 const StringRef SymbolicName;
1842
1843public:
Daniel Sandersbd83ad42017-10-24 01:48:34 +00001844 CopyRenderer(unsigned NewInsnID, StringRef SymbolicName)
1845 : OperandRenderer(OR_Copy), NewInsnID(NewInsnID),
Daniel Sanders05540042017-08-08 10:44:31 +00001846 SymbolicName(SymbolicName) {
1847 assert(!SymbolicName.empty() && "Cannot copy from an unspecified source");
1848 }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001849
1850 static bool classof(const OperandRenderer *R) {
1851 return R->getKind() == OR_Copy;
1852 }
1853
1854 const StringRef getSymbolicName() const { return SymbolicName; }
1855
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001856 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001857 const OperandMatcher &Operand = Rule.getOperandMatcher(SymbolicName);
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001858 unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001859 Table << MatchTable::Opcode("GIR_Copy") << MatchTable::Comment("NewInsnID")
1860 << MatchTable::IntValue(NewInsnID) << MatchTable::Comment("OldInsnID")
1861 << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
1862 << MatchTable::IntValue(Operand.getOperandIndex())
1863 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001864 }
1865};
1866
Daniel Sandersd66e0902017-10-23 18:19:24 +00001867/// A CopyOrAddZeroRegRenderer emits code to copy a single operand from an
1868/// existing instruction to the one being built. If the operand turns out to be
1869/// a 'G_CONSTANT 0' then it replaces the operand with a zero register.
1870class CopyOrAddZeroRegRenderer : public OperandRenderer {
1871protected:
1872 unsigned NewInsnID;
1873 /// The name of the operand.
1874 const StringRef SymbolicName;
1875 const Record *ZeroRegisterDef;
1876
1877public:
1878 CopyOrAddZeroRegRenderer(unsigned NewInsnID,
Daniel Sandersd66e0902017-10-23 18:19:24 +00001879 StringRef SymbolicName, Record *ZeroRegisterDef)
1880 : OperandRenderer(OR_CopyOrAddZeroReg), NewInsnID(NewInsnID),
1881 SymbolicName(SymbolicName), ZeroRegisterDef(ZeroRegisterDef) {
1882 assert(!SymbolicName.empty() && "Cannot copy from an unspecified source");
1883 }
1884
1885 static bool classof(const OperandRenderer *R) {
1886 return R->getKind() == OR_CopyOrAddZeroReg;
1887 }
1888
1889 const StringRef getSymbolicName() const { return SymbolicName; }
1890
1891 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
1892 const OperandMatcher &Operand = Rule.getOperandMatcher(SymbolicName);
1893 unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
1894 Table << MatchTable::Opcode("GIR_CopyOrAddZeroReg")
1895 << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
1896 << MatchTable::Comment("OldInsnID")
1897 << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
1898 << MatchTable::IntValue(Operand.getOperandIndex())
1899 << MatchTable::NamedValue(
1900 (ZeroRegisterDef->getValue("Namespace")
1901 ? ZeroRegisterDef->getValueAsString("Namespace")
1902 : ""),
1903 ZeroRegisterDef->getName())
1904 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
1905 }
1906};
1907
Daniel Sanders05540042017-08-08 10:44:31 +00001908/// A CopyConstantAsImmRenderer emits code to render a G_CONSTANT instruction to
1909/// an extended immediate operand.
1910class CopyConstantAsImmRenderer : public OperandRenderer {
1911protected:
1912 unsigned NewInsnID;
1913 /// The name of the operand.
1914 const std::string SymbolicName;
1915 bool Signed;
1916
1917public:
1918 CopyConstantAsImmRenderer(unsigned NewInsnID, StringRef SymbolicName)
1919 : OperandRenderer(OR_CopyConstantAsImm), NewInsnID(NewInsnID),
1920 SymbolicName(SymbolicName), Signed(true) {}
1921
1922 static bool classof(const OperandRenderer *R) {
1923 return R->getKind() == OR_CopyConstantAsImm;
1924 }
1925
1926 const StringRef getSymbolicName() const { return SymbolicName; }
1927
1928 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
1929 const InstructionMatcher &InsnMatcher = Rule.getInstructionMatcher(SymbolicName);
1930 unsigned OldInsnVarID = Rule.getInsnVarID(InsnMatcher);
1931 Table << MatchTable::Opcode(Signed ? "GIR_CopyConstantAsSImm"
1932 : "GIR_CopyConstantAsUImm")
1933 << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
1934 << MatchTable::Comment("OldInsnID")
1935 << MatchTable::IntValue(OldInsnVarID)
1936 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
1937 }
1938};
1939
Daniel Sanders11300ce2017-10-13 21:28:03 +00001940/// A CopyFConstantAsFPImmRenderer emits code to render a G_FCONSTANT
1941/// instruction to an extended immediate operand.
1942class CopyFConstantAsFPImmRenderer : public OperandRenderer {
1943protected:
1944 unsigned NewInsnID;
1945 /// The name of the operand.
1946 const std::string SymbolicName;
1947
1948public:
1949 CopyFConstantAsFPImmRenderer(unsigned NewInsnID, StringRef SymbolicName)
1950 : OperandRenderer(OR_CopyFConstantAsFPImm), NewInsnID(NewInsnID),
1951 SymbolicName(SymbolicName) {}
1952
1953 static bool classof(const OperandRenderer *R) {
1954 return R->getKind() == OR_CopyFConstantAsFPImm;
1955 }
1956
1957 const StringRef getSymbolicName() const { return SymbolicName; }
1958
1959 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
1960 const InstructionMatcher &InsnMatcher = Rule.getInstructionMatcher(SymbolicName);
1961 unsigned OldInsnVarID = Rule.getInsnVarID(InsnMatcher);
1962 Table << MatchTable::Opcode("GIR_CopyFConstantAsFPImm")
1963 << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
1964 << MatchTable::Comment("OldInsnID")
1965 << MatchTable::IntValue(OldInsnVarID)
1966 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
1967 }
1968};
1969
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00001970/// A CopySubRegRenderer emits code to copy a single register operand from an
1971/// existing instruction to the one being built and indicate that only a
1972/// subregister should be copied.
1973class CopySubRegRenderer : public OperandRenderer {
1974protected:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001975 unsigned NewInsnID;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00001976 /// The name of the operand.
1977 const StringRef SymbolicName;
1978 /// The subregister to extract.
1979 const CodeGenSubRegIndex *SubReg;
1980
1981public:
Daniel Sandersbd83ad42017-10-24 01:48:34 +00001982 CopySubRegRenderer(unsigned NewInsnID, StringRef SymbolicName,
1983 const CodeGenSubRegIndex *SubReg)
1984 : OperandRenderer(OR_CopySubReg), NewInsnID(NewInsnID),
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00001985 SymbolicName(SymbolicName), SubReg(SubReg) {}
1986
1987 static bool classof(const OperandRenderer *R) {
1988 return R->getKind() == OR_CopySubReg;
1989 }
1990
1991 const StringRef getSymbolicName() const { return SymbolicName; }
1992
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001993 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001994 const OperandMatcher &Operand = Rule.getOperandMatcher(SymbolicName);
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001995 unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001996 Table << MatchTable::Opcode("GIR_CopySubReg")
1997 << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
1998 << MatchTable::Comment("OldInsnID")
1999 << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
2000 << MatchTable::IntValue(Operand.getOperandIndex())
2001 << MatchTable::Comment("SubRegIdx")
2002 << MatchTable::IntValue(SubReg->EnumValue)
2003 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002004 }
2005};
2006
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002007/// Adds a specific physical register to the instruction being built.
2008/// This is typically useful for WZR/XZR on AArch64.
2009class AddRegisterRenderer : public OperandRenderer {
2010protected:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002011 unsigned InsnID;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002012 const Record *RegisterDef;
2013
2014public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002015 AddRegisterRenderer(unsigned InsnID, const Record *RegisterDef)
2016 : OperandRenderer(OR_Register), InsnID(InsnID), RegisterDef(RegisterDef) {
2017 }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002018
2019 static bool classof(const OperandRenderer *R) {
2020 return R->getKind() == OR_Register;
2021 }
2022
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002023 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2024 Table << MatchTable::Opcode("GIR_AddRegister")
2025 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2026 << MatchTable::NamedValue(
2027 (RegisterDef->getValue("Namespace")
2028 ? RegisterDef->getValueAsString("Namespace")
2029 : ""),
2030 RegisterDef->getName())
2031 << MatchTable::LineBreak;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002032 }
2033};
2034
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002035/// Adds a specific temporary virtual register to the instruction being built.
2036/// This is used to chain instructions together when emitting multiple
2037/// instructions.
2038class TempRegRenderer : public OperandRenderer {
2039protected:
2040 unsigned InsnID;
2041 unsigned TempRegID;
2042 bool IsDef;
2043
2044public:
2045 TempRegRenderer(unsigned InsnID, unsigned TempRegID, bool IsDef = false)
2046 : OperandRenderer(OR_Register), InsnID(InsnID), TempRegID(TempRegID),
2047 IsDef(IsDef) {}
2048
2049 static bool classof(const OperandRenderer *R) {
2050 return R->getKind() == OR_TempRegister;
2051 }
2052
2053 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2054 Table << MatchTable::Opcode("GIR_AddTempRegister")
2055 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2056 << MatchTable::Comment("TempRegID") << MatchTable::IntValue(TempRegID)
2057 << MatchTable::Comment("TempRegFlags");
2058 if (IsDef)
2059 Table << MatchTable::NamedValue("RegState::Define");
2060 else
2061 Table << MatchTable::IntValue(0);
2062 Table << MatchTable::LineBreak;
2063 }
2064};
2065
Daniel Sanders0ed28822017-04-12 08:23:08 +00002066/// Adds a specific immediate to the instruction being built.
2067class ImmRenderer : public OperandRenderer {
2068protected:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002069 unsigned InsnID;
Daniel Sanders0ed28822017-04-12 08:23:08 +00002070 int64_t Imm;
2071
2072public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002073 ImmRenderer(unsigned InsnID, int64_t Imm)
2074 : OperandRenderer(OR_Imm), InsnID(InsnID), Imm(Imm) {}
Daniel Sanders0ed28822017-04-12 08:23:08 +00002075
2076 static bool classof(const OperandRenderer *R) {
2077 return R->getKind() == OR_Imm;
2078 }
2079
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002080 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2081 Table << MatchTable::Opcode("GIR_AddImm") << MatchTable::Comment("InsnID")
2082 << MatchTable::IntValue(InsnID) << MatchTable::Comment("Imm")
2083 << MatchTable::IntValue(Imm) << MatchTable::LineBreak;
Daniel Sanders0ed28822017-04-12 08:23:08 +00002084 }
2085};
2086
Daniel Sanders2deea182017-04-22 15:11:04 +00002087/// Adds operands by calling a renderer function supplied by the ComplexPattern
2088/// matcher function.
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002089class RenderComplexPatternOperand : public OperandRenderer {
2090private:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002091 unsigned InsnID;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002092 const Record &TheDef;
Daniel Sanders2deea182017-04-22 15:11:04 +00002093 /// The name of the operand.
2094 const StringRef SymbolicName;
2095 /// The renderer number. This must be unique within a rule since it's used to
2096 /// identify a temporary variable to hold the renderer function.
2097 unsigned RendererID;
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002098 /// When provided, this is the suboperand of the ComplexPattern operand to
2099 /// render. Otherwise all the suboperands will be rendered.
2100 Optional<unsigned> SubOperand;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002101
2102 unsigned getNumOperands() const {
2103 return TheDef.getValueAsDag("Operands")->getNumArgs();
2104 }
2105
2106public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002107 RenderComplexPatternOperand(unsigned InsnID, const Record &TheDef,
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002108 StringRef SymbolicName, unsigned RendererID,
2109 Optional<unsigned> SubOperand = None)
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002110 : OperandRenderer(OR_ComplexPattern), InsnID(InsnID), TheDef(TheDef),
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002111 SymbolicName(SymbolicName), RendererID(RendererID),
2112 SubOperand(SubOperand) {}
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002113
2114 static bool classof(const OperandRenderer *R) {
2115 return R->getKind() == OR_ComplexPattern;
2116 }
2117
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002118 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002119 Table << MatchTable::Opcode(SubOperand.hasValue() ? "GIR_ComplexSubOperandRenderer"
2120 : "GIR_ComplexRenderer")
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002121 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2122 << MatchTable::Comment("RendererID")
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002123 << MatchTable::IntValue(RendererID);
2124 if (SubOperand.hasValue())
2125 Table << MatchTable::Comment("SubOperand")
2126 << MatchTable::IntValue(SubOperand.getValue());
2127 Table << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002128 }
2129};
2130
Volkan Kelesf7f25682018-01-16 18:44:05 +00002131class CustomRenderer : public OperandRenderer {
2132protected:
2133 unsigned InsnID;
2134 const Record &Renderer;
2135 /// The name of the operand.
2136 const std::string SymbolicName;
2137
2138public:
2139 CustomRenderer(unsigned InsnID, const Record &Renderer,
2140 StringRef SymbolicName)
2141 : OperandRenderer(OR_Custom), InsnID(InsnID), Renderer(Renderer),
2142 SymbolicName(SymbolicName) {}
2143
2144 static bool classof(const OperandRenderer *R) {
2145 return R->getKind() == OR_Custom;
2146 }
2147
2148 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2149 const InstructionMatcher &InsnMatcher =
2150 Rule.getInstructionMatcher(SymbolicName);
2151 unsigned OldInsnVarID = Rule.getInsnVarID(InsnMatcher);
2152 Table << MatchTable::Opcode("GIR_CustomRenderer")
2153 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2154 << MatchTable::Comment("OldInsnID")
2155 << MatchTable::IntValue(OldInsnVarID)
2156 << MatchTable::Comment("Renderer")
2157 << MatchTable::NamedValue(
2158 "GICR_" + Renderer.getValueAsString("RendererFn").str())
2159 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2160 }
2161};
2162
Ahmed Bougacha56ca3a92017-02-04 00:47:10 +00002163/// An action taken when all Matcher predicates succeeded for a parent rule.
2164///
2165/// Typical actions include:
2166/// * Changing the opcode of an instruction.
2167/// * Adding an operand to an instruction.
Daniel Sanders43c882c2017-02-01 10:53:10 +00002168class MatchAction {
2169public:
2170 virtual ~MatchAction() {}
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002171
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002172 /// Emit the MatchTable opcodes to implement the action.
Daniel Sandersa7b75262017-10-31 18:50:24 +00002173 virtual void emitActionOpcodes(MatchTable &Table,
2174 RuleMatcher &Rule) const = 0;
Daniel Sanders43c882c2017-02-01 10:53:10 +00002175};
2176
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +00002177/// Generates a comment describing the matched rule being acted upon.
2178class DebugCommentAction : public MatchAction {
2179private:
Daniel Sanders6ea17ed2017-10-31 18:07:03 +00002180 std::string S;
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +00002181
2182public:
Daniel Sanders6ea17ed2017-10-31 18:07:03 +00002183 DebugCommentAction(StringRef S) : S(S) {}
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +00002184
Daniel Sandersa7b75262017-10-31 18:50:24 +00002185 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sanders6ea17ed2017-10-31 18:07:03 +00002186 Table << MatchTable::Comment(S) << MatchTable::LineBreak;
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +00002187 }
2188};
2189
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002190/// Generates code to build an instruction or mutate an existing instruction
2191/// into the desired instruction when this is possible.
2192class BuildMIAction : public MatchAction {
Daniel Sanders43c882c2017-02-01 10:53:10 +00002193private:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002194 unsigned InsnID;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002195 const CodeGenInstruction *I;
Daniel Sanders64f745c2017-10-24 17:08:43 +00002196 const InstructionMatcher *Matched;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002197 std::vector<std::unique_ptr<OperandRenderer>> OperandRenderers;
2198
2199 /// True if the instruction can be built solely by mutating the opcode.
Daniel Sandersa7b75262017-10-31 18:50:24 +00002200 bool canMutate(RuleMatcher &Rule, const InstructionMatcher *Insn) const {
2201 if (!Insn)
Daniel Sandersab1d1192017-10-24 18:11:54 +00002202 return false;
2203
Daniel Sandersa7b75262017-10-31 18:50:24 +00002204 if (OperandRenderers.size() != Insn->getNumOperands())
Daniel Sanderse9fdba32017-04-29 17:30:09 +00002205 return false;
2206
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002207 for (const auto &Renderer : enumerate(OperandRenderers)) {
Zachary Turner309a0882017-03-13 16:24:10 +00002208 if (const auto *Copy = dyn_cast<CopyRenderer>(&*Renderer.value())) {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002209 const OperandMatcher &OM = Rule.getOperandMatcher(Copy->getSymbolicName());
Daniel Sandersa7b75262017-10-31 18:50:24 +00002210 if (Insn != &OM.getInstructionMatcher() ||
Daniel Sanders3016d3c2017-04-22 14:31:28 +00002211 OM.getOperandIndex() != Renderer.index())
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002212 return false;
2213 } else
2214 return false;
2215 }
2216
2217 return true;
2218 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002219
Daniel Sanders43c882c2017-02-01 10:53:10 +00002220public:
Daniel Sandersa7b75262017-10-31 18:50:24 +00002221 BuildMIAction(unsigned InsnID, const CodeGenInstruction *I)
2222 : InsnID(InsnID), I(I), Matched(nullptr) {}
2223
Daniel Sanders08464522018-01-29 21:09:12 +00002224 unsigned getInsnID() const { return InsnID; }
Daniel Sandersdf258e32017-10-31 19:09:29 +00002225 const CodeGenInstruction *getCGI() const { return I; }
2226
Daniel Sandersa7b75262017-10-31 18:50:24 +00002227 void chooseInsnToMutate(RuleMatcher &Rule) {
2228 for (const auto *MutateCandidate : Rule.mutatable_insns()) {
2229 if (canMutate(Rule, MutateCandidate)) {
2230 // Take the first one we're offered that we're able to mutate.
2231 Rule.reserveInsnMatcherForMutation(MutateCandidate);
2232 Matched = MutateCandidate;
2233 return;
2234 }
2235 }
2236 }
Daniel Sanders43c882c2017-02-01 10:53:10 +00002237
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002238 template <class Kind, class... Args>
2239 Kind &addRenderer(Args&&... args) {
2240 OperandRenderers.emplace_back(
Daniel Sanders198447a2017-11-01 00:29:47 +00002241 llvm::make_unique<Kind>(InsnID, std::forward<Args>(args)...));
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002242 return *static_cast<Kind *>(OperandRenderers.back().get());
2243 }
2244
Daniel Sandersa7b75262017-10-31 18:50:24 +00002245 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2246 if (Matched) {
2247 assert(canMutate(Rule, Matched) &&
2248 "Arranged to mutate an insn that isn't mutatable");
2249
2250 unsigned RecycleInsnID = Rule.getInsnVarID(*Matched);
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002251 Table << MatchTable::Opcode("GIR_MutateOpcode")
2252 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2253 << MatchTable::Comment("RecycleInsnID")
2254 << MatchTable::IntValue(RecycleInsnID)
2255 << MatchTable::Comment("Opcode")
2256 << MatchTable::NamedValue(I->Namespace, I->TheDef->getName())
2257 << MatchTable::LineBreak;
Tim Northover4340d642017-03-20 21:58:23 +00002258
2259 if (!I->ImplicitDefs.empty() || !I->ImplicitUses.empty()) {
Tim Northover4340d642017-03-20 21:58:23 +00002260 for (auto Def : I->ImplicitDefs) {
Diana Picus8abcbbb2017-05-02 09:40:49 +00002261 auto Namespace = Def->getValue("Namespace")
2262 ? Def->getValueAsString("Namespace")
2263 : "";
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002264 Table << MatchTable::Opcode("GIR_AddImplicitDef")
2265 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2266 << MatchTable::NamedValue(Namespace, Def->getName())
2267 << MatchTable::LineBreak;
Tim Northover4340d642017-03-20 21:58:23 +00002268 }
2269 for (auto Use : I->ImplicitUses) {
Diana Picus8abcbbb2017-05-02 09:40:49 +00002270 auto Namespace = Use->getValue("Namespace")
2271 ? Use->getValueAsString("Namespace")
2272 : "";
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002273 Table << MatchTable::Opcode("GIR_AddImplicitUse")
2274 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2275 << MatchTable::NamedValue(Namespace, Use->getName())
2276 << MatchTable::LineBreak;
Tim Northover4340d642017-03-20 21:58:23 +00002277 }
2278 }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002279 return;
2280 }
2281
2282 // TODO: Simple permutation looks like it could be almost as common as
2283 // mutation due to commutative operations.
2284
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002285 Table << MatchTable::Opcode("GIR_BuildMI") << MatchTable::Comment("InsnID")
2286 << MatchTable::IntValue(InsnID) << MatchTable::Comment("Opcode")
2287 << MatchTable::NamedValue(I->Namespace, I->TheDef->getName())
2288 << MatchTable::LineBreak;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002289 for (const auto &Renderer : OperandRenderers)
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002290 Renderer->emitRenderOpcodes(Table, Rule);
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002291
Florian Hahn3bc3ec62017-08-03 14:48:22 +00002292 if (I->mayLoad || I->mayStore) {
2293 Table << MatchTable::Opcode("GIR_MergeMemOperands")
2294 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2295 << MatchTable::Comment("MergeInsnID's");
2296 // Emit the ID's for all the instructions that are matched by this rule.
2297 // TODO: Limit this to matched instructions that mayLoad/mayStore or have
2298 // some other means of having a memoperand. Also limit this to
2299 // emitted instructions that expect to have a memoperand too. For
2300 // example, (G_SEXT (G_LOAD x)) that results in separate load and
2301 // sign-extend instructions shouldn't put the memoperand on the
2302 // sign-extend since it has no effect there.
2303 std::vector<unsigned> MergeInsnIDs;
2304 for (const auto &IDMatcherPair : Rule.defined_insn_vars())
2305 MergeInsnIDs.push_back(IDMatcherPair.second);
Mandeep Singh Grang1b0e2f22018-04-06 20:18:05 +00002306 llvm::sort(MergeInsnIDs.begin(), MergeInsnIDs.end());
Florian Hahn3bc3ec62017-08-03 14:48:22 +00002307 for (const auto &MergeInsnID : MergeInsnIDs)
2308 Table << MatchTable::IntValue(MergeInsnID);
Daniel Sanders05540042017-08-08 10:44:31 +00002309 Table << MatchTable::NamedValue("GIU_MergeMemOperands_EndOfList")
2310 << MatchTable::LineBreak;
Florian Hahn3bc3ec62017-08-03 14:48:22 +00002311 }
2312
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002313 // FIXME: This is a hack but it's sufficient for ISel. We'll need to do
2314 // better for combines. Particularly when there are multiple match
2315 // roots.
2316 if (InsnID == 0)
2317 Table << MatchTable::Opcode("GIR_EraseFromParent")
2318 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2319 << MatchTable::LineBreak;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002320 }
2321};
2322
2323/// Generates code to constrain the operands of an output instruction to the
2324/// register classes specified by the definition of that instruction.
2325class ConstrainOperandsToDefinitionAction : public MatchAction {
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002326 unsigned InsnID;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002327
2328public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002329 ConstrainOperandsToDefinitionAction(unsigned InsnID) : InsnID(InsnID) {}
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002330
Daniel Sandersa7b75262017-10-31 18:50:24 +00002331 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002332 Table << MatchTable::Opcode("GIR_ConstrainSelectedInstOperands")
2333 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2334 << MatchTable::LineBreak;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002335 }
2336};
2337
2338/// Generates code to constrain the specified operand of an output instruction
2339/// to the specified register class.
2340class ConstrainOperandToRegClassAction : public MatchAction {
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002341 unsigned InsnID;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002342 unsigned OpIdx;
2343 const CodeGenRegisterClass &RC;
2344
2345public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002346 ConstrainOperandToRegClassAction(unsigned InsnID, unsigned OpIdx,
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002347 const CodeGenRegisterClass &RC)
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002348 : InsnID(InsnID), OpIdx(OpIdx), RC(RC) {}
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002349
Daniel Sandersa7b75262017-10-31 18:50:24 +00002350 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002351 Table << MatchTable::Opcode("GIR_ConstrainOperandRC")
2352 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2353 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
2354 << MatchTable::Comment("RC " + RC.getName())
2355 << MatchTable::IntValue(RC.EnumValue) << MatchTable::LineBreak;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002356 }
2357};
2358
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002359/// Generates code to create a temporary register which can be used to chain
2360/// instructions together.
2361class MakeTempRegisterAction : public MatchAction {
2362private:
2363 LLTCodeGen Ty;
2364 unsigned TempRegID;
2365
2366public:
2367 MakeTempRegisterAction(const LLTCodeGen &Ty, unsigned TempRegID)
2368 : Ty(Ty), TempRegID(TempRegID) {}
2369
2370 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2371 Table << MatchTable::Opcode("GIR_MakeTempReg")
2372 << MatchTable::Comment("TempRegID") << MatchTable::IntValue(TempRegID)
2373 << MatchTable::Comment("TypeID")
2374 << MatchTable::NamedValue(Ty.getCxxEnumValue())
2375 << MatchTable::LineBreak;
2376 }
2377};
2378
Daniel Sanders05540042017-08-08 10:44:31 +00002379InstructionMatcher &RuleMatcher::addInstructionMatcher(StringRef SymbolicName) {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002380 Matchers.emplace_back(new InstructionMatcher(*this, SymbolicName));
Daniel Sandersa7b75262017-10-31 18:50:24 +00002381 MutatableInsns.insert(Matchers.back().get());
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002382 return *Matchers.back();
2383}
Ahmed Bougacha56ca3a92017-02-04 00:47:10 +00002384
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002385void RuleMatcher::addRequiredFeature(Record *Feature) {
2386 RequiredFeatures.push_back(Feature);
2387}
2388
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002389const std::vector<Record *> &RuleMatcher::getRequiredFeatures() const {
2390 return RequiredFeatures;
2391}
2392
Daniel Sanders7438b262017-10-31 23:03:18 +00002393// Emplaces an action of the specified Kind at the end of the action list.
2394//
2395// Returns a reference to the newly created action.
2396//
2397// Like std::vector::emplace_back(), may invalidate all iterators if the new
2398// size exceeds the capacity. Otherwise, only invalidates the past-the-end
2399// iterator.
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002400template <class Kind, class... Args>
2401Kind &RuleMatcher::addAction(Args &&... args) {
2402 Actions.emplace_back(llvm::make_unique<Kind>(std::forward<Args>(args)...));
2403 return *static_cast<Kind *>(Actions.back().get());
2404}
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002405
Daniel Sanders7438b262017-10-31 23:03:18 +00002406// Emplaces an action of the specified Kind before the given insertion point.
2407//
2408// Returns an iterator pointing at the newly created instruction.
2409//
2410// Like std::vector::insert(), may invalidate all iterators if the new size
2411// exceeds the capacity. Otherwise, only invalidates the iterators from the
2412// insertion point onwards.
2413template <class Kind, class... Args>
2414action_iterator RuleMatcher::insertAction(action_iterator InsertPt,
2415 Args &&... args) {
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002416 return Actions.emplace(InsertPt,
2417 llvm::make_unique<Kind>(std::forward<Args>(args)...));
Daniel Sanders7438b262017-10-31 23:03:18 +00002418}
Daniel Sandersdc662ff2017-01-26 11:10:14 +00002419
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002420unsigned
2421RuleMatcher::implicitlyDefineInsnVar(const InstructionMatcher &Matcher) {
2422 unsigned NewInsnVarID = NextInsnVarID++;
2423 InsnVariableIDs[&Matcher] = NewInsnVarID;
2424 return NewInsnVarID;
Daniel Sandersb96f40d2017-03-20 15:20:42 +00002425}
2426
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002427unsigned RuleMatcher::defineInsnVar(MatchTable &Table,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002428 const InstructionMatcher &Matcher,
2429 unsigned InsnID, unsigned OpIdx) {
2430 unsigned NewInsnVarID = implicitlyDefineInsnVar(Matcher);
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002431 Table << MatchTable::Opcode("GIM_RecordInsn")
2432 << MatchTable::Comment("DefineMI") << MatchTable::IntValue(NewInsnVarID)
2433 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnID)
2434 << MatchTable::Comment("OpIdx") << MatchTable::IntValue(OpIdx)
2435 << MatchTable::Comment("MIs[" + llvm::to_string(NewInsnVarID) + "]")
2436 << MatchTable::LineBreak;
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002437 return NewInsnVarID;
2438}
2439
2440unsigned RuleMatcher::getInsnVarID(const InstructionMatcher &InsnMatcher) const {
2441 const auto &I = InsnVariableIDs.find(&InsnMatcher);
2442 if (I != InsnVariableIDs.end())
Daniel Sandersb96f40d2017-03-20 15:20:42 +00002443 return I->second;
2444 llvm_unreachable("Matched Insn was not captured in a local variable");
2445}
2446
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002447void RuleMatcher::defineOperand(StringRef SymbolicName, OperandMatcher &OM) {
2448 if (DefinedOperands.find(SymbolicName) == DefinedOperands.end()) {
2449 DefinedOperands[SymbolicName] = &OM;
2450 return;
2451 }
2452
2453 // If the operand is already defined, then we must ensure both references in
2454 // the matcher have the exact same node.
2455 OM.addPredicate<SameOperandMatcher>(OM.getSymbolicName());
2456}
2457
Daniel Sanders05540042017-08-08 10:44:31 +00002458const InstructionMatcher &
2459RuleMatcher::getInstructionMatcher(StringRef SymbolicName) const {
2460 for (const auto &I : InsnVariableIDs)
2461 if (I.first->getSymbolicName() == SymbolicName)
2462 return *I.first;
2463 llvm_unreachable(
2464 ("Failed to lookup instruction " + SymbolicName).str().c_str());
2465}
2466
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002467const OperandMatcher &
2468RuleMatcher::getOperandMatcher(StringRef Name) const {
2469 const auto &I = DefinedOperands.find(Name);
2470
2471 if (I == DefinedOperands.end())
2472 PrintFatalError(SrcLoc, "Operand " + Name + " was not declared in matcher");
2473
2474 return *I->second;
2475}
2476
Daniel Sanders9d662d22017-07-06 10:06:12 +00002477/// Emit MatchTable opcodes to check the shape of the match and capture
Daniel Sandersb96f40d2017-03-20 15:20:42 +00002478/// instructions into local variables.
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002479void RuleMatcher::emitCaptureOpcodes(MatchTable &Table) {
Daniel Sandersb96f40d2017-03-20 15:20:42 +00002480 assert(Matchers.size() == 1 && "Cannot handle multi-root matchers yet");
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002481 unsigned InsnVarID = implicitlyDefineInsnVar(*Matchers.front());
Quentin Colombeta646ef02017-12-15 23:24:36 +00002482 (void)InsnVarID;
Quentin Colombetaad20be2017-12-15 23:07:42 +00002483 assert(Matchers.front()->getVarID() == InsnVarID &&
2484 "IDs differ between build and emit");
2485 Matchers.front()->emitCaptureOpcodes(Table, *this);
Daniel Sandersb96f40d2017-03-20 15:20:42 +00002486}
2487
Daniel Sanders8e82af22017-07-27 11:03:45 +00002488void RuleMatcher::emit(MatchTable &Table) {
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002489 if (Matchers.empty())
2490 llvm_unreachable("Unexpected empty matcher!");
Daniel Sandersdc662ff2017-01-26 11:10:14 +00002491
Quentin Colombet63a328c2017-12-19 02:57:23 +00002492 // Reset the ID generation so that the emitted IDs match the ones
2493 // we set while building the InstructionMatcher and such.
2494 clearImplicitMap();
2495
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002496 // The representation supports rules that require multiple roots such as:
2497 // %ptr(p0) = ...
2498 // %elt0(s32) = G_LOAD %ptr
2499 // %1(p0) = G_ADD %ptr, 4
2500 // %elt1(s32) = G_LOAD p0 %1
2501 // which could be usefully folded into:
2502 // %ptr(p0) = ...
2503 // %elt0(s32), %elt1(s32) = TGT_LOAD_PAIR %ptr
2504 // on some targets but we don't need to make use of that yet.
2505 assert(Matchers.size() == 1 && "Cannot handle multi-root matchers yet");
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002506
Daniel Sanders8e82af22017-07-27 11:03:45 +00002507 unsigned LabelID = Table.allocateLabelID();
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002508 Table << MatchTable::Opcode("GIM_Try", +1)
Daniel Sanders8e82af22017-07-27 11:03:45 +00002509 << MatchTable::Comment("On fail goto") << MatchTable::JumpTarget(LabelID)
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002510 << MatchTable::LineBreak;
2511
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002512 if (!RequiredFeatures.empty()) {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002513 Table << MatchTable::Opcode("GIM_CheckFeatures")
2514 << MatchTable::NamedValue(getNameForFeatureBitset(RequiredFeatures))
2515 << MatchTable::LineBreak;
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002516 }
Daniel Sandersb96f40d2017-03-20 15:20:42 +00002517
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002518 emitCaptureOpcodes(Table);
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002519
Quentin Colombetaad20be2017-12-15 23:07:42 +00002520 Matchers.front()->emitPredicateOpcodes(Table, *this);
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002521
Daniel Sandersbee57392017-04-04 13:25:23 +00002522 // We must also check if it's safe to fold the matched instructions.
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002523 if (InsnVariableIDs.size() >= 2) {
Galina Kistanova1754fee2017-05-25 01:51:53 +00002524 // Invert the map to create stable ordering (by var names)
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002525 SmallVector<unsigned, 2> InsnIDs;
2526 for (const auto &Pair : InsnVariableIDs) {
Daniel Sandersbee57392017-04-04 13:25:23 +00002527 // Skip the root node since it isn't moving anywhere. Everything else is
2528 // sinking to meet it.
2529 if (Pair.first == Matchers.front().get())
2530 continue;
2531
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002532 InsnIDs.push_back(Pair.second);
Galina Kistanova1754fee2017-05-25 01:51:53 +00002533 }
Mandeep Singh Grang1b0e2f22018-04-06 20:18:05 +00002534 llvm::sort(InsnIDs.begin(), InsnIDs.end());
Galina Kistanova1754fee2017-05-25 01:51:53 +00002535
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002536 for (const auto &InsnID : InsnIDs) {
Daniel Sandersbee57392017-04-04 13:25:23 +00002537 // Reject the difficult cases until we have a more accurate check.
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002538 Table << MatchTable::Opcode("GIM_CheckIsSafeToFold")
2539 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2540 << MatchTable::LineBreak;
Daniel Sandersbee57392017-04-04 13:25:23 +00002541
2542 // FIXME: Emit checks to determine it's _actually_ safe to fold and/or
2543 // account for unsafe cases.
2544 //
2545 // Example:
2546 // MI1--> %0 = ...
2547 // %1 = ... %0
2548 // MI0--> %2 = ... %0
2549 // It's not safe to erase MI1. We currently handle this by not
2550 // erasing %0 (even when it's dead).
2551 //
2552 // Example:
2553 // MI1--> %0 = load volatile @a
2554 // %1 = load volatile @a
2555 // MI0--> %2 = ... %0
2556 // It's not safe to sink %0's def past %1. We currently handle
2557 // this by rejecting all loads.
2558 //
2559 // Example:
2560 // MI1--> %0 = load @a
2561 // %1 = store @a
2562 // MI0--> %2 = ... %0
2563 // It's not safe to sink %0's def past %1. We currently handle
2564 // this by rejecting all loads.
2565 //
2566 // Example:
2567 // G_CONDBR %cond, @BB1
2568 // BB0:
2569 // MI1--> %0 = load @a
2570 // G_BR @BB1
2571 // BB1:
2572 // MI0--> %2 = ... %0
2573 // It's not always safe to sink %0 across control flow. In this
2574 // case it may introduce a memory fault. We currentl handle this
2575 // by rejecting all loads.
2576 }
2577 }
2578
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002579 for (const auto &MA : Actions)
Daniel Sandersa7b75262017-10-31 18:50:24 +00002580 MA->emitActionOpcodes(Table, *this);
Daniel Sandersf76f3152017-11-16 00:46:35 +00002581
Roman Tereshinbeb39312018-05-02 20:15:11 +00002582 if (Table.isWithCoverage())
Daniel Sandersf76f3152017-11-16 00:46:35 +00002583 Table << MatchTable::Opcode("GIR_Coverage") << MatchTable::IntValue(RuleID)
2584 << MatchTable::LineBreak;
2585
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002586 Table << MatchTable::Opcode("GIR_Done", -1) << MatchTable::LineBreak
Daniel Sanders8e82af22017-07-27 11:03:45 +00002587 << MatchTable::Label(LabelID);
Volkan Keles4f3fa792018-01-25 00:18:52 +00002588 ++NumPatternEmitted;
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002589}
Daniel Sanders43c882c2017-02-01 10:53:10 +00002590
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002591bool RuleMatcher::isHigherPriorityThan(const RuleMatcher &B) const {
2592 // Rules involving more match roots have higher priority.
2593 if (Matchers.size() > B.Matchers.size())
2594 return true;
2595 if (Matchers.size() < B.Matchers.size())
Daniel Sanders759ff412017-02-24 13:58:11 +00002596 return false;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002597
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002598 for (const auto &Matcher : zip(Matchers, B.Matchers)) {
2599 if (std::get<0>(Matcher)->isHigherPriorityThan(*std::get<1>(Matcher)))
2600 return true;
2601 if (std::get<1>(Matcher)->isHigherPriorityThan(*std::get<0>(Matcher)))
2602 return false;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002603 }
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002604
2605 return false;
Simon Pilgrima7d1da82017-03-15 22:50:47 +00002606}
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002607
Daniel Sanders2deea182017-04-22 15:11:04 +00002608unsigned RuleMatcher::countRendererFns() const {
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002609 return std::accumulate(
2610 Matchers.begin(), Matchers.end(), 0,
2611 [](unsigned A, const std::unique_ptr<InstructionMatcher> &Matcher) {
Daniel Sanders2deea182017-04-22 15:11:04 +00002612 return A + Matcher->countRendererFns();
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002613 });
2614}
2615
Daniel Sanders05540042017-08-08 10:44:31 +00002616bool OperandPredicateMatcher::isHigherPriorityThan(
2617 const OperandPredicateMatcher &B) const {
2618 // Generally speaking, an instruction is more important than an Int or a
2619 // LiteralInt because it can cover more nodes but theres an exception to
2620 // this. G_CONSTANT's are less important than either of those two because they
2621 // are more permissive.
Daniel Sandersedd07842017-08-17 09:26:14 +00002622
2623 const InstructionOperandMatcher *AOM =
2624 dyn_cast<InstructionOperandMatcher>(this);
2625 const InstructionOperandMatcher *BOM =
2626 dyn_cast<InstructionOperandMatcher>(&B);
2627 bool AIsConstantInsn = AOM && AOM->getInsnMatcher().isConstantInstruction();
2628 bool BIsConstantInsn = BOM && BOM->getInsnMatcher().isConstantInstruction();
2629
2630 if (AOM && BOM) {
2631 // The relative priorities between a G_CONSTANT and any other instruction
2632 // don't actually matter but this code is needed to ensure a strict weak
2633 // ordering. This is particularly important on Windows where the rules will
2634 // be incorrectly sorted without it.
2635 if (AIsConstantInsn != BIsConstantInsn)
2636 return AIsConstantInsn < BIsConstantInsn;
2637 return false;
Daniel Sanders05540042017-08-08 10:44:31 +00002638 }
Daniel Sandersedd07842017-08-17 09:26:14 +00002639
2640 if (AOM && AIsConstantInsn && (B.Kind == OPM_Int || B.Kind == OPM_LiteralInt))
2641 return false;
2642 if (BOM && BIsConstantInsn && (Kind == OPM_Int || Kind == OPM_LiteralInt))
2643 return true;
Daniel Sanders05540042017-08-08 10:44:31 +00002644
2645 return Kind < B.Kind;
Daniel Sanders75b84fc2017-08-08 13:21:26 +00002646}
Daniel Sanders05540042017-08-08 10:44:31 +00002647
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002648void SameOperandMatcher::emitPredicateOpcodes(MatchTable &Table,
Quentin Colombetaad20be2017-12-15 23:07:42 +00002649 RuleMatcher &Rule) const {
Daniel Sanders1e4569f2017-10-20 20:55:29 +00002650 const OperandMatcher &OtherOM = Rule.getOperandMatcher(MatchingName);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002651 unsigned OtherInsnVarID = Rule.getInsnVarID(OtherOM.getInstructionMatcher());
Quentin Colombetaad20be2017-12-15 23:07:42 +00002652 assert(OtherInsnVarID == OtherOM.getInstructionMatcher().getVarID());
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002653
2654 Table << MatchTable::Opcode("GIM_CheckIsSameOperand")
2655 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
2656 << MatchTable::Comment("OpIdx") << MatchTable::IntValue(OpIdx)
2657 << MatchTable::Comment("OtherMI")
2658 << MatchTable::IntValue(OtherInsnVarID)
2659 << MatchTable::Comment("OtherOpIdx")
2660 << MatchTable::IntValue(OtherOM.getOperandIndex())
2661 << MatchTable::LineBreak;
2662}
2663
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002664//===- GlobalISelEmitter class --------------------------------------------===//
2665
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002666class GlobalISelEmitter {
2667public:
2668 explicit GlobalISelEmitter(RecordKeeper &RK);
2669 void run(raw_ostream &OS);
2670
2671private:
2672 const RecordKeeper &RK;
2673 const CodeGenDAGPatterns CGP;
2674 const CodeGenTarget &Target;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002675 CodeGenRegBank CGRegs;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002676
Daniel Sanders39690bd2017-10-15 02:41:12 +00002677 /// Keep track of the equivalence between SDNodes and Instruction by mapping
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00002678 /// SDNodes to the GINodeEquiv mapping. We need to map to the GINodeEquiv to
2679 /// check for attributes on the relation such as CheckMMOIsNonAtomic.
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002680 /// This is defined using 'GINodeEquiv' in the target description.
Daniel Sanders39690bd2017-10-15 02:41:12 +00002681 DenseMap<Record *, Record *> NodeEquivs;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002682
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002683 /// Keep track of the equivalence between ComplexPattern's and
2684 /// GIComplexOperandMatcher. Map entries are specified by subclassing
2685 /// GIComplexPatternEquiv.
2686 DenseMap<const Record *, const Record *> ComplexPatternEquivs;
2687
Volkan Kelesf7f25682018-01-16 18:44:05 +00002688 /// Keep track of the equivalence between SDNodeXForm's and
2689 /// GICustomOperandRenderer. Map entries are specified by subclassing
2690 /// GISDNodeXFormEquiv.
2691 DenseMap<const Record *, const Record *> SDNodeXFormEquivs;
2692
Aditya Nandakumarb63e7632018-02-16 22:37:15 +00002693 /// Keep track of Scores of PatternsToMatch similar to how the DAG does.
2694 /// This adds compatibility for RuleMatchers to use this for ordering rules.
2695 DenseMap<uint64_t, int> RuleMatcherScores;
2696
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002697 // Map of predicates to their subtarget features.
Daniel Sanderse9fdba32017-04-29 17:30:09 +00002698 SubtargetFeatureInfoMap SubtargetFeatures;
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002699
Daniel Sandersf76f3152017-11-16 00:46:35 +00002700 // Rule coverage information.
2701 Optional<CodeGenCoverage> RuleCoverage;
2702
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002703 void gatherNodeEquivs();
Daniel Sanders39690bd2017-10-15 02:41:12 +00002704 Record *findNodeEquiv(Record *N) const;
Daniel Sandersf84bc372018-05-05 20:53:24 +00002705 const CodeGenInstruction *getEquivNode(Record &Equiv,
2706 const TreePatternNode *N) const;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002707
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002708 Error importRulePredicates(RuleMatcher &M, ArrayRef<Predicate> Predicates);
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002709 Expected<InstructionMatcher &> createAndImportSelDAGMatcher(
2710 RuleMatcher &Rule, InstructionMatcher &InsnMatcher,
2711 const TreePatternNode *Src, unsigned &TempOpIdx) const;
2712 Error importComplexPatternOperandMatcher(OperandMatcher &OM, Record *R,
2713 unsigned &TempOpIdx) const;
2714 Error importChildMatcher(RuleMatcher &Rule, InstructionMatcher &InsnMatcher,
Daniel Sandersa71f4542017-10-16 00:56:30 +00002715 const TreePatternNode *SrcChild,
2716 bool OperandIsAPointer, unsigned OpIdx,
Daniel Sandersc270c502017-03-30 09:36:33 +00002717 unsigned &TempOpIdx) const;
Daniel Sandersdf258e32017-10-31 19:09:29 +00002718
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002719 Expected<BuildMIAction &>
Daniel Sandersa7b75262017-10-31 18:50:24 +00002720 createAndImportInstructionRenderer(RuleMatcher &M,
2721 const TreePatternNode *Dst);
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002722 Expected<action_iterator> createAndImportSubInstructionRenderer(
2723 action_iterator InsertPt, RuleMatcher &M, const TreePatternNode *Dst,
2724 unsigned TempReg);
Daniel Sanders7438b262017-10-31 23:03:18 +00002725 Expected<action_iterator>
2726 createInstructionRenderer(action_iterator InsertPt, RuleMatcher &M,
2727 const TreePatternNode *Dst);
Daniel Sandersdf258e32017-10-31 19:09:29 +00002728 void importExplicitDefRenderers(BuildMIAction &DstMIBuilder);
Daniel Sanders7438b262017-10-31 23:03:18 +00002729 Expected<action_iterator>
2730 importExplicitUseRenderers(action_iterator InsertPt, RuleMatcher &M,
2731 BuildMIAction &DstMIBuilder,
Daniel Sandersdf258e32017-10-31 19:09:29 +00002732 const llvm::TreePatternNode *Dst);
Daniel Sanders7438b262017-10-31 23:03:18 +00002733 Expected<action_iterator>
2734 importExplicitUseRenderer(action_iterator InsertPt, RuleMatcher &Rule,
2735 BuildMIAction &DstMIBuilder,
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002736 TreePatternNode *DstChild);
Diana Picus382602f2017-05-17 08:57:28 +00002737 Error importDefaultOperandRenderers(BuildMIAction &DstMIBuilder,
2738 DagInit *DefaultOps) const;
Daniel Sandersc270c502017-03-30 09:36:33 +00002739 Error
Daniel Sandersffc7d582017-03-29 15:37:18 +00002740 importImplicitDefRenderers(BuildMIAction &DstMIBuilder,
2741 const std::vector<Record *> &ImplicitDefs) const;
2742
Daniel Sanders11300ce2017-10-13 21:28:03 +00002743 void emitImmPredicates(raw_ostream &OS, StringRef TypeIdentifier,
2744 StringRef Type,
Daniel Sanders649c5852017-10-13 20:42:18 +00002745 std::function<bool(const Record *R)> Filter);
2746
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002747 /// Analyze pattern \p P, returning a matcher for it if possible.
2748 /// Otherwise, return an Error explaining why we don't support it.
2749 Expected<RuleMatcher> runOnPattern(const PatternToMatch &P);
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002750
2751 void declareSubtargetFeature(Record *Predicate);
Daniel Sanders7e523672017-11-11 03:23:44 +00002752
Quentin Colombetec76d9c2017-12-18 19:47:41 +00002753 /// Takes a sequence of \p Rules and group them based on the predicates
2754 /// they share. \p StorageGroupMatcher is used as a memory container
Hiroshi Inoue501931b2018-01-24 05:04:35 +00002755 /// for the group that are created as part of this process.
Quentin Colombetec76d9c2017-12-18 19:47:41 +00002756 /// The optimization process does not change the relative order of
2757 /// the rules. In particular, we don't try to share predicates if
2758 /// that means reordering the rules (e.g., we won't group R1 and R3
2759 /// in the following example as it would imply reordering R2 and R3
2760 /// => R1 p1, R2 p2, R3 p1).
2761 ///
2762 /// What this optimization does looks like:
2763 /// Output without optimization:
2764 /// \verbatim
2765 /// # R1
2766 /// # predicate A
2767 /// # predicate B
2768 /// ...
2769 /// # R2
2770 /// # predicate A // <-- effectively this is going to be checked twice.
2771 /// // Once in R1 and once in R2.
2772 /// # predicate C
2773 /// \endverbatim
2774 /// Output with optimization:
2775 /// \verbatim
2776 /// # Group1_2
2777 /// # predicate A // <-- Check is now shared.
2778 /// # R1
2779 /// # predicate B
2780 /// # R2
2781 /// # predicate C
2782 /// \endverbatim
2783 std::vector<Matcher *> optimizeRules(
Roman Tereshin2d6d3762018-05-02 20:08:14 +00002784 ArrayRef<Matcher *> Rules,
Quentin Colombetec76d9c2017-12-18 19:47:41 +00002785 std::vector<std::unique_ptr<GroupMatcher>> &StorageGroupMatcher);
Roman Tereshin2d6d3762018-05-02 20:08:14 +00002786
Roman Tereshinbeb39312018-05-02 20:15:11 +00002787 MatchTable buildMatchTable(MutableArrayRef<RuleMatcher> Rules, bool Optimize,
2788 bool WithCoverage);
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002789};
2790
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002791void GlobalISelEmitter::gatherNodeEquivs() {
2792 assert(NodeEquivs.empty());
2793 for (Record *Equiv : RK.getAllDerivedDefinitions("GINodeEquiv"))
Daniel Sanders39690bd2017-10-15 02:41:12 +00002794 NodeEquivs[Equiv->getValueAsDef("Node")] = Equiv;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002795
2796 assert(ComplexPatternEquivs.empty());
2797 for (Record *Equiv : RK.getAllDerivedDefinitions("GIComplexPatternEquiv")) {
2798 Record *SelDAGEquiv = Equiv->getValueAsDef("SelDAGEquivalent");
2799 if (!SelDAGEquiv)
2800 continue;
2801 ComplexPatternEquivs[SelDAGEquiv] = Equiv;
2802 }
Volkan Kelesf7f25682018-01-16 18:44:05 +00002803
2804 assert(SDNodeXFormEquivs.empty());
2805 for (Record *Equiv : RK.getAllDerivedDefinitions("GISDNodeXFormEquiv")) {
2806 Record *SelDAGEquiv = Equiv->getValueAsDef("SelDAGEquivalent");
2807 if (!SelDAGEquiv)
2808 continue;
2809 SDNodeXFormEquivs[SelDAGEquiv] = Equiv;
2810 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002811}
2812
Daniel Sanders39690bd2017-10-15 02:41:12 +00002813Record *GlobalISelEmitter::findNodeEquiv(Record *N) const {
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002814 return NodeEquivs.lookup(N);
2815}
2816
Daniel Sandersf84bc372018-05-05 20:53:24 +00002817const CodeGenInstruction *
2818GlobalISelEmitter::getEquivNode(Record &Equiv, const TreePatternNode *N) const {
2819 for (const auto &Predicate : N->getPredicateFns()) {
2820 if (!Equiv.isValueUnset("IfSignExtend") && Predicate.isLoad() &&
2821 Predicate.isSignExtLoad())
2822 return &Target.getInstruction(Equiv.getValueAsDef("IfSignExtend"));
2823 if (!Equiv.isValueUnset("IfZeroExtend") && Predicate.isLoad() &&
2824 Predicate.isZeroExtLoad())
2825 return &Target.getInstruction(Equiv.getValueAsDef("IfZeroExtend"));
2826 }
2827 return &Target.getInstruction(Equiv.getValueAsDef("I"));
2828}
2829
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002830GlobalISelEmitter::GlobalISelEmitter(RecordKeeper &RK)
Daniel Sandersf84bc372018-05-05 20:53:24 +00002831 : RK(RK), CGP(RK), Target(CGP.getTargetInfo()),
2832 CGRegs(RK, Target.getHwModes()) {}
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002833
2834//===- Emitter ------------------------------------------------------------===//
2835
Daniel Sandersc270c502017-03-30 09:36:33 +00002836Error
Daniel Sandersffc7d582017-03-29 15:37:18 +00002837GlobalISelEmitter::importRulePredicates(RuleMatcher &M,
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002838 ArrayRef<Predicate> Predicates) {
2839 for (const Predicate &P : Predicates) {
2840 if (!P.Def)
2841 continue;
2842 declareSubtargetFeature(P.Def);
2843 M.addRequiredFeature(P.Def);
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002844 }
2845
Daniel Sandersc270c502017-03-30 09:36:33 +00002846 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00002847}
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002848
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00002849Expected<InstructionMatcher &> GlobalISelEmitter::createAndImportSelDAGMatcher(
2850 RuleMatcher &Rule, InstructionMatcher &InsnMatcher,
2851 const TreePatternNode *Src, unsigned &TempOpIdx) const {
2852 Record *SrcGIEquivOrNull = nullptr;
2853 const CodeGenInstruction *SrcGIOrNull = nullptr;
2854
2855 // Start with the defined operands (i.e., the results of the root operator).
2856 if (Src->getExtTypes().size() > 1)
2857 return failedImport("Src pattern has multiple results");
2858
2859 if (Src->isLeaf()) {
2860 Init *SrcInit = Src->getLeafValue();
2861 if (isa<IntInit>(SrcInit)) {
2862 InsnMatcher.addPredicate<InstructionOpcodeMatcher>(
2863 &Target.getInstruction(RK.getDef("G_CONSTANT")));
2864 } else
2865 return failedImport(
2866 "Unable to deduce gMIR opcode to handle Src (which is a leaf)");
2867 } else {
2868 SrcGIEquivOrNull = findNodeEquiv(Src->getOperator());
2869 if (!SrcGIEquivOrNull)
2870 return failedImport("Pattern operator lacks an equivalent Instruction" +
2871 explainOperator(Src->getOperator()));
Daniel Sandersf84bc372018-05-05 20:53:24 +00002872 SrcGIOrNull = getEquivNode(*SrcGIEquivOrNull, Src);
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00002873
2874 // The operators look good: match the opcode
2875 InsnMatcher.addPredicate<InstructionOpcodeMatcher>(SrcGIOrNull);
2876 }
2877
2878 unsigned OpIdx = 0;
2879 for (const TypeSetByHwMode &VTy : Src->getExtTypes()) {
2880 // Results don't have a name unless they are the root node. The caller will
2881 // set the name if appropriate.
2882 OperandMatcher &OM = InsnMatcher.addOperand(OpIdx++, "", TempOpIdx);
2883 if (auto Error = OM.addTypeCheckPredicate(VTy, false /* OperandIsAPointer */))
2884 return failedImport(toString(std::move(Error)) +
2885 " for result of Src pattern operator");
2886 }
2887
Daniel Sanders2c269f62017-08-24 09:11:20 +00002888 for (const auto &Predicate : Src->getPredicateFns()) {
2889 if (Predicate.isAlwaysTrue())
2890 continue;
2891
2892 if (Predicate.isImmediatePattern()) {
2893 InsnMatcher.addPredicate<InstructionImmPredicateMatcher>(Predicate);
2894 continue;
2895 }
2896
Daniel Sandersf84bc372018-05-05 20:53:24 +00002897 // G_LOAD is used for both non-extending and any-extending loads.
2898 if (Predicate.isLoad() && Predicate.isNonExtLoad()) {
2899 InsnMatcher.addPredicate<MemoryVsLLTSizePredicateMatcher>(
2900 0, MemoryVsLLTSizePredicateMatcher::EqualTo, 0);
2901 continue;
2902 }
2903 if (Predicate.isLoad() && Predicate.isAnyExtLoad()) {
2904 InsnMatcher.addPredicate<MemoryVsLLTSizePredicateMatcher>(
2905 0, MemoryVsLLTSizePredicateMatcher::LessThan, 0);
2906 continue;
2907 }
2908
2909 // No check required. We already did it by swapping the opcode.
2910 if (!SrcGIEquivOrNull->isValueUnset("IfSignExtend") &&
2911 Predicate.isSignExtLoad())
2912 continue;
2913
2914 // No check required. We already did it by swapping the opcode.
2915 if (!SrcGIEquivOrNull->isValueUnset("IfZeroExtend") &&
2916 Predicate.isZeroExtLoad())
Daniel Sandersa71f4542017-10-16 00:56:30 +00002917 continue;
2918
Daniel Sandersd66e0902017-10-23 18:19:24 +00002919 // No check required. G_STORE by itself is a non-extending store.
2920 if (Predicate.isNonTruncStore())
2921 continue;
2922
Daniel Sanders76664652017-11-28 22:07:05 +00002923 if (Predicate.isLoad() || Predicate.isStore() || Predicate.isAtomic()) {
2924 if (Predicate.getMemoryVT() != nullptr) {
2925 Optional<LLTCodeGen> MemTyOrNone =
2926 MVTToLLT(getValueType(Predicate.getMemoryVT()));
Daniel Sandersd66e0902017-10-23 18:19:24 +00002927
Daniel Sanders76664652017-11-28 22:07:05 +00002928 if (!MemTyOrNone)
2929 return failedImport("MemVT could not be converted to LLT");
Daniel Sandersd66e0902017-10-23 18:19:24 +00002930
Daniel Sandersf84bc372018-05-05 20:53:24 +00002931 // MMO's work in bytes so we must take care of unusual types like i1
2932 // don't round down.
2933 unsigned MemSizeInBits =
2934 llvm::alignTo(MemTyOrNone->get().getSizeInBits(), 8);
2935
2936 InsnMatcher.addPredicate<MemorySizePredicateMatcher>(
2937 0, MemSizeInBits / 8);
Daniel Sanders76664652017-11-28 22:07:05 +00002938 continue;
2939 }
2940 }
2941
2942 if (Predicate.isLoad() || Predicate.isStore()) {
2943 // No check required. A G_LOAD/G_STORE is an unindexed load.
2944 if (Predicate.isUnindexed())
2945 continue;
2946 }
2947
2948 if (Predicate.isAtomic()) {
2949 if (Predicate.isAtomicOrderingMonotonic()) {
2950 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
2951 "Monotonic");
2952 continue;
2953 }
2954 if (Predicate.isAtomicOrderingAcquire()) {
2955 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>("Acquire");
2956 continue;
2957 }
2958 if (Predicate.isAtomicOrderingRelease()) {
2959 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>("Release");
2960 continue;
2961 }
2962 if (Predicate.isAtomicOrderingAcquireRelease()) {
2963 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
2964 "AcquireRelease");
2965 continue;
2966 }
2967 if (Predicate.isAtomicOrderingSequentiallyConsistent()) {
2968 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
2969 "SequentiallyConsistent");
2970 continue;
2971 }
Daniel Sanders0c43b3a2017-11-30 21:05:59 +00002972
2973 if (Predicate.isAtomicOrderingAcquireOrStronger()) {
2974 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
2975 "Acquire", AtomicOrderingMMOPredicateMatcher::AO_OrStronger);
2976 continue;
2977 }
2978 if (Predicate.isAtomicOrderingWeakerThanAcquire()) {
2979 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
2980 "Acquire", AtomicOrderingMMOPredicateMatcher::AO_WeakerThan);
2981 continue;
2982 }
2983
2984 if (Predicate.isAtomicOrderingReleaseOrStronger()) {
2985 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
2986 "Release", AtomicOrderingMMOPredicateMatcher::AO_OrStronger);
2987 continue;
2988 }
2989 if (Predicate.isAtomicOrderingWeakerThanRelease()) {
2990 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
2991 "Release", AtomicOrderingMMOPredicateMatcher::AO_WeakerThan);
2992 continue;
2993 }
Daniel Sandersd66e0902017-10-23 18:19:24 +00002994 }
2995
Daniel Sanders2c269f62017-08-24 09:11:20 +00002996 return failedImport("Src pattern child has predicate (" +
2997 explainPredicates(Src) + ")");
2998 }
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00002999 if (SrcGIEquivOrNull && SrcGIEquivOrNull->getValueAsBit("CheckMMOIsNonAtomic"))
3000 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>("NotAtomic");
Daniel Sanders2c269f62017-08-24 09:11:20 +00003001
Daniel Sanders452c8ae2017-05-23 19:33:16 +00003002 if (Src->isLeaf()) {
3003 Init *SrcInit = Src->getLeafValue();
3004 if (IntInit *SrcIntInit = dyn_cast<IntInit>(SrcInit)) {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003005 OperandMatcher &OM =
3006 InsnMatcher.addOperand(OpIdx++, Src->getName(), TempOpIdx);
Daniel Sanders452c8ae2017-05-23 19:33:16 +00003007 OM.addPredicate<LiteralIntOperandMatcher>(SrcIntInit->getValue());
3008 } else
Daniel Sanders32291982017-06-28 13:50:04 +00003009 return failedImport(
3010 "Unable to deduce gMIR opcode to handle Src (which is a leaf)");
Daniel Sanders452c8ae2017-05-23 19:33:16 +00003011 } else {
Daniel Sanders85ffd362017-07-06 08:12:20 +00003012 assert(SrcGIOrNull &&
3013 "Expected to have already found an equivalent Instruction");
Daniel Sanders11300ce2017-10-13 21:28:03 +00003014 if (SrcGIOrNull->TheDef->getName() == "G_CONSTANT" ||
3015 SrcGIOrNull->TheDef->getName() == "G_FCONSTANT") {
3016 // imm/fpimm still have operands but we don't need to do anything with it
Daniel Sanders05540042017-08-08 10:44:31 +00003017 // here since we don't support ImmLeaf predicates yet. However, we still
3018 // need to note the hidden operand to get GIM_CheckNumOperands correct.
3019 InsnMatcher.addOperand(OpIdx++, "", TempOpIdx);
3020 return InsnMatcher;
3021 }
3022
Daniel Sanders452c8ae2017-05-23 19:33:16 +00003023 // Match the used operands (i.e. the children of the operator).
3024 for (unsigned i = 0, e = Src->getNumChildren(); i != e; ++i) {
Daniel Sanders85ffd362017-07-06 08:12:20 +00003025 TreePatternNode *SrcChild = Src->getChild(i);
3026
Daniel Sandersa71f4542017-10-16 00:56:30 +00003027 // SelectionDAG allows pointers to be represented with iN since it doesn't
3028 // distinguish between pointers and integers but they are different types in GlobalISel.
3029 // Coerce integers to pointers to address space 0 if the context indicates a pointer.
Daniel Sandersc54aa9c2017-11-18 00:16:44 +00003030 bool OperandIsAPointer = SrcGIOrNull->isOperandAPointer(i);
Daniel Sandersa71f4542017-10-16 00:56:30 +00003031
Daniel Sanders28887fe2017-09-19 12:56:36 +00003032 // For G_INTRINSIC/G_INTRINSIC_W_SIDE_EFFECTS, the operand immediately
3033 // following the defs is an intrinsic ID.
3034 if ((SrcGIOrNull->TheDef->getName() == "G_INTRINSIC" ||
3035 SrcGIOrNull->TheDef->getName() == "G_INTRINSIC_W_SIDE_EFFECTS") &&
3036 i == 0) {
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00003037 if (const CodeGenIntrinsic *II = Src->getIntrinsicInfo(CGP)) {
Daniel Sanders85ffd362017-07-06 08:12:20 +00003038 OperandMatcher &OM =
3039 InsnMatcher.addOperand(OpIdx++, SrcChild->getName(), TempOpIdx);
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00003040 OM.addPredicate<IntrinsicIDOperandMatcher>(II);
Daniel Sanders85ffd362017-07-06 08:12:20 +00003041 continue;
3042 }
3043
3044 return failedImport("Expected IntInit containing instrinsic ID)");
3045 }
3046
Daniel Sandersa71f4542017-10-16 00:56:30 +00003047 if (auto Error =
3048 importChildMatcher(Rule, InsnMatcher, SrcChild, OperandIsAPointer,
3049 OpIdx++, TempOpIdx))
Daniel Sanders452c8ae2017-05-23 19:33:16 +00003050 return std::move(Error);
3051 }
Daniel Sandersffc7d582017-03-29 15:37:18 +00003052 }
3053
3054 return InsnMatcher;
3055}
3056
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003057Error GlobalISelEmitter::importComplexPatternOperandMatcher(
3058 OperandMatcher &OM, Record *R, unsigned &TempOpIdx) const {
3059 const auto &ComplexPattern = ComplexPatternEquivs.find(R);
3060 if (ComplexPattern == ComplexPatternEquivs.end())
3061 return failedImport("SelectionDAG ComplexPattern (" + R->getName() +
3062 ") not mapped to GlobalISel");
3063
3064 OM.addPredicate<ComplexPatternOperandMatcher>(OM, *ComplexPattern->second);
3065 TempOpIdx++;
3066 return Error::success();
3067}
3068
3069Error GlobalISelEmitter::importChildMatcher(RuleMatcher &Rule,
3070 InstructionMatcher &InsnMatcher,
Daniel Sanders452c8ae2017-05-23 19:33:16 +00003071 const TreePatternNode *SrcChild,
Daniel Sandersa71f4542017-10-16 00:56:30 +00003072 bool OperandIsAPointer,
Daniel Sandersc270c502017-03-30 09:36:33 +00003073 unsigned OpIdx,
3074 unsigned &TempOpIdx) const {
Daniel Sanders4f3eb242017-04-05 13:14:03 +00003075 OperandMatcher &OM =
3076 InsnMatcher.addOperand(OpIdx, SrcChild->getName(), TempOpIdx);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003077 if (OM.isSameAsAnotherOperand())
3078 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00003079
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003080 ArrayRef<TypeSetByHwMode> ChildTypes = SrcChild->getExtTypes();
Daniel Sandersffc7d582017-03-29 15:37:18 +00003081 if (ChildTypes.size() != 1)
3082 return failedImport("Src pattern child has multiple results");
3083
3084 // Check MBB's before the type check since they are not a known type.
3085 if (!SrcChild->isLeaf()) {
3086 if (SrcChild->getOperator()->isSubClassOf("SDNode")) {
3087 auto &ChildSDNI = CGP.getSDNodeInfo(SrcChild->getOperator());
3088 if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") {
3089 OM.addPredicate<MBBOperandMatcher>();
Daniel Sandersc270c502017-03-30 09:36:33 +00003090 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00003091 }
3092 }
Daniel Sandersffc7d582017-03-29 15:37:18 +00003093 }
3094
Daniel Sandersa71f4542017-10-16 00:56:30 +00003095 if (auto Error =
3096 OM.addTypeCheckPredicate(ChildTypes.front(), OperandIsAPointer))
3097 return failedImport(toString(std::move(Error)) + " for Src operand (" +
3098 to_string(*SrcChild) + ")");
Daniel Sandersffc7d582017-03-29 15:37:18 +00003099
Daniel Sandersbee57392017-04-04 13:25:23 +00003100 // Check for nested instructions.
3101 if (!SrcChild->isLeaf()) {
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003102 if (SrcChild->getOperator()->isSubClassOf("ComplexPattern")) {
3103 // When a ComplexPattern is used as an operator, it should do the same
3104 // thing as when used as a leaf. However, the children of the operator
3105 // name the sub-operands that make up the complex operand and we must
3106 // prepare to reference them in the renderer too.
3107 unsigned RendererID = TempOpIdx;
3108 if (auto Error = importComplexPatternOperandMatcher(
3109 OM, SrcChild->getOperator(), TempOpIdx))
3110 return Error;
3111
3112 for (unsigned i = 0, e = SrcChild->getNumChildren(); i != e; ++i) {
3113 auto *SubOperand = SrcChild->getChild(i);
3114 if (!SubOperand->getName().empty())
3115 Rule.defineComplexSubOperand(SubOperand->getName(),
3116 SrcChild->getOperator(), RendererID, i);
3117 }
3118
3119 return Error::success();
3120 }
3121
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003122 auto MaybeInsnOperand = OM.addPredicate<InstructionOperandMatcher>(
3123 InsnMatcher.getRuleMatcher(), SrcChild->getName());
3124 if (!MaybeInsnOperand.hasValue()) {
3125 // This isn't strictly true. If the user were to provide exactly the same
3126 // matchers as the original operand then we could allow it. However, it's
3127 // simpler to not permit the redundant specification.
3128 return failedImport("Nested instruction cannot be the same as another operand");
3129 }
3130
Daniel Sandersbee57392017-04-04 13:25:23 +00003131 // Map the node to a gMIR instruction.
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003132 InstructionOperandMatcher &InsnOperand = **MaybeInsnOperand;
Daniel Sanders57938df2017-07-11 10:40:18 +00003133 auto InsnMatcherOrError = createAndImportSelDAGMatcher(
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003134 Rule, InsnOperand.getInsnMatcher(), SrcChild, TempOpIdx);
Daniel Sandersbee57392017-04-04 13:25:23 +00003135 if (auto Error = InsnMatcherOrError.takeError())
3136 return Error;
3137
3138 return Error::success();
3139 }
3140
Diana Picusd1b61812017-11-03 10:30:19 +00003141 if (SrcChild->hasAnyPredicate())
3142 return failedImport("Src pattern child has unsupported predicate");
3143
Daniel Sandersffc7d582017-03-29 15:37:18 +00003144 // Check for constant immediates.
3145 if (auto *ChildInt = dyn_cast<IntInit>(SrcChild->getLeafValue())) {
Daniel Sanders452c8ae2017-05-23 19:33:16 +00003146 OM.addPredicate<ConstantIntOperandMatcher>(ChildInt->getValue());
Daniel Sandersc270c502017-03-30 09:36:33 +00003147 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00003148 }
3149
3150 // Check for def's like register classes or ComplexPattern's.
3151 if (auto *ChildDefInit = dyn_cast<DefInit>(SrcChild->getLeafValue())) {
3152 auto *ChildRec = ChildDefInit->getDef();
3153
3154 // Check for register classes.
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003155 if (ChildRec->isSubClassOf("RegisterClass") ||
3156 ChildRec->isSubClassOf("RegisterOperand")) {
Daniel Sandersffc7d582017-03-29 15:37:18 +00003157 OM.addPredicate<RegisterBankOperandMatcher>(
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003158 Target.getRegisterClass(getInitValueAsRegClass(ChildDefInit)));
Daniel Sanders658541f2017-04-22 15:53:21 +00003159 return Error::success();
3160 }
3161
Daniel Sanders4d4e7652017-10-09 18:14:53 +00003162 // Check for ValueType.
3163 if (ChildRec->isSubClassOf("ValueType")) {
3164 // We already added a type check as standard practice so this doesn't need
3165 // to do anything.
3166 return Error::success();
3167 }
3168
Daniel Sandersffc7d582017-03-29 15:37:18 +00003169 // Check for ComplexPattern's.
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003170 if (ChildRec->isSubClassOf("ComplexPattern"))
3171 return importComplexPatternOperandMatcher(OM, ChildRec, TempOpIdx);
Daniel Sandersffc7d582017-03-29 15:37:18 +00003172
Daniel Sandersd0656a32017-04-13 09:45:37 +00003173 if (ChildRec->isSubClassOf("ImmLeaf")) {
3174 return failedImport(
3175 "Src pattern child def is an unsupported tablegen class (ImmLeaf)");
3176 }
3177
Daniel Sandersffc7d582017-03-29 15:37:18 +00003178 return failedImport(
3179 "Src pattern child def is an unsupported tablegen class");
3180 }
3181
3182 return failedImport("Src pattern child is an unsupported kind");
3183}
3184
Daniel Sanders7438b262017-10-31 23:03:18 +00003185Expected<action_iterator> GlobalISelEmitter::importExplicitUseRenderer(
3186 action_iterator InsertPt, RuleMatcher &Rule, BuildMIAction &DstMIBuilder,
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003187 TreePatternNode *DstChild) {
Daniel Sanders2c269f62017-08-24 09:11:20 +00003188
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003189 const auto &SubOperand = Rule.getComplexSubOperand(DstChild->getName());
3190 if (SubOperand.hasValue()) {
3191 DstMIBuilder.addRenderer<RenderComplexPatternOperand>(
Daniel Sanders198447a2017-11-01 00:29:47 +00003192 *std::get<0>(*SubOperand), DstChild->getName(),
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003193 std::get<1>(*SubOperand), std::get<2>(*SubOperand));
Daniel Sanders7438b262017-10-31 23:03:18 +00003194 return InsertPt;
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003195 }
3196
Daniel Sandersffc7d582017-03-29 15:37:18 +00003197 if (!DstChild->isLeaf()) {
Volkan Kelesf7f25682018-01-16 18:44:05 +00003198
3199 if (DstChild->getOperator()->isSubClassOf("SDNodeXForm")) {
3200 auto Child = DstChild->getChild(0);
3201 auto I = SDNodeXFormEquivs.find(DstChild->getOperator());
3202 if (I != SDNodeXFormEquivs.end()) {
3203 DstMIBuilder.addRenderer<CustomRenderer>(*I->second, Child->getName());
3204 return InsertPt;
3205 }
3206 return failedImport("SDNodeXForm " + Child->getName() +
3207 " has no custom renderer");
3208 }
3209
Daniel Sanders05540042017-08-08 10:44:31 +00003210 // We accept 'bb' here. It's an operator because BasicBlockSDNode isn't
3211 // inline, but in MI it's just another operand.
Daniel Sandersffc7d582017-03-29 15:37:18 +00003212 if (DstChild->getOperator()->isSubClassOf("SDNode")) {
3213 auto &ChildSDNI = CGP.getSDNodeInfo(DstChild->getOperator());
3214 if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") {
Daniel Sanders198447a2017-11-01 00:29:47 +00003215 DstMIBuilder.addRenderer<CopyRenderer>(DstChild->getName());
Daniel Sanders7438b262017-10-31 23:03:18 +00003216 return InsertPt;
Daniel Sandersffc7d582017-03-29 15:37:18 +00003217 }
3218 }
Daniel Sanders05540042017-08-08 10:44:31 +00003219
3220 // Similarly, imm is an operator in TreePatternNode's view but must be
3221 // rendered as operands.
3222 // FIXME: The target should be able to choose sign-extended when appropriate
3223 // (e.g. on Mips).
3224 if (DstChild->getOperator()->getName() == "imm") {
Daniel Sanders198447a2017-11-01 00:29:47 +00003225 DstMIBuilder.addRenderer<CopyConstantAsImmRenderer>(DstChild->getName());
Daniel Sanders7438b262017-10-31 23:03:18 +00003226 return InsertPt;
Daniel Sanders11300ce2017-10-13 21:28:03 +00003227 } else if (DstChild->getOperator()->getName() == "fpimm") {
3228 DstMIBuilder.addRenderer<CopyFConstantAsFPImmRenderer>(
Daniel Sanders198447a2017-11-01 00:29:47 +00003229 DstChild->getName());
Daniel Sanders7438b262017-10-31 23:03:18 +00003230 return InsertPt;
Daniel Sanders05540042017-08-08 10:44:31 +00003231 }
3232
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003233 if (DstChild->getOperator()->isSubClassOf("Instruction")) {
3234 ArrayRef<TypeSetByHwMode> ChildTypes = DstChild->getExtTypes();
3235 if (ChildTypes.size() != 1)
3236 return failedImport("Dst pattern child has multiple results");
3237
3238 Optional<LLTCodeGen> OpTyOrNone = None;
3239 if (ChildTypes.front().isMachineValueType())
3240 OpTyOrNone =
3241 MVTToLLT(ChildTypes.front().getMachineValueType().SimpleTy);
3242 if (!OpTyOrNone)
3243 return failedImport("Dst operand has an unsupported type");
3244
3245 unsigned TempRegID = Rule.allocateTempRegID();
3246 InsertPt = Rule.insertAction<MakeTempRegisterAction>(
3247 InsertPt, OpTyOrNone.getValue(), TempRegID);
3248 DstMIBuilder.addRenderer<TempRegRenderer>(TempRegID);
3249
3250 auto InsertPtOrError = createAndImportSubInstructionRenderer(
3251 ++InsertPt, Rule, DstChild, TempRegID);
3252 if (auto Error = InsertPtOrError.takeError())
3253 return std::move(Error);
3254 return InsertPtOrError.get();
3255 }
3256
Daniel Sanders2c269f62017-08-24 09:11:20 +00003257 return failedImport("Dst pattern child isn't a leaf node or an MBB" + llvm::to_string(*DstChild));
Daniel Sandersffc7d582017-03-29 15:37:18 +00003258 }
3259
Daniel Sandersf499b2b2017-11-30 18:48:35 +00003260 // It could be a specific immediate in which case we should just check for
3261 // that immediate.
3262 if (const IntInit *ChildIntInit =
3263 dyn_cast<IntInit>(DstChild->getLeafValue())) {
3264 DstMIBuilder.addRenderer<ImmRenderer>(ChildIntInit->getValue());
3265 return InsertPt;
3266 }
3267
Daniel Sandersffc7d582017-03-29 15:37:18 +00003268 // Otherwise, we're looking for a bog-standard RegisterClass operand.
Daniel Sandersffc7d582017-03-29 15:37:18 +00003269 if (auto *ChildDefInit = dyn_cast<DefInit>(DstChild->getLeafValue())) {
3270 auto *ChildRec = ChildDefInit->getDef();
3271
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003272 ArrayRef<TypeSetByHwMode> ChildTypes = DstChild->getExtTypes();
Daniel Sandersffc7d582017-03-29 15:37:18 +00003273 if (ChildTypes.size() != 1)
3274 return failedImport("Dst pattern child has multiple results");
3275
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003276 Optional<LLTCodeGen> OpTyOrNone = None;
3277 if (ChildTypes.front().isMachineValueType())
3278 OpTyOrNone = MVTToLLT(ChildTypes.front().getMachineValueType().SimpleTy);
Daniel Sandersffc7d582017-03-29 15:37:18 +00003279 if (!OpTyOrNone)
3280 return failedImport("Dst operand has an unsupported type");
3281
3282 if (ChildRec->isSubClassOf("Register")) {
Daniel Sanders198447a2017-11-01 00:29:47 +00003283 DstMIBuilder.addRenderer<AddRegisterRenderer>(ChildRec);
Daniel Sanders7438b262017-10-31 23:03:18 +00003284 return InsertPt;
Daniel Sandersffc7d582017-03-29 15:37:18 +00003285 }
3286
Daniel Sanders658541f2017-04-22 15:53:21 +00003287 if (ChildRec->isSubClassOf("RegisterClass") ||
Daniel Sanders4d4e7652017-10-09 18:14:53 +00003288 ChildRec->isSubClassOf("RegisterOperand") ||
3289 ChildRec->isSubClassOf("ValueType")) {
Daniel Sandersd66e0902017-10-23 18:19:24 +00003290 if (ChildRec->isSubClassOf("RegisterOperand") &&
3291 !ChildRec->isValueUnset("GIZeroRegister")) {
3292 DstMIBuilder.addRenderer<CopyOrAddZeroRegRenderer>(
Daniel Sanders198447a2017-11-01 00:29:47 +00003293 DstChild->getName(), ChildRec->getValueAsDef("GIZeroRegister"));
Daniel Sanders7438b262017-10-31 23:03:18 +00003294 return InsertPt;
Daniel Sandersd66e0902017-10-23 18:19:24 +00003295 }
3296
Daniel Sanders198447a2017-11-01 00:29:47 +00003297 DstMIBuilder.addRenderer<CopyRenderer>(DstChild->getName());
Daniel Sanders7438b262017-10-31 23:03:18 +00003298 return InsertPt;
Daniel Sandersffc7d582017-03-29 15:37:18 +00003299 }
3300
3301 if (ChildRec->isSubClassOf("ComplexPattern")) {
3302 const auto &ComplexPattern = ComplexPatternEquivs.find(ChildRec);
3303 if (ComplexPattern == ComplexPatternEquivs.end())
3304 return failedImport(
3305 "SelectionDAG ComplexPattern not mapped to GlobalISel");
3306
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003307 const OperandMatcher &OM = Rule.getOperandMatcher(DstChild->getName());
Daniel Sandersffc7d582017-03-29 15:37:18 +00003308 DstMIBuilder.addRenderer<RenderComplexPatternOperand>(
Daniel Sanders198447a2017-11-01 00:29:47 +00003309 *ComplexPattern->second, DstChild->getName(),
Daniel Sanders2deea182017-04-22 15:11:04 +00003310 OM.getAllocatedTemporariesBaseID());
Daniel Sanders7438b262017-10-31 23:03:18 +00003311 return InsertPt;
Daniel Sandersffc7d582017-03-29 15:37:18 +00003312 }
3313
3314 return failedImport(
3315 "Dst pattern child def is an unsupported tablegen class");
3316 }
3317
3318 return failedImport("Dst pattern child is an unsupported kind");
3319}
3320
Daniel Sandersc270c502017-03-30 09:36:33 +00003321Expected<BuildMIAction &> GlobalISelEmitter::createAndImportInstructionRenderer(
Daniel Sandersa7b75262017-10-31 18:50:24 +00003322 RuleMatcher &M, const TreePatternNode *Dst) {
Daniel Sanders7438b262017-10-31 23:03:18 +00003323 auto InsertPtOrError = createInstructionRenderer(M.actions_end(), M, Dst);
3324 if (auto Error = InsertPtOrError.takeError())
Daniel Sandersdf258e32017-10-31 19:09:29 +00003325 return std::move(Error);
3326
Daniel Sanders7438b262017-10-31 23:03:18 +00003327 action_iterator InsertPt = InsertPtOrError.get();
3328 BuildMIAction &DstMIBuilder = *static_cast<BuildMIAction *>(InsertPt->get());
Daniel Sandersdf258e32017-10-31 19:09:29 +00003329
3330 importExplicitDefRenderers(DstMIBuilder);
3331
Daniel Sanders7438b262017-10-31 23:03:18 +00003332 if (auto Error = importExplicitUseRenderers(InsertPt, M, DstMIBuilder, Dst)
3333 .takeError())
Daniel Sandersdf258e32017-10-31 19:09:29 +00003334 return std::move(Error);
3335
3336 return DstMIBuilder;
3337}
3338
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003339Expected<action_iterator>
3340GlobalISelEmitter::createAndImportSubInstructionRenderer(
Daniel Sanders08464522018-01-29 21:09:12 +00003341 const action_iterator InsertPt, RuleMatcher &M, const TreePatternNode *Dst,
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003342 unsigned TempRegID) {
3343 auto InsertPtOrError = createInstructionRenderer(InsertPt, M, Dst);
3344
3345 // TODO: Assert there's exactly one result.
3346
3347 if (auto Error = InsertPtOrError.takeError())
3348 return std::move(Error);
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003349
3350 BuildMIAction &DstMIBuilder =
3351 *static_cast<BuildMIAction *>(InsertPtOrError.get()->get());
3352
3353 // Assign the result to TempReg.
3354 DstMIBuilder.addRenderer<TempRegRenderer>(TempRegID, true);
3355
Daniel Sanders08464522018-01-29 21:09:12 +00003356 InsertPtOrError =
3357 importExplicitUseRenderers(InsertPtOrError.get(), M, DstMIBuilder, Dst);
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003358 if (auto Error = InsertPtOrError.takeError())
3359 return std::move(Error);
3360
Daniel Sanders08464522018-01-29 21:09:12 +00003361 M.insertAction<ConstrainOperandsToDefinitionAction>(InsertPt,
3362 DstMIBuilder.getInsnID());
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003363 return InsertPtOrError.get();
3364}
3365
Daniel Sanders7438b262017-10-31 23:03:18 +00003366Expected<action_iterator> GlobalISelEmitter::createInstructionRenderer(
3367 action_iterator InsertPt, RuleMatcher &M, const TreePatternNode *Dst) {
Daniel Sandersffc7d582017-03-29 15:37:18 +00003368 Record *DstOp = Dst->getOperator();
Daniel Sandersd0656a32017-04-13 09:45:37 +00003369 if (!DstOp->isSubClassOf("Instruction")) {
3370 if (DstOp->isSubClassOf("ValueType"))
3371 return failedImport(
3372 "Pattern operator isn't an instruction (it's a ValueType)");
Daniel Sandersffc7d582017-03-29 15:37:18 +00003373 return failedImport("Pattern operator isn't an instruction");
Daniel Sandersd0656a32017-04-13 09:45:37 +00003374 }
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003375 CodeGenInstruction *DstI = &Target.getInstruction(DstOp);
Daniel Sandersffc7d582017-03-29 15:37:18 +00003376
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003377 // COPY_TO_REGCLASS is just a copy with a ConstrainOperandToRegClassAction
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00003378 // attached. Similarly for EXTRACT_SUBREG except that's a subregister copy.
Daniel Sandersdf258e32017-10-31 19:09:29 +00003379 if (DstI->TheDef->getName() == "COPY_TO_REGCLASS")
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003380 DstI = &Target.getInstruction(RK.getDef("COPY"));
Daniel Sandersdf258e32017-10-31 19:09:29 +00003381 else if (DstI->TheDef->getName() == "EXTRACT_SUBREG")
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00003382 DstI = &Target.getInstruction(RK.getDef("COPY"));
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003383 else if (DstI->TheDef->getName() == "REG_SEQUENCE")
3384 return failedImport("Unable to emit REG_SEQUENCE");
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003385
Daniel Sanders198447a2017-11-01 00:29:47 +00003386 return M.insertAction<BuildMIAction>(InsertPt, M.allocateOutputInsnID(),
3387 DstI);
Daniel Sandersdf258e32017-10-31 19:09:29 +00003388}
3389
3390void GlobalISelEmitter::importExplicitDefRenderers(
3391 BuildMIAction &DstMIBuilder) {
3392 const CodeGenInstruction *DstI = DstMIBuilder.getCGI();
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003393 for (unsigned I = 0; I < DstI->Operands.NumDefs; ++I) {
3394 const CGIOperandList::OperandInfo &DstIOperand = DstI->Operands[I];
Daniel Sanders198447a2017-11-01 00:29:47 +00003395 DstMIBuilder.addRenderer<CopyRenderer>(DstIOperand.Name);
Daniel Sandersffc7d582017-03-29 15:37:18 +00003396 }
Daniel Sandersdf258e32017-10-31 19:09:29 +00003397}
3398
Daniel Sanders7438b262017-10-31 23:03:18 +00003399Expected<action_iterator> GlobalISelEmitter::importExplicitUseRenderers(
3400 action_iterator InsertPt, RuleMatcher &M, BuildMIAction &DstMIBuilder,
Daniel Sandersdf258e32017-10-31 19:09:29 +00003401 const llvm::TreePatternNode *Dst) {
3402 const CodeGenInstruction *DstI = DstMIBuilder.getCGI();
3403 CodeGenInstruction *OrigDstI = &Target.getInstruction(Dst->getOperator());
Daniel Sandersffc7d582017-03-29 15:37:18 +00003404
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00003405 // EXTRACT_SUBREG needs to use a subregister COPY.
Daniel Sandersdf258e32017-10-31 19:09:29 +00003406 if (OrigDstI->TheDef->getName() == "EXTRACT_SUBREG") {
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00003407 if (!Dst->getChild(0)->isLeaf())
3408 return failedImport("EXTRACT_SUBREG child #1 is not a leaf");
3409
Daniel Sanders32291982017-06-28 13:50:04 +00003410 if (DefInit *SubRegInit =
3411 dyn_cast<DefInit>(Dst->getChild(1)->getLeafValue())) {
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003412 Record *RCDef = getInitValueAsRegClass(Dst->getChild(0)->getLeafValue());
3413 if (!RCDef)
3414 return failedImport("EXTRACT_SUBREG child #0 could not "
3415 "be coerced to a register class");
3416
3417 CodeGenRegisterClass *RC = CGRegs.getRegClass(RCDef);
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00003418 CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef());
3419
3420 const auto &SrcRCDstRCPair =
3421 RC->getMatchingSubClassWithSubRegs(CGRegs, SubIdx);
3422 if (SrcRCDstRCPair.hasValue()) {
3423 assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
3424 if (SrcRCDstRCPair->first != RC)
3425 return failedImport("EXTRACT_SUBREG requires an additional COPY");
3426 }
3427
Daniel Sanders198447a2017-11-01 00:29:47 +00003428 DstMIBuilder.addRenderer<CopySubRegRenderer>(Dst->getChild(0)->getName(),
3429 SubIdx);
Daniel Sanders7438b262017-10-31 23:03:18 +00003430 return InsertPt;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00003431 }
3432
3433 return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
3434 }
3435
Daniel Sandersffc7d582017-03-29 15:37:18 +00003436 // Render the explicit uses.
Daniel Sandersdf258e32017-10-31 19:09:29 +00003437 unsigned DstINumUses = OrigDstI->Operands.size() - OrigDstI->Operands.NumDefs;
3438 unsigned ExpectedDstINumUses = Dst->getNumChildren();
3439 if (OrigDstI->TheDef->getName() == "COPY_TO_REGCLASS") {
3440 DstINumUses--; // Ignore the class constraint.
3441 ExpectedDstINumUses--;
3442 }
3443
Daniel Sanders0ed28822017-04-12 08:23:08 +00003444 unsigned Child = 0;
Diana Picus382602f2017-05-17 08:57:28 +00003445 unsigned NumDefaultOps = 0;
Daniel Sanders0ed28822017-04-12 08:23:08 +00003446 for (unsigned I = 0; I != DstINumUses; ++I) {
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003447 const CGIOperandList::OperandInfo &DstIOperand =
3448 DstI->Operands[DstI->Operands.NumDefs + I];
Daniel Sanders0ed28822017-04-12 08:23:08 +00003449
Diana Picus382602f2017-05-17 08:57:28 +00003450 // If the operand has default values, introduce them now.
3451 // FIXME: Until we have a decent test case that dictates we should do
3452 // otherwise, we're going to assume that operands with default values cannot
3453 // be specified in the patterns. Therefore, adding them will not cause us to
3454 // end up with too many rendered operands.
3455 if (DstIOperand.Rec->isSubClassOf("OperandWithDefaultOps")) {
Daniel Sanders0ed28822017-04-12 08:23:08 +00003456 DagInit *DefaultOps = DstIOperand.Rec->getValueAsDag("DefaultOps");
Diana Picus382602f2017-05-17 08:57:28 +00003457 if (auto Error = importDefaultOperandRenderers(DstMIBuilder, DefaultOps))
3458 return std::move(Error);
3459 ++NumDefaultOps;
Daniel Sanders0ed28822017-04-12 08:23:08 +00003460 continue;
3461 }
3462
Daniel Sanders7438b262017-10-31 23:03:18 +00003463 auto InsertPtOrError = importExplicitUseRenderer(InsertPt, M, DstMIBuilder,
3464 Dst->getChild(Child));
3465 if (auto Error = InsertPtOrError.takeError())
Daniel Sandersffc7d582017-03-29 15:37:18 +00003466 return std::move(Error);
Daniel Sanders7438b262017-10-31 23:03:18 +00003467 InsertPt = InsertPtOrError.get();
Daniel Sanders0ed28822017-04-12 08:23:08 +00003468 ++Child;
Daniel Sandersffc7d582017-03-29 15:37:18 +00003469 }
3470
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003471 if (NumDefaultOps + ExpectedDstINumUses != DstINumUses)
Diana Picuseb2057c2017-05-17 09:25:08 +00003472 return failedImport("Expected " + llvm::to_string(DstINumUses) +
Diana Picus382602f2017-05-17 08:57:28 +00003473 " used operands but found " +
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003474 llvm::to_string(ExpectedDstINumUses) +
Diana Picuseb2057c2017-05-17 09:25:08 +00003475 " explicit ones and " + llvm::to_string(NumDefaultOps) +
Diana Picus382602f2017-05-17 08:57:28 +00003476 " default ones");
3477
Daniel Sanders7438b262017-10-31 23:03:18 +00003478 return InsertPt;
Daniel Sandersffc7d582017-03-29 15:37:18 +00003479}
3480
Diana Picus382602f2017-05-17 08:57:28 +00003481Error GlobalISelEmitter::importDefaultOperandRenderers(
3482 BuildMIAction &DstMIBuilder, DagInit *DefaultOps) const {
Craig Topper481ff702017-05-29 21:49:34 +00003483 for (const auto *DefaultOp : DefaultOps->getArgs()) {
Diana Picus382602f2017-05-17 08:57:28 +00003484 // Look through ValueType operators.
3485 if (const DagInit *DefaultDagOp = dyn_cast<DagInit>(DefaultOp)) {
3486 if (const DefInit *DefaultDagOperator =
3487 dyn_cast<DefInit>(DefaultDagOp->getOperator())) {
3488 if (DefaultDagOperator->getDef()->isSubClassOf("ValueType"))
3489 DefaultOp = DefaultDagOp->getArg(0);
3490 }
3491 }
3492
3493 if (const DefInit *DefaultDefOp = dyn_cast<DefInit>(DefaultOp)) {
Daniel Sanders198447a2017-11-01 00:29:47 +00003494 DstMIBuilder.addRenderer<AddRegisterRenderer>(DefaultDefOp->getDef());
Diana Picus382602f2017-05-17 08:57:28 +00003495 continue;
3496 }
3497
3498 if (const IntInit *DefaultIntOp = dyn_cast<IntInit>(DefaultOp)) {
Daniel Sanders198447a2017-11-01 00:29:47 +00003499 DstMIBuilder.addRenderer<ImmRenderer>(DefaultIntOp->getValue());
Diana Picus382602f2017-05-17 08:57:28 +00003500 continue;
3501 }
3502
3503 return failedImport("Could not add default op");
3504 }
3505
3506 return Error::success();
3507}
3508
Daniel Sandersc270c502017-03-30 09:36:33 +00003509Error GlobalISelEmitter::importImplicitDefRenderers(
Daniel Sandersffc7d582017-03-29 15:37:18 +00003510 BuildMIAction &DstMIBuilder,
3511 const std::vector<Record *> &ImplicitDefs) const {
3512 if (!ImplicitDefs.empty())
3513 return failedImport("Pattern defines a physical register");
Daniel Sandersc270c502017-03-30 09:36:33 +00003514 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00003515}
3516
3517Expected<RuleMatcher> GlobalISelEmitter::runOnPattern(const PatternToMatch &P) {
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003518 // Keep track of the matchers and actions to emit.
Aditya Nandakumarb63e7632018-02-16 22:37:15 +00003519 int Score = P.getPatternComplexity(CGP);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003520 RuleMatcher M(P.getSrcRecord()->getLoc());
Aditya Nandakumarb63e7632018-02-16 22:37:15 +00003521 RuleMatcherScores[M.getRuleID()] = Score;
Daniel Sanders6ea17ed2017-10-31 18:07:03 +00003522 M.addAction<DebugCommentAction>(llvm::to_string(*P.getSrcPattern()) +
3523 " => " +
3524 llvm::to_string(*P.getDstPattern()));
Daniel Sandersf84bc372018-05-05 20:53:24 +00003525 M.addAction<DebugCommentAction>("Rule ID " + llvm::to_string(M.getRuleID()));
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003526
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003527 if (auto Error = importRulePredicates(M, P.getPredicates()))
Daniel Sandersffc7d582017-03-29 15:37:18 +00003528 return std::move(Error);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003529
3530 // Next, analyze the pattern operators.
3531 TreePatternNode *Src = P.getSrcPattern();
3532 TreePatternNode *Dst = P.getDstPattern();
3533
3534 // If the root of either pattern isn't a simple operator, ignore it.
Daniel Sandersd0656a32017-04-13 09:45:37 +00003535 if (auto Err = isTrivialOperatorNode(Dst))
3536 return failedImport("Dst pattern root isn't a trivial operator (" +
3537 toString(std::move(Err)) + ")");
3538 if (auto Err = isTrivialOperatorNode(Src))
3539 return failedImport("Src pattern root isn't a trivial operator (" +
3540 toString(std::move(Err)) + ")");
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003541
Quentin Colombetaad20be2017-12-15 23:07:42 +00003542 // The different predicates and matchers created during
3543 // addInstructionMatcher use the RuleMatcher M to set up their
3544 // instruction ID (InsnVarID) that are going to be used when
3545 // M is going to be emitted.
3546 // However, the code doing the emission still relies on the IDs
3547 // returned during that process by the RuleMatcher when issuing
3548 // the recordInsn opcodes.
3549 // Because of that:
3550 // 1. The order in which we created the predicates
3551 // and such must be the same as the order in which we emit them,
3552 // and
3553 // 2. We need to reset the generation of the IDs in M somewhere between
3554 // addInstructionMatcher and emit
3555 //
3556 // FIXME: Long term, we don't want to have to rely on this implicit
3557 // naming being the same. One possible solution would be to have
3558 // explicit operator for operation capture and reference those.
3559 // The plus side is that it would expose opportunities to share
3560 // the capture accross rules. The downside is that it would
3561 // introduce a dependency between predicates (captures must happen
3562 // before their first use.)
Daniel Sandersedd07842017-08-17 09:26:14 +00003563 InstructionMatcher &InsnMatcherTemp = M.addInstructionMatcher(Src->getName());
3564 unsigned TempOpIdx = 0;
3565 auto InsnMatcherOrError =
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003566 createAndImportSelDAGMatcher(M, InsnMatcherTemp, Src, TempOpIdx);
Daniel Sandersedd07842017-08-17 09:26:14 +00003567 if (auto Error = InsnMatcherOrError.takeError())
3568 return std::move(Error);
3569 InstructionMatcher &InsnMatcher = InsnMatcherOrError.get();
3570
3571 if (Dst->isLeaf()) {
3572 Record *RCDef = getInitValueAsRegClass(Dst->getLeafValue());
3573
3574 const CodeGenRegisterClass &RC = Target.getRegisterClass(RCDef);
3575 if (RCDef) {
3576 // We need to replace the def and all its uses with the specified
3577 // operand. However, we must also insert COPY's wherever needed.
3578 // For now, emit a copy and let the register allocator clean up.
3579 auto &DstI = Target.getInstruction(RK.getDef("COPY"));
3580 const auto &DstIOperand = DstI.Operands[0];
3581
3582 OperandMatcher &OM0 = InsnMatcher.getOperand(0);
3583 OM0.setSymbolicName(DstIOperand.Name);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003584 M.defineOperand(OM0.getSymbolicName(), OM0);
Daniel Sandersedd07842017-08-17 09:26:14 +00003585 OM0.addPredicate<RegisterBankOperandMatcher>(RC);
3586
Daniel Sanders198447a2017-11-01 00:29:47 +00003587 auto &DstMIBuilder =
3588 M.addAction<BuildMIAction>(M.allocateOutputInsnID(), &DstI);
3589 DstMIBuilder.addRenderer<CopyRenderer>(DstIOperand.Name);
3590 DstMIBuilder.addRenderer<CopyRenderer>(Dst->getName());
Daniel Sandersedd07842017-08-17 09:26:14 +00003591 M.addAction<ConstrainOperandToRegClassAction>(0, 0, RC);
3592
3593 // We're done with this pattern! It's eligible for GISel emission; return
3594 // it.
3595 ++NumPatternImported;
3596 return std::move(M);
3597 }
3598
Daniel Sanders452c8ae2017-05-23 19:33:16 +00003599 return failedImport("Dst pattern root isn't a known leaf");
Daniel Sandersedd07842017-08-17 09:26:14 +00003600 }
Daniel Sanders452c8ae2017-05-23 19:33:16 +00003601
Daniel Sandersbee57392017-04-04 13:25:23 +00003602 // Start with the defined operands (i.e., the results of the root operator).
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003603 Record *DstOp = Dst->getOperator();
3604 if (!DstOp->isSubClassOf("Instruction"))
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003605 return failedImport("Pattern operator isn't an instruction");
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003606
3607 auto &DstI = Target.getInstruction(DstOp);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003608 if (DstI.Operands.NumDefs != Src->getExtTypes().size())
Daniel Sandersd0656a32017-04-13 09:45:37 +00003609 return failedImport("Src pattern results and dst MI defs are different (" +
3610 to_string(Src->getExtTypes().size()) + " def(s) vs " +
3611 to_string(DstI.Operands.NumDefs) + " def(s))");
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003612
Daniel Sandersffc7d582017-03-29 15:37:18 +00003613 // The root of the match also has constraints on the register bank so that it
3614 // matches the result instruction.
3615 unsigned OpIdx = 0;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003616 for (const TypeSetByHwMode &VTy : Src->getExtTypes()) {
3617 (void)VTy;
Daniel Sandersffc7d582017-03-29 15:37:18 +00003618
Daniel Sanders066ebbf2017-02-24 15:43:30 +00003619 const auto &DstIOperand = DstI.Operands[OpIdx];
3620 Record *DstIOpRec = DstIOperand.Rec;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003621 if (DstI.TheDef->getName() == "COPY_TO_REGCLASS") {
3622 DstIOpRec = getInitValueAsRegClass(Dst->getChild(1)->getLeafValue());
3623
3624 if (DstIOpRec == nullptr)
3625 return failedImport(
3626 "COPY_TO_REGCLASS operand #1 isn't a register class");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00003627 } else if (DstI.TheDef->getName() == "EXTRACT_SUBREG") {
3628 if (!Dst->getChild(0)->isLeaf())
3629 return failedImport("EXTRACT_SUBREG operand #0 isn't a leaf");
3630
Daniel Sanders32291982017-06-28 13:50:04 +00003631 // We can assume that a subregister is in the same bank as it's super
3632 // register.
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00003633 DstIOpRec = getInitValueAsRegClass(Dst->getChild(0)->getLeafValue());
3634
3635 if (DstIOpRec == nullptr)
3636 return failedImport(
3637 "EXTRACT_SUBREG operand #0 isn't a register class");
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003638 } else if (DstIOpRec->isSubClassOf("RegisterOperand"))
Daniel Sanders658541f2017-04-22 15:53:21 +00003639 DstIOpRec = DstIOpRec->getValueAsDef("RegClass");
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003640 else if (!DstIOpRec->isSubClassOf("RegisterClass"))
Daniel Sanders32291982017-06-28 13:50:04 +00003641 return failedImport("Dst MI def isn't a register class" +
3642 to_string(*Dst));
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003643
Daniel Sandersffc7d582017-03-29 15:37:18 +00003644 OperandMatcher &OM = InsnMatcher.getOperand(OpIdx);
3645 OM.setSymbolicName(DstIOperand.Name);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003646 M.defineOperand(OM.getSymbolicName(), OM);
Daniel Sandersdc662ff2017-01-26 11:10:14 +00003647 OM.addPredicate<RegisterBankOperandMatcher>(
3648 Target.getRegisterClass(DstIOpRec));
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003649 ++OpIdx;
3650 }
3651
Daniel Sandersa7b75262017-10-31 18:50:24 +00003652 auto DstMIBuilderOrError = createAndImportInstructionRenderer(M, Dst);
Daniel Sandersffc7d582017-03-29 15:37:18 +00003653 if (auto Error = DstMIBuilderOrError.takeError())
3654 return std::move(Error);
3655 BuildMIAction &DstMIBuilder = DstMIBuilderOrError.get();
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003656
Daniel Sandersffc7d582017-03-29 15:37:18 +00003657 // Render the implicit defs.
3658 // These are only added to the root of the result.
Daniel Sandersc270c502017-03-30 09:36:33 +00003659 if (auto Error = importImplicitDefRenderers(DstMIBuilder, P.getDstRegs()))
Daniel Sandersffc7d582017-03-29 15:37:18 +00003660 return std::move(Error);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003661
Daniel Sandersa7b75262017-10-31 18:50:24 +00003662 DstMIBuilder.chooseInsnToMutate(M);
3663
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003664 // Constrain the registers to classes. This is normally derived from the
3665 // emitted instruction but a few instructions require special handling.
3666 if (DstI.TheDef->getName() == "COPY_TO_REGCLASS") {
3667 // COPY_TO_REGCLASS does not provide operand constraints itself but the
3668 // result is constrained to the class given by the second child.
3669 Record *DstIOpRec =
3670 getInitValueAsRegClass(Dst->getChild(1)->getLeafValue());
3671
3672 if (DstIOpRec == nullptr)
3673 return failedImport("COPY_TO_REGCLASS operand #1 isn't a register class");
3674
3675 M.addAction<ConstrainOperandToRegClassAction>(
Daniel Sandersd93a35a2017-07-05 09:39:33 +00003676 0, 0, Target.getRegisterClass(DstIOpRec));
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00003677
3678 // We're done with this pattern! It's eligible for GISel emission; return
3679 // it.
3680 ++NumPatternImported;
3681 return std::move(M);
3682 }
3683
3684 if (DstI.TheDef->getName() == "EXTRACT_SUBREG") {
3685 // EXTRACT_SUBREG selects into a subregister COPY but unlike most
3686 // instructions, the result register class is controlled by the
3687 // subregisters of the operand. As a result, we must constrain the result
3688 // class rather than check that it's already the right one.
3689 if (!Dst->getChild(0)->isLeaf())
3690 return failedImport("EXTRACT_SUBREG child #1 is not a leaf");
3691
Daniel Sanders320390b2017-06-28 15:16:03 +00003692 DefInit *SubRegInit = dyn_cast<DefInit>(Dst->getChild(1)->getLeafValue());
3693 if (!SubRegInit)
3694 return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00003695
Daniel Sanders320390b2017-06-28 15:16:03 +00003696 // Constrain the result to the same register bank as the operand.
3697 Record *DstIOpRec =
3698 getInitValueAsRegClass(Dst->getChild(0)->getLeafValue());
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00003699
Daniel Sanders320390b2017-06-28 15:16:03 +00003700 if (DstIOpRec == nullptr)
3701 return failedImport("EXTRACT_SUBREG operand #1 isn't a register class");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00003702
Daniel Sanders320390b2017-06-28 15:16:03 +00003703 CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef());
Daniel Sandersd93a35a2017-07-05 09:39:33 +00003704 CodeGenRegisterClass *SrcRC = CGRegs.getRegClass(DstIOpRec);
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00003705
Daniel Sanders320390b2017-06-28 15:16:03 +00003706 // It would be nice to leave this constraint implicit but we're required
3707 // to pick a register class so constrain the result to a register class
3708 // that can hold the correct MVT.
3709 //
3710 // FIXME: This may introduce an extra copy if the chosen class doesn't
3711 // actually contain the subregisters.
3712 assert(Src->getExtTypes().size() == 1 &&
3713 "Expected Src of EXTRACT_SUBREG to have one result type");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00003714
Daniel Sanders320390b2017-06-28 15:16:03 +00003715 const auto &SrcRCDstRCPair =
3716 SrcRC->getMatchingSubClassWithSubRegs(CGRegs, SubIdx);
3717 assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
Daniel Sandersd93a35a2017-07-05 09:39:33 +00003718 M.addAction<ConstrainOperandToRegClassAction>(0, 0, *SrcRCDstRCPair->second);
3719 M.addAction<ConstrainOperandToRegClassAction>(0, 1, *SrcRCDstRCPair->first);
3720
3721 // We're done with this pattern! It's eligible for GISel emission; return
3722 // it.
3723 ++NumPatternImported;
3724 return std::move(M);
3725 }
3726
3727 M.addAction<ConstrainOperandsToDefinitionAction>(0);
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003728
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003729 // We're done with this pattern! It's eligible for GISel emission; return it.
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00003730 ++NumPatternImported;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003731 return std::move(M);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003732}
3733
Daniel Sanders649c5852017-10-13 20:42:18 +00003734// Emit imm predicate table and an enum to reference them with.
3735// The 'Predicate_' part of the name is redundant but eliminating it is more
3736// trouble than it's worth.
3737void GlobalISelEmitter::emitImmPredicates(
Daniel Sanders11300ce2017-10-13 21:28:03 +00003738 raw_ostream &OS, StringRef TypeIdentifier, StringRef Type,
3739 std::function<bool(const Record *R)> Filter) {
Daniel Sanders649c5852017-10-13 20:42:18 +00003740 std::vector<const Record *> MatchedRecords;
3741 const auto &Defs = RK.getAllDerivedDefinitions("PatFrag");
3742 std::copy_if(Defs.begin(), Defs.end(), std::back_inserter(MatchedRecords),
3743 [&](Record *Record) {
3744 return !Record->getValueAsString("ImmediateCode").empty() &&
3745 Filter(Record);
3746 });
3747
Daniel Sanders11300ce2017-10-13 21:28:03 +00003748 if (!MatchedRecords.empty()) {
3749 OS << "// PatFrag predicates.\n"
3750 << "enum {\n";
Daniel Sanders2fed4ff2017-10-13 21:51:20 +00003751 std::string EnumeratorSeparator =
Daniel Sanders11300ce2017-10-13 21:28:03 +00003752 (" = GIPFP_" + TypeIdentifier + "_Invalid + 1,\n").str();
3753 for (const auto *Record : MatchedRecords) {
3754 OS << " GIPFP_" << TypeIdentifier << "_Predicate_" << Record->getName()
3755 << EnumeratorSeparator;
3756 EnumeratorSeparator = ",\n";
3757 }
3758 OS << "};\n";
Daniel Sanders649c5852017-10-13 20:42:18 +00003759 }
Daniel Sanders11300ce2017-10-13 21:28:03 +00003760
Daniel Sanders32de8bb2017-12-20 14:41:51 +00003761 OS << "bool " << Target.getName() << "InstructionSelector::testImmPredicate_"
Aaron Ballman82e17f52017-12-20 20:09:30 +00003762 << TypeIdentifier << "(unsigned PredicateID, " << Type
3763 << " Imm) const {\n";
3764 if (!MatchedRecords.empty())
3765 OS << " switch (PredicateID) {\n";
Daniel Sanders32de8bb2017-12-20 14:41:51 +00003766 for (const auto *Record : MatchedRecords) {
3767 OS << " case GIPFP_" << TypeIdentifier << "_Predicate_"
3768 << Record->getName() << ": {\n"
3769 << " " << Record->getValueAsString("ImmediateCode") << "\n"
3770 << " llvm_unreachable(\"ImmediateCode should have returned\");\n"
3771 << " return false;\n"
3772 << " }\n";
3773 }
Aaron Ballman82e17f52017-12-20 20:09:30 +00003774 if (!MatchedRecords.empty())
3775 OS << " }\n";
3776 OS << " llvm_unreachable(\"Unknown predicate\");\n"
Daniel Sanders32de8bb2017-12-20 14:41:51 +00003777 << " return false;\n"
3778 << "}\n";
Daniel Sanders649c5852017-10-13 20:42:18 +00003779}
3780
Quentin Colombetec76d9c2017-12-18 19:47:41 +00003781std::vector<Matcher *> GlobalISelEmitter::optimizeRules(
Roman Tereshin2d6d3762018-05-02 20:08:14 +00003782 ArrayRef<Matcher *> Rules,
Quentin Colombetec76d9c2017-12-18 19:47:41 +00003783 std::vector<std::unique_ptr<GroupMatcher>> &StorageGroupMatcher) {
3784 std::vector<Matcher *> OptRules;
3785 // Start with a stupid grouping for now.
3786 std::unique_ptr<GroupMatcher> CurrentGroup = make_unique<GroupMatcher>();
3787 assert(CurrentGroup->conditions_empty());
3788 unsigned NbGroup = 0;
Quentin Colombet34688b92017-12-18 21:25:53 +00003789 for (Matcher *Rule : Rules) {
3790 std::unique_ptr<PredicateMatcher> Predicate = Rule->forgetFirstCondition();
Quentin Colombetec76d9c2017-12-18 19:47:41 +00003791 if (!CurrentGroup->conditions_empty() &&
3792 !CurrentGroup->lastConditionMatches(*Predicate)) {
3793 // Start a new group.
3794 ++NbGroup;
3795 OptRules.push_back(CurrentGroup.get());
3796 StorageGroupMatcher.emplace_back(std::move(CurrentGroup));
3797 CurrentGroup = make_unique<GroupMatcher>();
3798 assert(CurrentGroup->conditions_empty());
3799 }
3800 if (CurrentGroup->conditions_empty())
3801 CurrentGroup->addCondition(std::move(Predicate));
Quentin Colombet34688b92017-12-18 21:25:53 +00003802 CurrentGroup->addRule(*Rule);
Quentin Colombetec76d9c2017-12-18 19:47:41 +00003803 }
3804 if (!CurrentGroup->conditions_empty()) {
3805 ++NbGroup;
3806 OptRules.push_back(CurrentGroup.get());
3807 StorageGroupMatcher.emplace_back(std::move(CurrentGroup));
3808 }
3809 DEBUG(dbgs() << "NbGroup: " << NbGroup << "\n");
3810 return OptRules;
3811}
3812
Roman Tereshin2d6d3762018-05-02 20:08:14 +00003813MatchTable
3814GlobalISelEmitter::buildMatchTable(MutableArrayRef<RuleMatcher> Rules,
Roman Tereshinbeb39312018-05-02 20:15:11 +00003815 bool Optimize, bool WithCoverage) {
Roman Tereshin2d6d3762018-05-02 20:08:14 +00003816 std::vector<Matcher *> InputRules;
3817 for (Matcher &Rule : Rules)
3818 InputRules.push_back(&Rule);
3819
3820 if (!Optimize)
Roman Tereshinbeb39312018-05-02 20:15:11 +00003821 return MatchTable::buildTable(InputRules, WithCoverage);
Roman Tereshin2d6d3762018-05-02 20:08:14 +00003822
3823 std::vector<std::unique_ptr<GroupMatcher>> StorageGroupMatcher;
3824 std::vector<Matcher *> OptRules =
3825 optimizeRules(InputRules, StorageGroupMatcher);
3826
Roman Tereshinbeb39312018-05-02 20:15:11 +00003827 return MatchTable::buildTable(OptRules, WithCoverage);
Roman Tereshin2d6d3762018-05-02 20:08:14 +00003828}
3829
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003830void GlobalISelEmitter::run(raw_ostream &OS) {
Daniel Sandersf76f3152017-11-16 00:46:35 +00003831 if (!UseCoverageFile.empty()) {
3832 RuleCoverage = CodeGenCoverage();
3833 auto RuleCoverageBufOrErr = MemoryBuffer::getFile(UseCoverageFile);
3834 if (!RuleCoverageBufOrErr) {
3835 PrintWarning(SMLoc(), "Missing rule coverage data");
3836 RuleCoverage = None;
3837 } else {
3838 if (!RuleCoverage->parse(*RuleCoverageBufOrErr.get(), Target.getName())) {
3839 PrintWarning(SMLoc(), "Ignoring invalid or missing rule coverage data");
3840 RuleCoverage = None;
3841 }
3842 }
3843 }
3844
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003845 // Track the GINodeEquiv definitions.
3846 gatherNodeEquivs();
3847
3848 emitSourceFileHeader(("Global Instruction Selector for the " +
3849 Target.getName() + " target").str(), OS);
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00003850 std::vector<RuleMatcher> Rules;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003851 // Look through the SelectionDAG patterns we found, possibly emitting some.
3852 for (const PatternToMatch &Pat : CGP.ptms()) {
3853 ++NumPatternTotal;
Daniel Sanders7e523672017-11-11 03:23:44 +00003854
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003855 auto MatcherOrErr = runOnPattern(Pat);
3856
3857 // The pattern analysis can fail, indicating an unsupported pattern.
3858 // Report that if we've been asked to do so.
3859 if (auto Err = MatcherOrErr.takeError()) {
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003860 if (WarnOnSkippedPatterns) {
3861 PrintWarning(Pat.getSrcRecord()->getLoc(),
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003862 "Skipped pattern: " + toString(std::move(Err)));
3863 } else {
3864 consumeError(std::move(Err));
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003865 }
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00003866 ++NumPatternImportsSkipped;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003867 continue;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003868 }
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003869
Daniel Sandersf76f3152017-11-16 00:46:35 +00003870 if (RuleCoverage) {
3871 if (RuleCoverage->isCovered(MatcherOrErr->getRuleID()))
3872 ++NumPatternsTested;
3873 else
3874 PrintWarning(Pat.getSrcRecord()->getLoc(),
3875 "Pattern is not covered by a test");
3876 }
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00003877 Rules.push_back(std::move(MatcherOrErr.get()));
3878 }
3879
Volkan Kelesf7f25682018-01-16 18:44:05 +00003880 // Comparison function to order records by name.
3881 auto orderByName = [](const Record *A, const Record *B) {
3882 return A->getName() < B->getName();
3883 };
3884
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003885 std::vector<Record *> ComplexPredicates =
3886 RK.getAllDerivedDefinitions("GIComplexOperandMatcher");
Mandeep Singh Grang1b0e2f22018-04-06 20:18:05 +00003887 llvm::sort(ComplexPredicates.begin(), ComplexPredicates.end(), orderByName);
Volkan Kelesf7f25682018-01-16 18:44:05 +00003888
3889 std::vector<Record *> CustomRendererFns =
3890 RK.getAllDerivedDefinitions("GICustomOperandRenderer");
Mandeep Singh Grang1b0e2f22018-04-06 20:18:05 +00003891 llvm::sort(CustomRendererFns.begin(), CustomRendererFns.end(), orderByName);
Volkan Kelesf7f25682018-01-16 18:44:05 +00003892
Daniel Sanders8a4bae92017-03-14 21:32:08 +00003893 unsigned MaxTemporaries = 0;
3894 for (const auto &Rule : Rules)
Daniel Sanders2deea182017-04-22 15:11:04 +00003895 MaxTemporaries = std::max(MaxTemporaries, Rule.countRendererFns());
Daniel Sanders8a4bae92017-03-14 21:32:08 +00003896
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003897 OS << "#ifdef GET_GLOBALISEL_PREDICATE_BITSET\n"
3898 << "const unsigned MAX_SUBTARGET_PREDICATES = " << SubtargetFeatures.size()
3899 << ";\n"
3900 << "using PredicateBitset = "
3901 "llvm::PredicateBitsetImpl<MAX_SUBTARGET_PREDICATES>;\n"
3902 << "#endif // ifdef GET_GLOBALISEL_PREDICATE_BITSET\n\n";
3903
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003904 OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n"
3905 << " mutable MatcherState State;\n"
3906 << " typedef "
Daniel Sanders1e4569f2017-10-20 20:55:29 +00003907 "ComplexRendererFns("
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003908 << Target.getName()
3909 << "InstructionSelector::*ComplexMatcherMemFn)(MachineOperand &) const;\n"
Volkan Kelesf7f25682018-01-16 18:44:05 +00003910
3911 << " typedef void(" << Target.getName()
3912 << "InstructionSelector::*CustomRendererFn)(MachineInstrBuilder &, const "
3913 "MachineInstr&) "
3914 "const;\n"
3915 << " const ISelInfoTy<PredicateBitset, ComplexMatcherMemFn, "
3916 "CustomRendererFn> "
3917 "ISelInfo;\n";
3918 OS << " static " << Target.getName()
Daniel Sandersea8711b2017-10-16 03:36:29 +00003919 << "InstructionSelector::ComplexMatcherMemFn ComplexPredicateFns[];\n"
Volkan Kelesf7f25682018-01-16 18:44:05 +00003920 << " static " << Target.getName()
3921 << "InstructionSelector::CustomRendererFn CustomRenderers[];\n"
Roman Tereshin2df4c222018-05-02 20:07:15 +00003922 << " bool testImmPredicate_I64(unsigned PredicateID, int64_t Imm) const "
Daniel Sanders32de8bb2017-12-20 14:41:51 +00003923 "override;\n"
Roman Tereshin2df4c222018-05-02 20:07:15 +00003924 << " bool testImmPredicate_APInt(unsigned PredicateID, const APInt &Imm) "
Daniel Sanders32de8bb2017-12-20 14:41:51 +00003925 "const override;\n"
Roman Tereshin2df4c222018-05-02 20:07:15 +00003926 << " bool testImmPredicate_APFloat(unsigned PredicateID, const APFloat "
Daniel Sanders32de8bb2017-12-20 14:41:51 +00003927 "&Imm) const override;\n"
Roman Tereshin2df4c222018-05-02 20:07:15 +00003928 << " const int64_t *getMatchTable() const override;\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003929 << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n\n";
Daniel Sanders8a4bae92017-03-14 21:32:08 +00003930
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003931 OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n"
3932 << ", State(" << MaxTemporaries << "),\n"
Volkan Kelesf7f25682018-01-16 18:44:05 +00003933 << "ISelInfo({TypeObjects, FeatureBitsets, ComplexPredicateFns, "
3934 "CustomRenderers})\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003935 << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n\n";
Daniel Sanders8a4bae92017-03-14 21:32:08 +00003936
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003937 OS << "#ifdef GET_GLOBALISEL_IMPL\n";
3938 SubtargetFeatureInfo::emitSubtargetFeatureBitEnumeration(SubtargetFeatures,
3939 OS);
Daniel Sanderse9fdba32017-04-29 17:30:09 +00003940
3941 // Separate subtarget features by how often they must be recomputed.
3942 SubtargetFeatureInfoMap ModuleFeatures;
3943 std::copy_if(SubtargetFeatures.begin(), SubtargetFeatures.end(),
3944 std::inserter(ModuleFeatures, ModuleFeatures.end()),
3945 [](const SubtargetFeatureInfoMap::value_type &X) {
3946 return !X.second.mustRecomputePerFunction();
3947 });
3948 SubtargetFeatureInfoMap FunctionFeatures;
3949 std::copy_if(SubtargetFeatures.begin(), SubtargetFeatures.end(),
3950 std::inserter(FunctionFeatures, FunctionFeatures.end()),
3951 [](const SubtargetFeatureInfoMap::value_type &X) {
3952 return X.second.mustRecomputePerFunction();
3953 });
3954
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003955 SubtargetFeatureInfo::emitComputeAvailableFeatures(
Daniel Sanderse9fdba32017-04-29 17:30:09 +00003956 Target.getName(), "InstructionSelector", "computeAvailableModuleFeatures",
3957 ModuleFeatures, OS);
3958 SubtargetFeatureInfo::emitComputeAvailableFeatures(
3959 Target.getName(), "InstructionSelector",
3960 "computeAvailableFunctionFeatures", FunctionFeatures, OS,
3961 "const MachineFunction *MF");
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003962
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003963 // Emit a table containing the LLT objects needed by the matcher and an enum
3964 // for the matcher to reference them with.
Daniel Sanders032e7f22017-08-17 13:18:35 +00003965 std::vector<LLTCodeGen> TypeObjects;
Daniel Sandersf84bc372018-05-05 20:53:24 +00003966 for (const auto &Ty : KnownTypes)
Daniel Sanders032e7f22017-08-17 13:18:35 +00003967 TypeObjects.push_back(Ty);
Mandeep Singh Grang1b0e2f22018-04-06 20:18:05 +00003968 llvm::sort(TypeObjects.begin(), TypeObjects.end());
Daniel Sanders49980702017-08-23 10:09:25 +00003969 OS << "// LLT Objects.\n"
3970 << "enum {\n";
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003971 for (const auto &TypeObject : TypeObjects) {
3972 OS << " ";
3973 TypeObject.emitCxxEnumValue(OS);
3974 OS << ",\n";
3975 }
3976 OS << "};\n"
3977 << "const static LLT TypeObjects[] = {\n";
3978 for (const auto &TypeObject : TypeObjects) {
3979 OS << " ";
3980 TypeObject.emitCxxConstructorCall(OS);
3981 OS << ",\n";
3982 }
3983 OS << "};\n\n";
3984
3985 // Emit a table containing the PredicateBitsets objects needed by the matcher
3986 // and an enum for the matcher to reference them with.
3987 std::vector<std::vector<Record *>> FeatureBitsets;
3988 for (auto &Rule : Rules)
3989 FeatureBitsets.push_back(Rule.getRequiredFeatures());
Mandeep Singh Grang1b0e2f22018-04-06 20:18:05 +00003990 llvm::sort(
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003991 FeatureBitsets.begin(), FeatureBitsets.end(),
3992 [&](const std::vector<Record *> &A, const std::vector<Record *> &B) {
3993 if (A.size() < B.size())
3994 return true;
3995 if (A.size() > B.size())
3996 return false;
3997 for (const auto &Pair : zip(A, B)) {
3998 if (std::get<0>(Pair)->getName() < std::get<1>(Pair)->getName())
3999 return true;
4000 if (std::get<0>(Pair)->getName() > std::get<1>(Pair)->getName())
4001 return false;
4002 }
4003 return false;
4004 });
4005 FeatureBitsets.erase(
4006 std::unique(FeatureBitsets.begin(), FeatureBitsets.end()),
4007 FeatureBitsets.end());
Daniel Sanders49980702017-08-23 10:09:25 +00004008 OS << "// Feature bitsets.\n"
4009 << "enum {\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00004010 << " GIFBS_Invalid,\n";
4011 for (const auto &FeatureBitset : FeatureBitsets) {
4012 if (FeatureBitset.empty())
4013 continue;
4014 OS << " " << getNameForFeatureBitset(FeatureBitset) << ",\n";
4015 }
4016 OS << "};\n"
4017 << "const static PredicateBitset FeatureBitsets[] {\n"
4018 << " {}, // GIFBS_Invalid\n";
4019 for (const auto &FeatureBitset : FeatureBitsets) {
4020 if (FeatureBitset.empty())
4021 continue;
4022 OS << " {";
4023 for (const auto &Feature : FeatureBitset) {
4024 const auto &I = SubtargetFeatures.find(Feature);
4025 assert(I != SubtargetFeatures.end() && "Didn't import predicate?");
4026 OS << I->second.getEnumBitName() << ", ";
4027 }
4028 OS << "},\n";
4029 }
4030 OS << "};\n\n";
4031
4032 // Emit complex predicate table and an enum to reference them with.
Daniel Sanders49980702017-08-23 10:09:25 +00004033 OS << "// ComplexPattern predicates.\n"
4034 << "enum {\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00004035 << " GICP_Invalid,\n";
4036 for (const auto &Record : ComplexPredicates)
4037 OS << " GICP_" << Record->getName() << ",\n";
4038 OS << "};\n"
4039 << "// See constructor for table contents\n\n";
4040
Daniel Sanders11300ce2017-10-13 21:28:03 +00004041 emitImmPredicates(OS, "I64", "int64_t", [](const Record *R) {
Daniel Sanders649c5852017-10-13 20:42:18 +00004042 bool Unset;
4043 return !R->getValueAsBitOrUnset("IsAPFloat", Unset) &&
4044 !R->getValueAsBit("IsAPInt");
4045 });
Daniel Sanders11300ce2017-10-13 21:28:03 +00004046 emitImmPredicates(OS, "APFloat", "const APFloat &", [](const Record *R) {
4047 bool Unset;
4048 return R->getValueAsBitOrUnset("IsAPFloat", Unset);
4049 });
4050 emitImmPredicates(OS, "APInt", "const APInt &", [](const Record *R) {
4051 return R->getValueAsBit("IsAPInt");
4052 });
Daniel Sandersea8711b2017-10-16 03:36:29 +00004053 OS << "\n";
4054
4055 OS << Target.getName() << "InstructionSelector::ComplexMatcherMemFn\n"
4056 << Target.getName() << "InstructionSelector::ComplexPredicateFns[] = {\n"
4057 << " nullptr, // GICP_Invalid\n";
4058 for (const auto &Record : ComplexPredicates)
4059 OS << " &" << Target.getName()
4060 << "InstructionSelector::" << Record->getValueAsString("MatcherFn")
4061 << ", // " << Record->getName() << "\n";
4062 OS << "};\n\n";
Daniel Sanders2c269f62017-08-24 09:11:20 +00004063
Volkan Kelesf7f25682018-01-16 18:44:05 +00004064 OS << "// Custom renderers.\n"
4065 << "enum {\n"
4066 << " GICR_Invalid,\n";
4067 for (const auto &Record : CustomRendererFns)
4068 OS << " GICR_" << Record->getValueAsString("RendererFn") << ", \n";
4069 OS << "};\n";
4070
4071 OS << Target.getName() << "InstructionSelector::CustomRendererFn\n"
4072 << Target.getName() << "InstructionSelector::CustomRenderers[] = {\n"
4073 << " nullptr, // GICP_Invalid\n";
4074 for (const auto &Record : CustomRendererFns)
4075 OS << " &" << Target.getName()
4076 << "InstructionSelector::" << Record->getValueAsString("RendererFn")
4077 << ", // " << Record->getName() << "\n";
4078 OS << "};\n\n";
4079
Quentin Colombetec76d9c2017-12-18 19:47:41 +00004080 std::stable_sort(Rules.begin(), Rules.end(), [&](const RuleMatcher &A,
4081 const RuleMatcher &B) {
Aditya Nandakumarb63e7632018-02-16 22:37:15 +00004082 int ScoreA = RuleMatcherScores[A.getRuleID()];
4083 int ScoreB = RuleMatcherScores[B.getRuleID()];
4084 if (ScoreA > ScoreB)
4085 return true;
4086 if (ScoreB > ScoreA)
4087 return false;
Quentin Colombetec76d9c2017-12-18 19:47:41 +00004088 if (A.isHigherPriorityThan(B)) {
4089 assert(!B.isHigherPriorityThan(A) && "Cannot be more important "
4090 "and less important at "
4091 "the same time");
4092 return true;
4093 }
4094 return false;
4095 });
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004096
Roman Tereshin2df4c222018-05-02 20:07:15 +00004097 OS << "bool " << Target.getName()
4098 << "InstructionSelector::selectImpl(MachineInstr &I, CodeGenCoverage "
4099 "&CoverageInfo) const {\n"
4100 << " MachineFunction &MF = *I.getParent()->getParent();\n"
4101 << " MachineRegisterInfo &MRI = MF.getRegInfo();\n"
4102 << " // FIXME: This should be computed on a per-function basis rather "
4103 "than per-insn.\n"
4104 << " AvailableFunctionFeatures = computeAvailableFunctionFeatures(&STI, "
4105 "&MF);\n"
4106 << " const PredicateBitset AvailableFeatures = getAvailableFeatures();\n"
4107 << " NewMIVector OutMIs;\n"
4108 << " State.MIs.clear();\n"
4109 << " State.MIs.push_back(&I);\n\n"
4110 << " if (executeMatchTable(*this, OutMIs, State, ISelInfo"
4111 << ", getMatchTable(), TII, MRI, TRI, RBI, AvailableFeatures"
4112 << ", CoverageInfo)) {\n"
4113 << " return true;\n"
4114 << " }\n\n"
4115 << " return false;\n"
4116 << "}\n\n";
4117
Roman Tereshinbeb39312018-05-02 20:15:11 +00004118 const MatchTable Table =
4119 buildMatchTable(Rules, OptimizeMatchTable, GenerateCoverage);
Roman Tereshin2df4c222018-05-02 20:07:15 +00004120 OS << "const int64_t *" << Target.getName()
4121 << "InstructionSelector::getMatchTable() const {\n";
4122 Table.emitDeclaration(OS);
4123 OS << " return ";
4124 Table.emitUse(OS);
4125 OS << ";\n}\n";
4126 OS << "#endif // ifdef GET_GLOBALISEL_IMPL\n";
Daniel Sanderse9fdba32017-04-29 17:30:09 +00004127
4128 OS << "#ifdef GET_GLOBALISEL_PREDICATES_DECL\n"
4129 << "PredicateBitset AvailableModuleFeatures;\n"
4130 << "mutable PredicateBitset AvailableFunctionFeatures;\n"
4131 << "PredicateBitset getAvailableFeatures() const {\n"
4132 << " return AvailableModuleFeatures | AvailableFunctionFeatures;\n"
4133 << "}\n"
4134 << "PredicateBitset\n"
4135 << "computeAvailableModuleFeatures(const " << Target.getName()
4136 << "Subtarget *Subtarget) const;\n"
4137 << "PredicateBitset\n"
4138 << "computeAvailableFunctionFeatures(const " << Target.getName()
4139 << "Subtarget *Subtarget,\n"
4140 << " const MachineFunction *MF) const;\n"
4141 << "#endif // ifdef GET_GLOBALISEL_PREDICATES_DECL\n";
4142
4143 OS << "#ifdef GET_GLOBALISEL_PREDICATES_INIT\n"
4144 << "AvailableModuleFeatures(computeAvailableModuleFeatures(&STI)),\n"
4145 << "AvailableFunctionFeatures()\n"
4146 << "#endif // ifdef GET_GLOBALISEL_PREDICATES_INIT\n";
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004147}
4148
Daniel Sanderse7b0d662017-04-21 15:59:56 +00004149void GlobalISelEmitter::declareSubtargetFeature(Record *Predicate) {
4150 if (SubtargetFeatures.count(Predicate) == 0)
4151 SubtargetFeatures.emplace(
4152 Predicate, SubtargetFeatureInfo(Predicate, SubtargetFeatures.size()));
4153}
4154
Quentin Colombetec76d9c2017-12-18 19:47:41 +00004155std::unique_ptr<PredicateMatcher> RuleMatcher::forgetFirstCondition() {
4156 assert(!insnmatchers_empty() &&
4157 "Trying to forget something that does not exist");
4158
4159 InstructionMatcher &Matcher = insnmatchers_front();
4160 std::unique_ptr<PredicateMatcher> Condition;
4161 if (!Matcher.predicates_empty())
4162 Condition = Matcher.predicates_pop_front();
4163 if (!Condition) {
4164 // If there is no more predicate on the instruction itself, look at its
4165 // operands.
4166 assert(!Matcher.operands_empty() &&
4167 "Empty instruction should have been discarded");
4168 OperandMatcher &OpMatcher = **Matcher.operands_begin();
4169 assert(!OpMatcher.predicates_empty() && "no operand constraint");
4170 Condition = OpMatcher.predicates_pop_front();
4171 // If this operand is free of constraints, rip it off.
4172 if (OpMatcher.predicates_empty())
4173 Matcher.pop_front();
4174 }
4175 // Rip the instruction off when it is empty.
4176 if (Matcher.operands_empty() && Matcher.predicates_empty())
4177 insnmatchers_pop_front();
4178 return Condition;
4179}
4180
4181bool GroupMatcher::lastConditionMatches(
4182 const PredicateMatcher &Predicate) const {
4183 const auto &LastCondition = conditions_back();
4184 return Predicate.isIdentical(*LastCondition);
4185}
4186
4187void GroupMatcher::emit(MatchTable &Table) {
4188 unsigned LabelID = Table.allocateLabelID();
4189 if (!conditions_empty()) {
4190 Table << MatchTable::Opcode("GIM_Try", +1)
4191 << MatchTable::Comment("On fail goto")
4192 << MatchTable::JumpTarget(LabelID) << MatchTable::LineBreak;
4193 for (auto &Condition : Conditions)
4194 Condition->emitPredicateOpcodes(
4195 Table, *static_cast<RuleMatcher *>(*Rules.begin()));
4196 }
4197 // Emit the conditions.
4198 // Then checks apply the rules.
4199 for (const auto &Rule : Rules)
4200 Rule->emit(Table);
4201 // If we don't succeeded for that block, that means we are not going to select
4202 // this instruction.
4203 if (!conditions_empty()) {
4204 Table << MatchTable::Opcode("GIM_Reject") << MatchTable::LineBreak;
4205 Table << MatchTable::Opcode("GIR_Done", -1) << MatchTable::LineBreak
4206 << MatchTable::Label(LabelID);
4207 }
4208}
4209
Quentin Colombetaad20be2017-12-15 23:07:42 +00004210unsigned OperandMatcher::getInsnVarID() const { return Insn.getVarID(); }
4211
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00004212} // end anonymous namespace
4213
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004214//===----------------------------------------------------------------------===//
4215
4216namespace llvm {
4217void EmitGlobalISel(RecordKeeper &RK, raw_ostream &OS) {
4218 GlobalISelEmitter(RK).run(OS);
4219}
4220} // End llvm namespace