blob: fbf0b4bd9ddd4a3397e0fe16e095aa882f65534b [file] [log] [blame]
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001//===- GlobalISelEmitter.cpp - Generate an instruction selector -----------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Ahmed Bougacha36f70352016-12-21 23:26:20 +00006//
7//===----------------------------------------------------------------------===//
8//
9/// \file
10/// This tablegen backend emits code for use by the GlobalISel instruction
11/// selector. See include/llvm/CodeGen/TargetGlobalISel.td.
12///
13/// This file analyzes the patterns recognized by the SelectionDAGISel tablegen
14/// backend, filters out the ones that are unsupported, maps
15/// SelectionDAG-specific constructs to their GlobalISel counterpart
16/// (when applicable: MVT to LLT; SDNode to generic Instruction).
17///
18/// Not all patterns are supported: pass the tablegen invocation
19/// "-warn-on-skipped-patterns" to emit a warning when a pattern is skipped,
20/// as well as why.
21///
22/// The generated file defines a single method:
23/// bool <Target>InstructionSelector::selectImpl(MachineInstr &I) const;
24/// intended to be used in InstructionSelector::select as the first-step
25/// selector for the patterns that don't require complex C++.
26///
27/// FIXME: We'll probably want to eventually define a base
28/// "TargetGenInstructionSelector" class.
29///
30//===----------------------------------------------------------------------===//
31
32#include "CodeGenDAGPatterns.h"
Daniel Sanderse7b0d662017-04-21 15:59:56 +000033#include "SubtargetFeatureInfo.h"
Ahmed Bougacha36f70352016-12-21 23:26:20 +000034#include "llvm/ADT/Optional.h"
Daniel Sanders0ed28822017-04-12 08:23:08 +000035#include "llvm/ADT/SmallSet.h"
Ahmed Bougacha36f70352016-12-21 23:26:20 +000036#include "llvm/ADT/Statistic.h"
Daniel Sandersf76f3152017-11-16 00:46:35 +000037#include "llvm/Support/CodeGenCoverage.h"
Ahmed Bougacha36f70352016-12-21 23:26:20 +000038#include "llvm/Support/CommandLine.h"
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +000039#include "llvm/Support/Error.h"
Daniel Sanders52b4ce72017-03-07 23:20:35 +000040#include "llvm/Support/LowLevelTypeImpl.h"
David Blaikie13e77db2018-03-23 23:58:25 +000041#include "llvm/Support/MachineValueType.h"
Pavel Labath52a82e22017-02-21 09:19:41 +000042#include "llvm/Support/ScopedPrinter.h"
Ahmed Bougacha36f70352016-12-21 23:26:20 +000043#include "llvm/TableGen/Error.h"
44#include "llvm/TableGen/Record.h"
45#include "llvm/TableGen/TableGenBackend.h"
Daniel Sanders8a4bae92017-03-14 21:32:08 +000046#include <numeric>
Daniel Sandersf76f3152017-11-16 00:46:35 +000047#include <string>
Ahmed Bougacha36f70352016-12-21 23:26:20 +000048using namespace llvm;
49
50#define DEBUG_TYPE "gisel-emitter"
51
52STATISTIC(NumPatternTotal, "Total number of patterns");
Daniel Sandersb41ce2b2017-02-20 14:31:27 +000053STATISTIC(NumPatternImported, "Number of patterns imported from SelectionDAG");
54STATISTIC(NumPatternImportsSkipped, "Number of SelectionDAG imports skipped");
Daniel Sandersf76f3152017-11-16 00:46:35 +000055STATISTIC(NumPatternsTested, "Number of patterns executed according to coverage information");
Ahmed Bougacha36f70352016-12-21 23:26:20 +000056STATISTIC(NumPatternEmitted, "Number of patterns emitted");
57
Daniel Sanders0848b232017-03-27 13:15:13 +000058cl::OptionCategory GlobalISelEmitterCat("Options for -gen-global-isel");
59
Ahmed Bougacha36f70352016-12-21 23:26:20 +000060static cl::opt<bool> WarnOnSkippedPatterns(
61 "warn-on-skipped-patterns",
62 cl::desc("Explain why a pattern was skipped for inclusion "
63 "in the GlobalISel selector"),
Daniel Sanders0848b232017-03-27 13:15:13 +000064 cl::init(false), cl::cat(GlobalISelEmitterCat));
Ahmed Bougacha36f70352016-12-21 23:26:20 +000065
Daniel Sandersf76f3152017-11-16 00:46:35 +000066static cl::opt<bool> GenerateCoverage(
67 "instrument-gisel-coverage",
68 cl::desc("Generate coverage instrumentation for GlobalISel"),
69 cl::init(false), cl::cat(GlobalISelEmitterCat));
70
71static cl::opt<std::string> UseCoverageFile(
72 "gisel-coverage-file", cl::init(""),
73 cl::desc("Specify file to retrieve coverage information from"),
74 cl::cat(GlobalISelEmitterCat));
75
Quentin Colombetec76d9c2017-12-18 19:47:41 +000076static cl::opt<bool> OptimizeMatchTable(
77 "optimize-match-table",
78 cl::desc("Generate an optimized version of the match table"),
79 cl::init(true), cl::cat(GlobalISelEmitterCat));
80
Daniel Sandersbdfebb82017-03-15 20:18:38 +000081namespace {
Ahmed Bougacha36f70352016-12-21 23:26:20 +000082//===- Helper functions ---------------------------------------------------===//
83
Daniel Sanders11300ce2017-10-13 21:28:03 +000084/// Get the name of the enum value used to number the predicate function.
85std::string getEnumNameForPredicate(const TreePredicateFn &Predicate) {
Daniel Sanders8ead1292018-06-15 23:13:43 +000086 if (Predicate.hasGISelPredicateCode())
87 return "GIPFP_MI_" + Predicate.getFnName();
Simon Pilgrim6ecae9f2017-10-14 21:27:53 +000088 return "GIPFP_" + Predicate.getImmTypeIdentifier().str() + "_" +
Daniel Sanders11300ce2017-10-13 21:28:03 +000089 Predicate.getFnName();
90}
91
92/// Get the opcode used to check this predicate.
93std::string getMatchOpcodeForPredicate(const TreePredicateFn &Predicate) {
Simon Pilgrim6ecae9f2017-10-14 21:27:53 +000094 return "GIM_Check" + Predicate.getImmTypeIdentifier().str() + "ImmPredicate";
Daniel Sanders11300ce2017-10-13 21:28:03 +000095}
96
Daniel Sanders52b4ce72017-03-07 23:20:35 +000097/// This class stands in for LLT wherever we want to tablegen-erate an
98/// equivalent at compiler run-time.
99class LLTCodeGen {
100private:
101 LLT Ty;
102
103public:
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000104 LLTCodeGen() = default;
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000105 LLTCodeGen(const LLT &Ty) : Ty(Ty) {}
106
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000107 std::string getCxxEnumValue() const {
108 std::string Str;
109 raw_string_ostream OS(Str);
110
111 emitCxxEnumValue(OS);
112 return OS.str();
113 }
114
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000115 void emitCxxEnumValue(raw_ostream &OS) const {
116 if (Ty.isScalar()) {
117 OS << "GILLT_s" << Ty.getSizeInBits();
118 return;
119 }
120 if (Ty.isVector()) {
121 OS << "GILLT_v" << Ty.getNumElements() << "s" << Ty.getScalarSizeInBits();
122 return;
123 }
Daniel Sandersa71f4542017-10-16 00:56:30 +0000124 if (Ty.isPointer()) {
125 OS << "GILLT_p" << Ty.getAddressSpace();
126 if (Ty.getSizeInBits() > 0)
127 OS << "s" << Ty.getSizeInBits();
128 return;
129 }
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000130 llvm_unreachable("Unhandled LLT");
131 }
132
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000133 void emitCxxConstructorCall(raw_ostream &OS) const {
134 if (Ty.isScalar()) {
135 OS << "LLT::scalar(" << Ty.getSizeInBits() << ")";
136 return;
137 }
138 if (Ty.isVector()) {
Daniel Sanders32291982017-06-28 13:50:04 +0000139 OS << "LLT::vector(" << Ty.getNumElements() << ", "
140 << Ty.getScalarSizeInBits() << ")";
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000141 return;
142 }
Daniel Sandersa71f4542017-10-16 00:56:30 +0000143 if (Ty.isPointer() && Ty.getSizeInBits() > 0) {
144 OS << "LLT::pointer(" << Ty.getAddressSpace() << ", "
145 << Ty.getSizeInBits() << ")";
146 return;
147 }
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000148 llvm_unreachable("Unhandled LLT");
149 }
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000150
151 const LLT &get() const { return Ty; }
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000152
Mandeep Singh Grang1b0e2f22018-04-06 20:18:05 +0000153 /// This ordering is used for std::unique() and llvm::sort(). There's no
Daniel Sanders032e7f22017-08-17 13:18:35 +0000154 /// particular logic behind the order but either A < B or B < A must be
155 /// true if A != B.
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000156 bool operator<(const LLTCodeGen &Other) const {
Daniel Sanders032e7f22017-08-17 13:18:35 +0000157 if (Ty.isValid() != Other.Ty.isValid())
158 return Ty.isValid() < Other.Ty.isValid();
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000159 if (!Ty.isValid())
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000160 return false;
Daniel Sanders032e7f22017-08-17 13:18:35 +0000161
162 if (Ty.isVector() != Other.Ty.isVector())
163 return Ty.isVector() < Other.Ty.isVector();
164 if (Ty.isScalar() != Other.Ty.isScalar())
165 return Ty.isScalar() < Other.Ty.isScalar();
166 if (Ty.isPointer() != Other.Ty.isPointer())
167 return Ty.isPointer() < Other.Ty.isPointer();
168
169 if (Ty.isPointer() && Ty.getAddressSpace() != Other.Ty.getAddressSpace())
170 return Ty.getAddressSpace() < Other.Ty.getAddressSpace();
171
172 if (Ty.isVector() && Ty.getNumElements() != Other.Ty.getNumElements())
173 return Ty.getNumElements() < Other.Ty.getNumElements();
174
175 return Ty.getSizeInBits() < Other.Ty.getSizeInBits();
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000176 }
Quentin Colombet893e0f12017-12-15 23:24:39 +0000177
178 bool operator==(const LLTCodeGen &B) const { return Ty == B.Ty; }
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000179};
180
Daniel Sandersf84bc372018-05-05 20:53:24 +0000181// Track all types that are used so we can emit the corresponding enum.
182std::set<LLTCodeGen> KnownTypes;
183
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000184class InstructionMatcher;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000185/// Convert an MVT to an equivalent LLT if possible, or the invalid LLT() for
186/// MVTs that don't map cleanly to an LLT (e.g., iPTR, *any, ...).
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000187static Optional<LLTCodeGen> MVTToLLT(MVT::SimpleValueType SVT) {
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000188 MVT VT(SVT);
Daniel Sandersa71f4542017-10-16 00:56:30 +0000189
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000190 if (VT.isVector() && VT.getVectorNumElements() != 1)
Daniel Sanders32291982017-06-28 13:50:04 +0000191 return LLTCodeGen(
192 LLT::vector(VT.getVectorNumElements(), VT.getScalarSizeInBits()));
Daniel Sandersa71f4542017-10-16 00:56:30 +0000193
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000194 if (VT.isInteger() || VT.isFloatingPoint())
195 return LLTCodeGen(LLT::scalar(VT.getSizeInBits()));
196 return None;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000197}
198
Florian Hahn6b1db822018-06-14 20:32:58 +0000199static std::string explainPredicates(const TreePatternNode *N) {
Daniel Sandersd0656a32017-04-13 09:45:37 +0000200 std::string Explanation = "";
201 StringRef Separator = "";
Nicolai Haehnle445b0b62018-11-30 14:15:13 +0000202 for (const TreePredicateCall &Call : N->getPredicateCalls()) {
203 const TreePredicateFn &P = Call.Fn;
Daniel Sandersd0656a32017-04-13 09:45:37 +0000204 Explanation +=
205 (Separator + P.getOrigPatFragRecord()->getRecord()->getName()).str();
Daniel Sanders76664652017-11-28 22:07:05 +0000206 Separator = ", ";
207
Daniel Sandersd0656a32017-04-13 09:45:37 +0000208 if (P.isAlwaysTrue())
209 Explanation += " always-true";
210 if (P.isImmediatePattern())
211 Explanation += " immediate";
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000212
213 if (P.isUnindexed())
214 Explanation += " unindexed";
215
216 if (P.isNonExtLoad())
217 Explanation += " non-extload";
218 if (P.isAnyExtLoad())
219 Explanation += " extload";
220 if (P.isSignExtLoad())
221 Explanation += " sextload";
222 if (P.isZeroExtLoad())
223 Explanation += " zextload";
224
225 if (P.isNonTruncStore())
226 Explanation += " non-truncstore";
227 if (P.isTruncStore())
228 Explanation += " truncstore";
229
230 if (Record *VT = P.getMemoryVT())
231 Explanation += (" MemVT=" + VT->getName()).str();
232 if (Record *VT = P.getScalarMemoryVT())
233 Explanation += (" ScalarVT(MemVT)=" + VT->getName()).str();
Daniel Sanders76664652017-11-28 22:07:05 +0000234
Matt Arsenaultd00d8572019-07-15 20:59:42 +0000235 if (ListInit *AddrSpaces = P.getAddressSpaces()) {
236 raw_string_ostream OS(Explanation);
237 OS << " AddressSpaces=[";
238
239 StringRef AddrSpaceSeparator;
240 for (Init *Val : AddrSpaces->getValues()) {
241 IntInit *IntVal = dyn_cast<IntInit>(Val);
242 if (!IntVal)
243 continue;
244
245 OS << AddrSpaceSeparator << IntVal->getValue();
246 AddrSpaceSeparator = ", ";
247 }
248
249 OS << ']';
250 }
251
Matt Arsenault52c26242019-07-31 00:14:43 +0000252 int64_t MinAlign = P.getMinAlignment();
253 if (MinAlign > 0)
254 Explanation += " MinAlign=" + utostr(MinAlign);
255
Daniel Sanders76664652017-11-28 22:07:05 +0000256 if (P.isAtomicOrderingMonotonic())
257 Explanation += " monotonic";
258 if (P.isAtomicOrderingAcquire())
259 Explanation += " acquire";
260 if (P.isAtomicOrderingRelease())
261 Explanation += " release";
262 if (P.isAtomicOrderingAcquireRelease())
263 Explanation += " acq_rel";
264 if (P.isAtomicOrderingSequentiallyConsistent())
265 Explanation += " seq_cst";
Daniel Sanders0c43b3a2017-11-30 21:05:59 +0000266 if (P.isAtomicOrderingAcquireOrStronger())
267 Explanation += " >=acquire";
268 if (P.isAtomicOrderingWeakerThanAcquire())
269 Explanation += " <acquire";
270 if (P.isAtomicOrderingReleaseOrStronger())
271 Explanation += " >=release";
272 if (P.isAtomicOrderingWeakerThanRelease())
273 Explanation += " <release";
Daniel Sandersd0656a32017-04-13 09:45:37 +0000274 }
275 return Explanation;
276}
277
Daniel Sandersd0656a32017-04-13 09:45:37 +0000278std::string explainOperator(Record *Operator) {
279 if (Operator->isSubClassOf("SDNode"))
Craig Topper2b8419a2017-05-31 19:01:11 +0000280 return (" (" + Operator->getValueAsString("Opcode") + ")").str();
Daniel Sandersd0656a32017-04-13 09:45:37 +0000281
282 if (Operator->isSubClassOf("Intrinsic"))
283 return (" (Operator is an Intrinsic, " + Operator->getName() + ")").str();
284
Daniel Sandersdf39cba2017-10-15 18:22:54 +0000285 if (Operator->isSubClassOf("ComplexPattern"))
286 return (" (Operator is an unmapped ComplexPattern, " + Operator->getName() +
287 ")")
288 .str();
289
Volkan Kelesf7f25682018-01-16 18:44:05 +0000290 if (Operator->isSubClassOf("SDNodeXForm"))
291 return (" (Operator is an unmapped SDNodeXForm, " + Operator->getName() +
292 ")")
293 .str();
294
Daniel Sandersdf39cba2017-10-15 18:22:54 +0000295 return (" (Operator " + Operator->getName() + " not understood)").str();
Daniel Sandersd0656a32017-04-13 09:45:37 +0000296}
297
298/// Helper function to let the emitter report skip reason error messages.
299static Error failedImport(const Twine &Reason) {
300 return make_error<StringError>(Reason, inconvertibleErrorCode());
301}
302
Florian Hahn6b1db822018-06-14 20:32:58 +0000303static Error isTrivialOperatorNode(const TreePatternNode *N) {
Daniel Sandersd0656a32017-04-13 09:45:37 +0000304 std::string Explanation = "";
305 std::string Separator = "";
Daniel Sanders2c269f62017-08-24 09:11:20 +0000306
307 bool HasUnsupportedPredicate = false;
Nicolai Haehnle445b0b62018-11-30 14:15:13 +0000308 for (const TreePredicateCall &Call : N->getPredicateCalls()) {
309 const TreePredicateFn &Predicate = Call.Fn;
310
Daniel Sanders2c269f62017-08-24 09:11:20 +0000311 if (Predicate.isAlwaysTrue())
312 continue;
313
314 if (Predicate.isImmediatePattern())
315 continue;
316
Daniel Sandersf84bc372018-05-05 20:53:24 +0000317 if (Predicate.isNonExtLoad() || Predicate.isAnyExtLoad() ||
318 Predicate.isSignExtLoad() || Predicate.isZeroExtLoad())
Daniel Sandersa71f4542017-10-16 00:56:30 +0000319 continue;
Daniel Sandersd66e0902017-10-23 18:19:24 +0000320
Matt Arsenault02772492019-07-15 21:15:20 +0000321 if (Predicate.isNonTruncStore() || Predicate.isTruncStore())
Daniel Sandersd66e0902017-10-23 18:19:24 +0000322 continue;
323
Daniel Sandersf84bc372018-05-05 20:53:24 +0000324 if (Predicate.isLoad() && Predicate.getMemoryVT())
325 continue;
326
Daniel Sanders76664652017-11-28 22:07:05 +0000327 if (Predicate.isLoad() || Predicate.isStore()) {
328 if (Predicate.isUnindexed())
329 continue;
330 }
331
Matt Arsenaultd00d8572019-07-15 20:59:42 +0000332 if (Predicate.isLoad() || Predicate.isStore() || Predicate.isAtomic()) {
333 const ListInit *AddrSpaces = Predicate.getAddressSpaces();
334 if (AddrSpaces && !AddrSpaces->empty())
335 continue;
Matt Arsenault52c26242019-07-31 00:14:43 +0000336
337 if (Predicate.getMinAlignment() > 0)
338 continue;
Matt Arsenaultd00d8572019-07-15 20:59:42 +0000339 }
340
Daniel Sanders76664652017-11-28 22:07:05 +0000341 if (Predicate.isAtomic() && Predicate.getMemoryVT())
342 continue;
343
344 if (Predicate.isAtomic() &&
345 (Predicate.isAtomicOrderingMonotonic() ||
346 Predicate.isAtomicOrderingAcquire() ||
347 Predicate.isAtomicOrderingRelease() ||
348 Predicate.isAtomicOrderingAcquireRelease() ||
Daniel Sanders0c43b3a2017-11-30 21:05:59 +0000349 Predicate.isAtomicOrderingSequentiallyConsistent() ||
350 Predicate.isAtomicOrderingAcquireOrStronger() ||
351 Predicate.isAtomicOrderingWeakerThanAcquire() ||
352 Predicate.isAtomicOrderingReleaseOrStronger() ||
353 Predicate.isAtomicOrderingWeakerThanRelease()))
Daniel Sandersd66e0902017-10-23 18:19:24 +0000354 continue;
355
Daniel Sanders8ead1292018-06-15 23:13:43 +0000356 if (Predicate.hasGISelPredicateCode())
357 continue;
358
Daniel Sanders2c269f62017-08-24 09:11:20 +0000359 HasUnsupportedPredicate = true;
Daniel Sandersd0656a32017-04-13 09:45:37 +0000360 Explanation = Separator + "Has a predicate (" + explainPredicates(N) + ")";
361 Separator = ", ";
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000362 Explanation += (Separator + "first-failing:" +
363 Predicate.getOrigPatFragRecord()->getRecord()->getName())
364 .str();
Daniel Sanders2c269f62017-08-24 09:11:20 +0000365 break;
Daniel Sandersd0656a32017-04-13 09:45:37 +0000366 }
367
Volkan Kelesf7f25682018-01-16 18:44:05 +0000368 if (!HasUnsupportedPredicate)
Daniel Sandersd0656a32017-04-13 09:45:37 +0000369 return Error::success();
370
371 return failedImport(Explanation);
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000372}
373
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +0000374static Record *getInitValueAsRegClass(Init *V) {
375 if (DefInit *VDefInit = dyn_cast<DefInit>(V)) {
376 if (VDefInit->getDef()->isSubClassOf("RegisterOperand"))
377 return VDefInit->getDef()->getValueAsDef("RegClass");
378 if (VDefInit->getDef()->isSubClassOf("RegisterClass"))
379 return VDefInit->getDef();
380 }
381 return nullptr;
382}
383
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000384std::string
385getNameForFeatureBitset(const std::vector<Record *> &FeatureBitset) {
386 std::string Name = "GIFBS";
387 for (const auto &Feature : FeatureBitset)
388 Name += ("_" + Feature->getName()).str();
389 return Name;
390}
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000391
392//===- MatchTable Helpers -------------------------------------------------===//
393
394class MatchTable;
395
396/// A record to be stored in a MatchTable.
397///
398/// This class represents any and all output that may be required to emit the
399/// MatchTable. Instances are most often configured to represent an opcode or
400/// value that will be emitted to the table with some formatting but it can also
401/// represent commas, comments, and other formatting instructions.
402struct MatchTableRecord {
403 enum RecordFlagsBits {
404 MTRF_None = 0x0,
405 /// Causes EmitStr to be formatted as comment when emitted.
406 MTRF_Comment = 0x1,
407 /// Causes the record value to be followed by a comma when emitted.
408 MTRF_CommaFollows = 0x2,
409 /// Causes the record value to be followed by a line break when emitted.
410 MTRF_LineBreakFollows = 0x4,
411 /// Indicates that the record defines a label and causes an additional
412 /// comment to be emitted containing the index of the label.
413 MTRF_Label = 0x8,
414 /// Causes the record to be emitted as the index of the label specified by
415 /// LabelID along with a comment indicating where that label is.
416 MTRF_JumpTarget = 0x10,
417 /// Causes the formatter to add a level of indentation before emitting the
418 /// record.
419 MTRF_Indent = 0x20,
420 /// Causes the formatter to remove a level of indentation after emitting the
421 /// record.
422 MTRF_Outdent = 0x40,
423 };
424
425 /// When MTRF_Label or MTRF_JumpTarget is used, indicates a label id to
426 /// reference or define.
427 unsigned LabelID;
428 /// The string to emit. Depending on the MTRF_* flags it may be a comment, a
429 /// value, a label name.
430 std::string EmitStr;
431
432private:
433 /// The number of MatchTable elements described by this record. Comments are 0
434 /// while values are typically 1. Values >1 may occur when we need to emit
435 /// values that exceed the size of a MatchTable element.
436 unsigned NumElements;
437
438public:
439 /// A bitfield of RecordFlagsBits flags.
440 unsigned Flags;
441
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000442 /// The actual run-time value, if known
443 int64_t RawValue;
444
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000445 MatchTableRecord(Optional<unsigned> LabelID_, StringRef EmitStr,
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000446 unsigned NumElements, unsigned Flags,
447 int64_t RawValue = std::numeric_limits<int64_t>::min())
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000448 : LabelID(LabelID_.hasValue() ? LabelID_.getValue() : ~0u),
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000449 EmitStr(EmitStr), NumElements(NumElements), Flags(Flags),
450 RawValue(RawValue) {
451
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000452 assert((!LabelID_.hasValue() || LabelID != ~0u) &&
453 "This value is reserved for non-labels");
454 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000455 MatchTableRecord(const MatchTableRecord &Other) = default;
456 MatchTableRecord(MatchTableRecord &&Other) = default;
457
458 /// Useful if a Match Table Record gets optimized out
459 void turnIntoComment() {
460 Flags |= MTRF_Comment;
461 Flags &= ~MTRF_CommaFollows;
462 NumElements = 0;
463 }
464
465 /// For Jump Table generation purposes
466 bool operator<(const MatchTableRecord &Other) const {
467 return RawValue < Other.RawValue;
468 }
469 int64_t getRawValue() const { return RawValue; }
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000470
471 void emit(raw_ostream &OS, bool LineBreakNextAfterThis,
472 const MatchTable &Table) const;
473 unsigned size() const { return NumElements; }
474};
475
Roman Tereshin2d6d3762018-05-02 20:08:14 +0000476class Matcher;
477
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000478/// Holds the contents of a generated MatchTable to enable formatting and the
479/// necessary index tracking needed to support GIM_Try.
480class MatchTable {
481 /// An unique identifier for the table. The generated table will be named
482 /// MatchTable${ID}.
483 unsigned ID;
484 /// The records that make up the table. Also includes comments describing the
485 /// values being emitted and line breaks to format it.
486 std::vector<MatchTableRecord> Contents;
487 /// The currently defined labels.
488 DenseMap<unsigned, unsigned> LabelMap;
489 /// Tracks the sum of MatchTableRecord::NumElements as the table is built.
Roman Tereshin2d6d3762018-05-02 20:08:14 +0000490 unsigned CurrentSize = 0;
Daniel Sanders8e82af22017-07-27 11:03:45 +0000491 /// A unique identifier for a MatchTable label.
Roman Tereshin2d6d3762018-05-02 20:08:14 +0000492 unsigned CurrentLabelID = 0;
Roman Tereshinbeb39312018-05-02 20:15:11 +0000493 /// Determines if the table should be instrumented for rule coverage tracking.
494 bool IsWithCoverage;
Daniel Sanders8e82af22017-07-27 11:03:45 +0000495
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000496public:
497 static MatchTableRecord LineBreak;
498 static MatchTableRecord Comment(StringRef Comment) {
499 return MatchTableRecord(None, Comment, 0, MatchTableRecord::MTRF_Comment);
500 }
501 static MatchTableRecord Opcode(StringRef Opcode, int IndentAdjust = 0) {
502 unsigned ExtraFlags = 0;
503 if (IndentAdjust > 0)
504 ExtraFlags |= MatchTableRecord::MTRF_Indent;
505 if (IndentAdjust < 0)
506 ExtraFlags |= MatchTableRecord::MTRF_Outdent;
507
508 return MatchTableRecord(None, Opcode, 1,
509 MatchTableRecord::MTRF_CommaFollows | ExtraFlags);
510 }
511 static MatchTableRecord NamedValue(StringRef NamedValue) {
512 return MatchTableRecord(None, NamedValue, 1,
513 MatchTableRecord::MTRF_CommaFollows);
514 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000515 static MatchTableRecord NamedValue(StringRef NamedValue, int64_t RawValue) {
516 return MatchTableRecord(None, NamedValue, 1,
517 MatchTableRecord::MTRF_CommaFollows, RawValue);
518 }
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000519 static MatchTableRecord NamedValue(StringRef Namespace,
520 StringRef NamedValue) {
521 return MatchTableRecord(None, (Namespace + "::" + NamedValue).str(), 1,
522 MatchTableRecord::MTRF_CommaFollows);
523 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000524 static MatchTableRecord NamedValue(StringRef Namespace, StringRef NamedValue,
525 int64_t RawValue) {
526 return MatchTableRecord(None, (Namespace + "::" + NamedValue).str(), 1,
527 MatchTableRecord::MTRF_CommaFollows, RawValue);
528 }
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000529 static MatchTableRecord IntValue(int64_t IntValue) {
530 return MatchTableRecord(None, llvm::to_string(IntValue), 1,
531 MatchTableRecord::MTRF_CommaFollows);
532 }
533 static MatchTableRecord Label(unsigned LabelID) {
534 return MatchTableRecord(LabelID, "Label " + llvm::to_string(LabelID), 0,
535 MatchTableRecord::MTRF_Label |
536 MatchTableRecord::MTRF_Comment |
537 MatchTableRecord::MTRF_LineBreakFollows);
538 }
539 static MatchTableRecord JumpTarget(unsigned LabelID) {
Daniel Sanders8e82af22017-07-27 11:03:45 +0000540 return MatchTableRecord(LabelID, "Label " + llvm::to_string(LabelID), 1,
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000541 MatchTableRecord::MTRF_JumpTarget |
542 MatchTableRecord::MTRF_Comment |
543 MatchTableRecord::MTRF_CommaFollows);
544 }
545
Roman Tereshinbeb39312018-05-02 20:15:11 +0000546 static MatchTable buildTable(ArrayRef<Matcher *> Rules, bool WithCoverage);
Roman Tereshin2d6d3762018-05-02 20:08:14 +0000547
Roman Tereshinbeb39312018-05-02 20:15:11 +0000548 MatchTable(bool WithCoverage, unsigned ID = 0)
549 : ID(ID), IsWithCoverage(WithCoverage) {}
550
551 bool isWithCoverage() const { return IsWithCoverage; }
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000552
553 void push_back(const MatchTableRecord &Value) {
554 if (Value.Flags & MatchTableRecord::MTRF_Label)
555 defineLabel(Value.LabelID);
556 Contents.push_back(Value);
557 CurrentSize += Value.size();
558 }
559
Roman Tereshin2d6d3762018-05-02 20:08:14 +0000560 unsigned allocateLabelID() { return CurrentLabelID++; }
Daniel Sanders8e82af22017-07-27 11:03:45 +0000561
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000562 void defineLabel(unsigned LabelID) {
Daniel Sanders8e82af22017-07-27 11:03:45 +0000563 LabelMap.insert(std::make_pair(LabelID, CurrentSize));
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000564 }
565
566 unsigned getLabelIndex(unsigned LabelID) const {
567 const auto I = LabelMap.find(LabelID);
568 assert(I != LabelMap.end() && "Use of undeclared label");
569 return I->second;
570 }
571
Daniel Sanders8e82af22017-07-27 11:03:45 +0000572 void emitUse(raw_ostream &OS) const { OS << "MatchTable" << ID; }
573
574 void emitDeclaration(raw_ostream &OS) const {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000575 unsigned Indentation = 4;
Daniel Sanderscbbbfe42017-07-27 12:47:31 +0000576 OS << " constexpr static int64_t MatchTable" << ID << "[] = {";
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000577 LineBreak.emit(OS, true, *this);
578 OS << std::string(Indentation, ' ');
579
580 for (auto I = Contents.begin(), E = Contents.end(); I != E;
581 ++I) {
582 bool LineBreakIsNext = false;
583 const auto &NextI = std::next(I);
584
585 if (NextI != E) {
586 if (NextI->EmitStr == "" &&
587 NextI->Flags == MatchTableRecord::MTRF_LineBreakFollows)
588 LineBreakIsNext = true;
589 }
590
591 if (I->Flags & MatchTableRecord::MTRF_Indent)
592 Indentation += 2;
593
594 I->emit(OS, LineBreakIsNext, *this);
595 if (I->Flags & MatchTableRecord::MTRF_LineBreakFollows)
596 OS << std::string(Indentation, ' ');
597
598 if (I->Flags & MatchTableRecord::MTRF_Outdent)
599 Indentation -= 2;
600 }
601 OS << "};\n";
602 }
603};
604
605MatchTableRecord MatchTable::LineBreak = {
606 None, "" /* Emit String */, 0 /* Elements */,
607 MatchTableRecord::MTRF_LineBreakFollows};
608
609void MatchTableRecord::emit(raw_ostream &OS, bool LineBreakIsNextAfterThis,
610 const MatchTable &Table) const {
611 bool UseLineComment =
612 LineBreakIsNextAfterThis | (Flags & MTRF_LineBreakFollows);
613 if (Flags & (MTRF_JumpTarget | MTRF_CommaFollows))
614 UseLineComment = false;
615
616 if (Flags & MTRF_Comment)
617 OS << (UseLineComment ? "// " : "/*");
618
619 OS << EmitStr;
620 if (Flags & MTRF_Label)
621 OS << ": @" << Table.getLabelIndex(LabelID);
622
623 if (Flags & MTRF_Comment && !UseLineComment)
624 OS << "*/";
625
626 if (Flags & MTRF_JumpTarget) {
627 if (Flags & MTRF_Comment)
628 OS << " ";
629 OS << Table.getLabelIndex(LabelID);
630 }
631
632 if (Flags & MTRF_CommaFollows) {
633 OS << ",";
634 if (!LineBreakIsNextAfterThis && !(Flags & MTRF_LineBreakFollows))
635 OS << " ";
636 }
637
638 if (Flags & MTRF_LineBreakFollows)
639 OS << "\n";
640}
641
642MatchTable &operator<<(MatchTable &Table, const MatchTableRecord &Value) {
643 Table.push_back(Value);
644 return Table;
645}
646
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000647//===- Matchers -----------------------------------------------------------===//
648
Daniel Sandersbee57392017-04-04 13:25:23 +0000649class OperandMatcher;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000650class MatchAction;
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000651class PredicateMatcher;
652class RuleMatcher;
653
654class Matcher {
655public:
656 virtual ~Matcher() = default;
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000657 virtual void optimize() {}
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000658 virtual void emit(MatchTable &Table) = 0;
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000659
660 virtual bool hasFirstCondition() const = 0;
661 virtual const PredicateMatcher &getFirstCondition() const = 0;
662 virtual std::unique_ptr<PredicateMatcher> popFirstCondition() = 0;
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000663};
664
Roman Tereshinbeb39312018-05-02 20:15:11 +0000665MatchTable MatchTable::buildTable(ArrayRef<Matcher *> Rules,
666 bool WithCoverage) {
667 MatchTable Table(WithCoverage);
Roman Tereshin2d6d3762018-05-02 20:08:14 +0000668 for (Matcher *Rule : Rules)
669 Rule->emit(Table);
670
671 return Table << MatchTable::Opcode("GIM_Reject") << MatchTable::LineBreak;
672}
673
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000674class GroupMatcher final : public Matcher {
675 /// Conditions that form a common prefix of all the matchers contained.
676 SmallVector<std::unique_ptr<PredicateMatcher>, 1> Conditions;
677
678 /// All the nested matchers, sharing a common prefix.
679 std::vector<Matcher *> Matchers;
680
681 /// An owning collection for any auxiliary matchers created while optimizing
682 /// nested matchers contained.
683 std::vector<std::unique_ptr<Matcher>> MatcherStorage;
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000684
685public:
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000686 /// Add a matcher to the collection of nested matchers if it meets the
687 /// requirements, and return true. If it doesn't, do nothing and return false.
688 ///
689 /// Expected to preserve its argument, so it could be moved out later on.
690 bool addMatcher(Matcher &Candidate);
691
692 /// Mark the matcher as fully-built and ensure any invariants expected by both
693 /// optimize() and emit(...) methods. Generally, both sequences of calls
694 /// are expected to lead to a sensible result:
695 ///
696 /// addMatcher(...)*; finalize(); optimize(); emit(...); and
697 /// addMatcher(...)*; finalize(); emit(...);
698 ///
699 /// or generally
700 ///
701 /// addMatcher(...)*; finalize(); { optimize()*; emit(...); }*
702 ///
703 /// Multiple calls to optimize() are expected to be handled gracefully, though
704 /// optimize() is not expected to be idempotent. Multiple calls to finalize()
705 /// aren't generally supported. emit(...) is expected to be non-mutating and
706 /// producing the exact same results upon repeated calls.
707 ///
708 /// addMatcher() calls after the finalize() call are not supported.
709 ///
710 /// finalize() and optimize() are both allowed to mutate the contained
711 /// matchers, so moving them out after finalize() is not supported.
712 void finalize();
Roman Tereshinfedae332018-05-23 02:04:19 +0000713 void optimize() override;
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000714 void emit(MatchTable &Table) override;
Quentin Colombet34688b92017-12-18 21:25:53 +0000715
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000716 /// Could be used to move out the matchers added previously, unless finalize()
717 /// has been already called. If any of the matchers are moved out, the group
718 /// becomes safe to destroy, but not safe to re-use for anything else.
719 iterator_range<std::vector<Matcher *>::iterator> matchers() {
720 return make_range(Matchers.begin(), Matchers.end());
Quentin Colombet34688b92017-12-18 21:25:53 +0000721 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000722 size_t size() const { return Matchers.size(); }
723 bool empty() const { return Matchers.empty(); }
724
725 std::unique_ptr<PredicateMatcher> popFirstCondition() override {
726 assert(!Conditions.empty() &&
727 "Trying to pop a condition from a condition-less group");
728 std::unique_ptr<PredicateMatcher> P = std::move(Conditions.front());
729 Conditions.erase(Conditions.begin());
730 return P;
731 }
732 const PredicateMatcher &getFirstCondition() const override {
733 assert(!Conditions.empty() &&
734 "Trying to get a condition from a condition-less group");
735 return *Conditions.front();
736 }
737 bool hasFirstCondition() const override { return !Conditions.empty(); }
738
739private:
740 /// See if a candidate matcher could be added to this group solely by
741 /// analyzing its first condition.
742 bool candidateConditionMatches(const PredicateMatcher &Predicate) const;
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000743};
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000744
Roman Tereshin0ee082f2018-05-22 19:37:59 +0000745class SwitchMatcher : public Matcher {
746 /// All the nested matchers, representing distinct switch-cases. The first
747 /// conditions (as Matcher::getFirstCondition() reports) of all the nested
748 /// matchers must share the same type and path to a value they check, in other
749 /// words, be isIdenticalDownToValue, but have different values they check
750 /// against.
751 std::vector<Matcher *> Matchers;
752
753 /// The representative condition, with a type and a path (InsnVarID and OpIdx
754 /// in most cases) shared by all the matchers contained.
755 std::unique_ptr<PredicateMatcher> Condition = nullptr;
756
757 /// Temporary set used to check that the case values don't repeat within the
758 /// same switch.
759 std::set<MatchTableRecord> Values;
760
761 /// An owning collection for any auxiliary matchers created while optimizing
762 /// nested matchers contained.
763 std::vector<std::unique_ptr<Matcher>> MatcherStorage;
764
765public:
766 bool addMatcher(Matcher &Candidate);
767
768 void finalize();
769 void emit(MatchTable &Table) override;
770
771 iterator_range<std::vector<Matcher *>::iterator> matchers() {
772 return make_range(Matchers.begin(), Matchers.end());
773 }
774 size_t size() const { return Matchers.size(); }
775 bool empty() const { return Matchers.empty(); }
776
777 std::unique_ptr<PredicateMatcher> popFirstCondition() override {
778 // SwitchMatcher doesn't have a common first condition for its cases, as all
779 // the cases only share a kind of a value (a type and a path to it) they
780 // match, but deliberately differ in the actual value they match.
781 llvm_unreachable("Trying to pop a condition from a condition-less group");
782 }
783 const PredicateMatcher &getFirstCondition() const override {
784 llvm_unreachable("Trying to pop a condition from a condition-less group");
785 }
786 bool hasFirstCondition() const override { return false; }
787
788private:
789 /// See if the predicate type has a Switch-implementation for it.
790 static bool isSupportedPredicateType(const PredicateMatcher &Predicate);
791
792 bool candidateConditionMatches(const PredicateMatcher &Predicate) const;
793
794 /// emit()-helper
795 static void emitPredicateSpecificOpcodes(const PredicateMatcher &P,
796 MatchTable &Table);
797};
798
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000799/// Generates code to check that a match rule matches.
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000800class RuleMatcher : public Matcher {
Daniel Sanders7438b262017-10-31 23:03:18 +0000801public:
Daniel Sanders08464522018-01-29 21:09:12 +0000802 using ActionList = std::list<std::unique_ptr<MatchAction>>;
803 using action_iterator = ActionList::iterator;
Daniel Sanders7438b262017-10-31 23:03:18 +0000804
805protected:
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000806 /// A list of matchers that all need to succeed for the current rule to match.
807 /// FIXME: This currently supports a single match position but could be
808 /// extended to support multiple positions to support div/rem fusion or
809 /// load-multiple instructions.
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000810 using MatchersTy = std::vector<std::unique_ptr<InstructionMatcher>> ;
811 MatchersTy Matchers;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000812
813 /// A list of actions that need to be taken when all predicates in this rule
814 /// have succeeded.
Daniel Sanders08464522018-01-29 21:09:12 +0000815 ActionList Actions;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000816
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000817 using DefinedInsnVariablesMap = std::map<InstructionMatcher *, unsigned>;
Daniel Sandersa7b75262017-10-31 18:50:24 +0000818
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000819 /// A map of instruction matchers to the local variables
Daniel Sanders078572b2017-08-02 11:03:36 +0000820 DefinedInsnVariablesMap InsnVariableIDs;
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000821
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000822 using MutatableInsnSet = SmallPtrSet<InstructionMatcher *, 4>;
Daniel Sandersa7b75262017-10-31 18:50:24 +0000823
824 // The set of instruction matchers that have not yet been claimed for mutation
825 // by a BuildMI.
826 MutatableInsnSet MutatableInsns;
827
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000828 /// A map of named operands defined by the matchers that may be referenced by
829 /// the renderers.
830 StringMap<OperandMatcher *> DefinedOperands;
831
Matt Arsenault3e45c702019-09-06 20:32:37 +0000832 /// A map of anonymous physical register operands defined by the matchers that
833 /// may be referenced by the renderers.
834 DenseMap<Record *, OperandMatcher *> PhysRegOperands;
835
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000836 /// ID for the next instruction variable defined with implicitlyDefineInsnVar()
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000837 unsigned NextInsnVarID;
838
Daniel Sanders198447a2017-11-01 00:29:47 +0000839 /// ID for the next output instruction allocated with allocateOutputInsnID()
840 unsigned NextOutputInsnID;
841
Daniel Sanders9cbe7c72017-11-01 19:57:57 +0000842 /// ID for the next temporary register ID allocated with allocateTempRegID()
843 unsigned NextTempRegID;
844
Daniel Sanderse7b0d662017-04-21 15:59:56 +0000845 std::vector<Record *> RequiredFeatures;
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000846 std::vector<std::unique_ptr<PredicateMatcher>> EpilogueMatchers;
Daniel Sanderse7b0d662017-04-21 15:59:56 +0000847
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000848 ArrayRef<SMLoc> SrcLoc;
849
Daniel Sandersdf39cba2017-10-15 18:22:54 +0000850 typedef std::tuple<Record *, unsigned, unsigned>
851 DefinedComplexPatternSubOperand;
852 typedef StringMap<DefinedComplexPatternSubOperand>
853 DefinedComplexPatternSubOperandMap;
854 /// A map of Symbolic Names to ComplexPattern sub-operands.
855 DefinedComplexPatternSubOperandMap ComplexSubOperands;
856
Daniel Sandersf76f3152017-11-16 00:46:35 +0000857 uint64_t RuleID;
858 static uint64_t NextRuleID;
859
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000860public:
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000861 RuleMatcher(ArrayRef<SMLoc> SrcLoc)
Daniel Sandersa7b75262017-10-31 18:50:24 +0000862 : Matchers(), Actions(), InsnVariableIDs(), MutatableInsns(),
Daniel Sanders198447a2017-11-01 00:29:47 +0000863 DefinedOperands(), NextInsnVarID(0), NextOutputInsnID(0),
Daniel Sandersf76f3152017-11-16 00:46:35 +0000864 NextTempRegID(0), SrcLoc(SrcLoc), ComplexSubOperands(),
865 RuleID(NextRuleID++) {}
Zachary Turnerb7dbd872017-03-20 19:56:52 +0000866 RuleMatcher(RuleMatcher &&Other) = default;
867 RuleMatcher &operator=(RuleMatcher &&Other) = default;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000868
Daniel Sandersf76f3152017-11-16 00:46:35 +0000869 uint64_t getRuleID() const { return RuleID; }
870
Daniel Sanders05540042017-08-08 10:44:31 +0000871 InstructionMatcher &addInstructionMatcher(StringRef SymbolicName);
Daniel Sanderse7b0d662017-04-21 15:59:56 +0000872 void addRequiredFeature(Record *Feature);
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000873 const std::vector<Record *> &getRequiredFeatures() const;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000874
875 template <class Kind, class... Args> Kind &addAction(Args &&... args);
Daniel Sanders7438b262017-10-31 23:03:18 +0000876 template <class Kind, class... Args>
877 action_iterator insertAction(action_iterator InsertPt, Args &&... args);
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000878
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000879 /// Define an instruction without emitting any code to do so.
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000880 unsigned implicitlyDefineInsnVar(InstructionMatcher &Matcher);
881
882 unsigned getInsnVarID(InstructionMatcher &InsnMatcher) const;
Daniel Sanders078572b2017-08-02 11:03:36 +0000883 DefinedInsnVariablesMap::const_iterator defined_insn_vars_begin() const {
884 return InsnVariableIDs.begin();
885 }
886 DefinedInsnVariablesMap::const_iterator defined_insn_vars_end() const {
887 return InsnVariableIDs.end();
888 }
889 iterator_range<typename DefinedInsnVariablesMap::const_iterator>
890 defined_insn_vars() const {
891 return make_range(defined_insn_vars_begin(), defined_insn_vars_end());
892 }
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000893
Daniel Sandersa7b75262017-10-31 18:50:24 +0000894 MutatableInsnSet::const_iterator mutatable_insns_begin() const {
895 return MutatableInsns.begin();
896 }
897 MutatableInsnSet::const_iterator mutatable_insns_end() const {
898 return MutatableInsns.end();
899 }
900 iterator_range<typename MutatableInsnSet::const_iterator>
901 mutatable_insns() const {
902 return make_range(mutatable_insns_begin(), mutatable_insns_end());
903 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000904 void reserveInsnMatcherForMutation(InstructionMatcher *InsnMatcher) {
Daniel Sandersa7b75262017-10-31 18:50:24 +0000905 bool R = MutatableInsns.erase(InsnMatcher);
906 assert(R && "Reserving a mutatable insn that isn't available");
907 (void)R;
908 }
909
Daniel Sanders7438b262017-10-31 23:03:18 +0000910 action_iterator actions_begin() { return Actions.begin(); }
911 action_iterator actions_end() { return Actions.end(); }
912 iterator_range<action_iterator> actions() {
913 return make_range(actions_begin(), actions_end());
914 }
915
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000916 void defineOperand(StringRef SymbolicName, OperandMatcher &OM);
917
Matt Arsenault3e45c702019-09-06 20:32:37 +0000918 void definePhysRegOperand(Record *Reg, OperandMatcher &OM);
919
Jessica Paquette1ed1dd62019-02-09 00:29:13 +0000920 Error defineComplexSubOperand(StringRef SymbolicName, Record *ComplexPattern,
921 unsigned RendererID, unsigned SubOperandID) {
922 if (ComplexSubOperands.count(SymbolicName))
923 return failedImport(
924 "Complex suboperand referenced more than once (Operand: " +
925 SymbolicName + ")");
926
Daniel Sandersdf39cba2017-10-15 18:22:54 +0000927 ComplexSubOperands[SymbolicName] =
928 std::make_tuple(ComplexPattern, RendererID, SubOperandID);
Jessica Paquette1ed1dd62019-02-09 00:29:13 +0000929
930 return Error::success();
Daniel Sandersdf39cba2017-10-15 18:22:54 +0000931 }
Jessica Paquette1ed1dd62019-02-09 00:29:13 +0000932
Daniel Sandersdf39cba2017-10-15 18:22:54 +0000933 Optional<DefinedComplexPatternSubOperand>
934 getComplexSubOperand(StringRef SymbolicName) const {
935 const auto &I = ComplexSubOperands.find(SymbolicName);
936 if (I == ComplexSubOperands.end())
937 return None;
938 return I->second;
939 }
940
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000941 InstructionMatcher &getInstructionMatcher(StringRef SymbolicName) const;
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000942 const OperandMatcher &getOperandMatcher(StringRef Name) const;
Matt Arsenault3e45c702019-09-06 20:32:37 +0000943 const OperandMatcher &getPhysRegOperandMatcher(Record *) const;
Daniel Sanders05540042017-08-08 10:44:31 +0000944
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000945 void optimize() override;
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000946 void emit(MatchTable &Table) override;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000947
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000948 /// Compare the priority of this object and B.
949 ///
950 /// Returns true if this object is more important than B.
951 bool isHigherPriorityThan(const RuleMatcher &B) const;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000952
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000953 /// Report the maximum number of temporary operands needed by the rule
954 /// matcher.
955 unsigned countRendererFns() const;
Daniel Sanders2deea182017-04-22 15:11:04 +0000956
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000957 std::unique_ptr<PredicateMatcher> popFirstCondition() override;
958 const PredicateMatcher &getFirstCondition() const override;
Roman Tereshin9a9fa492018-05-23 21:30:16 +0000959 LLTCodeGen getFirstConditionAsRootType();
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000960 bool hasFirstCondition() const override;
961 unsigned getNumOperands() const;
Roman Tereshin19da6672018-05-22 04:31:50 +0000962 StringRef getOpcode() const;
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000963
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000964 // FIXME: Remove this as soon as possible
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000965 InstructionMatcher &insnmatchers_front() const { return *Matchers.front(); }
Daniel Sanders198447a2017-11-01 00:29:47 +0000966
967 unsigned allocateOutputInsnID() { return NextOutputInsnID++; }
Daniel Sanders9cbe7c72017-11-01 19:57:57 +0000968 unsigned allocateTempRegID() { return NextTempRegID++; }
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000969
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000970 iterator_range<MatchersTy::iterator> insnmatchers() {
971 return make_range(Matchers.begin(), Matchers.end());
972 }
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000973 bool insnmatchers_empty() const { return Matchers.empty(); }
974 void insnmatchers_pop_front() { Matchers.erase(Matchers.begin()); }
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000975};
976
Daniel Sandersf76f3152017-11-16 00:46:35 +0000977uint64_t RuleMatcher::NextRuleID = 0;
978
Daniel Sanders7438b262017-10-31 23:03:18 +0000979using action_iterator = RuleMatcher::action_iterator;
980
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000981template <class PredicateTy> class PredicateListMatcher {
982private:
Daniel Sanders2c269f62017-08-24 09:11:20 +0000983 /// Template instantiations should specialize this to return a string to use
984 /// for the comment emitted when there are no predicates.
985 std::string getNoPredicateComment() const;
986
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000987protected:
988 using PredicatesTy = std::deque<std::unique_ptr<PredicateTy>>;
989 PredicatesTy Predicates;
Roman Tereshinf0dc9fa2018-05-21 22:04:39 +0000990
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000991 /// Track if the list of predicates was manipulated by one of the optimization
992 /// methods.
993 bool Optimized = false;
994
995public:
996 /// Construct a new predicate and add it to the matcher.
997 template <class Kind, class... Args>
998 Optional<Kind *> addPredicate(Args &&... args);
999
1000 typename PredicatesTy::iterator predicates_begin() {
Daniel Sanders32291982017-06-28 13:50:04 +00001001 return Predicates.begin();
1002 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001003 typename PredicatesTy::iterator predicates_end() {
Daniel Sanders32291982017-06-28 13:50:04 +00001004 return Predicates.end();
1005 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001006 iterator_range<typename PredicatesTy::iterator> predicates() {
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001007 return make_range(predicates_begin(), predicates_end());
1008 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001009 typename PredicatesTy::size_type predicates_size() const {
Daniel Sanders32291982017-06-28 13:50:04 +00001010 return Predicates.size();
1011 }
Quentin Colombetec76d9c2017-12-18 19:47:41 +00001012 bool predicates_empty() const { return Predicates.empty(); }
1013
1014 std::unique_ptr<PredicateTy> predicates_pop_front() {
1015 std::unique_ptr<PredicateTy> Front = std::move(Predicates.front());
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001016 Predicates.pop_front();
1017 Optimized = true;
Quentin Colombetec76d9c2017-12-18 19:47:41 +00001018 return Front;
1019 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001020
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001021 void prependPredicate(std::unique_ptr<PredicateTy> &&Predicate) {
1022 Predicates.push_front(std::move(Predicate));
1023 }
1024
1025 void eraseNullPredicates() {
1026 const auto NewEnd =
1027 std::stable_partition(Predicates.begin(), Predicates.end(),
1028 std::logical_not<std::unique_ptr<PredicateTy>>());
1029 if (NewEnd != Predicates.begin()) {
1030 Predicates.erase(Predicates.begin(), NewEnd);
1031 Optimized = true;
1032 }
1033 }
1034
Daniel Sanders9d662d22017-07-06 10:06:12 +00001035 /// Emit MatchTable opcodes that tests whether all the predicates are met.
Ahmed Bougachab67a3ce2017-01-26 22:07:37 +00001036 template <class... Args>
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001037 void emitPredicateListOpcodes(MatchTable &Table, Args &&... args) {
1038 if (Predicates.empty() && !Optimized) {
Daniel Sanders2c269f62017-08-24 09:11:20 +00001039 Table << MatchTable::Comment(getNoPredicateComment())
1040 << MatchTable::LineBreak;
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001041 return;
1042 }
1043
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001044 for (const auto &Predicate : predicates())
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001045 Predicate->emitPredicateOpcodes(Table, std::forward<Args>(args)...);
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001046 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001047};
1048
Quentin Colombet063d7982017-12-14 23:44:07 +00001049class PredicateMatcher {
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001050public:
Daniel Sanders759ff412017-02-24 13:58:11 +00001051 /// This enum is used for RTTI and also defines the priority that is given to
1052 /// the predicate when generating the matcher code. Kinds with higher priority
1053 /// must be tested first.
1054 ///
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001055 /// The relative priority of OPM_LLT, OPM_RegBank, and OPM_MBB do not matter
1056 /// but OPM_Int must have priority over OPM_RegBank since constant integers
1057 /// are represented by a virtual register defined by a G_CONSTANT instruction.
Quentin Colombet063d7982017-12-14 23:44:07 +00001058 ///
1059 /// Note: The relative priority between IPM_ and OPM_ does not matter, they
1060 /// are currently not compared between each other.
Daniel Sanders759ff412017-02-24 13:58:11 +00001061 enum PredicateKind {
Quentin Colombet063d7982017-12-14 23:44:07 +00001062 IPM_Opcode,
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001063 IPM_NumOperands,
Quentin Colombet063d7982017-12-14 23:44:07 +00001064 IPM_ImmPredicate,
1065 IPM_AtomicOrderingMMO,
Daniel Sandersf84bc372018-05-05 20:53:24 +00001066 IPM_MemoryLLTSize,
1067 IPM_MemoryVsLLTSize,
Matt Arsenaultd00d8572019-07-15 20:59:42 +00001068 IPM_MemoryAddressSpace,
Matt Arsenault52c26242019-07-31 00:14:43 +00001069 IPM_MemoryAlignment,
Daniel Sanders8ead1292018-06-15 23:13:43 +00001070 IPM_GenericPredicate,
Daniel Sanders1e4569f2017-10-20 20:55:29 +00001071 OPM_SameOperand,
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001072 OPM_ComplexPattern,
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00001073 OPM_IntrinsicID,
Matt Arsenault8ec5c102019-08-29 01:13:41 +00001074 OPM_CmpPredicate,
Daniel Sanders05540042017-08-08 10:44:31 +00001075 OPM_Instruction,
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001076 OPM_Int,
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001077 OPM_LiteralInt,
Daniel Sanders759ff412017-02-24 13:58:11 +00001078 OPM_LLT,
Daniel Sandersa71f4542017-10-16 00:56:30 +00001079 OPM_PointerToAny,
Daniel Sanders759ff412017-02-24 13:58:11 +00001080 OPM_RegBank,
1081 OPM_MBB,
1082 };
1083
1084protected:
1085 PredicateKind Kind;
Quentin Colombetaad20be2017-12-15 23:07:42 +00001086 unsigned InsnVarID;
1087 unsigned OpIdx;
Daniel Sanders759ff412017-02-24 13:58:11 +00001088
1089public:
Quentin Colombetaad20be2017-12-15 23:07:42 +00001090 PredicateMatcher(PredicateKind Kind, unsigned InsnVarID, unsigned OpIdx = ~0)
1091 : Kind(Kind), InsnVarID(InsnVarID), OpIdx(OpIdx) {}
Quentin Colombet063d7982017-12-14 23:44:07 +00001092
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001093 unsigned getInsnVarID() const { return InsnVarID; }
Quentin Colombetaad20be2017-12-15 23:07:42 +00001094 unsigned getOpIdx() const { return OpIdx; }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001095
Quentin Colombet063d7982017-12-14 23:44:07 +00001096 virtual ~PredicateMatcher() = default;
1097 /// Emit MatchTable opcodes that check the predicate for the given operand.
Quentin Colombetaad20be2017-12-15 23:07:42 +00001098 virtual void emitPredicateOpcodes(MatchTable &Table,
1099 RuleMatcher &Rule) const = 0;
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001100
Daniel Sanders759ff412017-02-24 13:58:11 +00001101 PredicateKind getKind() const { return Kind; }
Quentin Colombet893e0f12017-12-15 23:24:39 +00001102
1103 virtual bool isIdentical(const PredicateMatcher &B) const {
Quentin Colombet893e0f12017-12-15 23:24:39 +00001104 return B.getKind() == getKind() && InsnVarID == B.InsnVarID &&
1105 OpIdx == B.OpIdx;
1106 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001107
1108 virtual bool isIdenticalDownToValue(const PredicateMatcher &B) const {
1109 return hasValue() && PredicateMatcher::isIdentical(B);
1110 }
1111
1112 virtual MatchTableRecord getValue() const {
1113 assert(hasValue() && "Can not get a value of a value-less predicate!");
1114 llvm_unreachable("Not implemented yet");
1115 }
1116 virtual bool hasValue() const { return false; }
1117
1118 /// Report the maximum number of temporary operands needed by the predicate
1119 /// matcher.
1120 virtual unsigned countRendererFns() const { return 0; }
Quentin Colombet063d7982017-12-14 23:44:07 +00001121};
1122
1123/// Generates code to check a predicate of an operand.
1124///
1125/// Typical predicates include:
1126/// * Operand is a particular register.
1127/// * Operand is assigned a particular register bank.
1128/// * Operand is an MBB.
1129class OperandPredicateMatcher : public PredicateMatcher {
1130public:
Quentin Colombetaad20be2017-12-15 23:07:42 +00001131 OperandPredicateMatcher(PredicateKind Kind, unsigned InsnVarID,
1132 unsigned OpIdx)
1133 : PredicateMatcher(Kind, InsnVarID, OpIdx) {}
Quentin Colombet063d7982017-12-14 23:44:07 +00001134 virtual ~OperandPredicateMatcher() {}
Daniel Sanders759ff412017-02-24 13:58:11 +00001135
Daniel Sanders759ff412017-02-24 13:58:11 +00001136 /// Compare the priority of this object and B.
1137 ///
1138 /// Returns true if this object is more important than B.
Daniel Sanders05540042017-08-08 10:44:31 +00001139 virtual bool isHigherPriorityThan(const OperandPredicateMatcher &B) const;
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001140};
1141
Daniel Sanders2c269f62017-08-24 09:11:20 +00001142template <>
1143std::string
1144PredicateListMatcher<OperandPredicateMatcher>::getNoPredicateComment() const {
1145 return "No operand predicates";
1146}
1147
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001148/// Generates code to check that a register operand is defined by the same exact
1149/// one as another.
1150class SameOperandMatcher : public OperandPredicateMatcher {
Daniel Sanders1e4569f2017-10-20 20:55:29 +00001151 std::string MatchingName;
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001152
1153public:
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001154 SameOperandMatcher(unsigned InsnVarID, unsigned OpIdx, StringRef MatchingName)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001155 : OperandPredicateMatcher(OPM_SameOperand, InsnVarID, OpIdx),
1156 MatchingName(MatchingName) {}
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001157
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001158 static bool classof(const PredicateMatcher *P) {
Daniel Sanders1e4569f2017-10-20 20:55:29 +00001159 return P->getKind() == OPM_SameOperand;
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001160 }
1161
Quentin Colombetaad20be2017-12-15 23:07:42 +00001162 void emitPredicateOpcodes(MatchTable &Table,
1163 RuleMatcher &Rule) const override;
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001164
1165 bool isIdentical(const PredicateMatcher &B) const override {
1166 return OperandPredicateMatcher::isIdentical(B) &&
1167 MatchingName == cast<SameOperandMatcher>(&B)->MatchingName;
1168 }
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001169};
1170
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001171/// Generates code to check that an operand is a particular LLT.
1172class LLTOperandMatcher : public OperandPredicateMatcher {
1173protected:
Daniel Sanders52b4ce72017-03-07 23:20:35 +00001174 LLTCodeGen Ty;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001175
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001176public:
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001177 static std::map<LLTCodeGen, unsigned> TypeIDValues;
1178
1179 static void initTypeIDValuesMap() {
1180 TypeIDValues.clear();
1181
1182 unsigned ID = 0;
1183 for (const LLTCodeGen LLTy : KnownTypes)
1184 TypeIDValues[LLTy] = ID++;
1185 }
1186
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001187 LLTOperandMatcher(unsigned InsnVarID, unsigned OpIdx, const LLTCodeGen &Ty)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001188 : OperandPredicateMatcher(OPM_LLT, InsnVarID, OpIdx), Ty(Ty) {
Daniel Sanders032e7f22017-08-17 13:18:35 +00001189 KnownTypes.insert(Ty);
1190 }
Daniel Sanders759ff412017-02-24 13:58:11 +00001191
Quentin Colombet063d7982017-12-14 23:44:07 +00001192 static bool classof(const PredicateMatcher *P) {
Daniel Sanders759ff412017-02-24 13:58:11 +00001193 return P->getKind() == OPM_LLT;
1194 }
Quentin Colombet893e0f12017-12-15 23:24:39 +00001195 bool isIdentical(const PredicateMatcher &B) const override {
1196 return OperandPredicateMatcher::isIdentical(B) &&
1197 Ty == cast<LLTOperandMatcher>(&B)->Ty;
1198 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001199 MatchTableRecord getValue() const override {
1200 const auto VI = TypeIDValues.find(Ty);
1201 if (VI == TypeIDValues.end())
1202 return MatchTable::NamedValue(getTy().getCxxEnumValue());
1203 return MatchTable::NamedValue(getTy().getCxxEnumValue(), VI->second);
1204 }
1205 bool hasValue() const override {
1206 if (TypeIDValues.size() != KnownTypes.size())
1207 initTypeIDValuesMap();
1208 return TypeIDValues.count(Ty);
1209 }
1210
1211 LLTCodeGen getTy() const { return Ty; }
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001212
Quentin Colombetaad20be2017-12-15 23:07:42 +00001213 void emitPredicateOpcodes(MatchTable &Table,
1214 RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001215 Table << MatchTable::Opcode("GIM_CheckType") << MatchTable::Comment("MI")
1216 << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Op")
1217 << MatchTable::IntValue(OpIdx) << MatchTable::Comment("Type")
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001218 << getValue() << MatchTable::LineBreak;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001219 }
1220};
1221
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001222std::map<LLTCodeGen, unsigned> LLTOperandMatcher::TypeIDValues;
1223
Daniel Sandersa71f4542017-10-16 00:56:30 +00001224/// Generates code to check that an operand is a pointer to any address space.
1225///
1226/// In SelectionDAG, the types did not describe pointers or address spaces. As a
1227/// result, iN is used to describe a pointer of N bits to any address space and
1228/// PatFrag predicates are typically used to constrain the address space. There's
1229/// no reliable means to derive the missing type information from the pattern so
1230/// imported rules must test the components of a pointer separately.
1231///
Daniel Sandersea8711b2017-10-16 03:36:29 +00001232/// If SizeInBits is zero, then the pointer size will be obtained from the
1233/// subtarget.
Daniel Sandersa71f4542017-10-16 00:56:30 +00001234class PointerToAnyOperandMatcher : public OperandPredicateMatcher {
1235protected:
1236 unsigned SizeInBits;
1237
1238public:
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001239 PointerToAnyOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
1240 unsigned SizeInBits)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001241 : OperandPredicateMatcher(OPM_PointerToAny, InsnVarID, OpIdx),
1242 SizeInBits(SizeInBits) {}
Daniel Sandersa71f4542017-10-16 00:56:30 +00001243
1244 static bool classof(const OperandPredicateMatcher *P) {
1245 return P->getKind() == OPM_PointerToAny;
1246 }
1247
Quentin Colombetaad20be2017-12-15 23:07:42 +00001248 void emitPredicateOpcodes(MatchTable &Table,
1249 RuleMatcher &Rule) const override {
1250 Table << MatchTable::Opcode("GIM_CheckPointerToAny")
1251 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1252 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1253 << MatchTable::Comment("SizeInBits")
Daniel Sandersa71f4542017-10-16 00:56:30 +00001254 << MatchTable::IntValue(SizeInBits) << MatchTable::LineBreak;
1255 }
1256};
1257
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001258/// Generates code to check that an operand is a particular target constant.
1259class ComplexPatternOperandMatcher : public OperandPredicateMatcher {
1260protected:
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001261 const OperandMatcher &Operand;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001262 const Record &TheDef;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001263
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001264 unsigned getAllocatedTemporariesBaseID() const;
1265
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001266public:
Quentin Colombet893e0f12017-12-15 23:24:39 +00001267 bool isIdentical(const PredicateMatcher &B) const override { return false; }
1268
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001269 ComplexPatternOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
1270 const OperandMatcher &Operand,
1271 const Record &TheDef)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001272 : OperandPredicateMatcher(OPM_ComplexPattern, InsnVarID, OpIdx),
1273 Operand(Operand), TheDef(TheDef) {}
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001274
Quentin Colombet063d7982017-12-14 23:44:07 +00001275 static bool classof(const PredicateMatcher *P) {
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001276 return P->getKind() == OPM_ComplexPattern;
1277 }
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001278
Quentin Colombetaad20be2017-12-15 23:07:42 +00001279 void emitPredicateOpcodes(MatchTable &Table,
1280 RuleMatcher &Rule) const override {
Daniel Sanders2deea182017-04-22 15:11:04 +00001281 unsigned ID = getAllocatedTemporariesBaseID();
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001282 Table << MatchTable::Opcode("GIM_CheckComplexPattern")
1283 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1284 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1285 << MatchTable::Comment("Renderer") << MatchTable::IntValue(ID)
1286 << MatchTable::NamedValue(("GICP_" + TheDef.getName()).str())
1287 << MatchTable::LineBreak;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001288 }
1289
Daniel Sanders2deea182017-04-22 15:11:04 +00001290 unsigned countRendererFns() const override {
1291 return 1;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001292 }
1293};
1294
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001295/// Generates code to check that an operand is in a particular register bank.
1296class RegisterBankOperandMatcher : public OperandPredicateMatcher {
1297protected:
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001298 const CodeGenRegisterClass &RC;
1299
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001300public:
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001301 RegisterBankOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
1302 const CodeGenRegisterClass &RC)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001303 : OperandPredicateMatcher(OPM_RegBank, InsnVarID, OpIdx), RC(RC) {}
Daniel Sanders759ff412017-02-24 13:58:11 +00001304
Quentin Colombet893e0f12017-12-15 23:24:39 +00001305 bool isIdentical(const PredicateMatcher &B) const override {
1306 return OperandPredicateMatcher::isIdentical(B) &&
1307 RC.getDef() == cast<RegisterBankOperandMatcher>(&B)->RC.getDef();
1308 }
1309
Quentin Colombet063d7982017-12-14 23:44:07 +00001310 static bool classof(const PredicateMatcher *P) {
Daniel Sanders759ff412017-02-24 13:58:11 +00001311 return P->getKind() == OPM_RegBank;
1312 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001313
Quentin Colombetaad20be2017-12-15 23:07:42 +00001314 void emitPredicateOpcodes(MatchTable &Table,
1315 RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001316 Table << MatchTable::Opcode("GIM_CheckRegBankForClass")
1317 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1318 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1319 << MatchTable::Comment("RC")
1320 << MatchTable::NamedValue(RC.getQualifiedName() + "RegClassID")
1321 << MatchTable::LineBreak;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001322 }
1323};
1324
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001325/// Generates code to check that an operand is a basic block.
1326class MBBOperandMatcher : public OperandPredicateMatcher {
1327public:
Quentin Colombetaad20be2017-12-15 23:07:42 +00001328 MBBOperandMatcher(unsigned InsnVarID, unsigned OpIdx)
1329 : OperandPredicateMatcher(OPM_MBB, InsnVarID, OpIdx) {}
Daniel Sanders759ff412017-02-24 13:58:11 +00001330
Quentin Colombet063d7982017-12-14 23:44:07 +00001331 static bool classof(const PredicateMatcher *P) {
Daniel Sanders759ff412017-02-24 13:58:11 +00001332 return P->getKind() == OPM_MBB;
1333 }
1334
Quentin Colombetaad20be2017-12-15 23:07:42 +00001335 void emitPredicateOpcodes(MatchTable &Table,
1336 RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001337 Table << MatchTable::Opcode("GIM_CheckIsMBB") << MatchTable::Comment("MI")
1338 << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Op")
1339 << MatchTable::IntValue(OpIdx) << MatchTable::LineBreak;
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001340 }
1341};
1342
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001343/// Generates code to check that an operand is a G_CONSTANT with a particular
1344/// int.
1345class ConstantIntOperandMatcher : public OperandPredicateMatcher {
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001346protected:
1347 int64_t Value;
1348
1349public:
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001350 ConstantIntOperandMatcher(unsigned InsnVarID, unsigned OpIdx, int64_t Value)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001351 : OperandPredicateMatcher(OPM_Int, InsnVarID, OpIdx), Value(Value) {}
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001352
Quentin Colombet893e0f12017-12-15 23:24:39 +00001353 bool isIdentical(const PredicateMatcher &B) const override {
1354 return OperandPredicateMatcher::isIdentical(B) &&
1355 Value == cast<ConstantIntOperandMatcher>(&B)->Value;
1356 }
1357
Quentin Colombet063d7982017-12-14 23:44:07 +00001358 static bool classof(const PredicateMatcher *P) {
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001359 return P->getKind() == OPM_Int;
1360 }
1361
Quentin Colombetaad20be2017-12-15 23:07:42 +00001362 void emitPredicateOpcodes(MatchTable &Table,
1363 RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001364 Table << MatchTable::Opcode("GIM_CheckConstantInt")
1365 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1366 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1367 << MatchTable::IntValue(Value) << MatchTable::LineBreak;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001368 }
1369};
1370
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001371/// Generates code to check that an operand is a raw int (where MO.isImm() or
1372/// MO.isCImm() is true).
1373class LiteralIntOperandMatcher : public OperandPredicateMatcher {
1374protected:
1375 int64_t Value;
1376
1377public:
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001378 LiteralIntOperandMatcher(unsigned InsnVarID, unsigned OpIdx, int64_t Value)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001379 : OperandPredicateMatcher(OPM_LiteralInt, InsnVarID, OpIdx),
1380 Value(Value) {}
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001381
Quentin Colombet893e0f12017-12-15 23:24:39 +00001382 bool isIdentical(const PredicateMatcher &B) const override {
1383 return OperandPredicateMatcher::isIdentical(B) &&
1384 Value == cast<LiteralIntOperandMatcher>(&B)->Value;
1385 }
1386
Quentin Colombet063d7982017-12-14 23:44:07 +00001387 static bool classof(const PredicateMatcher *P) {
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001388 return P->getKind() == OPM_LiteralInt;
1389 }
1390
Quentin Colombetaad20be2017-12-15 23:07:42 +00001391 void emitPredicateOpcodes(MatchTable &Table,
1392 RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001393 Table << MatchTable::Opcode("GIM_CheckLiteralInt")
1394 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1395 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1396 << MatchTable::IntValue(Value) << MatchTable::LineBreak;
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001397 }
1398};
1399
Matt Arsenault8ec5c102019-08-29 01:13:41 +00001400/// Generates code to check that an operand is an CmpInst predicate
1401class CmpPredicateOperandMatcher : public OperandPredicateMatcher {
1402protected:
1403 std::string PredName;
1404
1405public:
1406 CmpPredicateOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
1407 std::string P)
1408 : OperandPredicateMatcher(OPM_CmpPredicate, InsnVarID, OpIdx), PredName(P) {}
1409
1410 bool isIdentical(const PredicateMatcher &B) const override {
1411 return OperandPredicateMatcher::isIdentical(B) &&
1412 PredName == cast<CmpPredicateOperandMatcher>(&B)->PredName;
1413 }
1414
1415 static bool classof(const PredicateMatcher *P) {
1416 return P->getKind() == OPM_CmpPredicate;
1417 }
1418
1419 void emitPredicateOpcodes(MatchTable &Table,
1420 RuleMatcher &Rule) const override {
1421 Table << MatchTable::Opcode("GIM_CheckCmpPredicate")
1422 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1423 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1424 << MatchTable::Comment("Predicate")
1425 << MatchTable::NamedValue("CmpInst", PredName)
1426 << MatchTable::LineBreak;
1427 }
1428};
1429
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00001430/// Generates code to check that an operand is an intrinsic ID.
1431class IntrinsicIDOperandMatcher : public OperandPredicateMatcher {
1432protected:
1433 const CodeGenIntrinsic *II;
1434
1435public:
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001436 IntrinsicIDOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
1437 const CodeGenIntrinsic *II)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001438 : OperandPredicateMatcher(OPM_IntrinsicID, InsnVarID, OpIdx), II(II) {}
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00001439
Quentin Colombet893e0f12017-12-15 23:24:39 +00001440 bool isIdentical(const PredicateMatcher &B) const override {
1441 return OperandPredicateMatcher::isIdentical(B) &&
1442 II == cast<IntrinsicIDOperandMatcher>(&B)->II;
1443 }
1444
Quentin Colombet063d7982017-12-14 23:44:07 +00001445 static bool classof(const PredicateMatcher *P) {
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00001446 return P->getKind() == OPM_IntrinsicID;
1447 }
1448
Quentin Colombetaad20be2017-12-15 23:07:42 +00001449 void emitPredicateOpcodes(MatchTable &Table,
1450 RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001451 Table << MatchTable::Opcode("GIM_CheckIntrinsicID")
1452 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1453 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1454 << MatchTable::NamedValue("Intrinsic::" + II->EnumName)
1455 << MatchTable::LineBreak;
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00001456 }
1457};
1458
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001459/// Generates code to check that a set of predicates match for a particular
1460/// operand.
1461class OperandMatcher : public PredicateListMatcher<OperandPredicateMatcher> {
1462protected:
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001463 InstructionMatcher &Insn;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001464 unsigned OpIdx;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001465 std::string SymbolicName;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001466
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001467 /// The index of the first temporary variable allocated to this operand. The
1468 /// number of allocated temporaries can be found with
Daniel Sanders2deea182017-04-22 15:11:04 +00001469 /// countRendererFns().
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001470 unsigned AllocatedTemporariesBaseID;
1471
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001472public:
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001473 OperandMatcher(InstructionMatcher &Insn, unsigned OpIdx,
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001474 const std::string &SymbolicName,
1475 unsigned AllocatedTemporariesBaseID)
1476 : Insn(Insn), OpIdx(OpIdx), SymbolicName(SymbolicName),
1477 AllocatedTemporariesBaseID(AllocatedTemporariesBaseID) {}
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001478
1479 bool hasSymbolicName() const { return !SymbolicName.empty(); }
1480 const StringRef getSymbolicName() const { return SymbolicName; }
Daniel Sandersffc7d582017-03-29 15:37:18 +00001481 void setSymbolicName(StringRef Name) {
1482 assert(SymbolicName.empty() && "Operand already has a symbolic name");
1483 SymbolicName = Name;
1484 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001485
1486 /// Construct a new operand predicate and add it to the matcher.
1487 template <class Kind, class... Args>
1488 Optional<Kind *> addPredicate(Args &&... args) {
1489 if (isSameAsAnotherOperand())
1490 return None;
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00001491 Predicates.emplace_back(std::make_unique<Kind>(
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001492 getInsnVarID(), getOpIdx(), std::forward<Args>(args)...));
1493 return static_cast<Kind *>(Predicates.back().get());
1494 }
1495
1496 unsigned getOpIdx() const { return OpIdx; }
Quentin Colombetaad20be2017-12-15 23:07:42 +00001497 unsigned getInsnVarID() const;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001498
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001499 std::string getOperandExpr(unsigned InsnVarID) const {
1500 return "State.MIs[" + llvm::to_string(InsnVarID) + "]->getOperand(" +
1501 llvm::to_string(OpIdx) + ")";
Daniel Sanderse604ef52017-02-20 15:30:43 +00001502 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001503
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001504 InstructionMatcher &getInstructionMatcher() const { return Insn; }
1505
Daniel Sandersa71f4542017-10-16 00:56:30 +00001506 Error addTypeCheckPredicate(const TypeSetByHwMode &VTy,
Reid Klecknercfdd4a22017-10-16 20:31:16 +00001507 bool OperandIsAPointer);
Daniel Sandersa71f4542017-10-16 00:56:30 +00001508
Daniel Sanders9d662d22017-07-06 10:06:12 +00001509 /// Emit MatchTable opcodes that test whether the instruction named in
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001510 /// InsnVarID matches all the predicates and all the operands.
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001511 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule) {
1512 if (!Optimized) {
1513 std::string Comment;
1514 raw_string_ostream CommentOS(Comment);
1515 CommentOS << "MIs[" << getInsnVarID() << "] ";
1516 if (SymbolicName.empty())
1517 CommentOS << "Operand " << OpIdx;
1518 else
1519 CommentOS << SymbolicName;
1520 Table << MatchTable::Comment(CommentOS.str()) << MatchTable::LineBreak;
1521 }
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001522
Quentin Colombetaad20be2017-12-15 23:07:42 +00001523 emitPredicateListOpcodes(Table, Rule);
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001524 }
Daniel Sanders759ff412017-02-24 13:58:11 +00001525
1526 /// Compare the priority of this object and B.
1527 ///
1528 /// Returns true if this object is more important than B.
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001529 bool isHigherPriorityThan(OperandMatcher &B) {
Daniel Sanders759ff412017-02-24 13:58:11 +00001530 // Operand matchers involving more predicates have higher priority.
1531 if (predicates_size() > B.predicates_size())
1532 return true;
1533 if (predicates_size() < B.predicates_size())
1534 return false;
1535
1536 // This assumes that predicates are added in a consistent order.
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001537 for (auto &&Predicate : zip(predicates(), B.predicates())) {
Daniel Sanders759ff412017-02-24 13:58:11 +00001538 if (std::get<0>(Predicate)->isHigherPriorityThan(*std::get<1>(Predicate)))
1539 return true;
1540 if (std::get<1>(Predicate)->isHigherPriorityThan(*std::get<0>(Predicate)))
1541 return false;
1542 }
1543
1544 return false;
1545 };
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001546
1547 /// Report the maximum number of temporary operands needed by the operand
1548 /// matcher.
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001549 unsigned countRendererFns() {
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001550 return std::accumulate(
1551 predicates().begin(), predicates().end(), 0,
1552 [](unsigned A,
1553 const std::unique_ptr<OperandPredicateMatcher> &Predicate) {
Daniel Sanders2deea182017-04-22 15:11:04 +00001554 return A + Predicate->countRendererFns();
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001555 });
1556 }
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001557
1558 unsigned getAllocatedTemporariesBaseID() const {
1559 return AllocatedTemporariesBaseID;
1560 }
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001561
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001562 bool isSameAsAnotherOperand() {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001563 for (const auto &Predicate : predicates())
1564 if (isa<SameOperandMatcher>(Predicate))
1565 return true;
1566 return false;
1567 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001568};
1569
Reid Klecknercfdd4a22017-10-16 20:31:16 +00001570Error OperandMatcher::addTypeCheckPredicate(const TypeSetByHwMode &VTy,
Quentin Colombetaad20be2017-12-15 23:07:42 +00001571 bool OperandIsAPointer) {
Reid Klecknercfdd4a22017-10-16 20:31:16 +00001572 if (!VTy.isMachineValueType())
1573 return failedImport("unsupported typeset");
1574
1575 if (VTy.getMachineValueType() == MVT::iPTR && OperandIsAPointer) {
1576 addPredicate<PointerToAnyOperandMatcher>(0);
1577 return Error::success();
1578 }
1579
1580 auto OpTyOrNone = MVTToLLT(VTy.getMachineValueType().SimpleTy);
1581 if (!OpTyOrNone)
1582 return failedImport("unsupported type");
1583
1584 if (OperandIsAPointer)
1585 addPredicate<PointerToAnyOperandMatcher>(OpTyOrNone->get().getSizeInBits());
Tom Stellard9ad714f2019-02-20 19:43:47 +00001586 else if (VTy.isPointer())
1587 addPredicate<LLTOperandMatcher>(LLT::pointer(VTy.getPtrAddrSpace(),
1588 OpTyOrNone->get().getSizeInBits()));
Reid Klecknercfdd4a22017-10-16 20:31:16 +00001589 else
1590 addPredicate<LLTOperandMatcher>(*OpTyOrNone);
1591 return Error::success();
1592}
1593
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001594unsigned ComplexPatternOperandMatcher::getAllocatedTemporariesBaseID() const {
1595 return Operand.getAllocatedTemporariesBaseID();
1596}
1597
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001598/// Generates code to check a predicate on an instruction.
1599///
1600/// Typical predicates include:
1601/// * The opcode of the instruction is a particular value.
1602/// * The nsw/nuw flag is/isn't set.
Quentin Colombet063d7982017-12-14 23:44:07 +00001603class InstructionPredicateMatcher : public PredicateMatcher {
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001604public:
Quentin Colombetaad20be2017-12-15 23:07:42 +00001605 InstructionPredicateMatcher(PredicateKind Kind, unsigned InsnVarID)
1606 : PredicateMatcher(Kind, InsnVarID) {}
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001607 virtual ~InstructionPredicateMatcher() {}
1608
Daniel Sanders759ff412017-02-24 13:58:11 +00001609 /// Compare the priority of this object and B.
1610 ///
1611 /// Returns true if this object is more important than B.
Daniel Sanders32291982017-06-28 13:50:04 +00001612 virtual bool
1613 isHigherPriorityThan(const InstructionPredicateMatcher &B) const {
Daniel Sanders759ff412017-02-24 13:58:11 +00001614 return Kind < B.Kind;
1615 };
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001616};
1617
Daniel Sanders2c269f62017-08-24 09:11:20 +00001618template <>
1619std::string
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001620PredicateListMatcher<PredicateMatcher>::getNoPredicateComment() const {
Daniel Sanders2c269f62017-08-24 09:11:20 +00001621 return "No instruction predicates";
1622}
1623
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001624/// Generates code to check the opcode of an instruction.
1625class InstructionOpcodeMatcher : public InstructionPredicateMatcher {
1626protected:
1627 const CodeGenInstruction *I;
1628
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001629 static DenseMap<const CodeGenInstruction *, unsigned> OpcodeValues;
1630
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001631public:
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001632 static void initOpcodeValuesMap(const CodeGenTarget &Target) {
1633 OpcodeValues.clear();
1634
1635 unsigned OpcodeValue = 0;
1636 for (const CodeGenInstruction *I : Target.getInstructionsByEnumValue())
1637 OpcodeValues[I] = OpcodeValue++;
1638 }
1639
Quentin Colombetaad20be2017-12-15 23:07:42 +00001640 InstructionOpcodeMatcher(unsigned InsnVarID, const CodeGenInstruction *I)
1641 : InstructionPredicateMatcher(IPM_Opcode, InsnVarID), I(I) {}
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001642
Quentin Colombet063d7982017-12-14 23:44:07 +00001643 static bool classof(const PredicateMatcher *P) {
Daniel Sanders759ff412017-02-24 13:58:11 +00001644 return P->getKind() == IPM_Opcode;
1645 }
1646
Quentin Colombet893e0f12017-12-15 23:24:39 +00001647 bool isIdentical(const PredicateMatcher &B) const override {
1648 return InstructionPredicateMatcher::isIdentical(B) &&
1649 I == cast<InstructionOpcodeMatcher>(&B)->I;
1650 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001651 MatchTableRecord getValue() const override {
1652 const auto VI = OpcodeValues.find(I);
1653 if (VI != OpcodeValues.end())
1654 return MatchTable::NamedValue(I->Namespace, I->TheDef->getName(),
1655 VI->second);
1656 return MatchTable::NamedValue(I->Namespace, I->TheDef->getName());
1657 }
1658 bool hasValue() const override { return OpcodeValues.count(I); }
Quentin Colombet893e0f12017-12-15 23:24:39 +00001659
Quentin Colombetaad20be2017-12-15 23:07:42 +00001660 void emitPredicateOpcodes(MatchTable &Table,
1661 RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001662 Table << MatchTable::Opcode("GIM_CheckOpcode") << MatchTable::Comment("MI")
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001663 << MatchTable::IntValue(InsnVarID) << getValue()
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001664 << MatchTable::LineBreak;
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001665 }
Daniel Sanders759ff412017-02-24 13:58:11 +00001666
1667 /// Compare the priority of this object and B.
1668 ///
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001669 /// Returns true if this object is more important than B.
Daniel Sanders32291982017-06-28 13:50:04 +00001670 bool
1671 isHigherPriorityThan(const InstructionPredicateMatcher &B) const override {
Daniel Sanders759ff412017-02-24 13:58:11 +00001672 if (InstructionPredicateMatcher::isHigherPriorityThan(B))
1673 return true;
1674 if (B.InstructionPredicateMatcher::isHigherPriorityThan(*this))
1675 return false;
1676
1677 // Prioritize opcodes for cosmetic reasons in the generated source. Although
1678 // this is cosmetic at the moment, we may want to drive a similar ordering
1679 // using instruction frequency information to improve compile time.
1680 if (const InstructionOpcodeMatcher *BO =
1681 dyn_cast<InstructionOpcodeMatcher>(&B))
1682 return I->TheDef->getName() < BO->I->TheDef->getName();
1683
1684 return false;
1685 };
Daniel Sanders05540042017-08-08 10:44:31 +00001686
1687 bool isConstantInstruction() const {
1688 return I->TheDef->getName() == "G_CONSTANT";
1689 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001690
Roman Tereshin19da6672018-05-22 04:31:50 +00001691 StringRef getOpcode() const { return I->TheDef->getName(); }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001692 unsigned getNumOperands() const { return I->Operands.size(); }
1693
1694 StringRef getOperandType(unsigned OpIdx) const {
1695 return I->Operands[OpIdx].OperandType;
1696 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001697};
1698
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001699DenseMap<const CodeGenInstruction *, unsigned>
1700 InstructionOpcodeMatcher::OpcodeValues;
1701
Roman Tereshin19da6672018-05-22 04:31:50 +00001702class InstructionNumOperandsMatcher final : public InstructionPredicateMatcher {
1703 unsigned NumOperands = 0;
1704
1705public:
1706 InstructionNumOperandsMatcher(unsigned InsnVarID, unsigned NumOperands)
1707 : InstructionPredicateMatcher(IPM_NumOperands, InsnVarID),
1708 NumOperands(NumOperands) {}
1709
1710 static bool classof(const PredicateMatcher *P) {
1711 return P->getKind() == IPM_NumOperands;
1712 }
1713
1714 bool isIdentical(const PredicateMatcher &B) const override {
1715 return InstructionPredicateMatcher::isIdentical(B) &&
1716 NumOperands == cast<InstructionNumOperandsMatcher>(&B)->NumOperands;
1717 }
1718
1719 void emitPredicateOpcodes(MatchTable &Table,
1720 RuleMatcher &Rule) const override {
1721 Table << MatchTable::Opcode("GIM_CheckNumOperands")
1722 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1723 << MatchTable::Comment("Expected")
1724 << MatchTable::IntValue(NumOperands) << MatchTable::LineBreak;
1725 }
1726};
1727
Daniel Sanders2c269f62017-08-24 09:11:20 +00001728/// Generates code to check that this instruction is a constant whose value
1729/// meets an immediate predicate.
1730///
1731/// Immediates are slightly odd since they are typically used like an operand
1732/// but are represented as an operator internally. We typically write simm8:$src
1733/// in a tablegen pattern, but this is just syntactic sugar for
1734/// (imm:i32)<<P:Predicate_simm8>>:$imm which more directly describes the nodes
1735/// that will be matched and the predicate (which is attached to the imm
1736/// operator) that will be tested. In SelectionDAG this describes a
1737/// ConstantSDNode whose internal value will be tested using the simm8 predicate.
1738///
1739/// The corresponding GlobalISel representation is %1 = G_CONSTANT iN Value. In
1740/// this representation, the immediate could be tested with an
1741/// InstructionMatcher, InstructionOpcodeMatcher, OperandMatcher, and a
1742/// OperandPredicateMatcher-subclass to check the Value meets the predicate but
1743/// there are two implementation issues with producing that matcher
1744/// configuration from the SelectionDAG pattern:
1745/// * ImmLeaf is a PatFrag whose root is an InstructionMatcher. This means that
1746/// were we to sink the immediate predicate to the operand we would have to
1747/// have two partial implementations of PatFrag support, one for immediates
1748/// and one for non-immediates.
1749/// * At the point we handle the predicate, the OperandMatcher hasn't been
1750/// created yet. If we were to sink the predicate to the OperandMatcher we
1751/// would also have to complicate (or duplicate) the code that descends and
1752/// creates matchers for the subtree.
1753/// Overall, it's simpler to handle it in the place it was found.
1754class InstructionImmPredicateMatcher : public InstructionPredicateMatcher {
1755protected:
1756 TreePredicateFn Predicate;
1757
1758public:
Quentin Colombetaad20be2017-12-15 23:07:42 +00001759 InstructionImmPredicateMatcher(unsigned InsnVarID,
1760 const TreePredicateFn &Predicate)
1761 : InstructionPredicateMatcher(IPM_ImmPredicate, InsnVarID),
1762 Predicate(Predicate) {}
Daniel Sanders2c269f62017-08-24 09:11:20 +00001763
Quentin Colombet893e0f12017-12-15 23:24:39 +00001764 bool isIdentical(const PredicateMatcher &B) const override {
1765 return InstructionPredicateMatcher::isIdentical(B) &&
1766 Predicate.getOrigPatFragRecord() ==
1767 cast<InstructionImmPredicateMatcher>(&B)
1768 ->Predicate.getOrigPatFragRecord();
1769 }
1770
Quentin Colombet063d7982017-12-14 23:44:07 +00001771 static bool classof(const PredicateMatcher *P) {
Daniel Sanders2c269f62017-08-24 09:11:20 +00001772 return P->getKind() == IPM_ImmPredicate;
1773 }
1774
Quentin Colombetaad20be2017-12-15 23:07:42 +00001775 void emitPredicateOpcodes(MatchTable &Table,
1776 RuleMatcher &Rule) const override {
Daniel Sanders11300ce2017-10-13 21:28:03 +00001777 Table << MatchTable::Opcode(getMatchOpcodeForPredicate(Predicate))
Daniel Sanders2c269f62017-08-24 09:11:20 +00001778 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1779 << MatchTable::Comment("Predicate")
Daniel Sanders11300ce2017-10-13 21:28:03 +00001780 << MatchTable::NamedValue(getEnumNameForPredicate(Predicate))
Daniel Sanders2c269f62017-08-24 09:11:20 +00001781 << MatchTable::LineBreak;
1782 }
1783};
1784
Daniel Sanders76664652017-11-28 22:07:05 +00001785/// Generates code to check that a memory instruction has a atomic ordering
1786/// MachineMemoryOperand.
1787class AtomicOrderingMMOPredicateMatcher : public InstructionPredicateMatcher {
Daniel Sanders0c43b3a2017-11-30 21:05:59 +00001788public:
1789 enum AOComparator {
1790 AO_Exactly,
1791 AO_OrStronger,
1792 AO_WeakerThan,
1793 };
1794
1795protected:
Daniel Sanders76664652017-11-28 22:07:05 +00001796 StringRef Order;
Daniel Sanders0c43b3a2017-11-30 21:05:59 +00001797 AOComparator Comparator;
Daniel Sanders76664652017-11-28 22:07:05 +00001798
Daniel Sanders39690bd2017-10-15 02:41:12 +00001799public:
Quentin Colombetaad20be2017-12-15 23:07:42 +00001800 AtomicOrderingMMOPredicateMatcher(unsigned InsnVarID, StringRef Order,
Daniel Sanders0c43b3a2017-11-30 21:05:59 +00001801 AOComparator Comparator = AO_Exactly)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001802 : InstructionPredicateMatcher(IPM_AtomicOrderingMMO, InsnVarID),
1803 Order(Order), Comparator(Comparator) {}
Daniel Sanders39690bd2017-10-15 02:41:12 +00001804
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001805 static bool classof(const PredicateMatcher *P) {
Daniel Sanders76664652017-11-28 22:07:05 +00001806 return P->getKind() == IPM_AtomicOrderingMMO;
Daniel Sanders39690bd2017-10-15 02:41:12 +00001807 }
1808
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001809 bool isIdentical(const PredicateMatcher &B) const override {
1810 if (!InstructionPredicateMatcher::isIdentical(B))
1811 return false;
1812 const auto &R = *cast<AtomicOrderingMMOPredicateMatcher>(&B);
1813 return Order == R.Order && Comparator == R.Comparator;
1814 }
1815
Quentin Colombetaad20be2017-12-15 23:07:42 +00001816 void emitPredicateOpcodes(MatchTable &Table,
1817 RuleMatcher &Rule) const override {
Daniel Sanders0c43b3a2017-11-30 21:05:59 +00001818 StringRef Opcode = "GIM_CheckAtomicOrdering";
1819
1820 if (Comparator == AO_OrStronger)
1821 Opcode = "GIM_CheckAtomicOrderingOrStrongerThan";
1822 if (Comparator == AO_WeakerThan)
1823 Opcode = "GIM_CheckAtomicOrderingWeakerThan";
1824
1825 Table << MatchTable::Opcode(Opcode) << MatchTable::Comment("MI")
1826 << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Order")
Daniel Sanders76664652017-11-28 22:07:05 +00001827 << MatchTable::NamedValue(("(int64_t)AtomicOrdering::" + Order).str())
Daniel Sanders39690bd2017-10-15 02:41:12 +00001828 << MatchTable::LineBreak;
1829 }
1830};
1831
Daniel Sandersf84bc372018-05-05 20:53:24 +00001832/// Generates code to check that the size of an MMO is exactly N bytes.
1833class MemorySizePredicateMatcher : public InstructionPredicateMatcher {
1834protected:
1835 unsigned MMOIdx;
1836 uint64_t Size;
1837
1838public:
1839 MemorySizePredicateMatcher(unsigned InsnVarID, unsigned MMOIdx, unsigned Size)
1840 : InstructionPredicateMatcher(IPM_MemoryLLTSize, InsnVarID),
1841 MMOIdx(MMOIdx), Size(Size) {}
1842
1843 static bool classof(const PredicateMatcher *P) {
1844 return P->getKind() == IPM_MemoryLLTSize;
1845 }
1846 bool isIdentical(const PredicateMatcher &B) const override {
1847 return InstructionPredicateMatcher::isIdentical(B) &&
1848 MMOIdx == cast<MemorySizePredicateMatcher>(&B)->MMOIdx &&
1849 Size == cast<MemorySizePredicateMatcher>(&B)->Size;
1850 }
1851
1852 void emitPredicateOpcodes(MatchTable &Table,
1853 RuleMatcher &Rule) const override {
1854 Table << MatchTable::Opcode("GIM_CheckMemorySizeEqualTo")
1855 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1856 << MatchTable::Comment("MMO") << MatchTable::IntValue(MMOIdx)
1857 << MatchTable::Comment("Size") << MatchTable::IntValue(Size)
1858 << MatchTable::LineBreak;
1859 }
1860};
1861
Matt Arsenaultd00d8572019-07-15 20:59:42 +00001862class MemoryAddressSpacePredicateMatcher : public InstructionPredicateMatcher {
1863protected:
1864 unsigned MMOIdx;
1865 SmallVector<unsigned, 4> AddrSpaces;
1866
1867public:
1868 MemoryAddressSpacePredicateMatcher(unsigned InsnVarID, unsigned MMOIdx,
1869 ArrayRef<unsigned> AddrSpaces)
1870 : InstructionPredicateMatcher(IPM_MemoryAddressSpace, InsnVarID),
1871 MMOIdx(MMOIdx), AddrSpaces(AddrSpaces.begin(), AddrSpaces.end()) {}
1872
1873 static bool classof(const PredicateMatcher *P) {
1874 return P->getKind() == IPM_MemoryAddressSpace;
1875 }
1876 bool isIdentical(const PredicateMatcher &B) const override {
1877 if (!InstructionPredicateMatcher::isIdentical(B))
1878 return false;
1879 auto *Other = cast<MemoryAddressSpacePredicateMatcher>(&B);
1880 return MMOIdx == Other->MMOIdx && AddrSpaces == Other->AddrSpaces;
1881 }
1882
1883 void emitPredicateOpcodes(MatchTable &Table,
1884 RuleMatcher &Rule) const override {
1885 Table << MatchTable::Opcode("GIM_CheckMemoryAddressSpace")
1886 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1887 << MatchTable::Comment("MMO") << MatchTable::IntValue(MMOIdx)
1888 // Encode number of address spaces to expect.
1889 << MatchTable::Comment("NumAddrSpace")
1890 << MatchTable::IntValue(AddrSpaces.size());
1891 for (unsigned AS : AddrSpaces)
1892 Table << MatchTable::Comment("AddrSpace") << MatchTable::IntValue(AS);
1893
1894 Table << MatchTable::LineBreak;
1895 }
1896};
1897
Matt Arsenault52c26242019-07-31 00:14:43 +00001898class MemoryAlignmentPredicateMatcher : public InstructionPredicateMatcher {
1899protected:
1900 unsigned MMOIdx;
1901 int MinAlign;
1902
1903public:
1904 MemoryAlignmentPredicateMatcher(unsigned InsnVarID, unsigned MMOIdx,
1905 int MinAlign)
1906 : InstructionPredicateMatcher(IPM_MemoryAlignment, InsnVarID),
1907 MMOIdx(MMOIdx), MinAlign(MinAlign) {
1908 assert(MinAlign > 0);
1909 }
1910
1911 static bool classof(const PredicateMatcher *P) {
1912 return P->getKind() == IPM_MemoryAlignment;
1913 }
1914
1915 bool isIdentical(const PredicateMatcher &B) const override {
1916 if (!InstructionPredicateMatcher::isIdentical(B))
1917 return false;
1918 auto *Other = cast<MemoryAlignmentPredicateMatcher>(&B);
1919 return MMOIdx == Other->MMOIdx && MinAlign == Other->MinAlign;
1920 }
1921
1922 void emitPredicateOpcodes(MatchTable &Table,
1923 RuleMatcher &Rule) const override {
1924 Table << MatchTable::Opcode("GIM_CheckMemoryAlignment")
1925 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1926 << MatchTable::Comment("MMO") << MatchTable::IntValue(MMOIdx)
1927 << MatchTable::Comment("MinAlign") << MatchTable::IntValue(MinAlign)
1928 << MatchTable::LineBreak;
1929 }
1930};
1931
Daniel Sandersf84bc372018-05-05 20:53:24 +00001932/// Generates code to check that the size of an MMO is less-than, equal-to, or
1933/// greater than a given LLT.
1934class MemoryVsLLTSizePredicateMatcher : public InstructionPredicateMatcher {
1935public:
1936 enum RelationKind {
1937 GreaterThan,
1938 EqualTo,
1939 LessThan,
1940 };
1941
1942protected:
1943 unsigned MMOIdx;
1944 RelationKind Relation;
1945 unsigned OpIdx;
1946
1947public:
1948 MemoryVsLLTSizePredicateMatcher(unsigned InsnVarID, unsigned MMOIdx,
1949 enum RelationKind Relation,
1950 unsigned OpIdx)
1951 : InstructionPredicateMatcher(IPM_MemoryVsLLTSize, InsnVarID),
1952 MMOIdx(MMOIdx), Relation(Relation), OpIdx(OpIdx) {}
1953
1954 static bool classof(const PredicateMatcher *P) {
1955 return P->getKind() == IPM_MemoryVsLLTSize;
1956 }
1957 bool isIdentical(const PredicateMatcher &B) const override {
1958 return InstructionPredicateMatcher::isIdentical(B) &&
1959 MMOIdx == cast<MemoryVsLLTSizePredicateMatcher>(&B)->MMOIdx &&
1960 Relation == cast<MemoryVsLLTSizePredicateMatcher>(&B)->Relation &&
1961 OpIdx == cast<MemoryVsLLTSizePredicateMatcher>(&B)->OpIdx;
1962 }
1963
1964 void emitPredicateOpcodes(MatchTable &Table,
1965 RuleMatcher &Rule) const override {
1966 Table << MatchTable::Opcode(Relation == EqualTo
1967 ? "GIM_CheckMemorySizeEqualToLLT"
1968 : Relation == GreaterThan
1969 ? "GIM_CheckMemorySizeGreaterThanLLT"
1970 : "GIM_CheckMemorySizeLessThanLLT")
1971 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1972 << MatchTable::Comment("MMO") << MatchTable::IntValue(MMOIdx)
1973 << MatchTable::Comment("OpIdx") << MatchTable::IntValue(OpIdx)
1974 << MatchTable::LineBreak;
1975 }
1976};
1977
Daniel Sanders8ead1292018-06-15 23:13:43 +00001978/// Generates code to check an arbitrary C++ instruction predicate.
1979class GenericInstructionPredicateMatcher : public InstructionPredicateMatcher {
1980protected:
1981 TreePredicateFn Predicate;
1982
1983public:
1984 GenericInstructionPredicateMatcher(unsigned InsnVarID,
1985 TreePredicateFn Predicate)
1986 : InstructionPredicateMatcher(IPM_GenericPredicate, InsnVarID),
1987 Predicate(Predicate) {}
1988
1989 static bool classof(const InstructionPredicateMatcher *P) {
1990 return P->getKind() == IPM_GenericPredicate;
1991 }
Daniel Sanders06f4ff12018-09-25 17:59:02 +00001992 bool isIdentical(const PredicateMatcher &B) const override {
1993 return InstructionPredicateMatcher::isIdentical(B) &&
1994 Predicate ==
1995 static_cast<const GenericInstructionPredicateMatcher &>(B)
1996 .Predicate;
1997 }
Daniel Sanders8ead1292018-06-15 23:13:43 +00001998 void emitPredicateOpcodes(MatchTable &Table,
1999 RuleMatcher &Rule) const override {
2000 Table << MatchTable::Opcode("GIM_CheckCxxInsnPredicate")
2001 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
2002 << MatchTable::Comment("FnId")
2003 << MatchTable::NamedValue(getEnumNameForPredicate(Predicate))
2004 << MatchTable::LineBreak;
2005 }
2006};
2007
Daniel Sandersdc662ff2017-01-26 11:10:14 +00002008/// Generates code to check that a set of predicates and operands match for a
2009/// particular instruction.
2010///
2011/// Typical predicates include:
2012/// * Has a specific opcode.
2013/// * Has an nsw/nuw flag or doesn't.
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002014class InstructionMatcher final : public PredicateListMatcher<PredicateMatcher> {
Daniel Sandersdc662ff2017-01-26 11:10:14 +00002015protected:
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002016 typedef std::vector<std::unique_ptr<OperandMatcher>> OperandVec;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002017
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002018 RuleMatcher &Rule;
2019
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002020 /// The operands to match. All rendered operands must be present even if the
2021 /// condition is always true.
2022 OperandVec Operands;
Roman Tereshin19da6672018-05-22 04:31:50 +00002023 bool NumOperandsCheck = true;
Daniel Sandersdc662ff2017-01-26 11:10:14 +00002024
Daniel Sanders05540042017-08-08 10:44:31 +00002025 std::string SymbolicName;
Quentin Colombetaad20be2017-12-15 23:07:42 +00002026 unsigned InsnVarID;
Daniel Sanders05540042017-08-08 10:44:31 +00002027
Matt Arsenault3e45c702019-09-06 20:32:37 +00002028 /// PhysRegInputs - List list has an entry for each explicitly specified
2029 /// physreg input to the pattern. The first elt is the Register node, the
2030 /// second is the recorded slot number the input pattern match saved it in.
2031 SmallVector<std::pair<Record *, unsigned>, 2> PhysRegInputs;
2032
Daniel Sandersdc662ff2017-01-26 11:10:14 +00002033public:
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002034 InstructionMatcher(RuleMatcher &Rule, StringRef SymbolicName)
Quentin Colombetaad20be2017-12-15 23:07:42 +00002035 : Rule(Rule), SymbolicName(SymbolicName) {
2036 // We create a new instruction matcher.
2037 // Get a new ID for that instruction.
2038 InsnVarID = Rule.implicitlyDefineInsnVar(*this);
2039 }
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002040
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002041 /// Construct a new instruction predicate and add it to the matcher.
2042 template <class Kind, class... Args>
2043 Optional<Kind *> addPredicate(Args &&... args) {
2044 Predicates.emplace_back(
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00002045 std::make_unique<Kind>(getInsnVarID(), std::forward<Args>(args)...));
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002046 return static_cast<Kind *>(Predicates.back().get());
2047 }
2048
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002049 RuleMatcher &getRuleMatcher() const { return Rule; }
Daniel Sanders05540042017-08-08 10:44:31 +00002050
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002051 unsigned getInsnVarID() const { return InsnVarID; }
Quentin Colombetaad20be2017-12-15 23:07:42 +00002052
Daniel Sandersdc662ff2017-01-26 11:10:14 +00002053 /// Add an operand to the matcher.
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002054 OperandMatcher &addOperand(unsigned OpIdx, const std::string &SymbolicName,
2055 unsigned AllocatedTemporariesBaseID) {
2056 Operands.emplace_back(new OperandMatcher(*this, OpIdx, SymbolicName,
2057 AllocatedTemporariesBaseID));
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002058 if (!SymbolicName.empty())
2059 Rule.defineOperand(SymbolicName, *Operands.back());
2060
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002061 return *Operands.back();
Daniel Sandersdc662ff2017-01-26 11:10:14 +00002062 }
2063
Daniel Sandersffc7d582017-03-29 15:37:18 +00002064 OperandMatcher &getOperand(unsigned OpIdx) {
2065 auto I = std::find_if(Operands.begin(), Operands.end(),
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002066 [&OpIdx](const std::unique_ptr<OperandMatcher> &X) {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002067 return X->getOpIdx() == OpIdx;
Daniel Sandersffc7d582017-03-29 15:37:18 +00002068 });
2069 if (I != Operands.end())
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002070 return **I;
Daniel Sandersffc7d582017-03-29 15:37:18 +00002071 llvm_unreachable("Failed to lookup operand");
2072 }
2073
Matt Arsenault3e45c702019-09-06 20:32:37 +00002074 OperandMatcher &addPhysRegInput(Record *Reg, unsigned OpIdx,
2075 unsigned TempOpIdx) {
2076 assert(SymbolicName.empty());
2077 OperandMatcher *OM = new OperandMatcher(*this, OpIdx, "", TempOpIdx);
2078 Operands.emplace_back(OM);
2079 Rule.definePhysRegOperand(Reg, *OM);
2080 PhysRegInputs.emplace_back(Reg, OpIdx);
2081 return *OM;
2082 }
2083
2084 ArrayRef<std::pair<Record *, unsigned>> getPhysRegInputs() const {
2085 return PhysRegInputs;
2086 }
2087
Daniel Sanders05540042017-08-08 10:44:31 +00002088 StringRef getSymbolicName() const { return SymbolicName; }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002089 unsigned getNumOperands() const { return Operands.size(); }
Daniel Sandersbee57392017-04-04 13:25:23 +00002090 OperandVec::iterator operands_begin() { return Operands.begin(); }
2091 OperandVec::iterator operands_end() { return Operands.end(); }
2092 iterator_range<OperandVec::iterator> operands() {
2093 return make_range(operands_begin(), operands_end());
2094 }
Daniel Sandersffc7d582017-03-29 15:37:18 +00002095 OperandVec::const_iterator operands_begin() const { return Operands.begin(); }
2096 OperandVec::const_iterator operands_end() const { return Operands.end(); }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002097 iterator_range<OperandVec::const_iterator> operands() const {
2098 return make_range(operands_begin(), operands_end());
2099 }
Quentin Colombetec76d9c2017-12-18 19:47:41 +00002100 bool operands_empty() const { return Operands.empty(); }
2101
2102 void pop_front() { Operands.erase(Operands.begin()); }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002103
Roman Tereshin19da6672018-05-22 04:31:50 +00002104 void optimize();
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002105
2106 /// Emit MatchTable opcodes that test whether the instruction named in
2107 /// InsnVarName matches all the predicates and all the operands.
2108 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule) {
Roman Tereshin19da6672018-05-22 04:31:50 +00002109 if (NumOperandsCheck)
2110 InstructionNumOperandsMatcher(InsnVarID, getNumOperands())
2111 .emitPredicateOpcodes(Table, Rule);
Daniel Sandersb96f40d2017-03-20 15:20:42 +00002112
Quentin Colombetaad20be2017-12-15 23:07:42 +00002113 emitPredicateListOpcodes(Table, Rule);
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002114
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002115 for (const auto &Operand : Operands)
Quentin Colombetaad20be2017-12-15 23:07:42 +00002116 Operand->emitPredicateOpcodes(Table, Rule);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002117 }
Daniel Sanders759ff412017-02-24 13:58:11 +00002118
2119 /// Compare the priority of this object and B.
2120 ///
2121 /// Returns true if this object is more important than B.
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002122 bool isHigherPriorityThan(InstructionMatcher &B) {
Daniel Sanders759ff412017-02-24 13:58:11 +00002123 // Instruction matchers involving more operands have higher priority.
2124 if (Operands.size() > B.Operands.size())
2125 return true;
2126 if (Operands.size() < B.Operands.size())
2127 return false;
2128
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002129 for (auto &&P : zip(predicates(), B.predicates())) {
2130 auto L = static_cast<InstructionPredicateMatcher *>(std::get<0>(P).get());
2131 auto R = static_cast<InstructionPredicateMatcher *>(std::get<1>(P).get());
2132 if (L->isHigherPriorityThan(*R))
Daniel Sanders759ff412017-02-24 13:58:11 +00002133 return true;
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002134 if (R->isHigherPriorityThan(*L))
Daniel Sanders759ff412017-02-24 13:58:11 +00002135 return false;
2136 }
2137
2138 for (const auto &Operand : zip(Operands, B.Operands)) {
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002139 if (std::get<0>(Operand)->isHigherPriorityThan(*std::get<1>(Operand)))
Daniel Sanders759ff412017-02-24 13:58:11 +00002140 return true;
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002141 if (std::get<1>(Operand)->isHigherPriorityThan(*std::get<0>(Operand)))
Daniel Sanders759ff412017-02-24 13:58:11 +00002142 return false;
2143 }
2144
2145 return false;
2146 };
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002147
2148 /// Report the maximum number of temporary operands needed by the instruction
2149 /// matcher.
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002150 unsigned countRendererFns() {
2151 return std::accumulate(
2152 predicates().begin(), predicates().end(), 0,
2153 [](unsigned A,
2154 const std::unique_ptr<PredicateMatcher> &Predicate) {
2155 return A + Predicate->countRendererFns();
2156 }) +
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002157 std::accumulate(
2158 Operands.begin(), Operands.end(), 0,
2159 [](unsigned A, const std::unique_ptr<OperandMatcher> &Operand) {
Daniel Sanders2deea182017-04-22 15:11:04 +00002160 return A + Operand->countRendererFns();
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002161 });
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002162 }
Daniel Sanders05540042017-08-08 10:44:31 +00002163
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002164 InstructionOpcodeMatcher &getOpcodeMatcher() {
2165 for (auto &P : predicates())
2166 if (auto *OpMatcher = dyn_cast<InstructionOpcodeMatcher>(P.get()))
2167 return *OpMatcher;
2168 llvm_unreachable("Didn't find an opcode matcher");
2169 }
2170
2171 bool isConstantInstruction() {
2172 return getOpcodeMatcher().isConstantInstruction();
Daniel Sanders05540042017-08-08 10:44:31 +00002173 }
Roman Tereshin19da6672018-05-22 04:31:50 +00002174
2175 StringRef getOpcode() { return getOpcodeMatcher().getOpcode(); }
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002176};
2177
Roman Tereshin19da6672018-05-22 04:31:50 +00002178StringRef RuleMatcher::getOpcode() const {
2179 return Matchers.front()->getOpcode();
2180}
2181
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002182unsigned RuleMatcher::getNumOperands() const {
2183 return Matchers.front()->getNumOperands();
2184}
2185
Roman Tereshin9a9fa492018-05-23 21:30:16 +00002186LLTCodeGen RuleMatcher::getFirstConditionAsRootType() {
2187 InstructionMatcher &InsnMatcher = *Matchers.front();
2188 if (!InsnMatcher.predicates_empty())
2189 if (const auto *TM =
2190 dyn_cast<LLTOperandMatcher>(&**InsnMatcher.predicates_begin()))
2191 if (TM->getInsnVarID() == 0 && TM->getOpIdx() == 0)
2192 return TM->getTy();
2193 return {};
2194}
2195
Daniel Sandersbee57392017-04-04 13:25:23 +00002196/// Generates code to check that the operand is a register defined by an
2197/// instruction that matches the given instruction matcher.
2198///
2199/// For example, the pattern:
2200/// (set $dst, (G_MUL (G_ADD $src1, $src2), $src3))
2201/// would use an InstructionOperandMatcher for operand 1 of the G_MUL to match
2202/// the:
2203/// (G_ADD $src1, $src2)
2204/// subpattern.
2205class InstructionOperandMatcher : public OperandPredicateMatcher {
2206protected:
2207 std::unique_ptr<InstructionMatcher> InsnMatcher;
2208
2209public:
Quentin Colombeteba10cb2017-12-18 22:12:13 +00002210 InstructionOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
2211 RuleMatcher &Rule, StringRef SymbolicName)
Quentin Colombetaad20be2017-12-15 23:07:42 +00002212 : OperandPredicateMatcher(OPM_Instruction, InsnVarID, OpIdx),
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002213 InsnMatcher(new InstructionMatcher(Rule, SymbolicName)) {}
Daniel Sandersbee57392017-04-04 13:25:23 +00002214
Quentin Colombet063d7982017-12-14 23:44:07 +00002215 static bool classof(const PredicateMatcher *P) {
Daniel Sandersbee57392017-04-04 13:25:23 +00002216 return P->getKind() == OPM_Instruction;
2217 }
2218
2219 InstructionMatcher &getInsnMatcher() const { return *InsnMatcher; }
2220
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002221 void emitCaptureOpcodes(MatchTable &Table, RuleMatcher &Rule) const {
2222 const unsigned NewInsnVarID = InsnMatcher->getInsnVarID();
2223 Table << MatchTable::Opcode("GIM_RecordInsn")
2224 << MatchTable::Comment("DefineMI")
2225 << MatchTable::IntValue(NewInsnVarID) << MatchTable::Comment("MI")
2226 << MatchTable::IntValue(getInsnVarID())
2227 << MatchTable::Comment("OpIdx") << MatchTable::IntValue(getOpIdx())
2228 << MatchTable::Comment("MIs[" + llvm::to_string(NewInsnVarID) + "]")
2229 << MatchTable::LineBreak;
Daniel Sandersbee57392017-04-04 13:25:23 +00002230 }
2231
Quentin Colombetaad20be2017-12-15 23:07:42 +00002232 void emitPredicateOpcodes(MatchTable &Table,
2233 RuleMatcher &Rule) const override {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002234 emitCaptureOpcodes(Table, Rule);
Quentin Colombetaad20be2017-12-15 23:07:42 +00002235 InsnMatcher->emitPredicateOpcodes(Table, Rule);
Daniel Sandersbee57392017-04-04 13:25:23 +00002236 }
Daniel Sanders12e6e702018-01-17 20:34:29 +00002237
2238 bool isHigherPriorityThan(const OperandPredicateMatcher &B) const override {
2239 if (OperandPredicateMatcher::isHigherPriorityThan(B))
2240 return true;
2241 if (B.OperandPredicateMatcher::isHigherPriorityThan(*this))
2242 return false;
2243
2244 if (const InstructionOperandMatcher *BP =
2245 dyn_cast<InstructionOperandMatcher>(&B))
2246 if (InsnMatcher->isHigherPriorityThan(*BP->InsnMatcher))
2247 return true;
2248 return false;
2249 }
Daniel Sandersbee57392017-04-04 13:25:23 +00002250};
2251
Roman Tereshin19da6672018-05-22 04:31:50 +00002252void InstructionMatcher::optimize() {
2253 SmallVector<std::unique_ptr<PredicateMatcher>, 8> Stash;
2254 const auto &OpcMatcher = getOpcodeMatcher();
2255
2256 Stash.push_back(predicates_pop_front());
2257 if (Stash.back().get() == &OpcMatcher) {
2258 if (NumOperandsCheck && OpcMatcher.getNumOperands() < getNumOperands())
2259 Stash.emplace_back(
2260 new InstructionNumOperandsMatcher(InsnVarID, getNumOperands()));
2261 NumOperandsCheck = false;
Roman Tereshinfedae332018-05-23 02:04:19 +00002262
2263 for (auto &OM : Operands)
2264 for (auto &OP : OM->predicates())
2265 if (isa<IntrinsicIDOperandMatcher>(OP)) {
2266 Stash.push_back(std::move(OP));
2267 OM->eraseNullPredicates();
2268 break;
2269 }
Roman Tereshin19da6672018-05-22 04:31:50 +00002270 }
2271
2272 if (InsnVarID > 0) {
2273 assert(!Operands.empty() && "Nested instruction is expected to def a vreg");
2274 for (auto &OP : Operands[0]->predicates())
2275 OP.reset();
2276 Operands[0]->eraseNullPredicates();
2277 }
Roman Tereshinb1ba1272018-05-23 19:16:59 +00002278 for (auto &OM : Operands) {
2279 for (auto &OP : OM->predicates())
2280 if (isa<LLTOperandMatcher>(OP))
2281 Stash.push_back(std::move(OP));
2282 OM->eraseNullPredicates();
2283 }
Roman Tereshin19da6672018-05-22 04:31:50 +00002284 while (!Stash.empty())
2285 prependPredicate(Stash.pop_back_val());
2286}
2287
Daniel Sanders43c882c2017-02-01 10:53:10 +00002288//===- Actions ------------------------------------------------------------===//
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002289class OperandRenderer {
2290public:
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002291 enum RendererKind {
2292 OR_Copy,
Daniel Sandersd66e0902017-10-23 18:19:24 +00002293 OR_CopyOrAddZeroReg,
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002294 OR_CopySubReg,
Matt Arsenault3e45c702019-09-06 20:32:37 +00002295 OR_CopyPhysReg,
Daniel Sanders05540042017-08-08 10:44:31 +00002296 OR_CopyConstantAsImm,
Daniel Sanders11300ce2017-10-13 21:28:03 +00002297 OR_CopyFConstantAsFPImm,
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002298 OR_Imm,
Matt Arsenault4a23ae52019-09-10 17:57:33 +00002299 OR_SubRegIndex,
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002300 OR_Register,
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002301 OR_TempRegister,
Volkan Kelesf7f25682018-01-16 18:44:05 +00002302 OR_ComplexPattern,
2303 OR_Custom
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002304 };
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002305
2306protected:
2307 RendererKind Kind;
2308
2309public:
2310 OperandRenderer(RendererKind Kind) : Kind(Kind) {}
2311 virtual ~OperandRenderer() {}
2312
2313 RendererKind getKind() const { return Kind; }
2314
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002315 virtual void emitRenderOpcodes(MatchTable &Table,
2316 RuleMatcher &Rule) const = 0;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002317};
2318
2319/// A CopyRenderer emits code to copy a single operand from an existing
2320/// instruction to the one being built.
2321class CopyRenderer : public OperandRenderer {
2322protected:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002323 unsigned NewInsnID;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002324 /// The name of the operand.
2325 const StringRef SymbolicName;
2326
2327public:
Daniel Sandersbd83ad42017-10-24 01:48:34 +00002328 CopyRenderer(unsigned NewInsnID, StringRef SymbolicName)
2329 : OperandRenderer(OR_Copy), NewInsnID(NewInsnID),
Daniel Sanders05540042017-08-08 10:44:31 +00002330 SymbolicName(SymbolicName) {
2331 assert(!SymbolicName.empty() && "Cannot copy from an unspecified source");
2332 }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002333
2334 static bool classof(const OperandRenderer *R) {
2335 return R->getKind() == OR_Copy;
2336 }
2337
2338 const StringRef getSymbolicName() const { return SymbolicName; }
2339
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002340 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002341 const OperandMatcher &Operand = Rule.getOperandMatcher(SymbolicName);
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002342 unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002343 Table << MatchTable::Opcode("GIR_Copy") << MatchTable::Comment("NewInsnID")
2344 << MatchTable::IntValue(NewInsnID) << MatchTable::Comment("OldInsnID")
2345 << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002346 << MatchTable::IntValue(Operand.getOpIdx())
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002347 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002348 }
2349};
2350
Matt Arsenault3e45c702019-09-06 20:32:37 +00002351/// A CopyRenderer emits code to copy a virtual register to a specific physical
2352/// register.
2353class CopyPhysRegRenderer : public OperandRenderer {
2354protected:
2355 unsigned NewInsnID;
2356 Record *PhysReg;
2357
2358public:
2359 CopyPhysRegRenderer(unsigned NewInsnID, Record *Reg)
2360 : OperandRenderer(OR_CopyPhysReg), NewInsnID(NewInsnID),
2361 PhysReg(Reg) {
2362 assert(PhysReg);
2363 }
2364
2365 static bool classof(const OperandRenderer *R) {
2366 return R->getKind() == OR_CopyPhysReg;
2367 }
2368
2369 Record *getPhysReg() const { return PhysReg; }
2370
2371 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2372 const OperandMatcher &Operand = Rule.getPhysRegOperandMatcher(PhysReg);
2373 unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
2374 Table << MatchTable::Opcode("GIR_Copy") << MatchTable::Comment("NewInsnID")
2375 << MatchTable::IntValue(NewInsnID) << MatchTable::Comment("OldInsnID")
2376 << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
2377 << MatchTable::IntValue(Operand.getOpIdx())
2378 << MatchTable::Comment(PhysReg->getName())
2379 << MatchTable::LineBreak;
2380 }
2381};
2382
Daniel Sandersd66e0902017-10-23 18:19:24 +00002383/// A CopyOrAddZeroRegRenderer emits code to copy a single operand from an
2384/// existing instruction to the one being built. If the operand turns out to be
2385/// a 'G_CONSTANT 0' then it replaces the operand with a zero register.
2386class CopyOrAddZeroRegRenderer : public OperandRenderer {
2387protected:
2388 unsigned NewInsnID;
2389 /// The name of the operand.
2390 const StringRef SymbolicName;
2391 const Record *ZeroRegisterDef;
2392
2393public:
2394 CopyOrAddZeroRegRenderer(unsigned NewInsnID,
Daniel Sandersd66e0902017-10-23 18:19:24 +00002395 StringRef SymbolicName, Record *ZeroRegisterDef)
2396 : OperandRenderer(OR_CopyOrAddZeroReg), NewInsnID(NewInsnID),
2397 SymbolicName(SymbolicName), ZeroRegisterDef(ZeroRegisterDef) {
2398 assert(!SymbolicName.empty() && "Cannot copy from an unspecified source");
2399 }
2400
2401 static bool classof(const OperandRenderer *R) {
2402 return R->getKind() == OR_CopyOrAddZeroReg;
2403 }
2404
2405 const StringRef getSymbolicName() const { return SymbolicName; }
2406
2407 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2408 const OperandMatcher &Operand = Rule.getOperandMatcher(SymbolicName);
2409 unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
2410 Table << MatchTable::Opcode("GIR_CopyOrAddZeroReg")
2411 << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
2412 << MatchTable::Comment("OldInsnID")
2413 << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002414 << MatchTable::IntValue(Operand.getOpIdx())
Daniel Sandersd66e0902017-10-23 18:19:24 +00002415 << MatchTable::NamedValue(
2416 (ZeroRegisterDef->getValue("Namespace")
2417 ? ZeroRegisterDef->getValueAsString("Namespace")
2418 : ""),
2419 ZeroRegisterDef->getName())
2420 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2421 }
2422};
2423
Daniel Sanders05540042017-08-08 10:44:31 +00002424/// A CopyConstantAsImmRenderer emits code to render a G_CONSTANT instruction to
2425/// an extended immediate operand.
2426class CopyConstantAsImmRenderer : public OperandRenderer {
2427protected:
2428 unsigned NewInsnID;
2429 /// The name of the operand.
2430 const std::string SymbolicName;
2431 bool Signed;
2432
2433public:
2434 CopyConstantAsImmRenderer(unsigned NewInsnID, StringRef SymbolicName)
2435 : OperandRenderer(OR_CopyConstantAsImm), NewInsnID(NewInsnID),
2436 SymbolicName(SymbolicName), Signed(true) {}
2437
2438 static bool classof(const OperandRenderer *R) {
2439 return R->getKind() == OR_CopyConstantAsImm;
2440 }
2441
2442 const StringRef getSymbolicName() const { return SymbolicName; }
2443
2444 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002445 InstructionMatcher &InsnMatcher = Rule.getInstructionMatcher(SymbolicName);
Daniel Sanders05540042017-08-08 10:44:31 +00002446 unsigned OldInsnVarID = Rule.getInsnVarID(InsnMatcher);
2447 Table << MatchTable::Opcode(Signed ? "GIR_CopyConstantAsSImm"
2448 : "GIR_CopyConstantAsUImm")
2449 << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
2450 << MatchTable::Comment("OldInsnID")
2451 << MatchTable::IntValue(OldInsnVarID)
2452 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2453 }
2454};
2455
Daniel Sanders11300ce2017-10-13 21:28:03 +00002456/// A CopyFConstantAsFPImmRenderer emits code to render a G_FCONSTANT
2457/// instruction to an extended immediate operand.
2458class CopyFConstantAsFPImmRenderer : public OperandRenderer {
2459protected:
2460 unsigned NewInsnID;
2461 /// The name of the operand.
2462 const std::string SymbolicName;
2463
2464public:
2465 CopyFConstantAsFPImmRenderer(unsigned NewInsnID, StringRef SymbolicName)
2466 : OperandRenderer(OR_CopyFConstantAsFPImm), NewInsnID(NewInsnID),
2467 SymbolicName(SymbolicName) {}
2468
2469 static bool classof(const OperandRenderer *R) {
2470 return R->getKind() == OR_CopyFConstantAsFPImm;
2471 }
2472
2473 const StringRef getSymbolicName() const { return SymbolicName; }
2474
2475 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002476 InstructionMatcher &InsnMatcher = Rule.getInstructionMatcher(SymbolicName);
Daniel Sanders11300ce2017-10-13 21:28:03 +00002477 unsigned OldInsnVarID = Rule.getInsnVarID(InsnMatcher);
2478 Table << MatchTable::Opcode("GIR_CopyFConstantAsFPImm")
2479 << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
2480 << MatchTable::Comment("OldInsnID")
2481 << MatchTable::IntValue(OldInsnVarID)
2482 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2483 }
2484};
2485
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002486/// A CopySubRegRenderer emits code to copy a single register operand from an
2487/// existing instruction to the one being built and indicate that only a
2488/// subregister should be copied.
2489class CopySubRegRenderer : public OperandRenderer {
2490protected:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002491 unsigned NewInsnID;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002492 /// The name of the operand.
2493 const StringRef SymbolicName;
2494 /// The subregister to extract.
2495 const CodeGenSubRegIndex *SubReg;
2496
2497public:
Daniel Sandersbd83ad42017-10-24 01:48:34 +00002498 CopySubRegRenderer(unsigned NewInsnID, StringRef SymbolicName,
2499 const CodeGenSubRegIndex *SubReg)
2500 : OperandRenderer(OR_CopySubReg), NewInsnID(NewInsnID),
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002501 SymbolicName(SymbolicName), SubReg(SubReg) {}
2502
2503 static bool classof(const OperandRenderer *R) {
2504 return R->getKind() == OR_CopySubReg;
2505 }
2506
2507 const StringRef getSymbolicName() const { return SymbolicName; }
2508
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002509 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002510 const OperandMatcher &Operand = Rule.getOperandMatcher(SymbolicName);
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002511 unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002512 Table << MatchTable::Opcode("GIR_CopySubReg")
2513 << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
2514 << MatchTable::Comment("OldInsnID")
2515 << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002516 << MatchTable::IntValue(Operand.getOpIdx())
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002517 << MatchTable::Comment("SubRegIdx")
2518 << MatchTable::IntValue(SubReg->EnumValue)
2519 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002520 }
2521};
2522
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002523/// Adds a specific physical register to the instruction being built.
2524/// This is typically useful for WZR/XZR on AArch64.
2525class AddRegisterRenderer : public OperandRenderer {
2526protected:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002527 unsigned InsnID;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002528 const Record *RegisterDef;
Matt Arsenault3e45c702019-09-06 20:32:37 +00002529 bool IsDef;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002530
2531public:
Matt Arsenault3e45c702019-09-06 20:32:37 +00002532 AddRegisterRenderer(unsigned InsnID, const Record *RegisterDef,
2533 bool IsDef = false)
2534 : OperandRenderer(OR_Register), InsnID(InsnID), RegisterDef(RegisterDef),
2535 IsDef(IsDef) {}
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002536
2537 static bool classof(const OperandRenderer *R) {
2538 return R->getKind() == OR_Register;
2539 }
2540
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002541 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2542 Table << MatchTable::Opcode("GIR_AddRegister")
2543 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2544 << MatchTable::NamedValue(
2545 (RegisterDef->getValue("Namespace")
2546 ? RegisterDef->getValueAsString("Namespace")
2547 : ""),
2548 RegisterDef->getName())
Matt Arsenault3e45c702019-09-06 20:32:37 +00002549 << MatchTable::Comment("AddRegisterRegFlags");
2550
2551 // TODO: This is encoded as a 64-bit element, but only 16 or 32-bits are
2552 // really needed for a physical register reference. We can pack the
2553 // register and flags in a single field.
2554 if (IsDef)
2555 Table << MatchTable::NamedValue("RegState::Define");
2556 else
2557 Table << MatchTable::IntValue(0);
2558 Table << MatchTable::LineBreak;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002559 }
2560};
2561
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002562/// Adds a specific temporary virtual register to the instruction being built.
2563/// This is used to chain instructions together when emitting multiple
2564/// instructions.
2565class TempRegRenderer : public OperandRenderer {
2566protected:
2567 unsigned InsnID;
2568 unsigned TempRegID;
2569 bool IsDef;
2570
2571public:
2572 TempRegRenderer(unsigned InsnID, unsigned TempRegID, bool IsDef = false)
2573 : OperandRenderer(OR_Register), InsnID(InsnID), TempRegID(TempRegID),
2574 IsDef(IsDef) {}
2575
2576 static bool classof(const OperandRenderer *R) {
2577 return R->getKind() == OR_TempRegister;
2578 }
2579
2580 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2581 Table << MatchTable::Opcode("GIR_AddTempRegister")
2582 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2583 << MatchTable::Comment("TempRegID") << MatchTable::IntValue(TempRegID)
2584 << MatchTable::Comment("TempRegFlags");
2585 if (IsDef)
2586 Table << MatchTable::NamedValue("RegState::Define");
2587 else
2588 Table << MatchTable::IntValue(0);
2589 Table << MatchTable::LineBreak;
2590 }
2591};
2592
Daniel Sanders0ed28822017-04-12 08:23:08 +00002593/// Adds a specific immediate to the instruction being built.
2594class ImmRenderer : public OperandRenderer {
2595protected:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002596 unsigned InsnID;
Daniel Sanders0ed28822017-04-12 08:23:08 +00002597 int64_t Imm;
2598
2599public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002600 ImmRenderer(unsigned InsnID, int64_t Imm)
2601 : OperandRenderer(OR_Imm), InsnID(InsnID), Imm(Imm) {}
Daniel Sanders0ed28822017-04-12 08:23:08 +00002602
2603 static bool classof(const OperandRenderer *R) {
2604 return R->getKind() == OR_Imm;
2605 }
2606
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002607 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2608 Table << MatchTable::Opcode("GIR_AddImm") << MatchTable::Comment("InsnID")
2609 << MatchTable::IntValue(InsnID) << MatchTable::Comment("Imm")
2610 << MatchTable::IntValue(Imm) << MatchTable::LineBreak;
Daniel Sanders0ed28822017-04-12 08:23:08 +00002611 }
2612};
2613
Matt Arsenault4a23ae52019-09-10 17:57:33 +00002614/// Adds an enum value for a subreg index to the instruction being built.
2615class SubRegIndexRenderer : public OperandRenderer {
2616protected:
2617 unsigned InsnID;
2618 const CodeGenSubRegIndex *SubRegIdx;
2619
2620public:
2621 SubRegIndexRenderer(unsigned InsnID, const CodeGenSubRegIndex *SRI)
2622 : OperandRenderer(OR_SubRegIndex), InsnID(InsnID), SubRegIdx(SRI) {}
2623
2624 static bool classof(const OperandRenderer *R) {
2625 return R->getKind() == OR_SubRegIndex;
2626 }
2627
2628 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2629 Table << MatchTable::Opcode("GIR_AddImm") << MatchTable::Comment("InsnID")
2630 << MatchTable::IntValue(InsnID) << MatchTable::Comment("SubRegIndex")
2631 << MatchTable::IntValue(SubRegIdx->EnumValue)
2632 << MatchTable::LineBreak;
2633 }
2634};
2635
Daniel Sanders2deea182017-04-22 15:11:04 +00002636/// Adds operands by calling a renderer function supplied by the ComplexPattern
2637/// matcher function.
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002638class RenderComplexPatternOperand : public OperandRenderer {
2639private:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002640 unsigned InsnID;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002641 const Record &TheDef;
Daniel Sanders2deea182017-04-22 15:11:04 +00002642 /// The name of the operand.
2643 const StringRef SymbolicName;
2644 /// The renderer number. This must be unique within a rule since it's used to
2645 /// identify a temporary variable to hold the renderer function.
2646 unsigned RendererID;
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002647 /// When provided, this is the suboperand of the ComplexPattern operand to
2648 /// render. Otherwise all the suboperands will be rendered.
2649 Optional<unsigned> SubOperand;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002650
2651 unsigned getNumOperands() const {
2652 return TheDef.getValueAsDag("Operands")->getNumArgs();
2653 }
2654
2655public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002656 RenderComplexPatternOperand(unsigned InsnID, const Record &TheDef,
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002657 StringRef SymbolicName, unsigned RendererID,
2658 Optional<unsigned> SubOperand = None)
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002659 : OperandRenderer(OR_ComplexPattern), InsnID(InsnID), TheDef(TheDef),
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002660 SymbolicName(SymbolicName), RendererID(RendererID),
2661 SubOperand(SubOperand) {}
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002662
2663 static bool classof(const OperandRenderer *R) {
2664 return R->getKind() == OR_ComplexPattern;
2665 }
2666
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002667 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002668 Table << MatchTable::Opcode(SubOperand.hasValue() ? "GIR_ComplexSubOperandRenderer"
2669 : "GIR_ComplexRenderer")
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002670 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2671 << MatchTable::Comment("RendererID")
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002672 << MatchTable::IntValue(RendererID);
2673 if (SubOperand.hasValue())
2674 Table << MatchTable::Comment("SubOperand")
2675 << MatchTable::IntValue(SubOperand.getValue());
2676 Table << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002677 }
2678};
2679
Volkan Kelesf7f25682018-01-16 18:44:05 +00002680class CustomRenderer : public OperandRenderer {
2681protected:
2682 unsigned InsnID;
2683 const Record &Renderer;
2684 /// The name of the operand.
2685 const std::string SymbolicName;
2686
2687public:
2688 CustomRenderer(unsigned InsnID, const Record &Renderer,
2689 StringRef SymbolicName)
2690 : OperandRenderer(OR_Custom), InsnID(InsnID), Renderer(Renderer),
2691 SymbolicName(SymbolicName) {}
2692
2693 static bool classof(const OperandRenderer *R) {
2694 return R->getKind() == OR_Custom;
2695 }
2696
2697 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002698 InstructionMatcher &InsnMatcher = Rule.getInstructionMatcher(SymbolicName);
Volkan Kelesf7f25682018-01-16 18:44:05 +00002699 unsigned OldInsnVarID = Rule.getInsnVarID(InsnMatcher);
2700 Table << MatchTable::Opcode("GIR_CustomRenderer")
2701 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2702 << MatchTable::Comment("OldInsnID")
2703 << MatchTable::IntValue(OldInsnVarID)
2704 << MatchTable::Comment("Renderer")
2705 << MatchTable::NamedValue(
2706 "GICR_" + Renderer.getValueAsString("RendererFn").str())
2707 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2708 }
2709};
2710
Ahmed Bougacha56ca3a92017-02-04 00:47:10 +00002711/// An action taken when all Matcher predicates succeeded for a parent rule.
2712///
2713/// Typical actions include:
2714/// * Changing the opcode of an instruction.
2715/// * Adding an operand to an instruction.
Daniel Sanders43c882c2017-02-01 10:53:10 +00002716class MatchAction {
2717public:
2718 virtual ~MatchAction() {}
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002719
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002720 /// Emit the MatchTable opcodes to implement the action.
Daniel Sandersa7b75262017-10-31 18:50:24 +00002721 virtual void emitActionOpcodes(MatchTable &Table,
2722 RuleMatcher &Rule) const = 0;
Daniel Sanders43c882c2017-02-01 10:53:10 +00002723};
2724
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +00002725/// Generates a comment describing the matched rule being acted upon.
2726class DebugCommentAction : public MatchAction {
2727private:
Daniel Sanders6ea17ed2017-10-31 18:07:03 +00002728 std::string S;
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +00002729
2730public:
Daniel Sanders6ea17ed2017-10-31 18:07:03 +00002731 DebugCommentAction(StringRef S) : S(S) {}
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +00002732
Daniel Sandersa7b75262017-10-31 18:50:24 +00002733 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sanders6ea17ed2017-10-31 18:07:03 +00002734 Table << MatchTable::Comment(S) << MatchTable::LineBreak;
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +00002735 }
2736};
2737
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002738/// Generates code to build an instruction or mutate an existing instruction
2739/// into the desired instruction when this is possible.
2740class BuildMIAction : public MatchAction {
Daniel Sanders43c882c2017-02-01 10:53:10 +00002741private:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002742 unsigned InsnID;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002743 const CodeGenInstruction *I;
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002744 InstructionMatcher *Matched;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002745 std::vector<std::unique_ptr<OperandRenderer>> OperandRenderers;
2746
2747 /// True if the instruction can be built solely by mutating the opcode.
Daniel Sandersa7b75262017-10-31 18:50:24 +00002748 bool canMutate(RuleMatcher &Rule, const InstructionMatcher *Insn) const {
2749 if (!Insn)
Daniel Sandersab1d1192017-10-24 18:11:54 +00002750 return false;
2751
Daniel Sandersa7b75262017-10-31 18:50:24 +00002752 if (OperandRenderers.size() != Insn->getNumOperands())
Daniel Sanderse9fdba32017-04-29 17:30:09 +00002753 return false;
2754
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002755 for (const auto &Renderer : enumerate(OperandRenderers)) {
Zachary Turner309a0882017-03-13 16:24:10 +00002756 if (const auto *Copy = dyn_cast<CopyRenderer>(&*Renderer.value())) {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002757 const OperandMatcher &OM = Rule.getOperandMatcher(Copy->getSymbolicName());
Daniel Sandersa7b75262017-10-31 18:50:24 +00002758 if (Insn != &OM.getInstructionMatcher() ||
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002759 OM.getOpIdx() != Renderer.index())
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002760 return false;
2761 } else
2762 return false;
2763 }
2764
2765 return true;
2766 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002767
Daniel Sanders43c882c2017-02-01 10:53:10 +00002768public:
Daniel Sandersa7b75262017-10-31 18:50:24 +00002769 BuildMIAction(unsigned InsnID, const CodeGenInstruction *I)
2770 : InsnID(InsnID), I(I), Matched(nullptr) {}
2771
Daniel Sanders08464522018-01-29 21:09:12 +00002772 unsigned getInsnID() const { return InsnID; }
Daniel Sandersdf258e32017-10-31 19:09:29 +00002773 const CodeGenInstruction *getCGI() const { return I; }
2774
Daniel Sandersa7b75262017-10-31 18:50:24 +00002775 void chooseInsnToMutate(RuleMatcher &Rule) {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002776 for (auto *MutateCandidate : Rule.mutatable_insns()) {
Daniel Sandersa7b75262017-10-31 18:50:24 +00002777 if (canMutate(Rule, MutateCandidate)) {
2778 // Take the first one we're offered that we're able to mutate.
2779 Rule.reserveInsnMatcherForMutation(MutateCandidate);
2780 Matched = MutateCandidate;
2781 return;
2782 }
2783 }
2784 }
Daniel Sanders43c882c2017-02-01 10:53:10 +00002785
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002786 template <class Kind, class... Args>
2787 Kind &addRenderer(Args&&... args) {
2788 OperandRenderers.emplace_back(
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00002789 std::make_unique<Kind>(InsnID, std::forward<Args>(args)...));
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002790 return *static_cast<Kind *>(OperandRenderers.back().get());
2791 }
2792
Daniel Sandersa7b75262017-10-31 18:50:24 +00002793 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2794 if (Matched) {
2795 assert(canMutate(Rule, Matched) &&
2796 "Arranged to mutate an insn that isn't mutatable");
2797
2798 unsigned RecycleInsnID = Rule.getInsnVarID(*Matched);
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002799 Table << MatchTable::Opcode("GIR_MutateOpcode")
2800 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2801 << MatchTable::Comment("RecycleInsnID")
2802 << MatchTable::IntValue(RecycleInsnID)
2803 << MatchTable::Comment("Opcode")
2804 << MatchTable::NamedValue(I->Namespace, I->TheDef->getName())
2805 << MatchTable::LineBreak;
Tim Northover4340d642017-03-20 21:58:23 +00002806
2807 if (!I->ImplicitDefs.empty() || !I->ImplicitUses.empty()) {
Tim Northover4340d642017-03-20 21:58:23 +00002808 for (auto Def : I->ImplicitDefs) {
Diana Picus8abcbbb2017-05-02 09:40:49 +00002809 auto Namespace = Def->getValue("Namespace")
2810 ? Def->getValueAsString("Namespace")
2811 : "";
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002812 Table << MatchTable::Opcode("GIR_AddImplicitDef")
2813 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2814 << MatchTable::NamedValue(Namespace, Def->getName())
2815 << MatchTable::LineBreak;
Tim Northover4340d642017-03-20 21:58:23 +00002816 }
2817 for (auto Use : I->ImplicitUses) {
Diana Picus8abcbbb2017-05-02 09:40:49 +00002818 auto Namespace = Use->getValue("Namespace")
2819 ? Use->getValueAsString("Namespace")
2820 : "";
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002821 Table << MatchTable::Opcode("GIR_AddImplicitUse")
2822 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2823 << MatchTable::NamedValue(Namespace, Use->getName())
2824 << MatchTable::LineBreak;
Tim Northover4340d642017-03-20 21:58:23 +00002825 }
2826 }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002827 return;
2828 }
2829
2830 // TODO: Simple permutation looks like it could be almost as common as
2831 // mutation due to commutative operations.
2832
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002833 Table << MatchTable::Opcode("GIR_BuildMI") << MatchTable::Comment("InsnID")
2834 << MatchTable::IntValue(InsnID) << MatchTable::Comment("Opcode")
2835 << MatchTable::NamedValue(I->Namespace, I->TheDef->getName())
2836 << MatchTable::LineBreak;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002837 for (const auto &Renderer : OperandRenderers)
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002838 Renderer->emitRenderOpcodes(Table, Rule);
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002839
Florian Hahn3bc3ec62017-08-03 14:48:22 +00002840 if (I->mayLoad || I->mayStore) {
2841 Table << MatchTable::Opcode("GIR_MergeMemOperands")
2842 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2843 << MatchTable::Comment("MergeInsnID's");
2844 // Emit the ID's for all the instructions that are matched by this rule.
2845 // TODO: Limit this to matched instructions that mayLoad/mayStore or have
2846 // some other means of having a memoperand. Also limit this to
2847 // emitted instructions that expect to have a memoperand too. For
2848 // example, (G_SEXT (G_LOAD x)) that results in separate load and
2849 // sign-extend instructions shouldn't put the memoperand on the
2850 // sign-extend since it has no effect there.
2851 std::vector<unsigned> MergeInsnIDs;
2852 for (const auto &IDMatcherPair : Rule.defined_insn_vars())
2853 MergeInsnIDs.push_back(IDMatcherPair.second);
Fangrui Song0cac7262018-09-27 02:13:45 +00002854 llvm::sort(MergeInsnIDs);
Florian Hahn3bc3ec62017-08-03 14:48:22 +00002855 for (const auto &MergeInsnID : MergeInsnIDs)
2856 Table << MatchTable::IntValue(MergeInsnID);
Daniel Sanders05540042017-08-08 10:44:31 +00002857 Table << MatchTable::NamedValue("GIU_MergeMemOperands_EndOfList")
2858 << MatchTable::LineBreak;
Florian Hahn3bc3ec62017-08-03 14:48:22 +00002859 }
2860
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002861 // FIXME: This is a hack but it's sufficient for ISel. We'll need to do
2862 // better for combines. Particularly when there are multiple match
2863 // roots.
2864 if (InsnID == 0)
2865 Table << MatchTable::Opcode("GIR_EraseFromParent")
2866 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2867 << MatchTable::LineBreak;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002868 }
2869};
2870
2871/// Generates code to constrain the operands of an output instruction to the
2872/// register classes specified by the definition of that instruction.
2873class ConstrainOperandsToDefinitionAction : public MatchAction {
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002874 unsigned InsnID;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002875
2876public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002877 ConstrainOperandsToDefinitionAction(unsigned InsnID) : InsnID(InsnID) {}
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002878
Daniel Sandersa7b75262017-10-31 18:50:24 +00002879 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002880 Table << MatchTable::Opcode("GIR_ConstrainSelectedInstOperands")
2881 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2882 << MatchTable::LineBreak;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002883 }
2884};
2885
2886/// Generates code to constrain the specified operand of an output instruction
2887/// to the specified register class.
2888class ConstrainOperandToRegClassAction : public MatchAction {
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002889 unsigned InsnID;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002890 unsigned OpIdx;
2891 const CodeGenRegisterClass &RC;
2892
2893public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002894 ConstrainOperandToRegClassAction(unsigned InsnID, unsigned OpIdx,
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002895 const CodeGenRegisterClass &RC)
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002896 : InsnID(InsnID), OpIdx(OpIdx), RC(RC) {}
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002897
Daniel Sandersa7b75262017-10-31 18:50:24 +00002898 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002899 Table << MatchTable::Opcode("GIR_ConstrainOperandRC")
2900 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2901 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
2902 << MatchTable::Comment("RC " + RC.getName())
2903 << MatchTable::IntValue(RC.EnumValue) << MatchTable::LineBreak;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002904 }
2905};
2906
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002907/// Generates code to create a temporary register which can be used to chain
2908/// instructions together.
2909class MakeTempRegisterAction : public MatchAction {
2910private:
2911 LLTCodeGen Ty;
2912 unsigned TempRegID;
2913
2914public:
2915 MakeTempRegisterAction(const LLTCodeGen &Ty, unsigned TempRegID)
Matt Arsenault4a23ae52019-09-10 17:57:33 +00002916 : Ty(Ty), TempRegID(TempRegID) {
2917 KnownTypes.insert(Ty);
2918 }
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002919
2920 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2921 Table << MatchTable::Opcode("GIR_MakeTempReg")
2922 << MatchTable::Comment("TempRegID") << MatchTable::IntValue(TempRegID)
2923 << MatchTable::Comment("TypeID")
2924 << MatchTable::NamedValue(Ty.getCxxEnumValue())
2925 << MatchTable::LineBreak;
2926 }
2927};
2928
Daniel Sanders05540042017-08-08 10:44:31 +00002929InstructionMatcher &RuleMatcher::addInstructionMatcher(StringRef SymbolicName) {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002930 Matchers.emplace_back(new InstructionMatcher(*this, SymbolicName));
Daniel Sandersa7b75262017-10-31 18:50:24 +00002931 MutatableInsns.insert(Matchers.back().get());
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002932 return *Matchers.back();
2933}
Ahmed Bougacha56ca3a92017-02-04 00:47:10 +00002934
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002935void RuleMatcher::addRequiredFeature(Record *Feature) {
2936 RequiredFeatures.push_back(Feature);
2937}
2938
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002939const std::vector<Record *> &RuleMatcher::getRequiredFeatures() const {
2940 return RequiredFeatures;
2941}
2942
Daniel Sanders7438b262017-10-31 23:03:18 +00002943// Emplaces an action of the specified Kind at the end of the action list.
2944//
2945// Returns a reference to the newly created action.
2946//
2947// Like std::vector::emplace_back(), may invalidate all iterators if the new
2948// size exceeds the capacity. Otherwise, only invalidates the past-the-end
2949// iterator.
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002950template <class Kind, class... Args>
2951Kind &RuleMatcher::addAction(Args &&... args) {
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00002952 Actions.emplace_back(std::make_unique<Kind>(std::forward<Args>(args)...));
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002953 return *static_cast<Kind *>(Actions.back().get());
2954}
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002955
Daniel Sanders7438b262017-10-31 23:03:18 +00002956// Emplaces an action of the specified Kind before the given insertion point.
2957//
2958// Returns an iterator pointing at the newly created instruction.
2959//
2960// Like std::vector::insert(), may invalidate all iterators if the new size
2961// exceeds the capacity. Otherwise, only invalidates the iterators from the
2962// insertion point onwards.
2963template <class Kind, class... Args>
2964action_iterator RuleMatcher::insertAction(action_iterator InsertPt,
2965 Args &&... args) {
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002966 return Actions.emplace(InsertPt,
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00002967 std::make_unique<Kind>(std::forward<Args>(args)...));
Daniel Sanders7438b262017-10-31 23:03:18 +00002968}
Daniel Sandersdc662ff2017-01-26 11:10:14 +00002969
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002970unsigned RuleMatcher::implicitlyDefineInsnVar(InstructionMatcher &Matcher) {
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002971 unsigned NewInsnVarID = NextInsnVarID++;
2972 InsnVariableIDs[&Matcher] = NewInsnVarID;
2973 return NewInsnVarID;
Daniel Sandersb96f40d2017-03-20 15:20:42 +00002974}
2975
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002976unsigned RuleMatcher::getInsnVarID(InstructionMatcher &InsnMatcher) const {
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002977 const auto &I = InsnVariableIDs.find(&InsnMatcher);
2978 if (I != InsnVariableIDs.end())
Daniel Sandersb96f40d2017-03-20 15:20:42 +00002979 return I->second;
2980 llvm_unreachable("Matched Insn was not captured in a local variable");
2981}
2982
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002983void RuleMatcher::defineOperand(StringRef SymbolicName, OperandMatcher &OM) {
2984 if (DefinedOperands.find(SymbolicName) == DefinedOperands.end()) {
2985 DefinedOperands[SymbolicName] = &OM;
2986 return;
2987 }
2988
2989 // If the operand is already defined, then we must ensure both references in
2990 // the matcher have the exact same node.
2991 OM.addPredicate<SameOperandMatcher>(OM.getSymbolicName());
2992}
2993
Matt Arsenault3e45c702019-09-06 20:32:37 +00002994void RuleMatcher::definePhysRegOperand(Record *Reg, OperandMatcher &OM) {
2995 if (PhysRegOperands.find(Reg) == PhysRegOperands.end()) {
2996 PhysRegOperands[Reg] = &OM;
2997 return;
2998 }
2999}
3000
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003001InstructionMatcher &
Daniel Sanders05540042017-08-08 10:44:31 +00003002RuleMatcher::getInstructionMatcher(StringRef SymbolicName) const {
3003 for (const auto &I : InsnVariableIDs)
3004 if (I.first->getSymbolicName() == SymbolicName)
3005 return *I.first;
3006 llvm_unreachable(
3007 ("Failed to lookup instruction " + SymbolicName).str().c_str());
3008}
3009
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003010const OperandMatcher &
Matt Arsenault3e45c702019-09-06 20:32:37 +00003011RuleMatcher::getPhysRegOperandMatcher(Record *Reg) const {
3012 const auto &I = PhysRegOperands.find(Reg);
3013
3014 if (I == PhysRegOperands.end()) {
3015 PrintFatalError(SrcLoc, "Register " + Reg->getName() +
3016 " was not declared in matcher");
3017 }
3018
3019 return *I->second;
3020}
3021
3022const OperandMatcher &
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003023RuleMatcher::getOperandMatcher(StringRef Name) const {
3024 const auto &I = DefinedOperands.find(Name);
3025
3026 if (I == DefinedOperands.end())
3027 PrintFatalError(SrcLoc, "Operand " + Name + " was not declared in matcher");
3028
3029 return *I->second;
3030}
3031
Daniel Sanders8e82af22017-07-27 11:03:45 +00003032void RuleMatcher::emit(MatchTable &Table) {
Daniel Sandersbdfebb82017-03-15 20:18:38 +00003033 if (Matchers.empty())
3034 llvm_unreachable("Unexpected empty matcher!");
Daniel Sandersdc662ff2017-01-26 11:10:14 +00003035
Daniel Sandersbdfebb82017-03-15 20:18:38 +00003036 // The representation supports rules that require multiple roots such as:
3037 // %ptr(p0) = ...
3038 // %elt0(s32) = G_LOAD %ptr
3039 // %1(p0) = G_ADD %ptr, 4
3040 // %elt1(s32) = G_LOAD p0 %1
3041 // which could be usefully folded into:
3042 // %ptr(p0) = ...
3043 // %elt0(s32), %elt1(s32) = TGT_LOAD_PAIR %ptr
3044 // on some targets but we don't need to make use of that yet.
3045 assert(Matchers.size() == 1 && "Cannot handle multi-root matchers yet");
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003046
Daniel Sanders8e82af22017-07-27 11:03:45 +00003047 unsigned LabelID = Table.allocateLabelID();
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00003048 Table << MatchTable::Opcode("GIM_Try", +1)
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003049 << MatchTable::Comment("On fail goto")
3050 << MatchTable::JumpTarget(LabelID)
3051 << MatchTable::Comment(("Rule ID " + Twine(RuleID) + " //").str())
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00003052 << MatchTable::LineBreak;
3053
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003054 if (!RequiredFeatures.empty()) {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00003055 Table << MatchTable::Opcode("GIM_CheckFeatures")
3056 << MatchTable::NamedValue(getNameForFeatureBitset(RequiredFeatures))
3057 << MatchTable::LineBreak;
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003058 }
Daniel Sandersb96f40d2017-03-20 15:20:42 +00003059
Quentin Colombetaad20be2017-12-15 23:07:42 +00003060 Matchers.front()->emitPredicateOpcodes(Table, *this);
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003061
Daniel Sandersbee57392017-04-04 13:25:23 +00003062 // We must also check if it's safe to fold the matched instructions.
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003063 if (InsnVariableIDs.size() >= 2) {
Galina Kistanova1754fee2017-05-25 01:51:53 +00003064 // Invert the map to create stable ordering (by var names)
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003065 SmallVector<unsigned, 2> InsnIDs;
3066 for (const auto &Pair : InsnVariableIDs) {
Daniel Sandersbee57392017-04-04 13:25:23 +00003067 // Skip the root node since it isn't moving anywhere. Everything else is
3068 // sinking to meet it.
3069 if (Pair.first == Matchers.front().get())
3070 continue;
3071
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003072 InsnIDs.push_back(Pair.second);
Galina Kistanova1754fee2017-05-25 01:51:53 +00003073 }
Fangrui Song0cac7262018-09-27 02:13:45 +00003074 llvm::sort(InsnIDs);
Galina Kistanova1754fee2017-05-25 01:51:53 +00003075
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003076 for (const auto &InsnID : InsnIDs) {
Daniel Sandersbee57392017-04-04 13:25:23 +00003077 // Reject the difficult cases until we have a more accurate check.
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00003078 Table << MatchTable::Opcode("GIM_CheckIsSafeToFold")
3079 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
3080 << MatchTable::LineBreak;
Daniel Sandersbee57392017-04-04 13:25:23 +00003081
3082 // FIXME: Emit checks to determine it's _actually_ safe to fold and/or
3083 // account for unsafe cases.
3084 //
3085 // Example:
3086 // MI1--> %0 = ...
3087 // %1 = ... %0
3088 // MI0--> %2 = ... %0
3089 // It's not safe to erase MI1. We currently handle this by not
3090 // erasing %0 (even when it's dead).
3091 //
3092 // Example:
3093 // MI1--> %0 = load volatile @a
3094 // %1 = load volatile @a
3095 // MI0--> %2 = ... %0
3096 // It's not safe to sink %0's def past %1. We currently handle
3097 // this by rejecting all loads.
3098 //
3099 // Example:
3100 // MI1--> %0 = load @a
3101 // %1 = store @a
3102 // MI0--> %2 = ... %0
3103 // It's not safe to sink %0's def past %1. We currently handle
3104 // this by rejecting all loads.
3105 //
3106 // Example:
3107 // G_CONDBR %cond, @BB1
3108 // BB0:
3109 // MI1--> %0 = load @a
3110 // G_BR @BB1
3111 // BB1:
3112 // MI0--> %2 = ... %0
3113 // It's not always safe to sink %0 across control flow. In this
3114 // case it may introduce a memory fault. We currentl handle this
3115 // by rejecting all loads.
3116 }
3117 }
3118
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003119 for (const auto &PM : EpilogueMatchers)
3120 PM->emitPredicateOpcodes(Table, *this);
3121
Daniel Sandersd93a35a2017-07-05 09:39:33 +00003122 for (const auto &MA : Actions)
Daniel Sandersa7b75262017-10-31 18:50:24 +00003123 MA->emitActionOpcodes(Table, *this);
Daniel Sandersf76f3152017-11-16 00:46:35 +00003124
Roman Tereshinbeb39312018-05-02 20:15:11 +00003125 if (Table.isWithCoverage())
Daniel Sandersf76f3152017-11-16 00:46:35 +00003126 Table << MatchTable::Opcode("GIR_Coverage") << MatchTable::IntValue(RuleID)
3127 << MatchTable::LineBreak;
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003128 else
3129 Table << MatchTable::Comment(("GIR_Coverage, " + Twine(RuleID) + ",").str())
3130 << MatchTable::LineBreak;
Daniel Sandersf76f3152017-11-16 00:46:35 +00003131
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00003132 Table << MatchTable::Opcode("GIR_Done", -1) << MatchTable::LineBreak
Daniel Sanders8e82af22017-07-27 11:03:45 +00003133 << MatchTable::Label(LabelID);
Volkan Keles4f3fa792018-01-25 00:18:52 +00003134 ++NumPatternEmitted;
Daniel Sandersbdfebb82017-03-15 20:18:38 +00003135}
Daniel Sanders43c882c2017-02-01 10:53:10 +00003136
Daniel Sandersbdfebb82017-03-15 20:18:38 +00003137bool RuleMatcher::isHigherPriorityThan(const RuleMatcher &B) const {
3138 // Rules involving more match roots have higher priority.
3139 if (Matchers.size() > B.Matchers.size())
3140 return true;
3141 if (Matchers.size() < B.Matchers.size())
Daniel Sanders759ff412017-02-24 13:58:11 +00003142 return false;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00003143
Daniel Sandersbdfebb82017-03-15 20:18:38 +00003144 for (const auto &Matcher : zip(Matchers, B.Matchers)) {
3145 if (std::get<0>(Matcher)->isHigherPriorityThan(*std::get<1>(Matcher)))
3146 return true;
3147 if (std::get<1>(Matcher)->isHigherPriorityThan(*std::get<0>(Matcher)))
3148 return false;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00003149 }
Daniel Sandersbdfebb82017-03-15 20:18:38 +00003150
3151 return false;
Simon Pilgrima7d1da82017-03-15 22:50:47 +00003152}
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003153
Daniel Sanders2deea182017-04-22 15:11:04 +00003154unsigned RuleMatcher::countRendererFns() const {
Daniel Sandersbdfebb82017-03-15 20:18:38 +00003155 return std::accumulate(
3156 Matchers.begin(), Matchers.end(), 0,
3157 [](unsigned A, const std::unique_ptr<InstructionMatcher> &Matcher) {
Daniel Sanders2deea182017-04-22 15:11:04 +00003158 return A + Matcher->countRendererFns();
Daniel Sandersbdfebb82017-03-15 20:18:38 +00003159 });
3160}
3161
Daniel Sanders05540042017-08-08 10:44:31 +00003162bool OperandPredicateMatcher::isHigherPriorityThan(
3163 const OperandPredicateMatcher &B) const {
3164 // Generally speaking, an instruction is more important than an Int or a
3165 // LiteralInt because it can cover more nodes but theres an exception to
3166 // this. G_CONSTANT's are less important than either of those two because they
3167 // are more permissive.
Daniel Sandersedd07842017-08-17 09:26:14 +00003168
3169 const InstructionOperandMatcher *AOM =
3170 dyn_cast<InstructionOperandMatcher>(this);
3171 const InstructionOperandMatcher *BOM =
3172 dyn_cast<InstructionOperandMatcher>(&B);
3173 bool AIsConstantInsn = AOM && AOM->getInsnMatcher().isConstantInstruction();
3174 bool BIsConstantInsn = BOM && BOM->getInsnMatcher().isConstantInstruction();
3175
3176 if (AOM && BOM) {
3177 // The relative priorities between a G_CONSTANT and any other instruction
3178 // don't actually matter but this code is needed to ensure a strict weak
3179 // ordering. This is particularly important on Windows where the rules will
3180 // be incorrectly sorted without it.
3181 if (AIsConstantInsn != BIsConstantInsn)
3182 return AIsConstantInsn < BIsConstantInsn;
3183 return false;
Daniel Sanders05540042017-08-08 10:44:31 +00003184 }
Daniel Sandersedd07842017-08-17 09:26:14 +00003185
3186 if (AOM && AIsConstantInsn && (B.Kind == OPM_Int || B.Kind == OPM_LiteralInt))
3187 return false;
3188 if (BOM && BIsConstantInsn && (Kind == OPM_Int || Kind == OPM_LiteralInt))
3189 return true;
Daniel Sanders05540042017-08-08 10:44:31 +00003190
3191 return Kind < B.Kind;
Daniel Sanders75b84fc2017-08-08 13:21:26 +00003192}
Daniel Sanders05540042017-08-08 10:44:31 +00003193
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003194void SameOperandMatcher::emitPredicateOpcodes(MatchTable &Table,
Quentin Colombetaad20be2017-12-15 23:07:42 +00003195 RuleMatcher &Rule) const {
Daniel Sanders1e4569f2017-10-20 20:55:29 +00003196 const OperandMatcher &OtherOM = Rule.getOperandMatcher(MatchingName);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003197 unsigned OtherInsnVarID = Rule.getInsnVarID(OtherOM.getInstructionMatcher());
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003198 assert(OtherInsnVarID == OtherOM.getInstructionMatcher().getInsnVarID());
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003199
3200 Table << MatchTable::Opcode("GIM_CheckIsSameOperand")
3201 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
3202 << MatchTable::Comment("OpIdx") << MatchTable::IntValue(OpIdx)
3203 << MatchTable::Comment("OtherMI")
3204 << MatchTable::IntValue(OtherInsnVarID)
3205 << MatchTable::Comment("OtherOpIdx")
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003206 << MatchTable::IntValue(OtherOM.getOpIdx())
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003207 << MatchTable::LineBreak;
3208}
3209
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003210//===- GlobalISelEmitter class --------------------------------------------===//
3211
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003212class GlobalISelEmitter {
3213public:
3214 explicit GlobalISelEmitter(RecordKeeper &RK);
3215 void run(raw_ostream &OS);
3216
3217private:
3218 const RecordKeeper &RK;
3219 const CodeGenDAGPatterns CGP;
3220 const CodeGenTarget &Target;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00003221 CodeGenRegBank CGRegs;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003222
Daniel Sanders39690bd2017-10-15 02:41:12 +00003223 /// Keep track of the equivalence between SDNodes and Instruction by mapping
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003224 /// SDNodes to the GINodeEquiv mapping. We need to map to the GINodeEquiv to
3225 /// check for attributes on the relation such as CheckMMOIsNonAtomic.
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003226 /// This is defined using 'GINodeEquiv' in the target description.
Daniel Sanders39690bd2017-10-15 02:41:12 +00003227 DenseMap<Record *, Record *> NodeEquivs;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003228
Daniel Sanders8a4bae92017-03-14 21:32:08 +00003229 /// Keep track of the equivalence between ComplexPattern's and
3230 /// GIComplexOperandMatcher. Map entries are specified by subclassing
3231 /// GIComplexPatternEquiv.
3232 DenseMap<const Record *, const Record *> ComplexPatternEquivs;
3233
Volkan Kelesf7f25682018-01-16 18:44:05 +00003234 /// Keep track of the equivalence between SDNodeXForm's and
3235 /// GICustomOperandRenderer. Map entries are specified by subclassing
3236 /// GISDNodeXFormEquiv.
3237 DenseMap<const Record *, const Record *> SDNodeXFormEquivs;
3238
Aditya Nandakumarb63e7632018-02-16 22:37:15 +00003239 /// Keep track of Scores of PatternsToMatch similar to how the DAG does.
3240 /// This adds compatibility for RuleMatchers to use this for ordering rules.
3241 DenseMap<uint64_t, int> RuleMatcherScores;
3242
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003243 // Map of predicates to their subtarget features.
Daniel Sanderse9fdba32017-04-29 17:30:09 +00003244 SubtargetFeatureInfoMap SubtargetFeatures;
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003245
Daniel Sandersf76f3152017-11-16 00:46:35 +00003246 // Rule coverage information.
3247 Optional<CodeGenCoverage> RuleCoverage;
3248
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003249 void gatherOpcodeValues();
3250 void gatherTypeIDValues();
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003251 void gatherNodeEquivs();
Daniel Sanders8ead1292018-06-15 23:13:43 +00003252
Daniel Sanders39690bd2017-10-15 02:41:12 +00003253 Record *findNodeEquiv(Record *N) const;
Daniel Sandersf84bc372018-05-05 20:53:24 +00003254 const CodeGenInstruction *getEquivNode(Record &Equiv,
Florian Hahn6b1db822018-06-14 20:32:58 +00003255 const TreePatternNode *N) const;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003256
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003257 Error importRulePredicates(RuleMatcher &M, ArrayRef<Predicate> Predicates);
Daniel Sanders8ead1292018-06-15 23:13:43 +00003258 Expected<InstructionMatcher &>
3259 createAndImportSelDAGMatcher(RuleMatcher &Rule,
3260 InstructionMatcher &InsnMatcher,
3261 const TreePatternNode *Src, unsigned &TempOpIdx);
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003262 Error importComplexPatternOperandMatcher(OperandMatcher &OM, Record *R,
3263 unsigned &TempOpIdx) const;
3264 Error importChildMatcher(RuleMatcher &Rule, InstructionMatcher &InsnMatcher,
Florian Hahn6b1db822018-06-14 20:32:58 +00003265 const TreePatternNode *SrcChild,
Daniel Sandersa71f4542017-10-16 00:56:30 +00003266 bool OperandIsAPointer, unsigned OpIdx,
Daniel Sanders8ead1292018-06-15 23:13:43 +00003267 unsigned &TempOpIdx);
Daniel Sandersdf258e32017-10-31 19:09:29 +00003268
Matt Arsenault3e45c702019-09-06 20:32:37 +00003269 Expected<BuildMIAction &> createAndImportInstructionRenderer(
3270 RuleMatcher &M, InstructionMatcher &InsnMatcher,
3271 const TreePatternNode *Src, const TreePatternNode *Dst);
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003272 Expected<action_iterator> createAndImportSubInstructionRenderer(
Florian Hahn6b1db822018-06-14 20:32:58 +00003273 action_iterator InsertPt, RuleMatcher &M, const TreePatternNode *Dst,
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003274 unsigned TempReg);
Daniel Sanders7438b262017-10-31 23:03:18 +00003275 Expected<action_iterator>
3276 createInstructionRenderer(action_iterator InsertPt, RuleMatcher &M,
Florian Hahn6b1db822018-06-14 20:32:58 +00003277 const TreePatternNode *Dst);
Daniel Sandersdf258e32017-10-31 19:09:29 +00003278 void importExplicitDefRenderers(BuildMIAction &DstMIBuilder);
Matt Arsenault3e45c702019-09-06 20:32:37 +00003279
Daniel Sanders7438b262017-10-31 23:03:18 +00003280 Expected<action_iterator>
3281 importExplicitUseRenderers(action_iterator InsertPt, RuleMatcher &M,
3282 BuildMIAction &DstMIBuilder,
Florian Hahn6b1db822018-06-14 20:32:58 +00003283 const llvm::TreePatternNode *Dst);
Daniel Sanders7438b262017-10-31 23:03:18 +00003284 Expected<action_iterator>
3285 importExplicitUseRenderer(action_iterator InsertPt, RuleMatcher &Rule,
3286 BuildMIAction &DstMIBuilder,
Florian Hahn6b1db822018-06-14 20:32:58 +00003287 TreePatternNode *DstChild);
Sjoerd Meijerde234842019-05-30 07:30:37 +00003288 Error importDefaultOperandRenderers(action_iterator InsertPt, RuleMatcher &M,
3289 BuildMIAction &DstMIBuilder,
Diana Picus382602f2017-05-17 08:57:28 +00003290 DagInit *DefaultOps) const;
Daniel Sandersc270c502017-03-30 09:36:33 +00003291 Error
Daniel Sandersffc7d582017-03-29 15:37:18 +00003292 importImplicitDefRenderers(BuildMIAction &DstMIBuilder,
3293 const std::vector<Record *> &ImplicitDefs) const;
3294
Daniel Sanders8ead1292018-06-15 23:13:43 +00003295 void emitCxxPredicateFns(raw_ostream &OS, StringRef CodeFieldName,
3296 StringRef TypeIdentifier, StringRef ArgType,
3297 StringRef ArgName, StringRef AdditionalDeclarations,
3298 std::function<bool(const Record *R)> Filter);
3299 void emitImmPredicateFns(raw_ostream &OS, StringRef TypeIdentifier,
3300 StringRef ArgType,
3301 std::function<bool(const Record *R)> Filter);
3302 void emitMIPredicateFns(raw_ostream &OS);
Daniel Sanders649c5852017-10-13 20:42:18 +00003303
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003304 /// Analyze pattern \p P, returning a matcher for it if possible.
3305 /// Otherwise, return an Error explaining why we don't support it.
3306 Expected<RuleMatcher> runOnPattern(const PatternToMatch &P);
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003307
3308 void declareSubtargetFeature(Record *Predicate);
Daniel Sanders7e523672017-11-11 03:23:44 +00003309
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003310 MatchTable buildMatchTable(MutableArrayRef<RuleMatcher> Rules, bool Optimize,
3311 bool WithCoverage);
3312
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00003313 /// Infer a CodeGenRegisterClass for the type of \p SuperRegNode. The returned
3314 /// CodeGenRegisterClass will support the CodeGenRegisterClass of
3315 /// \p SubRegNode, and the subregister index defined by \p SubRegIdxNode.
3316 /// If no register class is found, return None.
3317 Optional<const CodeGenRegisterClass *>
Jessica Paquette7080ffa2019-08-28 20:12:31 +00003318 inferSuperRegisterClassForNode(const TypeSetByHwMode &Ty,
3319 TreePatternNode *SuperRegNode,
3320 TreePatternNode *SubRegIdxNode);
Matt Arsenault9ceb6ed2019-09-06 00:05:58 +00003321 Optional<CodeGenSubRegIndex *>
3322 inferSubRegIndexForNode(TreePatternNode *SubRegIdxNode);
Jessica Paquette7080ffa2019-08-28 20:12:31 +00003323
3324 /// Infer a CodeGenRegisterClass which suppoorts \p Ty and \p SubRegIdxNode.
3325 /// Return None if no such class exists.
3326 Optional<const CodeGenRegisterClass *>
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00003327 inferSuperRegisterClass(const TypeSetByHwMode &Ty,
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00003328 TreePatternNode *SubRegIdxNode);
3329
3330 /// Return the CodeGenRegisterClass associated with \p Leaf if it has one.
3331 Optional<const CodeGenRegisterClass *>
3332 getRegClassFromLeaf(TreePatternNode *Leaf);
3333
3334 /// Return a CodeGenRegisterClass for \p N if one can be found. Return None
3335 /// otherwise.
3336 Optional<const CodeGenRegisterClass *>
3337 inferRegClassFromPattern(TreePatternNode *N);
3338
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003339public:
Quentin Colombetec76d9c2017-12-18 19:47:41 +00003340 /// Takes a sequence of \p Rules and group them based on the predicates
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003341 /// they share. \p MatcherStorage is used as a memory container
Hiroshi Inoue501931b2018-01-24 05:04:35 +00003342 /// for the group that are created as part of this process.
Quentin Colombetec76d9c2017-12-18 19:47:41 +00003343 ///
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003344 /// What this optimization does looks like if GroupT = GroupMatcher:
Quentin Colombetec76d9c2017-12-18 19:47:41 +00003345 /// Output without optimization:
3346 /// \verbatim
3347 /// # R1
3348 /// # predicate A
3349 /// # predicate B
3350 /// ...
3351 /// # R2
3352 /// # predicate A // <-- effectively this is going to be checked twice.
3353 /// // Once in R1 and once in R2.
3354 /// # predicate C
3355 /// \endverbatim
3356 /// Output with optimization:
3357 /// \verbatim
3358 /// # Group1_2
3359 /// # predicate A // <-- Check is now shared.
3360 /// # R1
3361 /// # predicate B
3362 /// # R2
3363 /// # predicate C
3364 /// \endverbatim
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003365 template <class GroupT>
3366 static std::vector<Matcher *> optimizeRules(
Roman Tereshin2d6d3762018-05-02 20:08:14 +00003367 ArrayRef<Matcher *> Rules,
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003368 std::vector<std::unique_ptr<Matcher>> &MatcherStorage);
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003369};
3370
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003371void GlobalISelEmitter::gatherOpcodeValues() {
3372 InstructionOpcodeMatcher::initOpcodeValuesMap(Target);
3373}
3374
3375void GlobalISelEmitter::gatherTypeIDValues() {
3376 LLTOperandMatcher::initTypeIDValuesMap();
3377}
3378
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003379void GlobalISelEmitter::gatherNodeEquivs() {
3380 assert(NodeEquivs.empty());
3381 for (Record *Equiv : RK.getAllDerivedDefinitions("GINodeEquiv"))
Daniel Sanders39690bd2017-10-15 02:41:12 +00003382 NodeEquivs[Equiv->getValueAsDef("Node")] = Equiv;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00003383
3384 assert(ComplexPatternEquivs.empty());
3385 for (Record *Equiv : RK.getAllDerivedDefinitions("GIComplexPatternEquiv")) {
3386 Record *SelDAGEquiv = Equiv->getValueAsDef("SelDAGEquivalent");
3387 if (!SelDAGEquiv)
3388 continue;
3389 ComplexPatternEquivs[SelDAGEquiv] = Equiv;
3390 }
Volkan Kelesf7f25682018-01-16 18:44:05 +00003391
3392 assert(SDNodeXFormEquivs.empty());
3393 for (Record *Equiv : RK.getAllDerivedDefinitions("GISDNodeXFormEquiv")) {
3394 Record *SelDAGEquiv = Equiv->getValueAsDef("SelDAGEquivalent");
3395 if (!SelDAGEquiv)
3396 continue;
3397 SDNodeXFormEquivs[SelDAGEquiv] = Equiv;
3398 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003399}
3400
Daniel Sanders39690bd2017-10-15 02:41:12 +00003401Record *GlobalISelEmitter::findNodeEquiv(Record *N) const {
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003402 return NodeEquivs.lookup(N);
3403}
3404
Daniel Sandersf84bc372018-05-05 20:53:24 +00003405const CodeGenInstruction *
Florian Hahn6b1db822018-06-14 20:32:58 +00003406GlobalISelEmitter::getEquivNode(Record &Equiv, const TreePatternNode *N) const {
Matt Arsenault8ec5c102019-08-29 01:13:41 +00003407 if (N->getNumChildren() >= 1) {
3408 // setcc operation maps to two different G_* instructions based on the type.
3409 if (!Equiv.isValueUnset("IfFloatingPoint") &&
3410 MVT(N->getChild(0)->getSimpleType(0)).isFloatingPoint())
3411 return &Target.getInstruction(Equiv.getValueAsDef("IfFloatingPoint"));
3412 }
3413
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00003414 for (const TreePredicateCall &Call : N->getPredicateCalls()) {
3415 const TreePredicateFn &Predicate = Call.Fn;
Daniel Sandersf84bc372018-05-05 20:53:24 +00003416 if (!Equiv.isValueUnset("IfSignExtend") && Predicate.isLoad() &&
3417 Predicate.isSignExtLoad())
3418 return &Target.getInstruction(Equiv.getValueAsDef("IfSignExtend"));
3419 if (!Equiv.isValueUnset("IfZeroExtend") && Predicate.isLoad() &&
3420 Predicate.isZeroExtLoad())
3421 return &Target.getInstruction(Equiv.getValueAsDef("IfZeroExtend"));
3422 }
Matt Arsenault8ec5c102019-08-29 01:13:41 +00003423
Daniel Sandersf84bc372018-05-05 20:53:24 +00003424 return &Target.getInstruction(Equiv.getValueAsDef("I"));
3425}
3426
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003427GlobalISelEmitter::GlobalISelEmitter(RecordKeeper &RK)
Daniel Sandersf84bc372018-05-05 20:53:24 +00003428 : RK(RK), CGP(RK), Target(CGP.getTargetInfo()),
3429 CGRegs(RK, Target.getHwModes()) {}
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003430
3431//===- Emitter ------------------------------------------------------------===//
3432
Daniel Sandersc270c502017-03-30 09:36:33 +00003433Error
Daniel Sandersffc7d582017-03-29 15:37:18 +00003434GlobalISelEmitter::importRulePredicates(RuleMatcher &M,
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003435 ArrayRef<Predicate> Predicates) {
3436 for (const Predicate &P : Predicates) {
Matt Arsenault57ef94f2019-07-30 15:56:43 +00003437 if (!P.Def || P.getCondString().empty())
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003438 continue;
3439 declareSubtargetFeature(P.Def);
3440 M.addRequiredFeature(P.Def);
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003441 }
3442
Daniel Sandersc270c502017-03-30 09:36:33 +00003443 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00003444}
Daniel Sanders8a4bae92017-03-14 21:32:08 +00003445
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003446Expected<InstructionMatcher &> GlobalISelEmitter::createAndImportSelDAGMatcher(
3447 RuleMatcher &Rule, InstructionMatcher &InsnMatcher,
Daniel Sanders8ead1292018-06-15 23:13:43 +00003448 const TreePatternNode *Src, unsigned &TempOpIdx) {
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003449 Record *SrcGIEquivOrNull = nullptr;
3450 const CodeGenInstruction *SrcGIOrNull = nullptr;
3451
3452 // Start with the defined operands (i.e., the results of the root operator).
Florian Hahn6b1db822018-06-14 20:32:58 +00003453 if (Src->getExtTypes().size() > 1)
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003454 return failedImport("Src pattern has multiple results");
3455
Florian Hahn6b1db822018-06-14 20:32:58 +00003456 if (Src->isLeaf()) {
3457 Init *SrcInit = Src->getLeafValue();
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003458 if (isa<IntInit>(SrcInit)) {
3459 InsnMatcher.addPredicate<InstructionOpcodeMatcher>(
3460 &Target.getInstruction(RK.getDef("G_CONSTANT")));
3461 } else
3462 return failedImport(
3463 "Unable to deduce gMIR opcode to handle Src (which is a leaf)");
3464 } else {
Florian Hahn6b1db822018-06-14 20:32:58 +00003465 SrcGIEquivOrNull = findNodeEquiv(Src->getOperator());
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003466 if (!SrcGIEquivOrNull)
3467 return failedImport("Pattern operator lacks an equivalent Instruction" +
Florian Hahn6b1db822018-06-14 20:32:58 +00003468 explainOperator(Src->getOperator()));
Daniel Sandersf84bc372018-05-05 20:53:24 +00003469 SrcGIOrNull = getEquivNode(*SrcGIEquivOrNull, Src);
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003470
3471 // The operators look good: match the opcode
3472 InsnMatcher.addPredicate<InstructionOpcodeMatcher>(SrcGIOrNull);
3473 }
3474
3475 unsigned OpIdx = 0;
Florian Hahn6b1db822018-06-14 20:32:58 +00003476 for (const TypeSetByHwMode &VTy : Src->getExtTypes()) {
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003477 // Results don't have a name unless they are the root node. The caller will
3478 // set the name if appropriate.
3479 OperandMatcher &OM = InsnMatcher.addOperand(OpIdx++, "", TempOpIdx);
3480 if (auto Error = OM.addTypeCheckPredicate(VTy, false /* OperandIsAPointer */))
3481 return failedImport(toString(std::move(Error)) +
3482 " for result of Src pattern operator");
3483 }
3484
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00003485 for (const TreePredicateCall &Call : Src->getPredicateCalls()) {
3486 const TreePredicateFn &Predicate = Call.Fn;
Daniel Sanders2c269f62017-08-24 09:11:20 +00003487 if (Predicate.isAlwaysTrue())
3488 continue;
3489
3490 if (Predicate.isImmediatePattern()) {
3491 InsnMatcher.addPredicate<InstructionImmPredicateMatcher>(Predicate);
3492 continue;
3493 }
3494
Matt Arsenaultd00d8572019-07-15 20:59:42 +00003495 // An address space check is needed in all contexts if there is one.
3496 if (Predicate.isLoad() || Predicate.isStore() || Predicate.isAtomic()) {
3497 if (const ListInit *AddrSpaces = Predicate.getAddressSpaces()) {
3498 SmallVector<unsigned, 4> ParsedAddrSpaces;
3499
3500 for (Init *Val : AddrSpaces->getValues()) {
3501 IntInit *IntVal = dyn_cast<IntInit>(Val);
3502 if (!IntVal)
3503 return failedImport("Address space is not an integer");
3504 ParsedAddrSpaces.push_back(IntVal->getValue());
3505 }
3506
3507 if (!ParsedAddrSpaces.empty()) {
3508 InsnMatcher.addPredicate<MemoryAddressSpacePredicateMatcher>(
3509 0, ParsedAddrSpaces);
3510 }
3511 }
Matt Arsenault52c26242019-07-31 00:14:43 +00003512
3513 int64_t MinAlign = Predicate.getMinAlignment();
3514 if (MinAlign > 0)
3515 InsnMatcher.addPredicate<MemoryAlignmentPredicateMatcher>(0, MinAlign);
Matt Arsenaultd00d8572019-07-15 20:59:42 +00003516 }
3517
3518 // G_LOAD is used for both non-extending and any-extending loads.
Daniel Sandersf84bc372018-05-05 20:53:24 +00003519 if (Predicate.isLoad() && Predicate.isNonExtLoad()) {
3520 InsnMatcher.addPredicate<MemoryVsLLTSizePredicateMatcher>(
3521 0, MemoryVsLLTSizePredicateMatcher::EqualTo, 0);
3522 continue;
3523 }
3524 if (Predicate.isLoad() && Predicate.isAnyExtLoad()) {
3525 InsnMatcher.addPredicate<MemoryVsLLTSizePredicateMatcher>(
3526 0, MemoryVsLLTSizePredicateMatcher::LessThan, 0);
3527 continue;
3528 }
3529
Amara Emerson52e6d522019-08-02 23:33:13 +00003530 if (Predicate.isStore()) {
3531 if (Predicate.isTruncStore()) {
3532 // FIXME: If MemoryVT is set, we end up with 2 checks for the MMO size.
3533 InsnMatcher.addPredicate<MemoryVsLLTSizePredicateMatcher>(
3534 0, MemoryVsLLTSizePredicateMatcher::LessThan, 0);
3535 continue;
3536 }
3537 if (Predicate.isNonTruncStore()) {
3538 // We need to check the sizes match here otherwise we could incorrectly
3539 // match truncating stores with non-truncating ones.
3540 InsnMatcher.addPredicate<MemoryVsLLTSizePredicateMatcher>(
3541 0, MemoryVsLLTSizePredicateMatcher::EqualTo, 0);
3542 }
Matt Arsenault02772492019-07-15 21:15:20 +00003543 }
3544
Daniel Sandersf84bc372018-05-05 20:53:24 +00003545 // No check required. We already did it by swapping the opcode.
3546 if (!SrcGIEquivOrNull->isValueUnset("IfSignExtend") &&
3547 Predicate.isSignExtLoad())
3548 continue;
3549
3550 // No check required. We already did it by swapping the opcode.
3551 if (!SrcGIEquivOrNull->isValueUnset("IfZeroExtend") &&
3552 Predicate.isZeroExtLoad())
Daniel Sandersa71f4542017-10-16 00:56:30 +00003553 continue;
3554
Daniel Sandersd66e0902017-10-23 18:19:24 +00003555 // No check required. G_STORE by itself is a non-extending store.
3556 if (Predicate.isNonTruncStore())
3557 continue;
3558
Daniel Sanders76664652017-11-28 22:07:05 +00003559 if (Predicate.isLoad() || Predicate.isStore() || Predicate.isAtomic()) {
3560 if (Predicate.getMemoryVT() != nullptr) {
3561 Optional<LLTCodeGen> MemTyOrNone =
3562 MVTToLLT(getValueType(Predicate.getMemoryVT()));
Daniel Sandersd66e0902017-10-23 18:19:24 +00003563
Daniel Sanders76664652017-11-28 22:07:05 +00003564 if (!MemTyOrNone)
3565 return failedImport("MemVT could not be converted to LLT");
Daniel Sandersd66e0902017-10-23 18:19:24 +00003566
Daniel Sandersf84bc372018-05-05 20:53:24 +00003567 // MMO's work in bytes so we must take care of unusual types like i1
3568 // don't round down.
3569 unsigned MemSizeInBits =
3570 llvm::alignTo(MemTyOrNone->get().getSizeInBits(), 8);
3571
3572 InsnMatcher.addPredicate<MemorySizePredicateMatcher>(
3573 0, MemSizeInBits / 8);
Daniel Sanders76664652017-11-28 22:07:05 +00003574 continue;
3575 }
3576 }
3577
3578 if (Predicate.isLoad() || Predicate.isStore()) {
3579 // No check required. A G_LOAD/G_STORE is an unindexed load.
3580 if (Predicate.isUnindexed())
3581 continue;
3582 }
3583
3584 if (Predicate.isAtomic()) {
3585 if (Predicate.isAtomicOrderingMonotonic()) {
3586 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3587 "Monotonic");
3588 continue;
3589 }
3590 if (Predicate.isAtomicOrderingAcquire()) {
3591 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>("Acquire");
3592 continue;
3593 }
3594 if (Predicate.isAtomicOrderingRelease()) {
3595 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>("Release");
3596 continue;
3597 }
3598 if (Predicate.isAtomicOrderingAcquireRelease()) {
3599 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3600 "AcquireRelease");
3601 continue;
3602 }
3603 if (Predicate.isAtomicOrderingSequentiallyConsistent()) {
3604 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3605 "SequentiallyConsistent");
3606 continue;
3607 }
Daniel Sanders0c43b3a2017-11-30 21:05:59 +00003608
3609 if (Predicate.isAtomicOrderingAcquireOrStronger()) {
3610 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3611 "Acquire", AtomicOrderingMMOPredicateMatcher::AO_OrStronger);
3612 continue;
3613 }
3614 if (Predicate.isAtomicOrderingWeakerThanAcquire()) {
3615 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3616 "Acquire", AtomicOrderingMMOPredicateMatcher::AO_WeakerThan);
3617 continue;
3618 }
3619
3620 if (Predicate.isAtomicOrderingReleaseOrStronger()) {
3621 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3622 "Release", AtomicOrderingMMOPredicateMatcher::AO_OrStronger);
3623 continue;
3624 }
3625 if (Predicate.isAtomicOrderingWeakerThanRelease()) {
3626 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3627 "Release", AtomicOrderingMMOPredicateMatcher::AO_WeakerThan);
3628 continue;
3629 }
Daniel Sandersd66e0902017-10-23 18:19:24 +00003630 }
3631
Daniel Sanders8ead1292018-06-15 23:13:43 +00003632 if (Predicate.hasGISelPredicateCode()) {
3633 InsnMatcher.addPredicate<GenericInstructionPredicateMatcher>(Predicate);
3634 continue;
3635 }
3636
Daniel Sanders2c269f62017-08-24 09:11:20 +00003637 return failedImport("Src pattern child has predicate (" +
3638 explainPredicates(Src) + ")");
3639 }
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003640 if (SrcGIEquivOrNull && SrcGIEquivOrNull->getValueAsBit("CheckMMOIsNonAtomic"))
3641 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>("NotAtomic");
Matt Arsenault63e6d8d2019-09-09 16:18:07 +00003642 else if (SrcGIEquivOrNull && SrcGIEquivOrNull->getValueAsBit("CheckMMOIsAtomic")) {
3643 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3644 "Unordered", AtomicOrderingMMOPredicateMatcher::AO_OrStronger);
3645 }
Daniel Sanders2c269f62017-08-24 09:11:20 +00003646
Florian Hahn6b1db822018-06-14 20:32:58 +00003647 if (Src->isLeaf()) {
3648 Init *SrcInit = Src->getLeafValue();
Daniel Sanders452c8ae2017-05-23 19:33:16 +00003649 if (IntInit *SrcIntInit = dyn_cast<IntInit>(SrcInit)) {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003650 OperandMatcher &OM =
Florian Hahn6b1db822018-06-14 20:32:58 +00003651 InsnMatcher.addOperand(OpIdx++, Src->getName(), TempOpIdx);
Daniel Sanders452c8ae2017-05-23 19:33:16 +00003652 OM.addPredicate<LiteralIntOperandMatcher>(SrcIntInit->getValue());
3653 } else
Daniel Sanders32291982017-06-28 13:50:04 +00003654 return failedImport(
3655 "Unable to deduce gMIR opcode to handle Src (which is a leaf)");
Daniel Sanders452c8ae2017-05-23 19:33:16 +00003656 } else {
Daniel Sanders85ffd362017-07-06 08:12:20 +00003657 assert(SrcGIOrNull &&
3658 "Expected to have already found an equivalent Instruction");
Daniel Sanders11300ce2017-10-13 21:28:03 +00003659 if (SrcGIOrNull->TheDef->getName() == "G_CONSTANT" ||
3660 SrcGIOrNull->TheDef->getName() == "G_FCONSTANT") {
3661 // imm/fpimm still have operands but we don't need to do anything with it
Daniel Sanders05540042017-08-08 10:44:31 +00003662 // here since we don't support ImmLeaf predicates yet. However, we still
3663 // need to note the hidden operand to get GIM_CheckNumOperands correct.
3664 InsnMatcher.addOperand(OpIdx++, "", TempOpIdx);
3665 return InsnMatcher;
3666 }
3667
Matt Arsenault8ec5c102019-08-29 01:13:41 +00003668 // Special case because the operand order is changed from setcc. The
3669 // predicate operand needs to be swapped from the last operand to the first
3670 // source.
3671
3672 unsigned NumChildren = Src->getNumChildren();
3673 bool IsFCmp = SrcGIOrNull->TheDef->getName() == "G_FCMP";
3674
3675 if (IsFCmp || SrcGIOrNull->TheDef->getName() == "G_ICMP") {
3676 TreePatternNode *SrcChild = Src->getChild(NumChildren - 1);
3677 if (SrcChild->isLeaf()) {
3678 DefInit *DI = dyn_cast<DefInit>(SrcChild->getLeafValue());
3679 Record *CCDef = DI ? DI->getDef() : nullptr;
3680 if (!CCDef || !CCDef->isSubClassOf("CondCode"))
3681 return failedImport("Unable to handle CondCode");
3682
3683 OperandMatcher &OM =
3684 InsnMatcher.addOperand(OpIdx++, SrcChild->getName(), TempOpIdx);
3685 StringRef PredType = IsFCmp ? CCDef->getValueAsString("FCmpPredicate") :
3686 CCDef->getValueAsString("ICmpPredicate");
3687
3688 if (!PredType.empty()) {
3689 OM.addPredicate<CmpPredicateOperandMatcher>(PredType);
3690 // Process the other 2 operands normally.
3691 --NumChildren;
3692 }
3693 }
3694 }
3695
Daniel Sanders452c8ae2017-05-23 19:33:16 +00003696 // Match the used operands (i.e. the children of the operator).
Jessica Paquette5c8a29f2019-08-20 22:04:10 +00003697 bool IsIntrinsic =
3698 SrcGIOrNull->TheDef->getName() == "G_INTRINSIC" ||
3699 SrcGIOrNull->TheDef->getName() == "G_INTRINSIC_W_SIDE_EFFECTS";
3700 const CodeGenIntrinsic *II = Src->getIntrinsicInfo(CGP);
3701 if (IsIntrinsic && !II)
3702 return failedImport("Expected IntInit containing intrinsic ID)");
3703
Matt Arsenault8ec5c102019-08-29 01:13:41 +00003704 for (unsigned i = 0; i != NumChildren; ++i) {
Florian Hahn6b1db822018-06-14 20:32:58 +00003705 TreePatternNode *SrcChild = Src->getChild(i);
Daniel Sanders85ffd362017-07-06 08:12:20 +00003706
Daniel Sandersa71f4542017-10-16 00:56:30 +00003707 // SelectionDAG allows pointers to be represented with iN since it doesn't
3708 // distinguish between pointers and integers but they are different types in GlobalISel.
3709 // Coerce integers to pointers to address space 0 if the context indicates a pointer.
Daniel Sandersc54aa9c2017-11-18 00:16:44 +00003710 bool OperandIsAPointer = SrcGIOrNull->isOperandAPointer(i);
Daniel Sandersa71f4542017-10-16 00:56:30 +00003711
Jessica Paquette5c8a29f2019-08-20 22:04:10 +00003712 if (IsIntrinsic) {
3713 // For G_INTRINSIC/G_INTRINSIC_W_SIDE_EFFECTS, the operand immediately
3714 // following the defs is an intrinsic ID.
3715 if (i == 0) {
Daniel Sanders85ffd362017-07-06 08:12:20 +00003716 OperandMatcher &OM =
Florian Hahn6b1db822018-06-14 20:32:58 +00003717 InsnMatcher.addOperand(OpIdx++, SrcChild->getName(), TempOpIdx);
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00003718 OM.addPredicate<IntrinsicIDOperandMatcher>(II);
Daniel Sanders85ffd362017-07-06 08:12:20 +00003719 continue;
3720 }
3721
Jessica Paquette5c8a29f2019-08-20 22:04:10 +00003722 // We have to check intrinsics for llvm_anyptr_ty parameters.
3723 //
3724 // Note that we have to look at the i-1th parameter, because we don't
3725 // have the intrinsic ID in the intrinsic's parameter list.
3726 OperandIsAPointer |= II->isParamAPointer(i - 1);
Daniel Sanders85ffd362017-07-06 08:12:20 +00003727 }
3728
Daniel Sandersa71f4542017-10-16 00:56:30 +00003729 if (auto Error =
3730 importChildMatcher(Rule, InsnMatcher, SrcChild, OperandIsAPointer,
3731 OpIdx++, TempOpIdx))
Daniel Sanders452c8ae2017-05-23 19:33:16 +00003732 return std::move(Error);
3733 }
Daniel Sandersffc7d582017-03-29 15:37:18 +00003734 }
3735
3736 return InsnMatcher;
3737}
3738
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003739Error GlobalISelEmitter::importComplexPatternOperandMatcher(
3740 OperandMatcher &OM, Record *R, unsigned &TempOpIdx) const {
3741 const auto &ComplexPattern = ComplexPatternEquivs.find(R);
3742 if (ComplexPattern == ComplexPatternEquivs.end())
3743 return failedImport("SelectionDAG ComplexPattern (" + R->getName() +
3744 ") not mapped to GlobalISel");
3745
3746 OM.addPredicate<ComplexPatternOperandMatcher>(OM, *ComplexPattern->second);
3747 TempOpIdx++;
3748 return Error::success();
3749}
3750
Matt Arsenault3e45c702019-09-06 20:32:37 +00003751// Get the name to use for a pattern operand. For an anonymous physical register
3752// input, this should use the register name.
3753static StringRef getSrcChildName(const TreePatternNode *SrcChild,
3754 Record *&PhysReg) {
3755 StringRef SrcChildName = SrcChild->getName();
3756 if (SrcChildName.empty() && SrcChild->isLeaf()) {
3757 if (auto *ChildDefInit = dyn_cast<DefInit>(SrcChild->getLeafValue())) {
3758 auto *ChildRec = ChildDefInit->getDef();
3759 if (ChildRec->isSubClassOf("Register")) {
3760 SrcChildName = ChildRec->getName();
3761 PhysReg = ChildRec;
3762 }
3763 }
3764 }
3765
3766 return SrcChildName;
3767}
3768
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003769Error GlobalISelEmitter::importChildMatcher(RuleMatcher &Rule,
3770 InstructionMatcher &InsnMatcher,
Florian Hahn6b1db822018-06-14 20:32:58 +00003771 const TreePatternNode *SrcChild,
Daniel Sandersa71f4542017-10-16 00:56:30 +00003772 bool OperandIsAPointer,
Daniel Sandersc270c502017-03-30 09:36:33 +00003773 unsigned OpIdx,
Daniel Sanders8ead1292018-06-15 23:13:43 +00003774 unsigned &TempOpIdx) {
Matt Arsenault3e45c702019-09-06 20:32:37 +00003775
3776 Record *PhysReg = nullptr;
3777 StringRef SrcChildName = getSrcChildName(SrcChild, PhysReg);
3778
3779 OperandMatcher &OM = PhysReg ?
3780 InsnMatcher.addPhysRegInput(PhysReg, OpIdx, TempOpIdx) :
3781 InsnMatcher.addOperand(OpIdx, SrcChildName, TempOpIdx);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003782 if (OM.isSameAsAnotherOperand())
3783 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00003784
Florian Hahn6b1db822018-06-14 20:32:58 +00003785 ArrayRef<TypeSetByHwMode> ChildTypes = SrcChild->getExtTypes();
Daniel Sandersffc7d582017-03-29 15:37:18 +00003786 if (ChildTypes.size() != 1)
3787 return failedImport("Src pattern child has multiple results");
3788
3789 // Check MBB's before the type check since they are not a known type.
Florian Hahn6b1db822018-06-14 20:32:58 +00003790 if (!SrcChild->isLeaf()) {
3791 if (SrcChild->getOperator()->isSubClassOf("SDNode")) {
3792 auto &ChildSDNI = CGP.getSDNodeInfo(SrcChild->getOperator());
Daniel Sandersffc7d582017-03-29 15:37:18 +00003793 if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") {
3794 OM.addPredicate<MBBOperandMatcher>();
Daniel Sandersc270c502017-03-30 09:36:33 +00003795 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00003796 }
3797 }
Daniel Sandersffc7d582017-03-29 15:37:18 +00003798 }
3799
Daniel Sandersa71f4542017-10-16 00:56:30 +00003800 if (auto Error =
3801 OM.addTypeCheckPredicate(ChildTypes.front(), OperandIsAPointer))
3802 return failedImport(toString(std::move(Error)) + " for Src operand (" +
Florian Hahn6b1db822018-06-14 20:32:58 +00003803 to_string(*SrcChild) + ")");
Daniel Sandersffc7d582017-03-29 15:37:18 +00003804
Daniel Sandersbee57392017-04-04 13:25:23 +00003805 // Check for nested instructions.
Florian Hahn6b1db822018-06-14 20:32:58 +00003806 if (!SrcChild->isLeaf()) {
3807 if (SrcChild->getOperator()->isSubClassOf("ComplexPattern")) {
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003808 // When a ComplexPattern is used as an operator, it should do the same
3809 // thing as when used as a leaf. However, the children of the operator
3810 // name the sub-operands that make up the complex operand and we must
3811 // prepare to reference them in the renderer too.
3812 unsigned RendererID = TempOpIdx;
3813 if (auto Error = importComplexPatternOperandMatcher(
Florian Hahn6b1db822018-06-14 20:32:58 +00003814 OM, SrcChild->getOperator(), TempOpIdx))
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003815 return Error;
3816
Florian Hahn6b1db822018-06-14 20:32:58 +00003817 for (unsigned i = 0, e = SrcChild->getNumChildren(); i != e; ++i) {
3818 auto *SubOperand = SrcChild->getChild(i);
Jessica Paquette1ed1dd62019-02-09 00:29:13 +00003819 if (!SubOperand->getName().empty()) {
3820 if (auto Error = Rule.defineComplexSubOperand(SubOperand->getName(),
3821 SrcChild->getOperator(),
3822 RendererID, i))
3823 return Error;
3824 }
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003825 }
3826
3827 return Error::success();
3828 }
3829
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003830 auto MaybeInsnOperand = OM.addPredicate<InstructionOperandMatcher>(
Florian Hahn6b1db822018-06-14 20:32:58 +00003831 InsnMatcher.getRuleMatcher(), SrcChild->getName());
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003832 if (!MaybeInsnOperand.hasValue()) {
3833 // This isn't strictly true. If the user were to provide exactly the same
3834 // matchers as the original operand then we could allow it. However, it's
3835 // simpler to not permit the redundant specification.
3836 return failedImport("Nested instruction cannot be the same as another operand");
3837 }
3838
Daniel Sandersbee57392017-04-04 13:25:23 +00003839 // Map the node to a gMIR instruction.
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003840 InstructionOperandMatcher &InsnOperand = **MaybeInsnOperand;
Daniel Sanders57938df2017-07-11 10:40:18 +00003841 auto InsnMatcherOrError = createAndImportSelDAGMatcher(
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003842 Rule, InsnOperand.getInsnMatcher(), SrcChild, TempOpIdx);
Daniel Sandersbee57392017-04-04 13:25:23 +00003843 if (auto Error = InsnMatcherOrError.takeError())
3844 return Error;
3845
3846 return Error::success();
3847 }
3848
Florian Hahn6b1db822018-06-14 20:32:58 +00003849 if (SrcChild->hasAnyPredicate())
Diana Picusd1b61812017-11-03 10:30:19 +00003850 return failedImport("Src pattern child has unsupported predicate");
3851
Daniel Sandersffc7d582017-03-29 15:37:18 +00003852 // Check for constant immediates.
Florian Hahn6b1db822018-06-14 20:32:58 +00003853 if (auto *ChildInt = dyn_cast<IntInit>(SrcChild->getLeafValue())) {
Daniel Sanders452c8ae2017-05-23 19:33:16 +00003854 OM.addPredicate<ConstantIntOperandMatcher>(ChildInt->getValue());
Daniel Sandersc270c502017-03-30 09:36:33 +00003855 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00003856 }
3857
3858 // Check for def's like register classes or ComplexPattern's.
Florian Hahn6b1db822018-06-14 20:32:58 +00003859 if (auto *ChildDefInit = dyn_cast<DefInit>(SrcChild->getLeafValue())) {
Daniel Sandersffc7d582017-03-29 15:37:18 +00003860 auto *ChildRec = ChildDefInit->getDef();
3861
3862 // Check for register classes.
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003863 if (ChildRec->isSubClassOf("RegisterClass") ||
3864 ChildRec->isSubClassOf("RegisterOperand")) {
Daniel Sandersffc7d582017-03-29 15:37:18 +00003865 OM.addPredicate<RegisterBankOperandMatcher>(
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003866 Target.getRegisterClass(getInitValueAsRegClass(ChildDefInit)));
Daniel Sanders658541f2017-04-22 15:53:21 +00003867 return Error::success();
3868 }
3869
Matt Arsenault3e45c702019-09-06 20:32:37 +00003870 if (ChildRec->isSubClassOf("Register")) {
3871 // This just be emitted as a copy to the specific register.
3872 ValueTypeByHwMode VT = ChildTypes.front().getValueTypeByHwMode();
3873 const CodeGenRegisterClass *RC
3874 = CGRegs.getMinimalPhysRegClass(ChildRec, &VT);
3875 if (!RC) {
3876 return failedImport(
3877 "Could not determine physical register class of pattern source");
3878 }
3879
3880 OM.addPredicate<RegisterBankOperandMatcher>(*RC);
3881 return Error::success();
3882 }
3883
Daniel Sanders4d4e7652017-10-09 18:14:53 +00003884 // Check for ValueType.
3885 if (ChildRec->isSubClassOf("ValueType")) {
3886 // We already added a type check as standard practice so this doesn't need
3887 // to do anything.
3888 return Error::success();
3889 }
3890
Daniel Sandersffc7d582017-03-29 15:37:18 +00003891 // Check for ComplexPattern's.
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003892 if (ChildRec->isSubClassOf("ComplexPattern"))
3893 return importComplexPatternOperandMatcher(OM, ChildRec, TempOpIdx);
Daniel Sandersffc7d582017-03-29 15:37:18 +00003894
Daniel Sandersd0656a32017-04-13 09:45:37 +00003895 if (ChildRec->isSubClassOf("ImmLeaf")) {
3896 return failedImport(
3897 "Src pattern child def is an unsupported tablegen class (ImmLeaf)");
3898 }
3899
Daniel Sandersffc7d582017-03-29 15:37:18 +00003900 return failedImport(
3901 "Src pattern child def is an unsupported tablegen class");
3902 }
3903
3904 return failedImport("Src pattern child is an unsupported kind");
3905}
3906
Daniel Sanders7438b262017-10-31 23:03:18 +00003907Expected<action_iterator> GlobalISelEmitter::importExplicitUseRenderer(
3908 action_iterator InsertPt, RuleMatcher &Rule, BuildMIAction &DstMIBuilder,
Florian Hahn6b1db822018-06-14 20:32:58 +00003909 TreePatternNode *DstChild) {
Daniel Sanders2c269f62017-08-24 09:11:20 +00003910
Florian Hahn6b1db822018-06-14 20:32:58 +00003911 const auto &SubOperand = Rule.getComplexSubOperand(DstChild->getName());
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003912 if (SubOperand.hasValue()) {
3913 DstMIBuilder.addRenderer<RenderComplexPatternOperand>(
Florian Hahn6b1db822018-06-14 20:32:58 +00003914 *std::get<0>(*SubOperand), DstChild->getName(),
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003915 std::get<1>(*SubOperand), std::get<2>(*SubOperand));
Daniel Sanders7438b262017-10-31 23:03:18 +00003916 return InsertPt;
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003917 }
3918
Florian Hahn6b1db822018-06-14 20:32:58 +00003919 if (!DstChild->isLeaf()) {
Volkan Kelesf7f25682018-01-16 18:44:05 +00003920
Florian Hahn6b1db822018-06-14 20:32:58 +00003921 if (DstChild->getOperator()->isSubClassOf("SDNodeXForm")) {
3922 auto Child = DstChild->getChild(0);
3923 auto I = SDNodeXFormEquivs.find(DstChild->getOperator());
Volkan Kelesf7f25682018-01-16 18:44:05 +00003924 if (I != SDNodeXFormEquivs.end()) {
Florian Hahn6b1db822018-06-14 20:32:58 +00003925 DstMIBuilder.addRenderer<CustomRenderer>(*I->second, Child->getName());
Volkan Kelesf7f25682018-01-16 18:44:05 +00003926 return InsertPt;
3927 }
Florian Hahn6b1db822018-06-14 20:32:58 +00003928 return failedImport("SDNodeXForm " + Child->getName() +
Volkan Kelesf7f25682018-01-16 18:44:05 +00003929 " has no custom renderer");
3930 }
3931
Daniel Sanders05540042017-08-08 10:44:31 +00003932 // We accept 'bb' here. It's an operator because BasicBlockSDNode isn't
3933 // inline, but in MI it's just another operand.
Florian Hahn6b1db822018-06-14 20:32:58 +00003934 if (DstChild->getOperator()->isSubClassOf("SDNode")) {
3935 auto &ChildSDNI = CGP.getSDNodeInfo(DstChild->getOperator());
Daniel Sandersffc7d582017-03-29 15:37:18 +00003936 if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") {
Florian Hahn6b1db822018-06-14 20:32:58 +00003937 DstMIBuilder.addRenderer<CopyRenderer>(DstChild->getName());
Daniel Sanders7438b262017-10-31 23:03:18 +00003938 return InsertPt;
Daniel Sandersffc7d582017-03-29 15:37:18 +00003939 }
3940 }
Daniel Sanders05540042017-08-08 10:44:31 +00003941
3942 // Similarly, imm is an operator in TreePatternNode's view but must be
3943 // rendered as operands.
3944 // FIXME: The target should be able to choose sign-extended when appropriate
3945 // (e.g. on Mips).
Florian Hahn6b1db822018-06-14 20:32:58 +00003946 if (DstChild->getOperator()->getName() == "imm") {
3947 DstMIBuilder.addRenderer<CopyConstantAsImmRenderer>(DstChild->getName());
Daniel Sanders7438b262017-10-31 23:03:18 +00003948 return InsertPt;
Florian Hahn6b1db822018-06-14 20:32:58 +00003949 } else if (DstChild->getOperator()->getName() == "fpimm") {
Daniel Sanders11300ce2017-10-13 21:28:03 +00003950 DstMIBuilder.addRenderer<CopyFConstantAsFPImmRenderer>(
Florian Hahn6b1db822018-06-14 20:32:58 +00003951 DstChild->getName());
Daniel Sanders7438b262017-10-31 23:03:18 +00003952 return InsertPt;
Daniel Sanders05540042017-08-08 10:44:31 +00003953 }
3954
Florian Hahn6b1db822018-06-14 20:32:58 +00003955 if (DstChild->getOperator()->isSubClassOf("Instruction")) {
3956 ArrayRef<TypeSetByHwMode> ChildTypes = DstChild->getExtTypes();
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003957 if (ChildTypes.size() != 1)
3958 return failedImport("Dst pattern child has multiple results");
3959
3960 Optional<LLTCodeGen> OpTyOrNone = None;
3961 if (ChildTypes.front().isMachineValueType())
3962 OpTyOrNone =
3963 MVTToLLT(ChildTypes.front().getMachineValueType().SimpleTy);
3964 if (!OpTyOrNone)
3965 return failedImport("Dst operand has an unsupported type");
3966
3967 unsigned TempRegID = Rule.allocateTempRegID();
3968 InsertPt = Rule.insertAction<MakeTempRegisterAction>(
3969 InsertPt, OpTyOrNone.getValue(), TempRegID);
3970 DstMIBuilder.addRenderer<TempRegRenderer>(TempRegID);
3971
3972 auto InsertPtOrError = createAndImportSubInstructionRenderer(
3973 ++InsertPt, Rule, DstChild, TempRegID);
3974 if (auto Error = InsertPtOrError.takeError())
3975 return std::move(Error);
3976 return InsertPtOrError.get();
3977 }
3978
Florian Hahn6b1db822018-06-14 20:32:58 +00003979 return failedImport("Dst pattern child isn't a leaf node or an MBB" + llvm::to_string(*DstChild));
Daniel Sandersffc7d582017-03-29 15:37:18 +00003980 }
3981
Daniel Sandersf499b2b2017-11-30 18:48:35 +00003982 // It could be a specific immediate in which case we should just check for
3983 // that immediate.
3984 if (const IntInit *ChildIntInit =
Florian Hahn6b1db822018-06-14 20:32:58 +00003985 dyn_cast<IntInit>(DstChild->getLeafValue())) {
Daniel Sandersf499b2b2017-11-30 18:48:35 +00003986 DstMIBuilder.addRenderer<ImmRenderer>(ChildIntInit->getValue());
3987 return InsertPt;
3988 }
3989
Daniel Sandersffc7d582017-03-29 15:37:18 +00003990 // Otherwise, we're looking for a bog-standard RegisterClass operand.
Florian Hahn6b1db822018-06-14 20:32:58 +00003991 if (auto *ChildDefInit = dyn_cast<DefInit>(DstChild->getLeafValue())) {
Daniel Sandersffc7d582017-03-29 15:37:18 +00003992 auto *ChildRec = ChildDefInit->getDef();
3993
Florian Hahn6b1db822018-06-14 20:32:58 +00003994 ArrayRef<TypeSetByHwMode> ChildTypes = DstChild->getExtTypes();
Daniel Sandersffc7d582017-03-29 15:37:18 +00003995 if (ChildTypes.size() != 1)
3996 return failedImport("Dst pattern child has multiple results");
3997
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003998 Optional<LLTCodeGen> OpTyOrNone = None;
3999 if (ChildTypes.front().isMachineValueType())
4000 OpTyOrNone = MVTToLLT(ChildTypes.front().getMachineValueType().SimpleTy);
Daniel Sandersffc7d582017-03-29 15:37:18 +00004001 if (!OpTyOrNone)
4002 return failedImport("Dst operand has an unsupported type");
4003
4004 if (ChildRec->isSubClassOf("Register")) {
Daniel Sanders198447a2017-11-01 00:29:47 +00004005 DstMIBuilder.addRenderer<AddRegisterRenderer>(ChildRec);
Daniel Sanders7438b262017-10-31 23:03:18 +00004006 return InsertPt;
Daniel Sandersffc7d582017-03-29 15:37:18 +00004007 }
4008
Daniel Sanders658541f2017-04-22 15:53:21 +00004009 if (ChildRec->isSubClassOf("RegisterClass") ||
Daniel Sanders4d4e7652017-10-09 18:14:53 +00004010 ChildRec->isSubClassOf("RegisterOperand") ||
4011 ChildRec->isSubClassOf("ValueType")) {
Daniel Sandersd66e0902017-10-23 18:19:24 +00004012 if (ChildRec->isSubClassOf("RegisterOperand") &&
4013 !ChildRec->isValueUnset("GIZeroRegister")) {
4014 DstMIBuilder.addRenderer<CopyOrAddZeroRegRenderer>(
Florian Hahn6b1db822018-06-14 20:32:58 +00004015 DstChild->getName(), ChildRec->getValueAsDef("GIZeroRegister"));
Daniel Sanders7438b262017-10-31 23:03:18 +00004016 return InsertPt;
Daniel Sandersd66e0902017-10-23 18:19:24 +00004017 }
4018
Florian Hahn6b1db822018-06-14 20:32:58 +00004019 DstMIBuilder.addRenderer<CopyRenderer>(DstChild->getName());
Daniel Sanders7438b262017-10-31 23:03:18 +00004020 return InsertPt;
Daniel Sandersffc7d582017-03-29 15:37:18 +00004021 }
4022
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004023 if (ChildRec->isSubClassOf("SubRegIndex")) {
4024 CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(ChildRec);
4025 DstMIBuilder.addRenderer<ImmRenderer>(SubIdx->EnumValue);
4026 return InsertPt;
4027 }
4028
Daniel Sandersffc7d582017-03-29 15:37:18 +00004029 if (ChildRec->isSubClassOf("ComplexPattern")) {
4030 const auto &ComplexPattern = ComplexPatternEquivs.find(ChildRec);
4031 if (ComplexPattern == ComplexPatternEquivs.end())
4032 return failedImport(
4033 "SelectionDAG ComplexPattern not mapped to GlobalISel");
4034
Florian Hahn6b1db822018-06-14 20:32:58 +00004035 const OperandMatcher &OM = Rule.getOperandMatcher(DstChild->getName());
Daniel Sandersffc7d582017-03-29 15:37:18 +00004036 DstMIBuilder.addRenderer<RenderComplexPatternOperand>(
Florian Hahn6b1db822018-06-14 20:32:58 +00004037 *ComplexPattern->second, DstChild->getName(),
Daniel Sanders2deea182017-04-22 15:11:04 +00004038 OM.getAllocatedTemporariesBaseID());
Daniel Sanders7438b262017-10-31 23:03:18 +00004039 return InsertPt;
Daniel Sandersffc7d582017-03-29 15:37:18 +00004040 }
4041
4042 return failedImport(
4043 "Dst pattern child def is an unsupported tablegen class");
4044 }
4045
4046 return failedImport("Dst pattern child is an unsupported kind");
4047}
4048
Daniel Sandersc270c502017-03-30 09:36:33 +00004049Expected<BuildMIAction &> GlobalISelEmitter::createAndImportInstructionRenderer(
Matt Arsenault3e45c702019-09-06 20:32:37 +00004050 RuleMatcher &M, InstructionMatcher &InsnMatcher, const TreePatternNode *Src,
4051 const TreePatternNode *Dst) {
Daniel Sanders7438b262017-10-31 23:03:18 +00004052 auto InsertPtOrError = createInstructionRenderer(M.actions_end(), M, Dst);
4053 if (auto Error = InsertPtOrError.takeError())
Daniel Sandersdf258e32017-10-31 19:09:29 +00004054 return std::move(Error);
4055
Daniel Sanders7438b262017-10-31 23:03:18 +00004056 action_iterator InsertPt = InsertPtOrError.get();
4057 BuildMIAction &DstMIBuilder = *static_cast<BuildMIAction *>(InsertPt->get());
Daniel Sandersdf258e32017-10-31 19:09:29 +00004058
Matt Arsenault3e45c702019-09-06 20:32:37 +00004059 for (auto PhysInput : InsnMatcher.getPhysRegInputs()) {
4060 InsertPt = M.insertAction<BuildMIAction>(
4061 InsertPt, M.allocateOutputInsnID(),
4062 &Target.getInstruction(RK.getDef("COPY")));
4063 BuildMIAction &CopyToPhysRegMIBuilder =
4064 *static_cast<BuildMIAction *>(InsertPt->get());
4065 CopyToPhysRegMIBuilder.addRenderer<AddRegisterRenderer>(PhysInput.first,
4066 true);
4067 CopyToPhysRegMIBuilder.addRenderer<CopyPhysRegRenderer>(PhysInput.first);
4068 }
4069
Daniel Sandersdf258e32017-10-31 19:09:29 +00004070 importExplicitDefRenderers(DstMIBuilder);
4071
Daniel Sanders7438b262017-10-31 23:03:18 +00004072 if (auto Error = importExplicitUseRenderers(InsertPt, M, DstMIBuilder, Dst)
4073 .takeError())
Daniel Sandersdf258e32017-10-31 19:09:29 +00004074 return std::move(Error);
4075
4076 return DstMIBuilder;
4077}
4078
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00004079Expected<action_iterator>
4080GlobalISelEmitter::createAndImportSubInstructionRenderer(
Florian Hahn6b1db822018-06-14 20:32:58 +00004081 const action_iterator InsertPt, RuleMatcher &M, const TreePatternNode *Dst,
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00004082 unsigned TempRegID) {
4083 auto InsertPtOrError = createInstructionRenderer(InsertPt, M, Dst);
4084
4085 // TODO: Assert there's exactly one result.
4086
4087 if (auto Error = InsertPtOrError.takeError())
4088 return std::move(Error);
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00004089
4090 BuildMIAction &DstMIBuilder =
4091 *static_cast<BuildMIAction *>(InsertPtOrError.get()->get());
4092
4093 // Assign the result to TempReg.
4094 DstMIBuilder.addRenderer<TempRegRenderer>(TempRegID, true);
4095
Daniel Sanders08464522018-01-29 21:09:12 +00004096 InsertPtOrError =
4097 importExplicitUseRenderers(InsertPtOrError.get(), M, DstMIBuilder, Dst);
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00004098 if (auto Error = InsertPtOrError.takeError())
4099 return std::move(Error);
4100
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004101 // We need to make sure that when we import an INSERT_SUBREG as a
4102 // subinstruction that it ends up being constrained to the correct super
4103 // register and subregister classes.
Matt Arsenault38fb3442019-09-04 16:19:34 +00004104 auto OpName = Target.getInstruction(Dst->getOperator()).TheDef->getName();
4105 if (OpName == "INSERT_SUBREG") {
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004106 auto SubClass = inferRegClassFromPattern(Dst->getChild(1));
4107 if (!SubClass)
4108 return failedImport(
4109 "Cannot infer register class from INSERT_SUBREG operand #1");
Jessica Paquette7080ffa2019-08-28 20:12:31 +00004110 Optional<const CodeGenRegisterClass *> SuperClass =
4111 inferSuperRegisterClassForNode(Dst->getExtType(0), Dst->getChild(0),
4112 Dst->getChild(2));
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004113 if (!SuperClass)
4114 return failedImport(
4115 "Cannot infer register class for INSERT_SUBREG operand #0");
4116 // The destination and the super register source of an INSERT_SUBREG must
4117 // be the same register class.
4118 M.insertAction<ConstrainOperandToRegClassAction>(
4119 InsertPt, DstMIBuilder.getInsnID(), 0, **SuperClass);
4120 M.insertAction<ConstrainOperandToRegClassAction>(
4121 InsertPt, DstMIBuilder.getInsnID(), 1, **SuperClass);
4122 M.insertAction<ConstrainOperandToRegClassAction>(
4123 InsertPt, DstMIBuilder.getInsnID(), 2, **SubClass);
4124 return InsertPtOrError.get();
4125 }
4126
Matt Arsenault9ceb6ed2019-09-06 00:05:58 +00004127 if (OpName == "EXTRACT_SUBREG") {
4128 // EXTRACT_SUBREG selects into a subregister COPY but unlike most
4129 // instructions, the result register class is controlled by the
4130 // subregisters of the operand. As a result, we must constrain the result
4131 // class rather than check that it's already the right one.
4132 auto SuperClass = inferRegClassFromPattern(Dst->getChild(0));
4133 if (!SuperClass)
4134 return failedImport(
4135 "Cannot infer register class from EXTRACT_SUBREG operand #0");
4136
4137 auto SubIdx = inferSubRegIndexForNode(Dst->getChild(1));
4138 if (!SubIdx)
4139 return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
4140
4141 const auto &SrcRCDstRCPair =
4142 (*SuperClass)->getMatchingSubClassWithSubRegs(CGRegs, *SubIdx);
4143 assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
4144 M.insertAction<ConstrainOperandToRegClassAction>(
4145 InsertPt, DstMIBuilder.getInsnID(), 0, *SrcRCDstRCPair->second);
4146 M.insertAction<ConstrainOperandToRegClassAction>(
4147 InsertPt, DstMIBuilder.getInsnID(), 1, *SrcRCDstRCPair->first);
4148
4149 // We're done with this pattern! It's eligible for GISel emission; return
4150 // it.
4151 return InsertPtOrError.get();
4152 }
4153
Jessica Paquette7080ffa2019-08-28 20:12:31 +00004154 // Similar to INSERT_SUBREG, we also have to handle SUBREG_TO_REG as a
4155 // subinstruction.
Matt Arsenault38fb3442019-09-04 16:19:34 +00004156 if (OpName == "SUBREG_TO_REG") {
4157 auto SubClass = inferRegClassFromPattern(Dst->getChild(1));
4158 if (!SubClass)
4159 return failedImport(
Jessica Paquette7080ffa2019-08-28 20:12:31 +00004160 "Cannot infer register class from SUBREG_TO_REG child #1");
Matt Arsenault38fb3442019-09-04 16:19:34 +00004161 auto SuperClass = inferSuperRegisterClass(Dst->getExtType(0),
4162 Dst->getChild(2));
4163 if (!SuperClass)
4164 return failedImport(
Jessica Paquette7080ffa2019-08-28 20:12:31 +00004165 "Cannot infer register class for SUBREG_TO_REG operand #0");
Matt Arsenault38fb3442019-09-04 16:19:34 +00004166 M.insertAction<ConstrainOperandToRegClassAction>(
Jessica Paquette7080ffa2019-08-28 20:12:31 +00004167 InsertPt, DstMIBuilder.getInsnID(), 0, **SuperClass);
Matt Arsenault38fb3442019-09-04 16:19:34 +00004168 M.insertAction<ConstrainOperandToRegClassAction>(
Jessica Paquette7080ffa2019-08-28 20:12:31 +00004169 InsertPt, DstMIBuilder.getInsnID(), 2, **SubClass);
Matt Arsenault38fb3442019-09-04 16:19:34 +00004170 return InsertPtOrError.get();
4171 }
Jessica Paquette7080ffa2019-08-28 20:12:31 +00004172
Daniel Sanders08464522018-01-29 21:09:12 +00004173 M.insertAction<ConstrainOperandsToDefinitionAction>(InsertPt,
4174 DstMIBuilder.getInsnID());
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00004175 return InsertPtOrError.get();
4176}
4177
Daniel Sanders7438b262017-10-31 23:03:18 +00004178Expected<action_iterator> GlobalISelEmitter::createInstructionRenderer(
Florian Hahn6b1db822018-06-14 20:32:58 +00004179 action_iterator InsertPt, RuleMatcher &M, const TreePatternNode *Dst) {
4180 Record *DstOp = Dst->getOperator();
Daniel Sandersd0656a32017-04-13 09:45:37 +00004181 if (!DstOp->isSubClassOf("Instruction")) {
4182 if (DstOp->isSubClassOf("ValueType"))
4183 return failedImport(
4184 "Pattern operator isn't an instruction (it's a ValueType)");
Daniel Sandersffc7d582017-03-29 15:37:18 +00004185 return failedImport("Pattern operator isn't an instruction");
Daniel Sandersd0656a32017-04-13 09:45:37 +00004186 }
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004187 CodeGenInstruction *DstI = &Target.getInstruction(DstOp);
Daniel Sandersffc7d582017-03-29 15:37:18 +00004188
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004189 // COPY_TO_REGCLASS is just a copy with a ConstrainOperandToRegClassAction
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004190 // attached. Similarly for EXTRACT_SUBREG except that's a subregister copy.
Matt Arsenault4a23ae52019-09-10 17:57:33 +00004191 StringRef Name = DstI->TheDef->getName();
4192 if (Name == "COPY_TO_REGCLASS" || Name == "EXTRACT_SUBREG")
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004193 DstI = &Target.getInstruction(RK.getDef("COPY"));
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004194
Daniel Sanders198447a2017-11-01 00:29:47 +00004195 return M.insertAction<BuildMIAction>(InsertPt, M.allocateOutputInsnID(),
4196 DstI);
Daniel Sandersdf258e32017-10-31 19:09:29 +00004197}
4198
4199void GlobalISelEmitter::importExplicitDefRenderers(
4200 BuildMIAction &DstMIBuilder) {
4201 const CodeGenInstruction *DstI = DstMIBuilder.getCGI();
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004202 for (unsigned I = 0; I < DstI->Operands.NumDefs; ++I) {
4203 const CGIOperandList::OperandInfo &DstIOperand = DstI->Operands[I];
Daniel Sanders198447a2017-11-01 00:29:47 +00004204 DstMIBuilder.addRenderer<CopyRenderer>(DstIOperand.Name);
Daniel Sandersffc7d582017-03-29 15:37:18 +00004205 }
Daniel Sandersdf258e32017-10-31 19:09:29 +00004206}
4207
Daniel Sanders7438b262017-10-31 23:03:18 +00004208Expected<action_iterator> GlobalISelEmitter::importExplicitUseRenderers(
4209 action_iterator InsertPt, RuleMatcher &M, BuildMIAction &DstMIBuilder,
Florian Hahn6b1db822018-06-14 20:32:58 +00004210 const llvm::TreePatternNode *Dst) {
Daniel Sandersdf258e32017-10-31 19:09:29 +00004211 const CodeGenInstruction *DstI = DstMIBuilder.getCGI();
Florian Hahn6b1db822018-06-14 20:32:58 +00004212 CodeGenInstruction *OrigDstI = &Target.getInstruction(Dst->getOperator());
Daniel Sandersffc7d582017-03-29 15:37:18 +00004213
Matt Arsenault4a23ae52019-09-10 17:57:33 +00004214 StringRef Name = OrigDstI->TheDef->getName();
4215 unsigned ExpectedDstINumUses = Dst->getNumChildren();
4216
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004217 // EXTRACT_SUBREG needs to use a subregister COPY.
Matt Arsenault4a23ae52019-09-10 17:57:33 +00004218 if (Name == "EXTRACT_SUBREG") {
Florian Hahn6b1db822018-06-14 20:32:58 +00004219 if (!Dst->getChild(0)->isLeaf())
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004220 return failedImport("EXTRACT_SUBREG child #1 is not a leaf");
4221
Daniel Sanders32291982017-06-28 13:50:04 +00004222 if (DefInit *SubRegInit =
Florian Hahn6b1db822018-06-14 20:32:58 +00004223 dyn_cast<DefInit>(Dst->getChild(1)->getLeafValue())) {
4224 Record *RCDef = getInitValueAsRegClass(Dst->getChild(0)->getLeafValue());
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00004225 if (!RCDef)
4226 return failedImport("EXTRACT_SUBREG child #0 could not "
4227 "be coerced to a register class");
4228
4229 CodeGenRegisterClass *RC = CGRegs.getRegClass(RCDef);
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004230 CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef());
4231
4232 const auto &SrcRCDstRCPair =
4233 RC->getMatchingSubClassWithSubRegs(CGRegs, SubIdx);
4234 if (SrcRCDstRCPair.hasValue()) {
4235 assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
4236 if (SrcRCDstRCPair->first != RC)
4237 return failedImport("EXTRACT_SUBREG requires an additional COPY");
4238 }
4239
Florian Hahn6b1db822018-06-14 20:32:58 +00004240 DstMIBuilder.addRenderer<CopySubRegRenderer>(Dst->getChild(0)->getName(),
Daniel Sanders198447a2017-11-01 00:29:47 +00004241 SubIdx);
Daniel Sanders7438b262017-10-31 23:03:18 +00004242 return InsertPt;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004243 }
4244
4245 return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
4246 }
4247
Matt Arsenault4a23ae52019-09-10 17:57:33 +00004248 if (Name == "REG_SEQUENCE") {
4249 if (!Dst->getChild(0)->isLeaf())
4250 return failedImport("REG_SEQUENCE child #0 is not a leaf");
4251
4252 Record *RCDef = getInitValueAsRegClass(Dst->getChild(0)->getLeafValue());
4253 if (!RCDef)
4254 return failedImport("REG_SEQUENCE child #0 could not "
4255 "be coerced to a register class");
4256
4257 if ((ExpectedDstINumUses - 1) % 2 != 0)
4258 return failedImport("Malformed REG_SEQUENCE");
4259
4260 for (unsigned I = 1; I != ExpectedDstINumUses; I += 2) {
4261 TreePatternNode *ValChild = Dst->getChild(I);
4262 TreePatternNode *SubRegChild = Dst->getChild(I + 1);
4263
4264 if (DefInit *SubRegInit =
4265 dyn_cast<DefInit>(SubRegChild->getLeafValue())) {
4266 CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef());
4267
4268 auto InsertPtOrError =
4269 importExplicitUseRenderer(InsertPt, M, DstMIBuilder, ValChild);
4270 if (auto Error = InsertPtOrError.takeError())
4271 return std::move(Error);
4272 InsertPt = InsertPtOrError.get();
4273 DstMIBuilder.addRenderer<SubRegIndexRenderer>(SubIdx);
4274 }
4275 }
4276
4277 return InsertPt;
4278 }
4279
Daniel Sandersffc7d582017-03-29 15:37:18 +00004280 // Render the explicit uses.
Daniel Sandersdf258e32017-10-31 19:09:29 +00004281 unsigned DstINumUses = OrigDstI->Operands.size() - OrigDstI->Operands.NumDefs;
Matt Arsenault4a23ae52019-09-10 17:57:33 +00004282 if (Name == "COPY_TO_REGCLASS") {
Daniel Sandersdf258e32017-10-31 19:09:29 +00004283 DstINumUses--; // Ignore the class constraint.
4284 ExpectedDstINumUses--;
4285 }
4286
Daniel Sanders0ed28822017-04-12 08:23:08 +00004287 unsigned Child = 0;
Diana Picus382602f2017-05-17 08:57:28 +00004288 unsigned NumDefaultOps = 0;
Daniel Sanders0ed28822017-04-12 08:23:08 +00004289 for (unsigned I = 0; I != DstINumUses; ++I) {
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004290 const CGIOperandList::OperandInfo &DstIOperand =
4291 DstI->Operands[DstI->Operands.NumDefs + I];
Daniel Sanders0ed28822017-04-12 08:23:08 +00004292
Diana Picus382602f2017-05-17 08:57:28 +00004293 // If the operand has default values, introduce them now.
4294 // FIXME: Until we have a decent test case that dictates we should do
4295 // otherwise, we're going to assume that operands with default values cannot
4296 // be specified in the patterns. Therefore, adding them will not cause us to
4297 // end up with too many rendered operands.
4298 if (DstIOperand.Rec->isSubClassOf("OperandWithDefaultOps")) {
Daniel Sanders0ed28822017-04-12 08:23:08 +00004299 DagInit *DefaultOps = DstIOperand.Rec->getValueAsDag("DefaultOps");
Sjoerd Meijerde234842019-05-30 07:30:37 +00004300 if (auto Error = importDefaultOperandRenderers(
4301 InsertPt, M, DstMIBuilder, DefaultOps))
Diana Picus382602f2017-05-17 08:57:28 +00004302 return std::move(Error);
4303 ++NumDefaultOps;
Daniel Sanders0ed28822017-04-12 08:23:08 +00004304 continue;
4305 }
4306
Daniel Sanders7438b262017-10-31 23:03:18 +00004307 auto InsertPtOrError = importExplicitUseRenderer(InsertPt, M, DstMIBuilder,
Florian Hahn6b1db822018-06-14 20:32:58 +00004308 Dst->getChild(Child));
Daniel Sanders7438b262017-10-31 23:03:18 +00004309 if (auto Error = InsertPtOrError.takeError())
Daniel Sandersffc7d582017-03-29 15:37:18 +00004310 return std::move(Error);
Daniel Sanders7438b262017-10-31 23:03:18 +00004311 InsertPt = InsertPtOrError.get();
Daniel Sanders0ed28822017-04-12 08:23:08 +00004312 ++Child;
Daniel Sandersffc7d582017-03-29 15:37:18 +00004313 }
4314
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004315 if (NumDefaultOps + ExpectedDstINumUses != DstINumUses)
Diana Picuseb2057c2017-05-17 09:25:08 +00004316 return failedImport("Expected " + llvm::to_string(DstINumUses) +
Diana Picus382602f2017-05-17 08:57:28 +00004317 " used operands but found " +
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004318 llvm::to_string(ExpectedDstINumUses) +
Diana Picuseb2057c2017-05-17 09:25:08 +00004319 " explicit ones and " + llvm::to_string(NumDefaultOps) +
Diana Picus382602f2017-05-17 08:57:28 +00004320 " default ones");
4321
Daniel Sanders7438b262017-10-31 23:03:18 +00004322 return InsertPt;
Daniel Sandersffc7d582017-03-29 15:37:18 +00004323}
4324
Diana Picus382602f2017-05-17 08:57:28 +00004325Error GlobalISelEmitter::importDefaultOperandRenderers(
Sjoerd Meijerde234842019-05-30 07:30:37 +00004326 action_iterator InsertPt, RuleMatcher &M, BuildMIAction &DstMIBuilder,
4327 DagInit *DefaultOps) const {
Craig Topper481ff702017-05-29 21:49:34 +00004328 for (const auto *DefaultOp : DefaultOps->getArgs()) {
Sjoerd Meijerde234842019-05-30 07:30:37 +00004329 Optional<LLTCodeGen> OpTyOrNone = None;
4330
Diana Picus382602f2017-05-17 08:57:28 +00004331 // Look through ValueType operators.
4332 if (const DagInit *DefaultDagOp = dyn_cast<DagInit>(DefaultOp)) {
4333 if (const DefInit *DefaultDagOperator =
4334 dyn_cast<DefInit>(DefaultDagOp->getOperator())) {
Sjoerd Meijer3cac8d22019-05-31 08:39:34 +00004335 if (DefaultDagOperator->getDef()->isSubClassOf("ValueType")) {
Sjoerd Meijerde234842019-05-30 07:30:37 +00004336 OpTyOrNone = MVTToLLT(getValueType(
4337 DefaultDagOperator->getDef()));
Diana Picus382602f2017-05-17 08:57:28 +00004338 DefaultOp = DefaultDagOp->getArg(0);
Sjoerd Meijer3cac8d22019-05-31 08:39:34 +00004339 }
Diana Picus382602f2017-05-17 08:57:28 +00004340 }
4341 }
4342
4343 if (const DefInit *DefaultDefOp = dyn_cast<DefInit>(DefaultOp)) {
Sjoerd Meijerde234842019-05-30 07:30:37 +00004344 auto Def = DefaultDefOp->getDef();
4345 if (Def->getName() == "undef_tied_input") {
4346 unsigned TempRegID = M.allocateTempRegID();
4347 M.insertAction<MakeTempRegisterAction>(
4348 InsertPt, OpTyOrNone.getValue(), TempRegID);
4349 InsertPt = M.insertAction<BuildMIAction>(
4350 InsertPt, M.allocateOutputInsnID(),
4351 &Target.getInstruction(RK.getDef("IMPLICIT_DEF")));
4352 BuildMIAction &IDMIBuilder = *static_cast<BuildMIAction *>(
4353 InsertPt->get());
4354 IDMIBuilder.addRenderer<TempRegRenderer>(TempRegID);
4355 DstMIBuilder.addRenderer<TempRegRenderer>(TempRegID);
4356 } else {
4357 DstMIBuilder.addRenderer<AddRegisterRenderer>(Def);
4358 }
Diana Picus382602f2017-05-17 08:57:28 +00004359 continue;
4360 }
4361
4362 if (const IntInit *DefaultIntOp = dyn_cast<IntInit>(DefaultOp)) {
Daniel Sanders198447a2017-11-01 00:29:47 +00004363 DstMIBuilder.addRenderer<ImmRenderer>(DefaultIntOp->getValue());
Diana Picus382602f2017-05-17 08:57:28 +00004364 continue;
4365 }
4366
4367 return failedImport("Could not add default op");
4368 }
4369
4370 return Error::success();
4371}
4372
Daniel Sandersc270c502017-03-30 09:36:33 +00004373Error GlobalISelEmitter::importImplicitDefRenderers(
Daniel Sandersffc7d582017-03-29 15:37:18 +00004374 BuildMIAction &DstMIBuilder,
4375 const std::vector<Record *> &ImplicitDefs) const {
4376 if (!ImplicitDefs.empty())
4377 return failedImport("Pattern defines a physical register");
Daniel Sandersc270c502017-03-30 09:36:33 +00004378 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00004379}
4380
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004381Optional<const CodeGenRegisterClass *>
4382GlobalISelEmitter::getRegClassFromLeaf(TreePatternNode *Leaf) {
4383 assert(Leaf && "Expected node?");
4384 assert(Leaf->isLeaf() && "Expected leaf?");
4385 Record *RCRec = getInitValueAsRegClass(Leaf->getLeafValue());
4386 if (!RCRec)
4387 return None;
4388 CodeGenRegisterClass *RC = CGRegs.getRegClass(RCRec);
4389 if (!RC)
4390 return None;
4391 return RC;
4392}
4393
4394Optional<const CodeGenRegisterClass *>
4395GlobalISelEmitter::inferRegClassFromPattern(TreePatternNode *N) {
4396 if (!N)
4397 return None;
4398
4399 if (N->isLeaf())
4400 return getRegClassFromLeaf(N);
4401
4402 // We don't have a leaf node, so we have to try and infer something. Check
4403 // that we have an instruction that we an infer something from.
4404
4405 // Only handle things that produce a single type.
4406 if (N->getNumTypes() != 1)
4407 return None;
4408 Record *OpRec = N->getOperator();
4409
4410 // We only want instructions.
4411 if (!OpRec->isSubClassOf("Instruction"))
4412 return None;
4413
4414 // Don't want to try and infer things when there could potentially be more
4415 // than one candidate register class.
4416 auto &Inst = Target.getInstruction(OpRec);
4417 if (Inst.Operands.NumDefs > 1)
4418 return None;
4419
4420 // Handle any special-case instructions which we can safely infer register
4421 // classes from.
4422 StringRef InstName = Inst.TheDef->getName();
Matt Arsenault38fb3442019-09-04 16:19:34 +00004423 bool IsRegSequence = InstName == "REG_SEQUENCE";
4424 if (IsRegSequence || InstName == "COPY_TO_REGCLASS") {
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004425 // If we have a COPY_TO_REGCLASS, then we need to handle it specially. It
4426 // has the desired register class as the first child.
Matt Arsenault38fb3442019-09-04 16:19:34 +00004427 TreePatternNode *RCChild = N->getChild(IsRegSequence ? 0 : 1);
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004428 if (!RCChild->isLeaf())
4429 return None;
4430 return getRegClassFromLeaf(RCChild);
4431 }
4432
4433 // Handle destination record types that we can safely infer a register class
4434 // from.
4435 const auto &DstIOperand = Inst.Operands[0];
4436 Record *DstIOpRec = DstIOperand.Rec;
4437 if (DstIOpRec->isSubClassOf("RegisterOperand")) {
4438 DstIOpRec = DstIOpRec->getValueAsDef("RegClass");
4439 const CodeGenRegisterClass &RC = Target.getRegisterClass(DstIOpRec);
4440 return &RC;
4441 }
4442
4443 if (DstIOpRec->isSubClassOf("RegisterClass")) {
4444 const CodeGenRegisterClass &RC = Target.getRegisterClass(DstIOpRec);
4445 return &RC;
4446 }
4447
4448 return None;
4449}
4450
4451Optional<const CodeGenRegisterClass *>
4452GlobalISelEmitter::inferSuperRegisterClass(const TypeSetByHwMode &Ty,
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004453 TreePatternNode *SubRegIdxNode) {
Jessica Paquette7080ffa2019-08-28 20:12:31 +00004454 assert(SubRegIdxNode && "Expected subregister index node!");
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004455 // We need a ValueTypeByHwMode for getSuperRegForSubReg.
4456 if (!Ty.isValueTypeByHwMode(false))
4457 return None;
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004458 if (!SubRegIdxNode->isLeaf())
4459 return None;
4460 DefInit *SubRegInit = dyn_cast<DefInit>(SubRegIdxNode->getLeafValue());
4461 if (!SubRegInit)
4462 return None;
4463 CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef());
4464
4465 // Use the information we found above to find a minimal register class which
4466 // supports the subregister and type we want.
4467 auto RC =
4468 Target.getSuperRegForSubReg(Ty.getValueTypeByHwMode(), CGRegs, SubIdx);
4469 if (!RC)
4470 return None;
4471 return *RC;
4472}
4473
Jessica Paquette7080ffa2019-08-28 20:12:31 +00004474Optional<const CodeGenRegisterClass *>
4475GlobalISelEmitter::inferSuperRegisterClassForNode(
4476 const TypeSetByHwMode &Ty, TreePatternNode *SuperRegNode,
4477 TreePatternNode *SubRegIdxNode) {
4478 assert(SuperRegNode && "Expected super register node!");
4479 // Check if we already have a defined register class for the super register
4480 // node. If we do, then we should preserve that rather than inferring anything
4481 // from the subregister index node. We can assume that whoever wrote the
4482 // pattern in the first place made sure that the super register and
4483 // subregister are compatible.
4484 if (Optional<const CodeGenRegisterClass *> SuperRegisterClass =
4485 inferRegClassFromPattern(SuperRegNode))
4486 return *SuperRegisterClass;
4487 return inferSuperRegisterClass(Ty, SubRegIdxNode);
4488}
4489
Matt Arsenault9ceb6ed2019-09-06 00:05:58 +00004490Optional<CodeGenSubRegIndex *>
4491GlobalISelEmitter::inferSubRegIndexForNode(TreePatternNode *SubRegIdxNode) {
4492 if (!SubRegIdxNode->isLeaf())
4493 return None;
4494
4495 DefInit *SubRegInit = dyn_cast<DefInit>(SubRegIdxNode->getLeafValue());
4496 if (!SubRegInit)
4497 return None;
4498 return CGRegs.getSubRegIdx(SubRegInit->getDef());
4499}
4500
Daniel Sandersffc7d582017-03-29 15:37:18 +00004501Expected<RuleMatcher> GlobalISelEmitter::runOnPattern(const PatternToMatch &P) {
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004502 // Keep track of the matchers and actions to emit.
Aditya Nandakumarb63e7632018-02-16 22:37:15 +00004503 int Score = P.getPatternComplexity(CGP);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00004504 RuleMatcher M(P.getSrcRecord()->getLoc());
Aditya Nandakumarb63e7632018-02-16 22:37:15 +00004505 RuleMatcherScores[M.getRuleID()] = Score;
Daniel Sanders6ea17ed2017-10-31 18:07:03 +00004506 M.addAction<DebugCommentAction>(llvm::to_string(*P.getSrcPattern()) +
4507 " => " +
4508 llvm::to_string(*P.getDstPattern()));
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004509
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004510 if (auto Error = importRulePredicates(M, P.getPredicates()))
Daniel Sandersffc7d582017-03-29 15:37:18 +00004511 return std::move(Error);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004512
4513 // Next, analyze the pattern operators.
Florian Hahn6b1db822018-06-14 20:32:58 +00004514 TreePatternNode *Src = P.getSrcPattern();
4515 TreePatternNode *Dst = P.getDstPattern();
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004516
4517 // If the root of either pattern isn't a simple operator, ignore it.
Daniel Sandersd0656a32017-04-13 09:45:37 +00004518 if (auto Err = isTrivialOperatorNode(Dst))
4519 return failedImport("Dst pattern root isn't a trivial operator (" +
4520 toString(std::move(Err)) + ")");
4521 if (auto Err = isTrivialOperatorNode(Src))
4522 return failedImport("Src pattern root isn't a trivial operator (" +
4523 toString(std::move(Err)) + ")");
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004524
Quentin Colombetaad20be2017-12-15 23:07:42 +00004525 // The different predicates and matchers created during
4526 // addInstructionMatcher use the RuleMatcher M to set up their
4527 // instruction ID (InsnVarID) that are going to be used when
4528 // M is going to be emitted.
4529 // However, the code doing the emission still relies on the IDs
4530 // returned during that process by the RuleMatcher when issuing
4531 // the recordInsn opcodes.
4532 // Because of that:
4533 // 1. The order in which we created the predicates
4534 // and such must be the same as the order in which we emit them,
4535 // and
4536 // 2. We need to reset the generation of the IDs in M somewhere between
4537 // addInstructionMatcher and emit
4538 //
4539 // FIXME: Long term, we don't want to have to rely on this implicit
4540 // naming being the same. One possible solution would be to have
4541 // explicit operator for operation capture and reference those.
4542 // The plus side is that it would expose opportunities to share
4543 // the capture accross rules. The downside is that it would
4544 // introduce a dependency between predicates (captures must happen
4545 // before their first use.)
Florian Hahn6b1db822018-06-14 20:32:58 +00004546 InstructionMatcher &InsnMatcherTemp = M.addInstructionMatcher(Src->getName());
Daniel Sandersedd07842017-08-17 09:26:14 +00004547 unsigned TempOpIdx = 0;
4548 auto InsnMatcherOrError =
Daniel Sandersdf39cba2017-10-15 18:22:54 +00004549 createAndImportSelDAGMatcher(M, InsnMatcherTemp, Src, TempOpIdx);
Daniel Sandersedd07842017-08-17 09:26:14 +00004550 if (auto Error = InsnMatcherOrError.takeError())
4551 return std::move(Error);
4552 InstructionMatcher &InsnMatcher = InsnMatcherOrError.get();
4553
Florian Hahn6b1db822018-06-14 20:32:58 +00004554 if (Dst->isLeaf()) {
4555 Record *RCDef = getInitValueAsRegClass(Dst->getLeafValue());
Daniel Sandersedd07842017-08-17 09:26:14 +00004556
4557 const CodeGenRegisterClass &RC = Target.getRegisterClass(RCDef);
4558 if (RCDef) {
4559 // We need to replace the def and all its uses with the specified
4560 // operand. However, we must also insert COPY's wherever needed.
4561 // For now, emit a copy and let the register allocator clean up.
4562 auto &DstI = Target.getInstruction(RK.getDef("COPY"));
4563 const auto &DstIOperand = DstI.Operands[0];
4564
4565 OperandMatcher &OM0 = InsnMatcher.getOperand(0);
4566 OM0.setSymbolicName(DstIOperand.Name);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00004567 M.defineOperand(OM0.getSymbolicName(), OM0);
Daniel Sandersedd07842017-08-17 09:26:14 +00004568 OM0.addPredicate<RegisterBankOperandMatcher>(RC);
4569
Daniel Sanders198447a2017-11-01 00:29:47 +00004570 auto &DstMIBuilder =
4571 M.addAction<BuildMIAction>(M.allocateOutputInsnID(), &DstI);
4572 DstMIBuilder.addRenderer<CopyRenderer>(DstIOperand.Name);
Florian Hahn6b1db822018-06-14 20:32:58 +00004573 DstMIBuilder.addRenderer<CopyRenderer>(Dst->getName());
Daniel Sandersedd07842017-08-17 09:26:14 +00004574 M.addAction<ConstrainOperandToRegClassAction>(0, 0, RC);
4575
4576 // We're done with this pattern! It's eligible for GISel emission; return
4577 // it.
4578 ++NumPatternImported;
4579 return std::move(M);
4580 }
4581
Daniel Sanders452c8ae2017-05-23 19:33:16 +00004582 return failedImport("Dst pattern root isn't a known leaf");
Daniel Sandersedd07842017-08-17 09:26:14 +00004583 }
Daniel Sanders452c8ae2017-05-23 19:33:16 +00004584
Daniel Sandersbee57392017-04-04 13:25:23 +00004585 // Start with the defined operands (i.e., the results of the root operator).
Florian Hahn6b1db822018-06-14 20:32:58 +00004586 Record *DstOp = Dst->getOperator();
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004587 if (!DstOp->isSubClassOf("Instruction"))
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00004588 return failedImport("Pattern operator isn't an instruction");
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004589
4590 auto &DstI = Target.getInstruction(DstOp);
Matt Arsenault38fb3442019-09-04 16:19:34 +00004591 StringRef DstIName = DstI.TheDef->getName();
4592
Florian Hahn6b1db822018-06-14 20:32:58 +00004593 if (DstI.Operands.NumDefs != Src->getExtTypes().size())
Daniel Sandersd0656a32017-04-13 09:45:37 +00004594 return failedImport("Src pattern results and dst MI defs are different (" +
Florian Hahn6b1db822018-06-14 20:32:58 +00004595 to_string(Src->getExtTypes().size()) + " def(s) vs " +
Daniel Sandersd0656a32017-04-13 09:45:37 +00004596 to_string(DstI.Operands.NumDefs) + " def(s))");
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004597
Daniel Sandersffc7d582017-03-29 15:37:18 +00004598 // The root of the match also has constraints on the register bank so that it
4599 // matches the result instruction.
4600 unsigned OpIdx = 0;
Florian Hahn6b1db822018-06-14 20:32:58 +00004601 for (const TypeSetByHwMode &VTy : Src->getExtTypes()) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004602 (void)VTy;
Daniel Sandersffc7d582017-03-29 15:37:18 +00004603
Daniel Sanders066ebbf2017-02-24 15:43:30 +00004604 const auto &DstIOperand = DstI.Operands[OpIdx];
4605 Record *DstIOpRec = DstIOperand.Rec;
Matt Arsenault38fb3442019-09-04 16:19:34 +00004606 if (DstIName == "COPY_TO_REGCLASS") {
Florian Hahn6b1db822018-06-14 20:32:58 +00004607 DstIOpRec = getInitValueAsRegClass(Dst->getChild(1)->getLeafValue());
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004608
4609 if (DstIOpRec == nullptr)
4610 return failedImport(
4611 "COPY_TO_REGCLASS operand #1 isn't a register class");
Matt Arsenault38fb3442019-09-04 16:19:34 +00004612 } else if (DstIName == "REG_SEQUENCE") {
4613 DstIOpRec = getInitValueAsRegClass(Dst->getChild(0)->getLeafValue());
4614 if (DstIOpRec == nullptr)
4615 return failedImport("REG_SEQUENCE operand #0 isn't a register class");
4616 } else if (DstIName == "EXTRACT_SUBREG") {
Florian Hahn6b1db822018-06-14 20:32:58 +00004617 if (!Dst->getChild(0)->isLeaf())
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004618 return failedImport("EXTRACT_SUBREG operand #0 isn't a leaf");
4619
Daniel Sanders32291982017-06-28 13:50:04 +00004620 // We can assume that a subregister is in the same bank as it's super
4621 // register.
Florian Hahn6b1db822018-06-14 20:32:58 +00004622 DstIOpRec = getInitValueAsRegClass(Dst->getChild(0)->getLeafValue());
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004623
4624 if (DstIOpRec == nullptr)
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004625 return failedImport("EXTRACT_SUBREG operand #0 isn't a register class");
Matt Arsenault38fb3442019-09-04 16:19:34 +00004626 } else if (DstIName == "INSERT_SUBREG") {
Jessica Paquette7080ffa2019-08-28 20:12:31 +00004627 auto MaybeSuperClass = inferSuperRegisterClassForNode(
4628 VTy, Dst->getChild(0), Dst->getChild(2));
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004629 if (!MaybeSuperClass)
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004630 return failedImport(
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004631 "Cannot infer register class for INSERT_SUBREG operand #0");
4632 // Move to the next pattern here, because the register class we found
4633 // doesn't necessarily have a record associated with it. So, we can't
4634 // set DstIOpRec using this.
4635 OperandMatcher &OM = InsnMatcher.getOperand(OpIdx);
4636 OM.setSymbolicName(DstIOperand.Name);
4637 M.defineOperand(OM.getSymbolicName(), OM);
4638 OM.addPredicate<RegisterBankOperandMatcher>(**MaybeSuperClass);
4639 ++OpIdx;
4640 continue;
Matt Arsenault38fb3442019-09-04 16:19:34 +00004641 } else if (DstIName == "SUBREG_TO_REG") {
Jessica Paquette7080ffa2019-08-28 20:12:31 +00004642 auto MaybeRegClass = inferSuperRegisterClass(VTy, Dst->getChild(2));
4643 if (!MaybeRegClass)
4644 return failedImport(
4645 "Cannot infer register class for SUBREG_TO_REG operand #0");
4646 OperandMatcher &OM = InsnMatcher.getOperand(OpIdx);
4647 OM.setSymbolicName(DstIOperand.Name);
4648 M.defineOperand(OM.getSymbolicName(), OM);
4649 OM.addPredicate<RegisterBankOperandMatcher>(**MaybeRegClass);
4650 ++OpIdx;
4651 continue;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004652 } else if (DstIOpRec->isSubClassOf("RegisterOperand"))
Daniel Sanders658541f2017-04-22 15:53:21 +00004653 DstIOpRec = DstIOpRec->getValueAsDef("RegClass");
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004654 else if (!DstIOpRec->isSubClassOf("RegisterClass"))
Florian Hahn6b1db822018-06-14 20:32:58 +00004655 return failedImport("Dst MI def isn't a register class" +
4656 to_string(*Dst));
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004657
Daniel Sandersffc7d582017-03-29 15:37:18 +00004658 OperandMatcher &OM = InsnMatcher.getOperand(OpIdx);
4659 OM.setSymbolicName(DstIOperand.Name);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00004660 M.defineOperand(OM.getSymbolicName(), OM);
Daniel Sandersdc662ff2017-01-26 11:10:14 +00004661 OM.addPredicate<RegisterBankOperandMatcher>(
4662 Target.getRegisterClass(DstIOpRec));
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004663 ++OpIdx;
4664 }
4665
Matt Arsenault3e45c702019-09-06 20:32:37 +00004666 auto DstMIBuilderOrError =
4667 createAndImportInstructionRenderer(M, InsnMatcher, Src, Dst);
Daniel Sandersffc7d582017-03-29 15:37:18 +00004668 if (auto Error = DstMIBuilderOrError.takeError())
4669 return std::move(Error);
4670 BuildMIAction &DstMIBuilder = DstMIBuilderOrError.get();
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004671
Daniel Sandersffc7d582017-03-29 15:37:18 +00004672 // Render the implicit defs.
4673 // These are only added to the root of the result.
Daniel Sandersc270c502017-03-30 09:36:33 +00004674 if (auto Error = importImplicitDefRenderers(DstMIBuilder, P.getDstRegs()))
Daniel Sandersffc7d582017-03-29 15:37:18 +00004675 return std::move(Error);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004676
Daniel Sandersa7b75262017-10-31 18:50:24 +00004677 DstMIBuilder.chooseInsnToMutate(M);
4678
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004679 // Constrain the registers to classes. This is normally derived from the
4680 // emitted instruction but a few instructions require special handling.
Matt Arsenault38fb3442019-09-04 16:19:34 +00004681 if (DstIName == "COPY_TO_REGCLASS") {
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004682 // COPY_TO_REGCLASS does not provide operand constraints itself but the
4683 // result is constrained to the class given by the second child.
4684 Record *DstIOpRec =
Florian Hahn6b1db822018-06-14 20:32:58 +00004685 getInitValueAsRegClass(Dst->getChild(1)->getLeafValue());
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004686
4687 if (DstIOpRec == nullptr)
4688 return failedImport("COPY_TO_REGCLASS operand #1 isn't a register class");
4689
4690 M.addAction<ConstrainOperandToRegClassAction>(
Daniel Sandersd93a35a2017-07-05 09:39:33 +00004691 0, 0, Target.getRegisterClass(DstIOpRec));
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004692
4693 // We're done with this pattern! It's eligible for GISel emission; return
4694 // it.
4695 ++NumPatternImported;
4696 return std::move(M);
4697 }
4698
Matt Arsenault38fb3442019-09-04 16:19:34 +00004699 if (DstIName == "EXTRACT_SUBREG") {
Matt Arsenault9ceb6ed2019-09-06 00:05:58 +00004700 auto SuperClass = inferRegClassFromPattern(Dst->getChild(0));
4701 if (!SuperClass)
4702 return failedImport(
4703 "Cannot infer register class from EXTRACT_SUBREG operand #0");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004704
Matt Arsenault9ceb6ed2019-09-06 00:05:58 +00004705 auto SubIdx = inferSubRegIndexForNode(Dst->getChild(1));
4706 if (!SubIdx)
Daniel Sanders320390b2017-06-28 15:16:03 +00004707 return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004708
Daniel Sanders320390b2017-06-28 15:16:03 +00004709 // It would be nice to leave this constraint implicit but we're required
4710 // to pick a register class so constrain the result to a register class
4711 // that can hold the correct MVT.
4712 //
4713 // FIXME: This may introduce an extra copy if the chosen class doesn't
4714 // actually contain the subregisters.
Florian Hahn6b1db822018-06-14 20:32:58 +00004715 assert(Src->getExtTypes().size() == 1 &&
Daniel Sanders320390b2017-06-28 15:16:03 +00004716 "Expected Src of EXTRACT_SUBREG to have one result type");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004717
Daniel Sanders320390b2017-06-28 15:16:03 +00004718 const auto &SrcRCDstRCPair =
Matt Arsenault9ceb6ed2019-09-06 00:05:58 +00004719 (*SuperClass)->getMatchingSubClassWithSubRegs(CGRegs, *SubIdx);
Daniel Sanders320390b2017-06-28 15:16:03 +00004720 assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
Daniel Sandersd93a35a2017-07-05 09:39:33 +00004721 M.addAction<ConstrainOperandToRegClassAction>(0, 0, *SrcRCDstRCPair->second);
4722 M.addAction<ConstrainOperandToRegClassAction>(0, 1, *SrcRCDstRCPair->first);
4723
4724 // We're done with this pattern! It's eligible for GISel emission; return
4725 // it.
4726 ++NumPatternImported;
4727 return std::move(M);
4728 }
4729
Matt Arsenault38fb3442019-09-04 16:19:34 +00004730 if (DstIName == "INSERT_SUBREG") {
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004731 assert(Src->getExtTypes().size() == 1 &&
4732 "Expected Src of INSERT_SUBREG to have one result type");
4733 // We need to constrain the destination, a super regsister source, and a
4734 // subregister source.
4735 auto SubClass = inferRegClassFromPattern(Dst->getChild(1));
4736 if (!SubClass)
4737 return failedImport(
4738 "Cannot infer register class from INSERT_SUBREG operand #1");
Jessica Paquette7080ffa2019-08-28 20:12:31 +00004739 auto SuperClass = inferSuperRegisterClassForNode(
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004740 Src->getExtType(0), Dst->getChild(0), Dst->getChild(2));
4741 if (!SuperClass)
4742 return failedImport(
4743 "Cannot infer register class for INSERT_SUBREG operand #0");
4744 M.addAction<ConstrainOperandToRegClassAction>(0, 0, **SuperClass);
4745 M.addAction<ConstrainOperandToRegClassAction>(0, 1, **SuperClass);
4746 M.addAction<ConstrainOperandToRegClassAction>(0, 2, **SubClass);
4747 ++NumPatternImported;
4748 return std::move(M);
4749 }
4750
Matt Arsenault38fb3442019-09-04 16:19:34 +00004751 if (DstIName == "SUBREG_TO_REG") {
Jessica Paquette7080ffa2019-08-28 20:12:31 +00004752 // We need to constrain the destination and subregister source.
4753 assert(Src->getExtTypes().size() == 1 &&
4754 "Expected Src of SUBREG_TO_REG to have one result type");
4755
4756 // Attempt to infer the subregister source from the first child. If it has
4757 // an explicitly given register class, we'll use that. Otherwise, we will
4758 // fail.
4759 auto SubClass = inferRegClassFromPattern(Dst->getChild(1));
4760 if (!SubClass)
4761 return failedImport(
4762 "Cannot infer register class from SUBREG_TO_REG child #1");
4763 // We don't have a child to look at that might have a super register node.
4764 auto SuperClass =
4765 inferSuperRegisterClass(Src->getExtType(0), Dst->getChild(2));
4766 if (!SuperClass)
4767 return failedImport(
4768 "Cannot infer register class for SUBREG_TO_REG operand #0");
4769 M.addAction<ConstrainOperandToRegClassAction>(0, 0, **SuperClass);
4770 M.addAction<ConstrainOperandToRegClassAction>(0, 2, **SubClass);
4771 ++NumPatternImported;
4772 return std::move(M);
4773 }
4774
Daniel Sandersd93a35a2017-07-05 09:39:33 +00004775 M.addAction<ConstrainOperandsToDefinitionAction>(0);
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004776
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00004777 // We're done with this pattern! It's eligible for GISel emission; return it.
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00004778 ++NumPatternImported;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00004779 return std::move(M);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004780}
4781
Daniel Sanders649c5852017-10-13 20:42:18 +00004782// Emit imm predicate table and an enum to reference them with.
4783// The 'Predicate_' part of the name is redundant but eliminating it is more
4784// trouble than it's worth.
Daniel Sanders8ead1292018-06-15 23:13:43 +00004785void GlobalISelEmitter::emitCxxPredicateFns(
4786 raw_ostream &OS, StringRef CodeFieldName, StringRef TypeIdentifier,
4787 StringRef ArgType, StringRef ArgName, StringRef AdditionalDeclarations,
Daniel Sanders11300ce2017-10-13 21:28:03 +00004788 std::function<bool(const Record *R)> Filter) {
Daniel Sanders649c5852017-10-13 20:42:18 +00004789 std::vector<const Record *> MatchedRecords;
4790 const auto &Defs = RK.getAllDerivedDefinitions("PatFrag");
4791 std::copy_if(Defs.begin(), Defs.end(), std::back_inserter(MatchedRecords),
4792 [&](Record *Record) {
Daniel Sanders8ead1292018-06-15 23:13:43 +00004793 return !Record->getValueAsString(CodeFieldName).empty() &&
Daniel Sanders649c5852017-10-13 20:42:18 +00004794 Filter(Record);
4795 });
4796
Daniel Sanders11300ce2017-10-13 21:28:03 +00004797 if (!MatchedRecords.empty()) {
4798 OS << "// PatFrag predicates.\n"
4799 << "enum {\n";
Daniel Sanders2fed4ff2017-10-13 21:51:20 +00004800 std::string EnumeratorSeparator =
Daniel Sanders11300ce2017-10-13 21:28:03 +00004801 (" = GIPFP_" + TypeIdentifier + "_Invalid + 1,\n").str();
4802 for (const auto *Record : MatchedRecords) {
4803 OS << " GIPFP_" << TypeIdentifier << "_Predicate_" << Record->getName()
4804 << EnumeratorSeparator;
4805 EnumeratorSeparator = ",\n";
4806 }
4807 OS << "};\n";
Daniel Sanders649c5852017-10-13 20:42:18 +00004808 }
Daniel Sanders11300ce2017-10-13 21:28:03 +00004809
Daniel Sanders8ead1292018-06-15 23:13:43 +00004810 OS << "bool " << Target.getName() << "InstructionSelector::test" << ArgName
4811 << "Predicate_" << TypeIdentifier << "(unsigned PredicateID, " << ArgType << " "
4812 << ArgName << ") const {\n"
4813 << AdditionalDeclarations;
4814 if (!AdditionalDeclarations.empty())
4815 OS << "\n";
Aaron Ballman82e17f52017-12-20 20:09:30 +00004816 if (!MatchedRecords.empty())
4817 OS << " switch (PredicateID) {\n";
Daniel Sanders32de8bb2017-12-20 14:41:51 +00004818 for (const auto *Record : MatchedRecords) {
4819 OS << " case GIPFP_" << TypeIdentifier << "_Predicate_"
4820 << Record->getName() << ": {\n"
Daniel Sanders8ead1292018-06-15 23:13:43 +00004821 << " " << Record->getValueAsString(CodeFieldName) << "\n"
4822 << " llvm_unreachable(\"" << CodeFieldName
4823 << " should have returned\");\n"
Daniel Sanders32de8bb2017-12-20 14:41:51 +00004824 << " return false;\n"
4825 << " }\n";
4826 }
Aaron Ballman82e17f52017-12-20 20:09:30 +00004827 if (!MatchedRecords.empty())
4828 OS << " }\n";
4829 OS << " llvm_unreachable(\"Unknown predicate\");\n"
Daniel Sanders32de8bb2017-12-20 14:41:51 +00004830 << " return false;\n"
4831 << "}\n";
Daniel Sanders649c5852017-10-13 20:42:18 +00004832}
4833
Daniel Sanders8ead1292018-06-15 23:13:43 +00004834void GlobalISelEmitter::emitImmPredicateFns(
4835 raw_ostream &OS, StringRef TypeIdentifier, StringRef ArgType,
4836 std::function<bool(const Record *R)> Filter) {
4837 return emitCxxPredicateFns(OS, "ImmediateCode", TypeIdentifier, ArgType,
4838 "Imm", "", Filter);
4839}
4840
4841void GlobalISelEmitter::emitMIPredicateFns(raw_ostream &OS) {
4842 return emitCxxPredicateFns(
4843 OS, "GISelPredicateCode", "MI", "const MachineInstr &", "MI",
4844 " const MachineFunction &MF = *MI.getParent()->getParent();\n"
Andrei Elovikov36cbbff2018-06-26 07:05:08 +00004845 " const MachineRegisterInfo &MRI = MF.getRegInfo();\n"
4846 " (void)MRI;",
Daniel Sanders8ead1292018-06-15 23:13:43 +00004847 [](const Record *R) { return true; });
4848}
4849
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004850template <class GroupT>
Quentin Colombetec76d9c2017-12-18 19:47:41 +00004851std::vector<Matcher *> GlobalISelEmitter::optimizeRules(
Roman Tereshin2d6d3762018-05-02 20:08:14 +00004852 ArrayRef<Matcher *> Rules,
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004853 std::vector<std::unique_ptr<Matcher>> &MatcherStorage) {
4854
Quentin Colombetec76d9c2017-12-18 19:47:41 +00004855 std::vector<Matcher *> OptRules;
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00004856 std::unique_ptr<GroupT> CurrentGroup = std::make_unique<GroupT>();
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004857 assert(CurrentGroup->empty() && "Newly created group isn't empty!");
4858 unsigned NumGroups = 0;
4859
4860 auto ProcessCurrentGroup = [&]() {
4861 if (CurrentGroup->empty())
4862 // An empty group is good to be reused:
4863 return;
4864
4865 // If the group isn't large enough to provide any benefit, move all the
4866 // added rules out of it and make sure to re-create the group to properly
4867 // re-initialize it:
4868 if (CurrentGroup->size() < 2)
4869 for (Matcher *M : CurrentGroup->matchers())
4870 OptRules.push_back(M);
4871 else {
4872 CurrentGroup->finalize();
Roman Tereshin8bdf7be2018-05-21 22:21:24 +00004873 OptRules.push_back(CurrentGroup.get());
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004874 MatcherStorage.emplace_back(std::move(CurrentGroup));
4875 ++NumGroups;
Roman Tereshin8bdf7be2018-05-21 22:21:24 +00004876 }
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00004877 CurrentGroup = std::make_unique<GroupT>();
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004878 };
4879 for (Matcher *Rule : Rules) {
4880 // Greedily add as many matchers as possible to the current group:
4881 if (CurrentGroup->addMatcher(*Rule))
4882 continue;
4883
4884 ProcessCurrentGroup();
4885 assert(CurrentGroup->empty() && "A group wasn't properly re-initialized");
4886
4887 // Try to add the pending matcher to a newly created empty group:
4888 if (!CurrentGroup->addMatcher(*Rule))
4889 // If we couldn't add the matcher to an empty group, that group type
4890 // doesn't support that kind of matchers at all, so just skip it:
4891 OptRules.push_back(Rule);
Quentin Colombetec76d9c2017-12-18 19:47:41 +00004892 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004893 ProcessCurrentGroup();
4894
Nicola Zaghen03d0b912018-05-23 15:09:29 +00004895 LLVM_DEBUG(dbgs() << "NumGroups: " << NumGroups << "\n");
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004896 assert(CurrentGroup->empty() && "The last group wasn't properly processed");
Quentin Colombetec76d9c2017-12-18 19:47:41 +00004897 return OptRules;
4898}
4899
Roman Tereshin2d6d3762018-05-02 20:08:14 +00004900MatchTable
4901GlobalISelEmitter::buildMatchTable(MutableArrayRef<RuleMatcher> Rules,
Roman Tereshinbeb39312018-05-02 20:15:11 +00004902 bool Optimize, bool WithCoverage) {
Roman Tereshin2d6d3762018-05-02 20:08:14 +00004903 std::vector<Matcher *> InputRules;
4904 for (Matcher &Rule : Rules)
4905 InputRules.push_back(&Rule);
4906
4907 if (!Optimize)
Roman Tereshinbeb39312018-05-02 20:15:11 +00004908 return MatchTable::buildTable(InputRules, WithCoverage);
Roman Tereshin2d6d3762018-05-02 20:08:14 +00004909
Roman Tereshin77013602018-05-22 16:54:27 +00004910 unsigned CurrentOrdering = 0;
4911 StringMap<unsigned> OpcodeOrder;
4912 for (RuleMatcher &Rule : Rules) {
4913 const StringRef Opcode = Rule.getOpcode();
4914 assert(!Opcode.empty() && "Didn't expect an undefined opcode");
4915 if (OpcodeOrder.count(Opcode) == 0)
4916 OpcodeOrder[Opcode] = CurrentOrdering++;
4917 }
4918
4919 std::stable_sort(InputRules.begin(), InputRules.end(),
4920 [&OpcodeOrder](const Matcher *A, const Matcher *B) {
4921 auto *L = static_cast<const RuleMatcher *>(A);
4922 auto *R = static_cast<const RuleMatcher *>(B);
4923 return std::make_tuple(OpcodeOrder[L->getOpcode()],
4924 L->getNumOperands()) <
4925 std::make_tuple(OpcodeOrder[R->getOpcode()],
4926 R->getNumOperands());
4927 });
4928
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004929 for (Matcher *Rule : InputRules)
4930 Rule->optimize();
4931
4932 std::vector<std::unique_ptr<Matcher>> MatcherStorage;
Roman Tereshin2d6d3762018-05-02 20:08:14 +00004933 std::vector<Matcher *> OptRules =
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004934 optimizeRules<GroupMatcher>(InputRules, MatcherStorage);
4935
4936 for (Matcher *Rule : OptRules)
4937 Rule->optimize();
Roman Tereshin2d6d3762018-05-02 20:08:14 +00004938
Roman Tereshin0ee082f2018-05-22 19:37:59 +00004939 OptRules = optimizeRules<SwitchMatcher>(OptRules, MatcherStorage);
4940
Roman Tereshinbeb39312018-05-02 20:15:11 +00004941 return MatchTable::buildTable(OptRules, WithCoverage);
Roman Tereshin2d6d3762018-05-02 20:08:14 +00004942}
4943
Roman Tereshinfedae332018-05-23 02:04:19 +00004944void GroupMatcher::optimize() {
Roman Tereshin9a9fa492018-05-23 21:30:16 +00004945 // Make sure we only sort by a specific predicate within a range of rules that
4946 // all have that predicate checked against a specific value (not a wildcard):
4947 auto F = Matchers.begin();
4948 auto T = F;
4949 auto E = Matchers.end();
4950 while (T != E) {
4951 while (T != E) {
4952 auto *R = static_cast<RuleMatcher *>(*T);
4953 if (!R->getFirstConditionAsRootType().get().isValid())
4954 break;
4955 ++T;
4956 }
4957 std::stable_sort(F, T, [](Matcher *A, Matcher *B) {
4958 auto *L = static_cast<RuleMatcher *>(A);
4959 auto *R = static_cast<RuleMatcher *>(B);
4960 return L->getFirstConditionAsRootType() <
4961 R->getFirstConditionAsRootType();
4962 });
4963 if (T != E)
4964 F = ++T;
4965 }
Roman Tereshinfedae332018-05-23 02:04:19 +00004966 GlobalISelEmitter::optimizeRules<GroupMatcher>(Matchers, MatcherStorage)
4967 .swap(Matchers);
Roman Tereshina4c410d2018-05-24 00:24:15 +00004968 GlobalISelEmitter::optimizeRules<SwitchMatcher>(Matchers, MatcherStorage)
4969 .swap(Matchers);
Roman Tereshinfedae332018-05-23 02:04:19 +00004970}
4971
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004972void GlobalISelEmitter::run(raw_ostream &OS) {
Daniel Sandersf76f3152017-11-16 00:46:35 +00004973 if (!UseCoverageFile.empty()) {
4974 RuleCoverage = CodeGenCoverage();
4975 auto RuleCoverageBufOrErr = MemoryBuffer::getFile(UseCoverageFile);
4976 if (!RuleCoverageBufOrErr) {
4977 PrintWarning(SMLoc(), "Missing rule coverage data");
4978 RuleCoverage = None;
4979 } else {
4980 if (!RuleCoverage->parse(*RuleCoverageBufOrErr.get(), Target.getName())) {
4981 PrintWarning(SMLoc(), "Ignoring invalid or missing rule coverage data");
4982 RuleCoverage = None;
4983 }
4984 }
4985 }
4986
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004987 // Track the run-time opcode values
4988 gatherOpcodeValues();
4989 // Track the run-time LLT ID values
4990 gatherTypeIDValues();
4991
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004992 // Track the GINodeEquiv definitions.
4993 gatherNodeEquivs();
4994
4995 emitSourceFileHeader(("Global Instruction Selector for the " +
4996 Target.getName() + " target").str(), OS);
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00004997 std::vector<RuleMatcher> Rules;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004998 // Look through the SelectionDAG patterns we found, possibly emitting some.
4999 for (const PatternToMatch &Pat : CGP.ptms()) {
5000 ++NumPatternTotal;
Daniel Sanders7e523672017-11-11 03:23:44 +00005001
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00005002 auto MatcherOrErr = runOnPattern(Pat);
5003
5004 // The pattern analysis can fail, indicating an unsupported pattern.
5005 // Report that if we've been asked to do so.
5006 if (auto Err = MatcherOrErr.takeError()) {
Ahmed Bougacha36f70352016-12-21 23:26:20 +00005007 if (WarnOnSkippedPatterns) {
5008 PrintWarning(Pat.getSrcRecord()->getLoc(),
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00005009 "Skipped pattern: " + toString(std::move(Err)));
5010 } else {
5011 consumeError(std::move(Err));
Ahmed Bougacha36f70352016-12-21 23:26:20 +00005012 }
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00005013 ++NumPatternImportsSkipped;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00005014 continue;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00005015 }
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00005016
Daniel Sandersf76f3152017-11-16 00:46:35 +00005017 if (RuleCoverage) {
5018 if (RuleCoverage->isCovered(MatcherOrErr->getRuleID()))
5019 ++NumPatternsTested;
5020 else
5021 PrintWarning(Pat.getSrcRecord()->getLoc(),
5022 "Pattern is not covered by a test");
5023 }
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00005024 Rules.push_back(std::move(MatcherOrErr.get()));
5025 }
5026
Volkan Kelesf7f25682018-01-16 18:44:05 +00005027 // Comparison function to order records by name.
5028 auto orderByName = [](const Record *A, const Record *B) {
5029 return A->getName() < B->getName();
5030 };
5031
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00005032 std::vector<Record *> ComplexPredicates =
5033 RK.getAllDerivedDefinitions("GIComplexOperandMatcher");
Fangrui Song0cac7262018-09-27 02:13:45 +00005034 llvm::sort(ComplexPredicates, orderByName);
Volkan Kelesf7f25682018-01-16 18:44:05 +00005035
5036 std::vector<Record *> CustomRendererFns =
5037 RK.getAllDerivedDefinitions("GICustomOperandRenderer");
Fangrui Song0cac7262018-09-27 02:13:45 +00005038 llvm::sort(CustomRendererFns, orderByName);
Volkan Kelesf7f25682018-01-16 18:44:05 +00005039
Daniel Sanders8a4bae92017-03-14 21:32:08 +00005040 unsigned MaxTemporaries = 0;
5041 for (const auto &Rule : Rules)
Daniel Sanders2deea182017-04-22 15:11:04 +00005042 MaxTemporaries = std::max(MaxTemporaries, Rule.countRendererFns());
Daniel Sanders8a4bae92017-03-14 21:32:08 +00005043
Daniel Sanderse7b0d662017-04-21 15:59:56 +00005044 OS << "#ifdef GET_GLOBALISEL_PREDICATE_BITSET\n"
5045 << "const unsigned MAX_SUBTARGET_PREDICATES = " << SubtargetFeatures.size()
5046 << ";\n"
5047 << "using PredicateBitset = "
5048 "llvm::PredicateBitsetImpl<MAX_SUBTARGET_PREDICATES>;\n"
5049 << "#endif // ifdef GET_GLOBALISEL_PREDICATE_BITSET\n\n";
5050
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00005051 OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n"
5052 << " mutable MatcherState State;\n"
5053 << " typedef "
Daniel Sanders1e4569f2017-10-20 20:55:29 +00005054 "ComplexRendererFns("
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00005055 << Target.getName()
5056 << "InstructionSelector::*ComplexMatcherMemFn)(MachineOperand &) const;\n"
Volkan Kelesf7f25682018-01-16 18:44:05 +00005057
5058 << " typedef void(" << Target.getName()
5059 << "InstructionSelector::*CustomRendererFn)(MachineInstrBuilder &, const "
5060 "MachineInstr&) "
5061 "const;\n"
5062 << " const ISelInfoTy<PredicateBitset, ComplexMatcherMemFn, "
5063 "CustomRendererFn> "
5064 "ISelInfo;\n";
5065 OS << " static " << Target.getName()
Daniel Sandersea8711b2017-10-16 03:36:29 +00005066 << "InstructionSelector::ComplexMatcherMemFn ComplexPredicateFns[];\n"
Volkan Kelesf7f25682018-01-16 18:44:05 +00005067 << " static " << Target.getName()
5068 << "InstructionSelector::CustomRendererFn CustomRenderers[];\n"
Roman Tereshin2df4c222018-05-02 20:07:15 +00005069 << " bool testImmPredicate_I64(unsigned PredicateID, int64_t Imm) const "
Daniel Sanders32de8bb2017-12-20 14:41:51 +00005070 "override;\n"
Roman Tereshin2df4c222018-05-02 20:07:15 +00005071 << " bool testImmPredicate_APInt(unsigned PredicateID, const APInt &Imm) "
Daniel Sanders32de8bb2017-12-20 14:41:51 +00005072 "const override;\n"
Roman Tereshin2df4c222018-05-02 20:07:15 +00005073 << " bool testImmPredicate_APFloat(unsigned PredicateID, const APFloat "
Daniel Sanders32de8bb2017-12-20 14:41:51 +00005074 "&Imm) const override;\n"
Roman Tereshin2df4c222018-05-02 20:07:15 +00005075 << " const int64_t *getMatchTable() const override;\n"
Daniel Sanders8ead1292018-06-15 23:13:43 +00005076 << " bool testMIPredicate_MI(unsigned PredicateID, const MachineInstr &MI) "
5077 "const override;\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00005078 << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n\n";
Daniel Sanders8a4bae92017-03-14 21:32:08 +00005079
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00005080 OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n"
5081 << ", State(" << MaxTemporaries << "),\n"
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005082 << "ISelInfo(TypeObjects, NumTypeObjects, FeatureBitsets"
5083 << ", ComplexPredicateFns, CustomRenderers)\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00005084 << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n\n";
Daniel Sanders8a4bae92017-03-14 21:32:08 +00005085
Daniel Sanderse7b0d662017-04-21 15:59:56 +00005086 OS << "#ifdef GET_GLOBALISEL_IMPL\n";
5087 SubtargetFeatureInfo::emitSubtargetFeatureBitEnumeration(SubtargetFeatures,
5088 OS);
Daniel Sanderse9fdba32017-04-29 17:30:09 +00005089
5090 // Separate subtarget features by how often they must be recomputed.
5091 SubtargetFeatureInfoMap ModuleFeatures;
5092 std::copy_if(SubtargetFeatures.begin(), SubtargetFeatures.end(),
5093 std::inserter(ModuleFeatures, ModuleFeatures.end()),
5094 [](const SubtargetFeatureInfoMap::value_type &X) {
5095 return !X.second.mustRecomputePerFunction();
5096 });
5097 SubtargetFeatureInfoMap FunctionFeatures;
5098 std::copy_if(SubtargetFeatures.begin(), SubtargetFeatures.end(),
5099 std::inserter(FunctionFeatures, FunctionFeatures.end()),
5100 [](const SubtargetFeatureInfoMap::value_type &X) {
5101 return X.second.mustRecomputePerFunction();
5102 });
5103
Daniel Sanderse7b0d662017-04-21 15:59:56 +00005104 SubtargetFeatureInfo::emitComputeAvailableFeatures(
Daniel Sanderse9fdba32017-04-29 17:30:09 +00005105 Target.getName(), "InstructionSelector", "computeAvailableModuleFeatures",
5106 ModuleFeatures, OS);
5107 SubtargetFeatureInfo::emitComputeAvailableFeatures(
5108 Target.getName(), "InstructionSelector",
5109 "computeAvailableFunctionFeatures", FunctionFeatures, OS,
5110 "const MachineFunction *MF");
Daniel Sanderse7b0d662017-04-21 15:59:56 +00005111
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00005112 // Emit a table containing the LLT objects needed by the matcher and an enum
5113 // for the matcher to reference them with.
Daniel Sanders032e7f22017-08-17 13:18:35 +00005114 std::vector<LLTCodeGen> TypeObjects;
Daniel Sandersf84bc372018-05-05 20:53:24 +00005115 for (const auto &Ty : KnownTypes)
Daniel Sanders032e7f22017-08-17 13:18:35 +00005116 TypeObjects.push_back(Ty);
Fangrui Song0cac7262018-09-27 02:13:45 +00005117 llvm::sort(TypeObjects);
Daniel Sanders49980702017-08-23 10:09:25 +00005118 OS << "// LLT Objects.\n"
5119 << "enum {\n";
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00005120 for (const auto &TypeObject : TypeObjects) {
5121 OS << " ";
5122 TypeObject.emitCxxEnumValue(OS);
5123 OS << ",\n";
5124 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005125 OS << "};\n";
5126 OS << "const static size_t NumTypeObjects = " << TypeObjects.size() << ";\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00005127 << "const static LLT TypeObjects[] = {\n";
5128 for (const auto &TypeObject : TypeObjects) {
5129 OS << " ";
5130 TypeObject.emitCxxConstructorCall(OS);
5131 OS << ",\n";
5132 }
5133 OS << "};\n\n";
5134
5135 // Emit a table containing the PredicateBitsets objects needed by the matcher
5136 // and an enum for the matcher to reference them with.
5137 std::vector<std::vector<Record *>> FeatureBitsets;
5138 for (auto &Rule : Rules)
5139 FeatureBitsets.push_back(Rule.getRequiredFeatures());
Fangrui Song3507c6e2018-09-30 22:31:29 +00005140 llvm::sort(FeatureBitsets, [&](const std::vector<Record *> &A,
5141 const std::vector<Record *> &B) {
5142 if (A.size() < B.size())
5143 return true;
5144 if (A.size() > B.size())
5145 return false;
5146 for (const auto &Pair : zip(A, B)) {
5147 if (std::get<0>(Pair)->getName() < std::get<1>(Pair)->getName())
5148 return true;
5149 if (std::get<0>(Pair)->getName() > std::get<1>(Pair)->getName())
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00005150 return false;
Fangrui Song3507c6e2018-09-30 22:31:29 +00005151 }
5152 return false;
5153 });
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00005154 FeatureBitsets.erase(
5155 std::unique(FeatureBitsets.begin(), FeatureBitsets.end()),
5156 FeatureBitsets.end());
Daniel Sanders49980702017-08-23 10:09:25 +00005157 OS << "// Feature bitsets.\n"
5158 << "enum {\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00005159 << " GIFBS_Invalid,\n";
5160 for (const auto &FeatureBitset : FeatureBitsets) {
5161 if (FeatureBitset.empty())
5162 continue;
5163 OS << " " << getNameForFeatureBitset(FeatureBitset) << ",\n";
5164 }
5165 OS << "};\n"
5166 << "const static PredicateBitset FeatureBitsets[] {\n"
5167 << " {}, // GIFBS_Invalid\n";
5168 for (const auto &FeatureBitset : FeatureBitsets) {
5169 if (FeatureBitset.empty())
5170 continue;
5171 OS << " {";
5172 for (const auto &Feature : FeatureBitset) {
5173 const auto &I = SubtargetFeatures.find(Feature);
5174 assert(I != SubtargetFeatures.end() && "Didn't import predicate?");
5175 OS << I->second.getEnumBitName() << ", ";
5176 }
5177 OS << "},\n";
5178 }
5179 OS << "};\n\n";
5180
5181 // Emit complex predicate table and an enum to reference them with.
Daniel Sanders49980702017-08-23 10:09:25 +00005182 OS << "// ComplexPattern predicates.\n"
5183 << "enum {\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00005184 << " GICP_Invalid,\n";
5185 for (const auto &Record : ComplexPredicates)
5186 OS << " GICP_" << Record->getName() << ",\n";
5187 OS << "};\n"
5188 << "// See constructor for table contents\n\n";
5189
Daniel Sanders8ead1292018-06-15 23:13:43 +00005190 emitImmPredicateFns(OS, "I64", "int64_t", [](const Record *R) {
Daniel Sanders649c5852017-10-13 20:42:18 +00005191 bool Unset;
5192 return !R->getValueAsBitOrUnset("IsAPFloat", Unset) &&
5193 !R->getValueAsBit("IsAPInt");
5194 });
Daniel Sanders8ead1292018-06-15 23:13:43 +00005195 emitImmPredicateFns(OS, "APFloat", "const APFloat &", [](const Record *R) {
Daniel Sanders11300ce2017-10-13 21:28:03 +00005196 bool Unset;
5197 return R->getValueAsBitOrUnset("IsAPFloat", Unset);
5198 });
Daniel Sanders8ead1292018-06-15 23:13:43 +00005199 emitImmPredicateFns(OS, "APInt", "const APInt &", [](const Record *R) {
Daniel Sanders11300ce2017-10-13 21:28:03 +00005200 return R->getValueAsBit("IsAPInt");
5201 });
Daniel Sanders8ead1292018-06-15 23:13:43 +00005202 emitMIPredicateFns(OS);
Daniel Sandersea8711b2017-10-16 03:36:29 +00005203 OS << "\n";
5204
5205 OS << Target.getName() << "InstructionSelector::ComplexMatcherMemFn\n"
5206 << Target.getName() << "InstructionSelector::ComplexPredicateFns[] = {\n"
5207 << " nullptr, // GICP_Invalid\n";
5208 for (const auto &Record : ComplexPredicates)
5209 OS << " &" << Target.getName()
5210 << "InstructionSelector::" << Record->getValueAsString("MatcherFn")
5211 << ", // " << Record->getName() << "\n";
5212 OS << "};\n\n";
Daniel Sanders2c269f62017-08-24 09:11:20 +00005213
Volkan Kelesf7f25682018-01-16 18:44:05 +00005214 OS << "// Custom renderers.\n"
5215 << "enum {\n"
5216 << " GICR_Invalid,\n";
5217 for (const auto &Record : CustomRendererFns)
5218 OS << " GICR_" << Record->getValueAsString("RendererFn") << ", \n";
5219 OS << "};\n";
5220
5221 OS << Target.getName() << "InstructionSelector::CustomRendererFn\n"
5222 << Target.getName() << "InstructionSelector::CustomRenderers[] = {\n"
5223 << " nullptr, // GICP_Invalid\n";
5224 for (const auto &Record : CustomRendererFns)
5225 OS << " &" << Target.getName()
5226 << "InstructionSelector::" << Record->getValueAsString("RendererFn")
5227 << ", // " << Record->getName() << "\n";
5228 OS << "};\n\n";
5229
Fangrui Songefd94c52019-04-23 14:51:27 +00005230 llvm::stable_sort(Rules, [&](const RuleMatcher &A, const RuleMatcher &B) {
Aditya Nandakumarb63e7632018-02-16 22:37:15 +00005231 int ScoreA = RuleMatcherScores[A.getRuleID()];
5232 int ScoreB = RuleMatcherScores[B.getRuleID()];
5233 if (ScoreA > ScoreB)
5234 return true;
5235 if (ScoreB > ScoreA)
5236 return false;
Quentin Colombetec76d9c2017-12-18 19:47:41 +00005237 if (A.isHigherPriorityThan(B)) {
5238 assert(!B.isHigherPriorityThan(A) && "Cannot be more important "
5239 "and less important at "
5240 "the same time");
5241 return true;
5242 }
5243 return false;
5244 });
Ahmed Bougacha36f70352016-12-21 23:26:20 +00005245
Roman Tereshin2df4c222018-05-02 20:07:15 +00005246 OS << "bool " << Target.getName()
5247 << "InstructionSelector::selectImpl(MachineInstr &I, CodeGenCoverage "
5248 "&CoverageInfo) const {\n"
5249 << " MachineFunction &MF = *I.getParent()->getParent();\n"
5250 << " MachineRegisterInfo &MRI = MF.getRegInfo();\n"
5251 << " // FIXME: This should be computed on a per-function basis rather "
5252 "than per-insn.\n"
5253 << " AvailableFunctionFeatures = computeAvailableFunctionFeatures(&STI, "
5254 "&MF);\n"
5255 << " const PredicateBitset AvailableFeatures = getAvailableFeatures();\n"
5256 << " NewMIVector OutMIs;\n"
5257 << " State.MIs.clear();\n"
5258 << " State.MIs.push_back(&I);\n\n"
5259 << " if (executeMatchTable(*this, OutMIs, State, ISelInfo"
5260 << ", getMatchTable(), TII, MRI, TRI, RBI, AvailableFeatures"
5261 << ", CoverageInfo)) {\n"
5262 << " return true;\n"
5263 << " }\n\n"
5264 << " return false;\n"
5265 << "}\n\n";
5266
Roman Tereshinbeb39312018-05-02 20:15:11 +00005267 const MatchTable Table =
5268 buildMatchTable(Rules, OptimizeMatchTable, GenerateCoverage);
Roman Tereshin2df4c222018-05-02 20:07:15 +00005269 OS << "const int64_t *" << Target.getName()
5270 << "InstructionSelector::getMatchTable() const {\n";
5271 Table.emitDeclaration(OS);
5272 OS << " return ";
5273 Table.emitUse(OS);
5274 OS << ";\n}\n";
5275 OS << "#endif // ifdef GET_GLOBALISEL_IMPL\n";
Daniel Sanderse9fdba32017-04-29 17:30:09 +00005276
5277 OS << "#ifdef GET_GLOBALISEL_PREDICATES_DECL\n"
5278 << "PredicateBitset AvailableModuleFeatures;\n"
5279 << "mutable PredicateBitset AvailableFunctionFeatures;\n"
5280 << "PredicateBitset getAvailableFeatures() const {\n"
5281 << " return AvailableModuleFeatures | AvailableFunctionFeatures;\n"
5282 << "}\n"
5283 << "PredicateBitset\n"
5284 << "computeAvailableModuleFeatures(const " << Target.getName()
5285 << "Subtarget *Subtarget) const;\n"
5286 << "PredicateBitset\n"
5287 << "computeAvailableFunctionFeatures(const " << Target.getName()
5288 << "Subtarget *Subtarget,\n"
5289 << " const MachineFunction *MF) const;\n"
5290 << "#endif // ifdef GET_GLOBALISEL_PREDICATES_DECL\n";
5291
5292 OS << "#ifdef GET_GLOBALISEL_PREDICATES_INIT\n"
5293 << "AvailableModuleFeatures(computeAvailableModuleFeatures(&STI)),\n"
5294 << "AvailableFunctionFeatures()\n"
5295 << "#endif // ifdef GET_GLOBALISEL_PREDICATES_INIT\n";
Ahmed Bougacha36f70352016-12-21 23:26:20 +00005296}
5297
Daniel Sanderse7b0d662017-04-21 15:59:56 +00005298void GlobalISelEmitter::declareSubtargetFeature(Record *Predicate) {
5299 if (SubtargetFeatures.count(Predicate) == 0)
5300 SubtargetFeatures.emplace(
5301 Predicate, SubtargetFeatureInfo(Predicate, SubtargetFeatures.size()));
5302}
5303
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005304void RuleMatcher::optimize() {
5305 for (auto &Item : InsnVariableIDs) {
5306 InstructionMatcher &InsnMatcher = *Item.first;
5307 for (auto &OM : InsnMatcher.operands()) {
Roman Tereshin5f5e5502018-05-23 23:58:10 +00005308 // Complex Patterns are usually expensive and they relatively rarely fail
5309 // on their own: more often we end up throwing away all the work done by a
5310 // matching part of a complex pattern because some other part of the
5311 // enclosing pattern didn't match. All of this makes it beneficial to
5312 // delay complex patterns until the very end of the rule matching,
5313 // especially for targets having lots of complex patterns.
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005314 for (auto &OP : OM->predicates())
Roman Tereshin5f5e5502018-05-23 23:58:10 +00005315 if (isa<ComplexPatternOperandMatcher>(OP))
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005316 EpilogueMatchers.emplace_back(std::move(OP));
5317 OM->eraseNullPredicates();
5318 }
5319 InsnMatcher.optimize();
Quentin Colombetec76d9c2017-12-18 19:47:41 +00005320 }
Fangrui Song3507c6e2018-09-30 22:31:29 +00005321 llvm::sort(EpilogueMatchers, [](const std::unique_ptr<PredicateMatcher> &L,
5322 const std::unique_ptr<PredicateMatcher> &R) {
5323 return std::make_tuple(L->getKind(), L->getInsnVarID(), L->getOpIdx()) <
5324 std::make_tuple(R->getKind(), R->getInsnVarID(), R->getOpIdx());
5325 });
Quentin Colombetec76d9c2017-12-18 19:47:41 +00005326}
5327
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005328bool RuleMatcher::hasFirstCondition() const {
5329 if (insnmatchers_empty())
5330 return false;
5331 InstructionMatcher &Matcher = insnmatchers_front();
5332 if (!Matcher.predicates_empty())
5333 return true;
5334 for (auto &OM : Matcher.operands())
5335 for (auto &OP : OM->predicates())
5336 if (!isa<InstructionOperandMatcher>(OP))
5337 return true;
5338 return false;
5339}
5340
5341const PredicateMatcher &RuleMatcher::getFirstCondition() const {
5342 assert(!insnmatchers_empty() &&
5343 "Trying to get a condition from an empty RuleMatcher");
5344
5345 InstructionMatcher &Matcher = insnmatchers_front();
5346 if (!Matcher.predicates_empty())
5347 return **Matcher.predicates_begin();
5348 // If there is no more predicate on the instruction itself, look at its
5349 // operands.
5350 for (auto &OM : Matcher.operands())
5351 for (auto &OP : OM->predicates())
5352 if (!isa<InstructionOperandMatcher>(OP))
5353 return *OP;
5354
5355 llvm_unreachable("Trying to get a condition from an InstructionMatcher with "
5356 "no conditions");
5357}
5358
5359std::unique_ptr<PredicateMatcher> RuleMatcher::popFirstCondition() {
5360 assert(!insnmatchers_empty() &&
5361 "Trying to pop a condition from an empty RuleMatcher");
5362
5363 InstructionMatcher &Matcher = insnmatchers_front();
5364 if (!Matcher.predicates_empty())
5365 return Matcher.predicates_pop_front();
5366 // If there is no more predicate on the instruction itself, look at its
5367 // operands.
5368 for (auto &OM : Matcher.operands())
5369 for (auto &OP : OM->predicates())
5370 if (!isa<InstructionOperandMatcher>(OP)) {
5371 std::unique_ptr<PredicateMatcher> Result = std::move(OP);
5372 OM->eraseNullPredicates();
5373 return Result;
5374 }
5375
5376 llvm_unreachable("Trying to pop a condition from an InstructionMatcher with "
5377 "no conditions");
5378}
5379
5380bool GroupMatcher::candidateConditionMatches(
Quentin Colombetec76d9c2017-12-18 19:47:41 +00005381 const PredicateMatcher &Predicate) const {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005382
5383 if (empty()) {
5384 // Sharing predicates for nested instructions is not supported yet as we
5385 // currently don't hoist the GIM_RecordInsn's properly, therefore we can
5386 // only work on the original root instruction (InsnVarID == 0):
5387 if (Predicate.getInsnVarID() != 0)
5388 return false;
5389 // ... otherwise an empty group can handle any predicate with no specific
5390 // requirements:
5391 return true;
5392 }
5393
5394 const Matcher &Representative = **Matchers.begin();
5395 const auto &RepresentativeCondition = Representative.getFirstCondition();
5396 // ... if not empty, the group can only accomodate matchers with the exact
5397 // same first condition:
5398 return Predicate.isIdentical(RepresentativeCondition);
5399}
5400
5401bool GroupMatcher::addMatcher(Matcher &Candidate) {
5402 if (!Candidate.hasFirstCondition())
5403 return false;
5404
5405 const PredicateMatcher &Predicate = Candidate.getFirstCondition();
5406 if (!candidateConditionMatches(Predicate))
5407 return false;
5408
5409 Matchers.push_back(&Candidate);
5410 return true;
5411}
5412
5413void GroupMatcher::finalize() {
5414 assert(Conditions.empty() && "Already finalized?");
5415 if (empty())
5416 return;
5417
5418 Matcher &FirstRule = **Matchers.begin();
Roman Tereshin152fc162018-05-23 22:50:53 +00005419 for (;;) {
5420 // All the checks are expected to succeed during the first iteration:
5421 for (const auto &Rule : Matchers)
5422 if (!Rule->hasFirstCondition())
5423 return;
5424 const auto &FirstCondition = FirstRule.getFirstCondition();
5425 for (unsigned I = 1, E = Matchers.size(); I < E; ++I)
5426 if (!Matchers[I]->getFirstCondition().isIdentical(FirstCondition))
5427 return;
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005428
Roman Tereshin152fc162018-05-23 22:50:53 +00005429 Conditions.push_back(FirstRule.popFirstCondition());
5430 for (unsigned I = 1, E = Matchers.size(); I < E; ++I)
5431 Matchers[I]->popFirstCondition();
5432 }
Quentin Colombetec76d9c2017-12-18 19:47:41 +00005433}
5434
5435void GroupMatcher::emit(MatchTable &Table) {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005436 unsigned LabelID = ~0U;
5437 if (!Conditions.empty()) {
5438 LabelID = Table.allocateLabelID();
Quentin Colombetec76d9c2017-12-18 19:47:41 +00005439 Table << MatchTable::Opcode("GIM_Try", +1)
5440 << MatchTable::Comment("On fail goto")
5441 << MatchTable::JumpTarget(LabelID) << MatchTable::LineBreak;
Quentin Colombetec76d9c2017-12-18 19:47:41 +00005442 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005443 for (auto &Condition : Conditions)
5444 Condition->emitPredicateOpcodes(
5445 Table, *static_cast<RuleMatcher *>(*Matchers.begin()));
5446
5447 for (const auto &M : Matchers)
5448 M->emit(Table);
5449
5450 // Exit the group
5451 if (!Conditions.empty())
5452 Table << MatchTable::Opcode("GIM_Reject", -1) << MatchTable::LineBreak
Quentin Colombetec76d9c2017-12-18 19:47:41 +00005453 << MatchTable::Label(LabelID);
Quentin Colombetec76d9c2017-12-18 19:47:41 +00005454}
5455
Roman Tereshin0ee082f2018-05-22 19:37:59 +00005456bool SwitchMatcher::isSupportedPredicateType(const PredicateMatcher &P) {
Roman Tereshina4c410d2018-05-24 00:24:15 +00005457 return isa<InstructionOpcodeMatcher>(P) || isa<LLTOperandMatcher>(P);
Roman Tereshin0ee082f2018-05-22 19:37:59 +00005458}
5459
5460bool SwitchMatcher::candidateConditionMatches(
5461 const PredicateMatcher &Predicate) const {
5462
5463 if (empty()) {
5464 // Sharing predicates for nested instructions is not supported yet as we
5465 // currently don't hoist the GIM_RecordInsn's properly, therefore we can
5466 // only work on the original root instruction (InsnVarID == 0):
5467 if (Predicate.getInsnVarID() != 0)
5468 return false;
5469 // ... while an attempt to add even a root matcher to an empty SwitchMatcher
5470 // could fail as not all the types of conditions are supported:
5471 if (!isSupportedPredicateType(Predicate))
5472 return false;
5473 // ... or the condition might not have a proper implementation of
5474 // getValue() / isIdenticalDownToValue() yet:
5475 if (!Predicate.hasValue())
5476 return false;
5477 // ... otherwise an empty Switch can accomodate the condition with no
5478 // further requirements:
5479 return true;
5480 }
5481
5482 const Matcher &CaseRepresentative = **Matchers.begin();
5483 const auto &RepresentativeCondition = CaseRepresentative.getFirstCondition();
5484 // Switch-cases must share the same kind of condition and path to the value it
5485 // checks:
5486 if (!Predicate.isIdenticalDownToValue(RepresentativeCondition))
5487 return false;
5488
5489 const auto Value = Predicate.getValue();
5490 // ... but be unique with respect to the actual value they check:
5491 return Values.count(Value) == 0;
5492}
5493
5494bool SwitchMatcher::addMatcher(Matcher &Candidate) {
5495 if (!Candidate.hasFirstCondition())
5496 return false;
5497
5498 const PredicateMatcher &Predicate = Candidate.getFirstCondition();
5499 if (!candidateConditionMatches(Predicate))
5500 return false;
5501 const auto Value = Predicate.getValue();
5502 Values.insert(Value);
5503
5504 Matchers.push_back(&Candidate);
5505 return true;
5506}
5507
5508void SwitchMatcher::finalize() {
5509 assert(Condition == nullptr && "Already finalized");
5510 assert(Values.size() == Matchers.size() && "Broken SwitchMatcher");
5511 if (empty())
5512 return;
5513
5514 std::stable_sort(Matchers.begin(), Matchers.end(),
5515 [](const Matcher *L, const Matcher *R) {
5516 return L->getFirstCondition().getValue() <
5517 R->getFirstCondition().getValue();
5518 });
5519 Condition = Matchers[0]->popFirstCondition();
5520 for (unsigned I = 1, E = Values.size(); I < E; ++I)
5521 Matchers[I]->popFirstCondition();
5522}
5523
5524void SwitchMatcher::emitPredicateSpecificOpcodes(const PredicateMatcher &P,
5525 MatchTable &Table) {
5526 assert(isSupportedPredicateType(P) && "Predicate type is not supported");
5527
5528 if (const auto *Condition = dyn_cast<InstructionOpcodeMatcher>(&P)) {
5529 Table << MatchTable::Opcode("GIM_SwitchOpcode") << MatchTable::Comment("MI")
5530 << MatchTable::IntValue(Condition->getInsnVarID());
5531 return;
5532 }
Roman Tereshina4c410d2018-05-24 00:24:15 +00005533 if (const auto *Condition = dyn_cast<LLTOperandMatcher>(&P)) {
5534 Table << MatchTable::Opcode("GIM_SwitchType") << MatchTable::Comment("MI")
5535 << MatchTable::IntValue(Condition->getInsnVarID())
5536 << MatchTable::Comment("Op")
5537 << MatchTable::IntValue(Condition->getOpIdx());
5538 return;
5539 }
Roman Tereshin0ee082f2018-05-22 19:37:59 +00005540
5541 llvm_unreachable("emitPredicateSpecificOpcodes is broken: can not handle a "
5542 "predicate type that is claimed to be supported");
5543}
5544
5545void SwitchMatcher::emit(MatchTable &Table) {
5546 assert(Values.size() == Matchers.size() && "Broken SwitchMatcher");
5547 if (empty())
5548 return;
5549 assert(Condition != nullptr &&
5550 "Broken SwitchMatcher, hasn't been finalized?");
5551
5552 std::vector<unsigned> LabelIDs(Values.size());
5553 std::generate(LabelIDs.begin(), LabelIDs.end(),
5554 [&Table]() { return Table.allocateLabelID(); });
5555 const unsigned Default = Table.allocateLabelID();
5556
5557 const int64_t LowerBound = Values.begin()->getRawValue();
5558 const int64_t UpperBound = Values.rbegin()->getRawValue() + 1;
5559
5560 emitPredicateSpecificOpcodes(*Condition, Table);
5561
5562 Table << MatchTable::Comment("[") << MatchTable::IntValue(LowerBound)
5563 << MatchTable::IntValue(UpperBound) << MatchTable::Comment(")")
5564 << MatchTable::Comment("default:") << MatchTable::JumpTarget(Default);
5565
5566 int64_t J = LowerBound;
5567 auto VI = Values.begin();
5568 for (unsigned I = 0, E = Values.size(); I < E; ++I) {
5569 auto V = *VI++;
5570 while (J++ < V.getRawValue())
5571 Table << MatchTable::IntValue(0);
5572 V.turnIntoComment();
5573 Table << MatchTable::LineBreak << V << MatchTable::JumpTarget(LabelIDs[I]);
5574 }
5575 Table << MatchTable::LineBreak;
5576
5577 for (unsigned I = 0, E = Values.size(); I < E; ++I) {
5578 Table << MatchTable::Label(LabelIDs[I]);
5579 Matchers[I]->emit(Table);
5580 Table << MatchTable::Opcode("GIM_Reject") << MatchTable::LineBreak;
5581 }
5582 Table << MatchTable::Label(Default);
5583}
5584
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005585unsigned OperandMatcher::getInsnVarID() const { return Insn.getInsnVarID(); }
Quentin Colombetaad20be2017-12-15 23:07:42 +00005586
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00005587} // end anonymous namespace
5588
Ahmed Bougacha36f70352016-12-21 23:26:20 +00005589//===----------------------------------------------------------------------===//
5590
5591namespace llvm {
5592void EmitGlobalISel(RecordKeeper &RK, raw_ostream &OS) {
5593 GlobalISelEmitter(RK).run(OS);
5594}
5595} // End llvm namespace