blob: b9c88b517388ba1a99617dfcf1100df3680b8329 [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) {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000451 assert((!LabelID_.hasValue() || LabelID != ~0u) &&
452 "This value is reserved for non-labels");
453 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000454 MatchTableRecord(const MatchTableRecord &Other) = default;
455 MatchTableRecord(MatchTableRecord &&Other) = default;
456
457 /// Useful if a Match Table Record gets optimized out
458 void turnIntoComment() {
459 Flags |= MTRF_Comment;
460 Flags &= ~MTRF_CommaFollows;
461 NumElements = 0;
462 }
463
464 /// For Jump Table generation purposes
465 bool operator<(const MatchTableRecord &Other) const {
466 return RawValue < Other.RawValue;
467 }
468 int64_t getRawValue() const { return RawValue; }
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000469
470 void emit(raw_ostream &OS, bool LineBreakNextAfterThis,
471 const MatchTable &Table) const;
472 unsigned size() const { return NumElements; }
473};
474
Roman Tereshin2d6d3762018-05-02 20:08:14 +0000475class Matcher;
476
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000477/// Holds the contents of a generated MatchTable to enable formatting and the
478/// necessary index tracking needed to support GIM_Try.
479class MatchTable {
480 /// An unique identifier for the table. The generated table will be named
481 /// MatchTable${ID}.
482 unsigned ID;
483 /// The records that make up the table. Also includes comments describing the
484 /// values being emitted and line breaks to format it.
485 std::vector<MatchTableRecord> Contents;
486 /// The currently defined labels.
487 DenseMap<unsigned, unsigned> LabelMap;
488 /// Tracks the sum of MatchTableRecord::NumElements as the table is built.
Roman Tereshin2d6d3762018-05-02 20:08:14 +0000489 unsigned CurrentSize = 0;
Daniel Sanders8e82af22017-07-27 11:03:45 +0000490 /// A unique identifier for a MatchTable label.
Roman Tereshin2d6d3762018-05-02 20:08:14 +0000491 unsigned CurrentLabelID = 0;
Roman Tereshinbeb39312018-05-02 20:15:11 +0000492 /// Determines if the table should be instrumented for rule coverage tracking.
493 bool IsWithCoverage;
Daniel Sanders8e82af22017-07-27 11:03:45 +0000494
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000495public:
496 static MatchTableRecord LineBreak;
497 static MatchTableRecord Comment(StringRef Comment) {
498 return MatchTableRecord(None, Comment, 0, MatchTableRecord::MTRF_Comment);
499 }
500 static MatchTableRecord Opcode(StringRef Opcode, int IndentAdjust = 0) {
501 unsigned ExtraFlags = 0;
502 if (IndentAdjust > 0)
503 ExtraFlags |= MatchTableRecord::MTRF_Indent;
504 if (IndentAdjust < 0)
505 ExtraFlags |= MatchTableRecord::MTRF_Outdent;
506
507 return MatchTableRecord(None, Opcode, 1,
508 MatchTableRecord::MTRF_CommaFollows | ExtraFlags);
509 }
510 static MatchTableRecord NamedValue(StringRef NamedValue) {
511 return MatchTableRecord(None, NamedValue, 1,
512 MatchTableRecord::MTRF_CommaFollows);
513 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000514 static MatchTableRecord NamedValue(StringRef NamedValue, int64_t RawValue) {
515 return MatchTableRecord(None, NamedValue, 1,
516 MatchTableRecord::MTRF_CommaFollows, RawValue);
517 }
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000518 static MatchTableRecord NamedValue(StringRef Namespace,
519 StringRef NamedValue) {
520 return MatchTableRecord(None, (Namespace + "::" + NamedValue).str(), 1,
521 MatchTableRecord::MTRF_CommaFollows);
522 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000523 static MatchTableRecord NamedValue(StringRef Namespace, StringRef NamedValue,
524 int64_t RawValue) {
525 return MatchTableRecord(None, (Namespace + "::" + NamedValue).str(), 1,
526 MatchTableRecord::MTRF_CommaFollows, RawValue);
527 }
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000528 static MatchTableRecord IntValue(int64_t IntValue) {
529 return MatchTableRecord(None, llvm::to_string(IntValue), 1,
530 MatchTableRecord::MTRF_CommaFollows);
531 }
532 static MatchTableRecord Label(unsigned LabelID) {
533 return MatchTableRecord(LabelID, "Label " + llvm::to_string(LabelID), 0,
534 MatchTableRecord::MTRF_Label |
535 MatchTableRecord::MTRF_Comment |
536 MatchTableRecord::MTRF_LineBreakFollows);
537 }
538 static MatchTableRecord JumpTarget(unsigned LabelID) {
Daniel Sanders8e82af22017-07-27 11:03:45 +0000539 return MatchTableRecord(LabelID, "Label " + llvm::to_string(LabelID), 1,
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000540 MatchTableRecord::MTRF_JumpTarget |
541 MatchTableRecord::MTRF_Comment |
542 MatchTableRecord::MTRF_CommaFollows);
543 }
544
Roman Tereshinbeb39312018-05-02 20:15:11 +0000545 static MatchTable buildTable(ArrayRef<Matcher *> Rules, bool WithCoverage);
Roman Tereshin2d6d3762018-05-02 20:08:14 +0000546
Roman Tereshinbeb39312018-05-02 20:15:11 +0000547 MatchTable(bool WithCoverage, unsigned ID = 0)
548 : ID(ID), IsWithCoverage(WithCoverage) {}
549
550 bool isWithCoverage() const { return IsWithCoverage; }
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000551
552 void push_back(const MatchTableRecord &Value) {
553 if (Value.Flags & MatchTableRecord::MTRF_Label)
554 defineLabel(Value.LabelID);
555 Contents.push_back(Value);
556 CurrentSize += Value.size();
557 }
558
Roman Tereshin2d6d3762018-05-02 20:08:14 +0000559 unsigned allocateLabelID() { return CurrentLabelID++; }
Daniel Sanders8e82af22017-07-27 11:03:45 +0000560
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000561 void defineLabel(unsigned LabelID) {
Daniel Sanders8e82af22017-07-27 11:03:45 +0000562 LabelMap.insert(std::make_pair(LabelID, CurrentSize));
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000563 }
564
565 unsigned getLabelIndex(unsigned LabelID) const {
566 const auto I = LabelMap.find(LabelID);
567 assert(I != LabelMap.end() && "Use of undeclared label");
568 return I->second;
569 }
570
Daniel Sanders8e82af22017-07-27 11:03:45 +0000571 void emitUse(raw_ostream &OS) const { OS << "MatchTable" << ID; }
572
573 void emitDeclaration(raw_ostream &OS) const {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000574 unsigned Indentation = 4;
Daniel Sanderscbbbfe42017-07-27 12:47:31 +0000575 OS << " constexpr static int64_t MatchTable" << ID << "[] = {";
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000576 LineBreak.emit(OS, true, *this);
577 OS << std::string(Indentation, ' ');
578
579 for (auto I = Contents.begin(), E = Contents.end(); I != E;
580 ++I) {
581 bool LineBreakIsNext = false;
582 const auto &NextI = std::next(I);
583
584 if (NextI != E) {
585 if (NextI->EmitStr == "" &&
586 NextI->Flags == MatchTableRecord::MTRF_LineBreakFollows)
587 LineBreakIsNext = true;
588 }
589
590 if (I->Flags & MatchTableRecord::MTRF_Indent)
591 Indentation += 2;
592
593 I->emit(OS, LineBreakIsNext, *this);
594 if (I->Flags & MatchTableRecord::MTRF_LineBreakFollows)
595 OS << std::string(Indentation, ' ');
596
597 if (I->Flags & MatchTableRecord::MTRF_Outdent)
598 Indentation -= 2;
599 }
600 OS << "};\n";
601 }
602};
603
604MatchTableRecord MatchTable::LineBreak = {
605 None, "" /* Emit String */, 0 /* Elements */,
606 MatchTableRecord::MTRF_LineBreakFollows};
607
608void MatchTableRecord::emit(raw_ostream &OS, bool LineBreakIsNextAfterThis,
609 const MatchTable &Table) const {
610 bool UseLineComment =
Simon Pilgrim43fe9af2019-11-02 21:01:45 +0000611 LineBreakIsNextAfterThis || (Flags & MTRF_LineBreakFollows);
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000612 if (Flags & (MTRF_JumpTarget | MTRF_CommaFollows))
613 UseLineComment = false;
614
615 if (Flags & MTRF_Comment)
616 OS << (UseLineComment ? "// " : "/*");
617
618 OS << EmitStr;
619 if (Flags & MTRF_Label)
620 OS << ": @" << Table.getLabelIndex(LabelID);
621
Simon Pilgrim43fe9af2019-11-02 21:01:45 +0000622 if ((Flags & MTRF_Comment) && !UseLineComment)
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000623 OS << "*/";
624
625 if (Flags & MTRF_JumpTarget) {
626 if (Flags & MTRF_Comment)
627 OS << " ";
628 OS << Table.getLabelIndex(LabelID);
629 }
630
631 if (Flags & MTRF_CommaFollows) {
632 OS << ",";
633 if (!LineBreakIsNextAfterThis && !(Flags & MTRF_LineBreakFollows))
634 OS << " ";
635 }
636
637 if (Flags & MTRF_LineBreakFollows)
638 OS << "\n";
639}
640
641MatchTable &operator<<(MatchTable &Table, const MatchTableRecord &Value) {
642 Table.push_back(Value);
643 return Table;
644}
645
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000646//===- Matchers -----------------------------------------------------------===//
647
Daniel Sandersbee57392017-04-04 13:25:23 +0000648class OperandMatcher;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000649class MatchAction;
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000650class PredicateMatcher;
651class RuleMatcher;
652
653class Matcher {
654public:
655 virtual ~Matcher() = default;
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000656 virtual void optimize() {}
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000657 virtual void emit(MatchTable &Table) = 0;
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000658
659 virtual bool hasFirstCondition() const = 0;
660 virtual const PredicateMatcher &getFirstCondition() const = 0;
661 virtual std::unique_ptr<PredicateMatcher> popFirstCondition() = 0;
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000662};
663
Roman Tereshinbeb39312018-05-02 20:15:11 +0000664MatchTable MatchTable::buildTable(ArrayRef<Matcher *> Rules,
665 bool WithCoverage) {
666 MatchTable Table(WithCoverage);
Roman Tereshin2d6d3762018-05-02 20:08:14 +0000667 for (Matcher *Rule : Rules)
668 Rule->emit(Table);
669
670 return Table << MatchTable::Opcode("GIM_Reject") << MatchTable::LineBreak;
671}
672
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000673class GroupMatcher final : public Matcher {
674 /// Conditions that form a common prefix of all the matchers contained.
675 SmallVector<std::unique_ptr<PredicateMatcher>, 1> Conditions;
676
677 /// All the nested matchers, sharing a common prefix.
678 std::vector<Matcher *> Matchers;
679
680 /// An owning collection for any auxiliary matchers created while optimizing
681 /// nested matchers contained.
682 std::vector<std::unique_ptr<Matcher>> MatcherStorage;
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000683
684public:
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000685 /// Add a matcher to the collection of nested matchers if it meets the
686 /// requirements, and return true. If it doesn't, do nothing and return false.
687 ///
688 /// Expected to preserve its argument, so it could be moved out later on.
689 bool addMatcher(Matcher &Candidate);
690
691 /// Mark the matcher as fully-built and ensure any invariants expected by both
692 /// optimize() and emit(...) methods. Generally, both sequences of calls
693 /// are expected to lead to a sensible result:
694 ///
695 /// addMatcher(...)*; finalize(); optimize(); emit(...); and
696 /// addMatcher(...)*; finalize(); emit(...);
697 ///
698 /// or generally
699 ///
700 /// addMatcher(...)*; finalize(); { optimize()*; emit(...); }*
701 ///
702 /// Multiple calls to optimize() are expected to be handled gracefully, though
703 /// optimize() is not expected to be idempotent. Multiple calls to finalize()
704 /// aren't generally supported. emit(...) is expected to be non-mutating and
705 /// producing the exact same results upon repeated calls.
706 ///
707 /// addMatcher() calls after the finalize() call are not supported.
708 ///
709 /// finalize() and optimize() are both allowed to mutate the contained
710 /// matchers, so moving them out after finalize() is not supported.
711 void finalize();
Roman Tereshinfedae332018-05-23 02:04:19 +0000712 void optimize() override;
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000713 void emit(MatchTable &Table) override;
Quentin Colombet34688b92017-12-18 21:25:53 +0000714
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000715 /// Could be used to move out the matchers added previously, unless finalize()
716 /// has been already called. If any of the matchers are moved out, the group
717 /// becomes safe to destroy, but not safe to re-use for anything else.
718 iterator_range<std::vector<Matcher *>::iterator> matchers() {
719 return make_range(Matchers.begin(), Matchers.end());
Quentin Colombet34688b92017-12-18 21:25:53 +0000720 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000721 size_t size() const { return Matchers.size(); }
722 bool empty() const { return Matchers.empty(); }
723
724 std::unique_ptr<PredicateMatcher> popFirstCondition() override {
725 assert(!Conditions.empty() &&
726 "Trying to pop a condition from a condition-less group");
727 std::unique_ptr<PredicateMatcher> P = std::move(Conditions.front());
728 Conditions.erase(Conditions.begin());
729 return P;
730 }
731 const PredicateMatcher &getFirstCondition() const override {
732 assert(!Conditions.empty() &&
733 "Trying to get a condition from a condition-less group");
734 return *Conditions.front();
735 }
736 bool hasFirstCondition() const override { return !Conditions.empty(); }
737
738private:
739 /// See if a candidate matcher could be added to this group solely by
740 /// analyzing its first condition.
741 bool candidateConditionMatches(const PredicateMatcher &Predicate) const;
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000742};
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000743
Roman Tereshin0ee082f2018-05-22 19:37:59 +0000744class SwitchMatcher : public Matcher {
745 /// All the nested matchers, representing distinct switch-cases. The first
746 /// conditions (as Matcher::getFirstCondition() reports) of all the nested
747 /// matchers must share the same type and path to a value they check, in other
748 /// words, be isIdenticalDownToValue, but have different values they check
749 /// against.
750 std::vector<Matcher *> Matchers;
751
752 /// The representative condition, with a type and a path (InsnVarID and OpIdx
753 /// in most cases) shared by all the matchers contained.
754 std::unique_ptr<PredicateMatcher> Condition = nullptr;
755
756 /// Temporary set used to check that the case values don't repeat within the
757 /// same switch.
758 std::set<MatchTableRecord> Values;
759
760 /// An owning collection for any auxiliary matchers created while optimizing
761 /// nested matchers contained.
762 std::vector<std::unique_ptr<Matcher>> MatcherStorage;
763
764public:
765 bool addMatcher(Matcher &Candidate);
766
767 void finalize();
768 void emit(MatchTable &Table) override;
769
770 iterator_range<std::vector<Matcher *>::iterator> matchers() {
771 return make_range(Matchers.begin(), Matchers.end());
772 }
773 size_t size() const { return Matchers.size(); }
774 bool empty() const { return Matchers.empty(); }
775
776 std::unique_ptr<PredicateMatcher> popFirstCondition() override {
777 // SwitchMatcher doesn't have a common first condition for its cases, as all
778 // the cases only share a kind of a value (a type and a path to it) they
779 // match, but deliberately differ in the actual value they match.
780 llvm_unreachable("Trying to pop a condition from a condition-less group");
781 }
782 const PredicateMatcher &getFirstCondition() const override {
783 llvm_unreachable("Trying to pop a condition from a condition-less group");
784 }
785 bool hasFirstCondition() const override { return false; }
786
787private:
788 /// See if the predicate type has a Switch-implementation for it.
789 static bool isSupportedPredicateType(const PredicateMatcher &Predicate);
790
791 bool candidateConditionMatches(const PredicateMatcher &Predicate) const;
792
793 /// emit()-helper
794 static void emitPredicateSpecificOpcodes(const PredicateMatcher &P,
795 MatchTable &Table);
796};
797
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000798/// Generates code to check that a match rule matches.
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000799class RuleMatcher : public Matcher {
Daniel Sanders7438b262017-10-31 23:03:18 +0000800public:
Daniel Sanders08464522018-01-29 21:09:12 +0000801 using ActionList = std::list<std::unique_ptr<MatchAction>>;
802 using action_iterator = ActionList::iterator;
Daniel Sanders7438b262017-10-31 23:03:18 +0000803
804protected:
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000805 /// A list of matchers that all need to succeed for the current rule to match.
806 /// FIXME: This currently supports a single match position but could be
807 /// extended to support multiple positions to support div/rem fusion or
808 /// load-multiple instructions.
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000809 using MatchersTy = std::vector<std::unique_ptr<InstructionMatcher>> ;
810 MatchersTy Matchers;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000811
812 /// A list of actions that need to be taken when all predicates in this rule
813 /// have succeeded.
Daniel Sanders08464522018-01-29 21:09:12 +0000814 ActionList Actions;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000815
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000816 using DefinedInsnVariablesMap = std::map<InstructionMatcher *, unsigned>;
Daniel Sandersa7b75262017-10-31 18:50:24 +0000817
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000818 /// A map of instruction matchers to the local variables
Daniel Sanders078572b2017-08-02 11:03:36 +0000819 DefinedInsnVariablesMap InsnVariableIDs;
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000820
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000821 using MutatableInsnSet = SmallPtrSet<InstructionMatcher *, 4>;
Daniel Sandersa7b75262017-10-31 18:50:24 +0000822
823 // The set of instruction matchers that have not yet been claimed for mutation
824 // by a BuildMI.
825 MutatableInsnSet MutatableInsns;
826
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000827 /// A map of named operands defined by the matchers that may be referenced by
828 /// the renderers.
829 StringMap<OperandMatcher *> DefinedOperands;
830
Matt Arsenault3e45c702019-09-06 20:32:37 +0000831 /// A map of anonymous physical register operands defined by the matchers that
832 /// may be referenced by the renderers.
833 DenseMap<Record *, OperandMatcher *> PhysRegOperands;
834
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000835 /// ID for the next instruction variable defined with implicitlyDefineInsnVar()
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000836 unsigned NextInsnVarID;
837
Daniel Sanders198447a2017-11-01 00:29:47 +0000838 /// ID for the next output instruction allocated with allocateOutputInsnID()
839 unsigned NextOutputInsnID;
840
Daniel Sanders9cbe7c72017-11-01 19:57:57 +0000841 /// ID for the next temporary register ID allocated with allocateTempRegID()
842 unsigned NextTempRegID;
843
Daniel Sanderse7b0d662017-04-21 15:59:56 +0000844 std::vector<Record *> RequiredFeatures;
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000845 std::vector<std::unique_ptr<PredicateMatcher>> EpilogueMatchers;
Daniel Sanderse7b0d662017-04-21 15:59:56 +0000846
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000847 ArrayRef<SMLoc> SrcLoc;
848
Daniel Sandersdf39cba2017-10-15 18:22:54 +0000849 typedef std::tuple<Record *, unsigned, unsigned>
850 DefinedComplexPatternSubOperand;
851 typedef StringMap<DefinedComplexPatternSubOperand>
852 DefinedComplexPatternSubOperandMap;
853 /// A map of Symbolic Names to ComplexPattern sub-operands.
854 DefinedComplexPatternSubOperandMap ComplexSubOperands;
855
Daniel Sandersf76f3152017-11-16 00:46:35 +0000856 uint64_t RuleID;
857 static uint64_t NextRuleID;
858
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000859public:
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000860 RuleMatcher(ArrayRef<SMLoc> SrcLoc)
Daniel Sandersa7b75262017-10-31 18:50:24 +0000861 : Matchers(), Actions(), InsnVariableIDs(), MutatableInsns(),
Daniel Sanders198447a2017-11-01 00:29:47 +0000862 DefinedOperands(), NextInsnVarID(0), NextOutputInsnID(0),
Daniel Sandersf76f3152017-11-16 00:46:35 +0000863 NextTempRegID(0), SrcLoc(SrcLoc), ComplexSubOperands(),
864 RuleID(NextRuleID++) {}
Zachary Turnerb7dbd872017-03-20 19:56:52 +0000865 RuleMatcher(RuleMatcher &&Other) = default;
866 RuleMatcher &operator=(RuleMatcher &&Other) = default;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000867
Daniel Sandersf76f3152017-11-16 00:46:35 +0000868 uint64_t getRuleID() const { return RuleID; }
869
Daniel Sanders05540042017-08-08 10:44:31 +0000870 InstructionMatcher &addInstructionMatcher(StringRef SymbolicName);
Daniel Sanderse7b0d662017-04-21 15:59:56 +0000871 void addRequiredFeature(Record *Feature);
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000872 const std::vector<Record *> &getRequiredFeatures() const;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000873
874 template <class Kind, class... Args> Kind &addAction(Args &&... args);
Daniel Sanders7438b262017-10-31 23:03:18 +0000875 template <class Kind, class... Args>
876 action_iterator insertAction(action_iterator InsertPt, Args &&... args);
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000877
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000878 /// Define an instruction without emitting any code to do so.
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000879 unsigned implicitlyDefineInsnVar(InstructionMatcher &Matcher);
880
881 unsigned getInsnVarID(InstructionMatcher &InsnMatcher) const;
Daniel Sanders078572b2017-08-02 11:03:36 +0000882 DefinedInsnVariablesMap::const_iterator defined_insn_vars_begin() const {
883 return InsnVariableIDs.begin();
884 }
885 DefinedInsnVariablesMap::const_iterator defined_insn_vars_end() const {
886 return InsnVariableIDs.end();
887 }
888 iterator_range<typename DefinedInsnVariablesMap::const_iterator>
889 defined_insn_vars() const {
890 return make_range(defined_insn_vars_begin(), defined_insn_vars_end());
891 }
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000892
Daniel Sandersa7b75262017-10-31 18:50:24 +0000893 MutatableInsnSet::const_iterator mutatable_insns_begin() const {
894 return MutatableInsns.begin();
895 }
896 MutatableInsnSet::const_iterator mutatable_insns_end() const {
897 return MutatableInsns.end();
898 }
899 iterator_range<typename MutatableInsnSet::const_iterator>
900 mutatable_insns() const {
901 return make_range(mutatable_insns_begin(), mutatable_insns_end());
902 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000903 void reserveInsnMatcherForMutation(InstructionMatcher *InsnMatcher) {
Daniel Sandersa7b75262017-10-31 18:50:24 +0000904 bool R = MutatableInsns.erase(InsnMatcher);
905 assert(R && "Reserving a mutatable insn that isn't available");
906 (void)R;
907 }
908
Daniel Sanders7438b262017-10-31 23:03:18 +0000909 action_iterator actions_begin() { return Actions.begin(); }
910 action_iterator actions_end() { return Actions.end(); }
911 iterator_range<action_iterator> actions() {
912 return make_range(actions_begin(), actions_end());
913 }
914
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000915 void defineOperand(StringRef SymbolicName, OperandMatcher &OM);
916
Matt Arsenault3e45c702019-09-06 20:32:37 +0000917 void definePhysRegOperand(Record *Reg, OperandMatcher &OM);
918
Jessica Paquette1ed1dd62019-02-09 00:29:13 +0000919 Error defineComplexSubOperand(StringRef SymbolicName, Record *ComplexPattern,
920 unsigned RendererID, unsigned SubOperandID) {
921 if (ComplexSubOperands.count(SymbolicName))
922 return failedImport(
923 "Complex suboperand referenced more than once (Operand: " +
924 SymbolicName + ")");
925
Daniel Sandersdf39cba2017-10-15 18:22:54 +0000926 ComplexSubOperands[SymbolicName] =
927 std::make_tuple(ComplexPattern, RendererID, SubOperandID);
Jessica Paquette1ed1dd62019-02-09 00:29:13 +0000928
929 return Error::success();
Daniel Sandersdf39cba2017-10-15 18:22:54 +0000930 }
Jessica Paquette1ed1dd62019-02-09 00:29:13 +0000931
Daniel Sandersdf39cba2017-10-15 18:22:54 +0000932 Optional<DefinedComplexPatternSubOperand>
933 getComplexSubOperand(StringRef SymbolicName) const {
934 const auto &I = ComplexSubOperands.find(SymbolicName);
935 if (I == ComplexSubOperands.end())
936 return None;
937 return I->second;
938 }
939
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000940 InstructionMatcher &getInstructionMatcher(StringRef SymbolicName) const;
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000941 const OperandMatcher &getOperandMatcher(StringRef Name) const;
Matt Arsenault3e45c702019-09-06 20:32:37 +0000942 const OperandMatcher &getPhysRegOperandMatcher(Record *) const;
Daniel Sanders05540042017-08-08 10:44:31 +0000943
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000944 void optimize() override;
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000945 void emit(MatchTable &Table) override;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000946
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000947 /// Compare the priority of this object and B.
948 ///
949 /// Returns true if this object is more important than B.
950 bool isHigherPriorityThan(const RuleMatcher &B) const;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000951
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000952 /// Report the maximum number of temporary operands needed by the rule
953 /// matcher.
954 unsigned countRendererFns() const;
Daniel Sanders2deea182017-04-22 15:11:04 +0000955
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000956 std::unique_ptr<PredicateMatcher> popFirstCondition() override;
957 const PredicateMatcher &getFirstCondition() const override;
Roman Tereshin9a9fa492018-05-23 21:30:16 +0000958 LLTCodeGen getFirstConditionAsRootType();
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000959 bool hasFirstCondition() const override;
960 unsigned getNumOperands() const;
Roman Tereshin19da6672018-05-22 04:31:50 +0000961 StringRef getOpcode() const;
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000962
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000963 // FIXME: Remove this as soon as possible
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000964 InstructionMatcher &insnmatchers_front() const { return *Matchers.front(); }
Daniel Sanders198447a2017-11-01 00:29:47 +0000965
966 unsigned allocateOutputInsnID() { return NextOutputInsnID++; }
Daniel Sanders9cbe7c72017-11-01 19:57:57 +0000967 unsigned allocateTempRegID() { return NextTempRegID++; }
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000968
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000969 iterator_range<MatchersTy::iterator> insnmatchers() {
970 return make_range(Matchers.begin(), Matchers.end());
971 }
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000972 bool insnmatchers_empty() const { return Matchers.empty(); }
973 void insnmatchers_pop_front() { Matchers.erase(Matchers.begin()); }
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000974};
975
Daniel Sandersf76f3152017-11-16 00:46:35 +0000976uint64_t RuleMatcher::NextRuleID = 0;
977
Daniel Sanders7438b262017-10-31 23:03:18 +0000978using action_iterator = RuleMatcher::action_iterator;
979
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000980template <class PredicateTy> class PredicateListMatcher {
981private:
Daniel Sanders2c269f62017-08-24 09:11:20 +0000982 /// Template instantiations should specialize this to return a string to use
983 /// for the comment emitted when there are no predicates.
984 std::string getNoPredicateComment() const;
985
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000986protected:
987 using PredicatesTy = std::deque<std::unique_ptr<PredicateTy>>;
988 PredicatesTy Predicates;
Roman Tereshinf0dc9fa2018-05-21 22:04:39 +0000989
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000990 /// Track if the list of predicates was manipulated by one of the optimization
991 /// methods.
992 bool Optimized = false;
993
994public:
995 /// Construct a new predicate and add it to the matcher.
996 template <class Kind, class... Args>
997 Optional<Kind *> addPredicate(Args &&... args);
998
999 typename PredicatesTy::iterator predicates_begin() {
Daniel Sanders32291982017-06-28 13:50:04 +00001000 return Predicates.begin();
1001 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001002 typename PredicatesTy::iterator predicates_end() {
Daniel Sanders32291982017-06-28 13:50:04 +00001003 return Predicates.end();
1004 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001005 iterator_range<typename PredicatesTy::iterator> predicates() {
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001006 return make_range(predicates_begin(), predicates_end());
1007 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001008 typename PredicatesTy::size_type predicates_size() const {
Daniel Sanders32291982017-06-28 13:50:04 +00001009 return Predicates.size();
1010 }
Quentin Colombetec76d9c2017-12-18 19:47:41 +00001011 bool predicates_empty() const { return Predicates.empty(); }
1012
1013 std::unique_ptr<PredicateTy> predicates_pop_front() {
1014 std::unique_ptr<PredicateTy> Front = std::move(Predicates.front());
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001015 Predicates.pop_front();
1016 Optimized = true;
Quentin Colombetec76d9c2017-12-18 19:47:41 +00001017 return Front;
1018 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001019
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001020 void prependPredicate(std::unique_ptr<PredicateTy> &&Predicate) {
1021 Predicates.push_front(std::move(Predicate));
1022 }
1023
1024 void eraseNullPredicates() {
1025 const auto NewEnd =
1026 std::stable_partition(Predicates.begin(), Predicates.end(),
1027 std::logical_not<std::unique_ptr<PredicateTy>>());
1028 if (NewEnd != Predicates.begin()) {
1029 Predicates.erase(Predicates.begin(), NewEnd);
1030 Optimized = true;
1031 }
1032 }
1033
Daniel Sanders9d662d22017-07-06 10:06:12 +00001034 /// Emit MatchTable opcodes that tests whether all the predicates are met.
Ahmed Bougachab67a3ce2017-01-26 22:07:37 +00001035 template <class... Args>
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001036 void emitPredicateListOpcodes(MatchTable &Table, Args &&... args) {
1037 if (Predicates.empty() && !Optimized) {
Daniel Sanders2c269f62017-08-24 09:11:20 +00001038 Table << MatchTable::Comment(getNoPredicateComment())
1039 << MatchTable::LineBreak;
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001040 return;
1041 }
1042
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001043 for (const auto &Predicate : predicates())
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001044 Predicate->emitPredicateOpcodes(Table, std::forward<Args>(args)...);
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001045 }
Matt Arsenault1254f6d2020-06-20 21:38:43 -04001046
1047 /// Provide a function to avoid emitting certain predicates. This is used to
1048 /// defer some predicate checks until after others
1049 using PredicateFilterFunc = std::function<bool(const PredicateTy&)>;
1050
1051 /// Emit MatchTable opcodes for predicates which satisfy \p
1052 /// ShouldEmitPredicate. This should be called multiple times to ensure all
1053 /// predicates are eventually added to the match table.
1054 template <class... Args>
1055 void emitFilteredPredicateListOpcodes(PredicateFilterFunc ShouldEmitPredicate,
1056 MatchTable &Table, Args &&... args) {
1057 if (Predicates.empty() && !Optimized) {
1058 Table << MatchTable::Comment(getNoPredicateComment())
1059 << MatchTable::LineBreak;
1060 return;
1061 }
1062
1063 for (const auto &Predicate : predicates()) {
1064 if (ShouldEmitPredicate(*Predicate))
1065 Predicate->emitPredicateOpcodes(Table, std::forward<Args>(args)...);
1066 }
1067 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001068};
1069
Quentin Colombet063d7982017-12-14 23:44:07 +00001070class PredicateMatcher {
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001071public:
Daniel Sanders759ff412017-02-24 13:58:11 +00001072 /// This enum is used for RTTI and also defines the priority that is given to
1073 /// the predicate when generating the matcher code. Kinds with higher priority
1074 /// must be tested first.
1075 ///
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001076 /// The relative priority of OPM_LLT, OPM_RegBank, and OPM_MBB do not matter
1077 /// but OPM_Int must have priority over OPM_RegBank since constant integers
1078 /// are represented by a virtual register defined by a G_CONSTANT instruction.
Quentin Colombet063d7982017-12-14 23:44:07 +00001079 ///
1080 /// Note: The relative priority between IPM_ and OPM_ does not matter, they
1081 /// are currently not compared between each other.
Daniel Sanders759ff412017-02-24 13:58:11 +00001082 enum PredicateKind {
Quentin Colombet063d7982017-12-14 23:44:07 +00001083 IPM_Opcode,
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001084 IPM_NumOperands,
Quentin Colombet063d7982017-12-14 23:44:07 +00001085 IPM_ImmPredicate,
Matt Arsenault3ecab8e2019-09-19 16:26:14 +00001086 IPM_Imm,
Quentin Colombet063d7982017-12-14 23:44:07 +00001087 IPM_AtomicOrderingMMO,
Daniel Sandersf84bc372018-05-05 20:53:24 +00001088 IPM_MemoryLLTSize,
1089 IPM_MemoryVsLLTSize,
Matt Arsenaultd00d8572019-07-15 20:59:42 +00001090 IPM_MemoryAddressSpace,
Matt Arsenault52c26242019-07-31 00:14:43 +00001091 IPM_MemoryAlignment,
Daniel Sanders8ead1292018-06-15 23:13:43 +00001092 IPM_GenericPredicate,
Daniel Sanders1e4569f2017-10-20 20:55:29 +00001093 OPM_SameOperand,
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001094 OPM_ComplexPattern,
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00001095 OPM_IntrinsicID,
Matt Arsenault8ec5c102019-08-29 01:13:41 +00001096 OPM_CmpPredicate,
Daniel Sanders05540042017-08-08 10:44:31 +00001097 OPM_Instruction,
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001098 OPM_Int,
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001099 OPM_LiteralInt,
Daniel Sanders759ff412017-02-24 13:58:11 +00001100 OPM_LLT,
Daniel Sandersa71f4542017-10-16 00:56:30 +00001101 OPM_PointerToAny,
Daniel Sanders759ff412017-02-24 13:58:11 +00001102 OPM_RegBank,
1103 OPM_MBB,
1104 };
1105
1106protected:
1107 PredicateKind Kind;
Quentin Colombetaad20be2017-12-15 23:07:42 +00001108 unsigned InsnVarID;
1109 unsigned OpIdx;
Daniel Sanders759ff412017-02-24 13:58:11 +00001110
1111public:
Quentin Colombetaad20be2017-12-15 23:07:42 +00001112 PredicateMatcher(PredicateKind Kind, unsigned InsnVarID, unsigned OpIdx = ~0)
1113 : Kind(Kind), InsnVarID(InsnVarID), OpIdx(OpIdx) {}
Quentin Colombet063d7982017-12-14 23:44:07 +00001114
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001115 unsigned getInsnVarID() const { return InsnVarID; }
Quentin Colombetaad20be2017-12-15 23:07:42 +00001116 unsigned getOpIdx() const { return OpIdx; }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001117
Quentin Colombet063d7982017-12-14 23:44:07 +00001118 virtual ~PredicateMatcher() = default;
1119 /// Emit MatchTable opcodes that check the predicate for the given operand.
Quentin Colombetaad20be2017-12-15 23:07:42 +00001120 virtual void emitPredicateOpcodes(MatchTable &Table,
1121 RuleMatcher &Rule) const = 0;
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001122
Daniel Sanders759ff412017-02-24 13:58:11 +00001123 PredicateKind getKind() const { return Kind; }
Quentin Colombet893e0f12017-12-15 23:24:39 +00001124
Matt Arsenault1254f6d2020-06-20 21:38:43 -04001125 bool dependsOnOperands() const {
1126 // Custom predicates really depend on the context pattern of the
1127 // instruction, not just the individual instruction. This therefore
1128 // implicitly depends on all other pattern constraints.
1129 return Kind == IPM_GenericPredicate;
1130 }
1131
Quentin Colombet893e0f12017-12-15 23:24:39 +00001132 virtual bool isIdentical(const PredicateMatcher &B) const {
Quentin Colombet893e0f12017-12-15 23:24:39 +00001133 return B.getKind() == getKind() && InsnVarID == B.InsnVarID &&
1134 OpIdx == B.OpIdx;
1135 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001136
1137 virtual bool isIdenticalDownToValue(const PredicateMatcher &B) const {
1138 return hasValue() && PredicateMatcher::isIdentical(B);
1139 }
1140
1141 virtual MatchTableRecord getValue() const {
1142 assert(hasValue() && "Can not get a value of a value-less predicate!");
1143 llvm_unreachable("Not implemented yet");
1144 }
1145 virtual bool hasValue() const { return false; }
1146
1147 /// Report the maximum number of temporary operands needed by the predicate
1148 /// matcher.
1149 virtual unsigned countRendererFns() const { return 0; }
Quentin Colombet063d7982017-12-14 23:44:07 +00001150};
1151
1152/// Generates code to check a predicate of an operand.
1153///
1154/// Typical predicates include:
1155/// * Operand is a particular register.
1156/// * Operand is assigned a particular register bank.
1157/// * Operand is an MBB.
1158class OperandPredicateMatcher : public PredicateMatcher {
1159public:
Quentin Colombetaad20be2017-12-15 23:07:42 +00001160 OperandPredicateMatcher(PredicateKind Kind, unsigned InsnVarID,
1161 unsigned OpIdx)
1162 : PredicateMatcher(Kind, InsnVarID, OpIdx) {}
Quentin Colombet063d7982017-12-14 23:44:07 +00001163 virtual ~OperandPredicateMatcher() {}
Daniel Sanders759ff412017-02-24 13:58:11 +00001164
Daniel Sanders759ff412017-02-24 13:58:11 +00001165 /// Compare the priority of this object and B.
1166 ///
1167 /// Returns true if this object is more important than B.
Daniel Sanders05540042017-08-08 10:44:31 +00001168 virtual bool isHigherPriorityThan(const OperandPredicateMatcher &B) const;
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001169};
1170
Daniel Sanders2c269f62017-08-24 09:11:20 +00001171template <>
1172std::string
1173PredicateListMatcher<OperandPredicateMatcher>::getNoPredicateComment() const {
1174 return "No operand predicates";
1175}
1176
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001177/// Generates code to check that a register operand is defined by the same exact
1178/// one as another.
1179class SameOperandMatcher : public OperandPredicateMatcher {
Daniel Sanders1e4569f2017-10-20 20:55:29 +00001180 std::string MatchingName;
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001181
1182public:
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001183 SameOperandMatcher(unsigned InsnVarID, unsigned OpIdx, StringRef MatchingName)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001184 : OperandPredicateMatcher(OPM_SameOperand, InsnVarID, OpIdx),
1185 MatchingName(MatchingName) {}
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001186
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001187 static bool classof(const PredicateMatcher *P) {
Daniel Sanders1e4569f2017-10-20 20:55:29 +00001188 return P->getKind() == OPM_SameOperand;
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001189 }
1190
Quentin Colombetaad20be2017-12-15 23:07:42 +00001191 void emitPredicateOpcodes(MatchTable &Table,
1192 RuleMatcher &Rule) const override;
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001193
1194 bool isIdentical(const PredicateMatcher &B) const override {
1195 return OperandPredicateMatcher::isIdentical(B) &&
1196 MatchingName == cast<SameOperandMatcher>(&B)->MatchingName;
1197 }
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001198};
1199
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001200/// Generates code to check that an operand is a particular LLT.
1201class LLTOperandMatcher : public OperandPredicateMatcher {
1202protected:
Daniel Sanders52b4ce72017-03-07 23:20:35 +00001203 LLTCodeGen Ty;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001204
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001205public:
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001206 static std::map<LLTCodeGen, unsigned> TypeIDValues;
1207
1208 static void initTypeIDValuesMap() {
1209 TypeIDValues.clear();
1210
1211 unsigned ID = 0;
Mark de Wevere8d448e2019-12-22 18:58:32 +01001212 for (const LLTCodeGen &LLTy : KnownTypes)
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001213 TypeIDValues[LLTy] = ID++;
1214 }
1215
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001216 LLTOperandMatcher(unsigned InsnVarID, unsigned OpIdx, const LLTCodeGen &Ty)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001217 : OperandPredicateMatcher(OPM_LLT, InsnVarID, OpIdx), Ty(Ty) {
Daniel Sanders032e7f22017-08-17 13:18:35 +00001218 KnownTypes.insert(Ty);
1219 }
Daniel Sanders759ff412017-02-24 13:58:11 +00001220
Quentin Colombet063d7982017-12-14 23:44:07 +00001221 static bool classof(const PredicateMatcher *P) {
Daniel Sanders759ff412017-02-24 13:58:11 +00001222 return P->getKind() == OPM_LLT;
1223 }
Quentin Colombet893e0f12017-12-15 23:24:39 +00001224 bool isIdentical(const PredicateMatcher &B) const override {
1225 return OperandPredicateMatcher::isIdentical(B) &&
1226 Ty == cast<LLTOperandMatcher>(&B)->Ty;
1227 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001228 MatchTableRecord getValue() const override {
1229 const auto VI = TypeIDValues.find(Ty);
1230 if (VI == TypeIDValues.end())
1231 return MatchTable::NamedValue(getTy().getCxxEnumValue());
1232 return MatchTable::NamedValue(getTy().getCxxEnumValue(), VI->second);
1233 }
1234 bool hasValue() const override {
1235 if (TypeIDValues.size() != KnownTypes.size())
1236 initTypeIDValuesMap();
1237 return TypeIDValues.count(Ty);
1238 }
1239
1240 LLTCodeGen getTy() const { return Ty; }
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001241
Quentin Colombetaad20be2017-12-15 23:07:42 +00001242 void emitPredicateOpcodes(MatchTable &Table,
1243 RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001244 Table << MatchTable::Opcode("GIM_CheckType") << MatchTable::Comment("MI")
1245 << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Op")
1246 << MatchTable::IntValue(OpIdx) << MatchTable::Comment("Type")
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001247 << getValue() << MatchTable::LineBreak;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001248 }
1249};
1250
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001251std::map<LLTCodeGen, unsigned> LLTOperandMatcher::TypeIDValues;
1252
Daniel Sandersa71f4542017-10-16 00:56:30 +00001253/// Generates code to check that an operand is a pointer to any address space.
1254///
1255/// In SelectionDAG, the types did not describe pointers or address spaces. As a
1256/// result, iN is used to describe a pointer of N bits to any address space and
1257/// PatFrag predicates are typically used to constrain the address space. There's
1258/// no reliable means to derive the missing type information from the pattern so
1259/// imported rules must test the components of a pointer separately.
1260///
Daniel Sandersea8711b2017-10-16 03:36:29 +00001261/// If SizeInBits is zero, then the pointer size will be obtained from the
1262/// subtarget.
Daniel Sandersa71f4542017-10-16 00:56:30 +00001263class PointerToAnyOperandMatcher : public OperandPredicateMatcher {
1264protected:
1265 unsigned SizeInBits;
1266
1267public:
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001268 PointerToAnyOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
1269 unsigned SizeInBits)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001270 : OperandPredicateMatcher(OPM_PointerToAny, InsnVarID, OpIdx),
1271 SizeInBits(SizeInBits) {}
Daniel Sandersa71f4542017-10-16 00:56:30 +00001272
1273 static bool classof(const OperandPredicateMatcher *P) {
1274 return P->getKind() == OPM_PointerToAny;
1275 }
1276
Quentin Colombetaad20be2017-12-15 23:07:42 +00001277 void emitPredicateOpcodes(MatchTable &Table,
1278 RuleMatcher &Rule) const override {
1279 Table << MatchTable::Opcode("GIM_CheckPointerToAny")
1280 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1281 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1282 << MatchTable::Comment("SizeInBits")
Daniel Sandersa71f4542017-10-16 00:56:30 +00001283 << MatchTable::IntValue(SizeInBits) << MatchTable::LineBreak;
1284 }
1285};
1286
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001287/// Generates code to check that an operand is a particular target constant.
1288class ComplexPatternOperandMatcher : public OperandPredicateMatcher {
1289protected:
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001290 const OperandMatcher &Operand;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001291 const Record &TheDef;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001292
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001293 unsigned getAllocatedTemporariesBaseID() const;
1294
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001295public:
Quentin Colombet893e0f12017-12-15 23:24:39 +00001296 bool isIdentical(const PredicateMatcher &B) const override { return false; }
1297
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001298 ComplexPatternOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
1299 const OperandMatcher &Operand,
1300 const Record &TheDef)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001301 : OperandPredicateMatcher(OPM_ComplexPattern, InsnVarID, OpIdx),
1302 Operand(Operand), TheDef(TheDef) {}
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001303
Quentin Colombet063d7982017-12-14 23:44:07 +00001304 static bool classof(const PredicateMatcher *P) {
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001305 return P->getKind() == OPM_ComplexPattern;
1306 }
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001307
Quentin Colombetaad20be2017-12-15 23:07:42 +00001308 void emitPredicateOpcodes(MatchTable &Table,
1309 RuleMatcher &Rule) const override {
Daniel Sanders2deea182017-04-22 15:11:04 +00001310 unsigned ID = getAllocatedTemporariesBaseID();
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001311 Table << MatchTable::Opcode("GIM_CheckComplexPattern")
1312 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1313 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1314 << MatchTable::Comment("Renderer") << MatchTable::IntValue(ID)
1315 << MatchTable::NamedValue(("GICP_" + TheDef.getName()).str())
1316 << MatchTable::LineBreak;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001317 }
1318
Daniel Sanders2deea182017-04-22 15:11:04 +00001319 unsigned countRendererFns() const override {
1320 return 1;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001321 }
1322};
1323
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001324/// Generates code to check that an operand is in a particular register bank.
1325class RegisterBankOperandMatcher : public OperandPredicateMatcher {
1326protected:
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001327 const CodeGenRegisterClass &RC;
1328
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001329public:
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001330 RegisterBankOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
1331 const CodeGenRegisterClass &RC)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001332 : OperandPredicateMatcher(OPM_RegBank, InsnVarID, OpIdx), RC(RC) {}
Daniel Sanders759ff412017-02-24 13:58:11 +00001333
Quentin Colombet893e0f12017-12-15 23:24:39 +00001334 bool isIdentical(const PredicateMatcher &B) const override {
1335 return OperandPredicateMatcher::isIdentical(B) &&
1336 RC.getDef() == cast<RegisterBankOperandMatcher>(&B)->RC.getDef();
1337 }
1338
Quentin Colombet063d7982017-12-14 23:44:07 +00001339 static bool classof(const PredicateMatcher *P) {
Daniel Sanders759ff412017-02-24 13:58:11 +00001340 return P->getKind() == OPM_RegBank;
1341 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001342
Quentin Colombetaad20be2017-12-15 23:07:42 +00001343 void emitPredicateOpcodes(MatchTable &Table,
1344 RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001345 Table << MatchTable::Opcode("GIM_CheckRegBankForClass")
1346 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1347 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1348 << MatchTable::Comment("RC")
1349 << MatchTable::NamedValue(RC.getQualifiedName() + "RegClassID")
1350 << MatchTable::LineBreak;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001351 }
1352};
1353
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001354/// Generates code to check that an operand is a basic block.
1355class MBBOperandMatcher : public OperandPredicateMatcher {
1356public:
Quentin Colombetaad20be2017-12-15 23:07:42 +00001357 MBBOperandMatcher(unsigned InsnVarID, unsigned OpIdx)
1358 : OperandPredicateMatcher(OPM_MBB, InsnVarID, OpIdx) {}
Daniel Sanders759ff412017-02-24 13:58:11 +00001359
Quentin Colombet063d7982017-12-14 23:44:07 +00001360 static bool classof(const PredicateMatcher *P) {
Daniel Sanders759ff412017-02-24 13:58:11 +00001361 return P->getKind() == OPM_MBB;
1362 }
1363
Quentin Colombetaad20be2017-12-15 23:07:42 +00001364 void emitPredicateOpcodes(MatchTable &Table,
1365 RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001366 Table << MatchTable::Opcode("GIM_CheckIsMBB") << MatchTable::Comment("MI")
1367 << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Op")
1368 << MatchTable::IntValue(OpIdx) << MatchTable::LineBreak;
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001369 }
1370};
1371
Matt Arsenault3ecab8e2019-09-19 16:26:14 +00001372class ImmOperandMatcher : public OperandPredicateMatcher {
1373public:
1374 ImmOperandMatcher(unsigned InsnVarID, unsigned OpIdx)
1375 : OperandPredicateMatcher(IPM_Imm, InsnVarID, OpIdx) {}
1376
1377 static bool classof(const PredicateMatcher *P) {
1378 return P->getKind() == IPM_Imm;
1379 }
1380
1381 void emitPredicateOpcodes(MatchTable &Table,
1382 RuleMatcher &Rule) const override {
1383 Table << MatchTable::Opcode("GIM_CheckIsImm") << MatchTable::Comment("MI")
1384 << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Op")
1385 << MatchTable::IntValue(OpIdx) << MatchTable::LineBreak;
1386 }
1387};
1388
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001389/// Generates code to check that an operand is a G_CONSTANT with a particular
1390/// int.
1391class ConstantIntOperandMatcher : public OperandPredicateMatcher {
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001392protected:
1393 int64_t Value;
1394
1395public:
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001396 ConstantIntOperandMatcher(unsigned InsnVarID, unsigned OpIdx, int64_t Value)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001397 : OperandPredicateMatcher(OPM_Int, InsnVarID, OpIdx), Value(Value) {}
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001398
Quentin Colombet893e0f12017-12-15 23:24:39 +00001399 bool isIdentical(const PredicateMatcher &B) const override {
1400 return OperandPredicateMatcher::isIdentical(B) &&
1401 Value == cast<ConstantIntOperandMatcher>(&B)->Value;
1402 }
1403
Quentin Colombet063d7982017-12-14 23:44:07 +00001404 static bool classof(const PredicateMatcher *P) {
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001405 return P->getKind() == OPM_Int;
1406 }
1407
Quentin Colombetaad20be2017-12-15 23:07:42 +00001408 void emitPredicateOpcodes(MatchTable &Table,
1409 RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001410 Table << MatchTable::Opcode("GIM_CheckConstantInt")
1411 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1412 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1413 << MatchTable::IntValue(Value) << MatchTable::LineBreak;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001414 }
1415};
1416
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001417/// Generates code to check that an operand is a raw int (where MO.isImm() or
1418/// MO.isCImm() is true).
1419class LiteralIntOperandMatcher : public OperandPredicateMatcher {
1420protected:
1421 int64_t Value;
1422
1423public:
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001424 LiteralIntOperandMatcher(unsigned InsnVarID, unsigned OpIdx, int64_t Value)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001425 : OperandPredicateMatcher(OPM_LiteralInt, InsnVarID, OpIdx),
1426 Value(Value) {}
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001427
Quentin Colombet893e0f12017-12-15 23:24:39 +00001428 bool isIdentical(const PredicateMatcher &B) const override {
1429 return OperandPredicateMatcher::isIdentical(B) &&
1430 Value == cast<LiteralIntOperandMatcher>(&B)->Value;
1431 }
1432
Quentin Colombet063d7982017-12-14 23:44:07 +00001433 static bool classof(const PredicateMatcher *P) {
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001434 return P->getKind() == OPM_LiteralInt;
1435 }
1436
Quentin Colombetaad20be2017-12-15 23:07:42 +00001437 void emitPredicateOpcodes(MatchTable &Table,
1438 RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001439 Table << MatchTable::Opcode("GIM_CheckLiteralInt")
1440 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1441 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1442 << MatchTable::IntValue(Value) << MatchTable::LineBreak;
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001443 }
1444};
1445
Matt Arsenault8ec5c102019-08-29 01:13:41 +00001446/// Generates code to check that an operand is an CmpInst predicate
1447class CmpPredicateOperandMatcher : public OperandPredicateMatcher {
1448protected:
1449 std::string PredName;
1450
1451public:
1452 CmpPredicateOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
1453 std::string P)
1454 : OperandPredicateMatcher(OPM_CmpPredicate, InsnVarID, OpIdx), PredName(P) {}
1455
1456 bool isIdentical(const PredicateMatcher &B) const override {
1457 return OperandPredicateMatcher::isIdentical(B) &&
1458 PredName == cast<CmpPredicateOperandMatcher>(&B)->PredName;
1459 }
1460
1461 static bool classof(const PredicateMatcher *P) {
1462 return P->getKind() == OPM_CmpPredicate;
1463 }
1464
1465 void emitPredicateOpcodes(MatchTable &Table,
1466 RuleMatcher &Rule) const override {
1467 Table << MatchTable::Opcode("GIM_CheckCmpPredicate")
1468 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1469 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1470 << MatchTable::Comment("Predicate")
1471 << MatchTable::NamedValue("CmpInst", PredName)
1472 << MatchTable::LineBreak;
1473 }
1474};
1475
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00001476/// Generates code to check that an operand is an intrinsic ID.
1477class IntrinsicIDOperandMatcher : public OperandPredicateMatcher {
1478protected:
1479 const CodeGenIntrinsic *II;
1480
1481public:
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001482 IntrinsicIDOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
1483 const CodeGenIntrinsic *II)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001484 : OperandPredicateMatcher(OPM_IntrinsicID, InsnVarID, OpIdx), II(II) {}
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00001485
Quentin Colombet893e0f12017-12-15 23:24:39 +00001486 bool isIdentical(const PredicateMatcher &B) const override {
1487 return OperandPredicateMatcher::isIdentical(B) &&
1488 II == cast<IntrinsicIDOperandMatcher>(&B)->II;
1489 }
1490
Quentin Colombet063d7982017-12-14 23:44:07 +00001491 static bool classof(const PredicateMatcher *P) {
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00001492 return P->getKind() == OPM_IntrinsicID;
1493 }
1494
Quentin Colombetaad20be2017-12-15 23:07:42 +00001495 void emitPredicateOpcodes(MatchTable &Table,
1496 RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001497 Table << MatchTable::Opcode("GIM_CheckIntrinsicID")
1498 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1499 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1500 << MatchTable::NamedValue("Intrinsic::" + II->EnumName)
1501 << MatchTable::LineBreak;
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00001502 }
1503};
1504
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001505/// Generates code to check that a set of predicates match for a particular
1506/// operand.
1507class OperandMatcher : public PredicateListMatcher<OperandPredicateMatcher> {
1508protected:
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001509 InstructionMatcher &Insn;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001510 unsigned OpIdx;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001511 std::string SymbolicName;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001512
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001513 /// The index of the first temporary variable allocated to this operand. The
1514 /// number of allocated temporaries can be found with
Daniel Sanders2deea182017-04-22 15:11:04 +00001515 /// countRendererFns().
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001516 unsigned AllocatedTemporariesBaseID;
1517
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001518public:
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001519 OperandMatcher(InstructionMatcher &Insn, unsigned OpIdx,
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001520 const std::string &SymbolicName,
1521 unsigned AllocatedTemporariesBaseID)
1522 : Insn(Insn), OpIdx(OpIdx), SymbolicName(SymbolicName),
1523 AllocatedTemporariesBaseID(AllocatedTemporariesBaseID) {}
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001524
1525 bool hasSymbolicName() const { return !SymbolicName.empty(); }
1526 const StringRef getSymbolicName() const { return SymbolicName; }
Daniel Sandersffc7d582017-03-29 15:37:18 +00001527 void setSymbolicName(StringRef Name) {
1528 assert(SymbolicName.empty() && "Operand already has a symbolic name");
Benjamin Krameradcd0262020-01-28 20:23:46 +01001529 SymbolicName = std::string(Name);
Daniel Sandersffc7d582017-03-29 15:37:18 +00001530 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001531
1532 /// Construct a new operand predicate and add it to the matcher.
1533 template <class Kind, class... Args>
1534 Optional<Kind *> addPredicate(Args &&... args) {
1535 if (isSameAsAnotherOperand())
1536 return None;
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00001537 Predicates.emplace_back(std::make_unique<Kind>(
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001538 getInsnVarID(), getOpIdx(), std::forward<Args>(args)...));
1539 return static_cast<Kind *>(Predicates.back().get());
1540 }
1541
1542 unsigned getOpIdx() const { return OpIdx; }
Quentin Colombetaad20be2017-12-15 23:07:42 +00001543 unsigned getInsnVarID() const;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001544
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001545 std::string getOperandExpr(unsigned InsnVarID) const {
1546 return "State.MIs[" + llvm::to_string(InsnVarID) + "]->getOperand(" +
1547 llvm::to_string(OpIdx) + ")";
Daniel Sanderse604ef52017-02-20 15:30:43 +00001548 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001549
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001550 InstructionMatcher &getInstructionMatcher() const { return Insn; }
1551
Daniel Sandersa71f4542017-10-16 00:56:30 +00001552 Error addTypeCheckPredicate(const TypeSetByHwMode &VTy,
Reid Klecknercfdd4a22017-10-16 20:31:16 +00001553 bool OperandIsAPointer);
Daniel Sandersa71f4542017-10-16 00:56:30 +00001554
Daniel Sanders9d662d22017-07-06 10:06:12 +00001555 /// Emit MatchTable opcodes that test whether the instruction named in
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001556 /// InsnVarID matches all the predicates and all the operands.
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001557 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule) {
1558 if (!Optimized) {
1559 std::string Comment;
1560 raw_string_ostream CommentOS(Comment);
1561 CommentOS << "MIs[" << getInsnVarID() << "] ";
1562 if (SymbolicName.empty())
1563 CommentOS << "Operand " << OpIdx;
1564 else
1565 CommentOS << SymbolicName;
1566 Table << MatchTable::Comment(CommentOS.str()) << MatchTable::LineBreak;
1567 }
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001568
Quentin Colombetaad20be2017-12-15 23:07:42 +00001569 emitPredicateListOpcodes(Table, Rule);
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001570 }
Daniel Sanders759ff412017-02-24 13:58:11 +00001571
1572 /// Compare the priority of this object and B.
1573 ///
1574 /// Returns true if this object is more important than B.
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001575 bool isHigherPriorityThan(OperandMatcher &B) {
Daniel Sanders759ff412017-02-24 13:58:11 +00001576 // Operand matchers involving more predicates have higher priority.
1577 if (predicates_size() > B.predicates_size())
1578 return true;
1579 if (predicates_size() < B.predicates_size())
1580 return false;
1581
1582 // This assumes that predicates are added in a consistent order.
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001583 for (auto &&Predicate : zip(predicates(), B.predicates())) {
Daniel Sanders759ff412017-02-24 13:58:11 +00001584 if (std::get<0>(Predicate)->isHigherPriorityThan(*std::get<1>(Predicate)))
1585 return true;
1586 if (std::get<1>(Predicate)->isHigherPriorityThan(*std::get<0>(Predicate)))
1587 return false;
1588 }
1589
1590 return false;
1591 };
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001592
1593 /// Report the maximum number of temporary operands needed by the operand
1594 /// matcher.
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001595 unsigned countRendererFns() {
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001596 return std::accumulate(
1597 predicates().begin(), predicates().end(), 0,
1598 [](unsigned A,
1599 const std::unique_ptr<OperandPredicateMatcher> &Predicate) {
Daniel Sanders2deea182017-04-22 15:11:04 +00001600 return A + Predicate->countRendererFns();
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001601 });
1602 }
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001603
1604 unsigned getAllocatedTemporariesBaseID() const {
1605 return AllocatedTemporariesBaseID;
1606 }
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001607
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001608 bool isSameAsAnotherOperand() {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001609 for (const auto &Predicate : predicates())
1610 if (isa<SameOperandMatcher>(Predicate))
1611 return true;
1612 return false;
1613 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001614};
1615
Reid Klecknercfdd4a22017-10-16 20:31:16 +00001616Error OperandMatcher::addTypeCheckPredicate(const TypeSetByHwMode &VTy,
Quentin Colombetaad20be2017-12-15 23:07:42 +00001617 bool OperandIsAPointer) {
Reid Klecknercfdd4a22017-10-16 20:31:16 +00001618 if (!VTy.isMachineValueType())
1619 return failedImport("unsupported typeset");
1620
1621 if (VTy.getMachineValueType() == MVT::iPTR && OperandIsAPointer) {
1622 addPredicate<PointerToAnyOperandMatcher>(0);
1623 return Error::success();
1624 }
1625
1626 auto OpTyOrNone = MVTToLLT(VTy.getMachineValueType().SimpleTy);
1627 if (!OpTyOrNone)
1628 return failedImport("unsupported type");
1629
1630 if (OperandIsAPointer)
1631 addPredicate<PointerToAnyOperandMatcher>(OpTyOrNone->get().getSizeInBits());
Tom Stellard9ad714f2019-02-20 19:43:47 +00001632 else if (VTy.isPointer())
1633 addPredicate<LLTOperandMatcher>(LLT::pointer(VTy.getPtrAddrSpace(),
1634 OpTyOrNone->get().getSizeInBits()));
Reid Klecknercfdd4a22017-10-16 20:31:16 +00001635 else
1636 addPredicate<LLTOperandMatcher>(*OpTyOrNone);
1637 return Error::success();
1638}
1639
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001640unsigned ComplexPatternOperandMatcher::getAllocatedTemporariesBaseID() const {
1641 return Operand.getAllocatedTemporariesBaseID();
1642}
1643
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001644/// Generates code to check a predicate on an instruction.
1645///
1646/// Typical predicates include:
1647/// * The opcode of the instruction is a particular value.
1648/// * The nsw/nuw flag is/isn't set.
Quentin Colombet063d7982017-12-14 23:44:07 +00001649class InstructionPredicateMatcher : public PredicateMatcher {
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001650public:
Quentin Colombetaad20be2017-12-15 23:07:42 +00001651 InstructionPredicateMatcher(PredicateKind Kind, unsigned InsnVarID)
1652 : PredicateMatcher(Kind, InsnVarID) {}
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001653 virtual ~InstructionPredicateMatcher() {}
1654
Daniel Sanders759ff412017-02-24 13:58:11 +00001655 /// Compare the priority of this object and B.
1656 ///
1657 /// Returns true if this object is more important than B.
Daniel Sanders32291982017-06-28 13:50:04 +00001658 virtual bool
1659 isHigherPriorityThan(const InstructionPredicateMatcher &B) const {
Daniel Sanders759ff412017-02-24 13:58:11 +00001660 return Kind < B.Kind;
1661 };
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001662};
1663
Daniel Sanders2c269f62017-08-24 09:11:20 +00001664template <>
1665std::string
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001666PredicateListMatcher<PredicateMatcher>::getNoPredicateComment() const {
Daniel Sanders2c269f62017-08-24 09:11:20 +00001667 return "No instruction predicates";
1668}
1669
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001670/// Generates code to check the opcode of an instruction.
1671class InstructionOpcodeMatcher : public InstructionPredicateMatcher {
1672protected:
1673 const CodeGenInstruction *I;
1674
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001675 static DenseMap<const CodeGenInstruction *, unsigned> OpcodeValues;
1676
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001677public:
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001678 static void initOpcodeValuesMap(const CodeGenTarget &Target) {
1679 OpcodeValues.clear();
1680
1681 unsigned OpcodeValue = 0;
1682 for (const CodeGenInstruction *I : Target.getInstructionsByEnumValue())
1683 OpcodeValues[I] = OpcodeValue++;
1684 }
1685
Quentin Colombetaad20be2017-12-15 23:07:42 +00001686 InstructionOpcodeMatcher(unsigned InsnVarID, const CodeGenInstruction *I)
1687 : InstructionPredicateMatcher(IPM_Opcode, InsnVarID), I(I) {}
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001688
Quentin Colombet063d7982017-12-14 23:44:07 +00001689 static bool classof(const PredicateMatcher *P) {
Daniel Sanders759ff412017-02-24 13:58:11 +00001690 return P->getKind() == IPM_Opcode;
1691 }
1692
Quentin Colombet893e0f12017-12-15 23:24:39 +00001693 bool isIdentical(const PredicateMatcher &B) const override {
1694 return InstructionPredicateMatcher::isIdentical(B) &&
1695 I == cast<InstructionOpcodeMatcher>(&B)->I;
1696 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001697 MatchTableRecord getValue() const override {
1698 const auto VI = OpcodeValues.find(I);
1699 if (VI != OpcodeValues.end())
1700 return MatchTable::NamedValue(I->Namespace, I->TheDef->getName(),
1701 VI->second);
1702 return MatchTable::NamedValue(I->Namespace, I->TheDef->getName());
1703 }
1704 bool hasValue() const override { return OpcodeValues.count(I); }
Quentin Colombet893e0f12017-12-15 23:24:39 +00001705
Quentin Colombetaad20be2017-12-15 23:07:42 +00001706 void emitPredicateOpcodes(MatchTable &Table,
1707 RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001708 Table << MatchTable::Opcode("GIM_CheckOpcode") << MatchTable::Comment("MI")
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001709 << MatchTable::IntValue(InsnVarID) << getValue()
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001710 << MatchTable::LineBreak;
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001711 }
Daniel Sanders759ff412017-02-24 13:58:11 +00001712
1713 /// Compare the priority of this object and B.
1714 ///
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001715 /// Returns true if this object is more important than B.
Daniel Sanders32291982017-06-28 13:50:04 +00001716 bool
1717 isHigherPriorityThan(const InstructionPredicateMatcher &B) const override {
Daniel Sanders759ff412017-02-24 13:58:11 +00001718 if (InstructionPredicateMatcher::isHigherPriorityThan(B))
1719 return true;
1720 if (B.InstructionPredicateMatcher::isHigherPriorityThan(*this))
1721 return false;
1722
1723 // Prioritize opcodes for cosmetic reasons in the generated source. Although
1724 // this is cosmetic at the moment, we may want to drive a similar ordering
1725 // using instruction frequency information to improve compile time.
1726 if (const InstructionOpcodeMatcher *BO =
1727 dyn_cast<InstructionOpcodeMatcher>(&B))
1728 return I->TheDef->getName() < BO->I->TheDef->getName();
1729
1730 return false;
1731 };
Daniel Sanders05540042017-08-08 10:44:31 +00001732
1733 bool isConstantInstruction() const {
1734 return I->TheDef->getName() == "G_CONSTANT";
1735 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001736
Roman Tereshin19da6672018-05-22 04:31:50 +00001737 StringRef getOpcode() const { return I->TheDef->getName(); }
Roman Tereshin6082a062019-10-30 20:58:46 -07001738 bool isVariadicNumOperands() const { return I->Operands.isVariadic; }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001739
1740 StringRef getOperandType(unsigned OpIdx) const {
1741 return I->Operands[OpIdx].OperandType;
1742 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001743};
1744
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001745DenseMap<const CodeGenInstruction *, unsigned>
1746 InstructionOpcodeMatcher::OpcodeValues;
1747
Roman Tereshin19da6672018-05-22 04:31:50 +00001748class InstructionNumOperandsMatcher final : public InstructionPredicateMatcher {
1749 unsigned NumOperands = 0;
1750
1751public:
1752 InstructionNumOperandsMatcher(unsigned InsnVarID, unsigned NumOperands)
1753 : InstructionPredicateMatcher(IPM_NumOperands, InsnVarID),
1754 NumOperands(NumOperands) {}
1755
1756 static bool classof(const PredicateMatcher *P) {
1757 return P->getKind() == IPM_NumOperands;
1758 }
1759
1760 bool isIdentical(const PredicateMatcher &B) const override {
1761 return InstructionPredicateMatcher::isIdentical(B) &&
1762 NumOperands == cast<InstructionNumOperandsMatcher>(&B)->NumOperands;
1763 }
1764
1765 void emitPredicateOpcodes(MatchTable &Table,
1766 RuleMatcher &Rule) const override {
1767 Table << MatchTable::Opcode("GIM_CheckNumOperands")
1768 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1769 << MatchTable::Comment("Expected")
1770 << MatchTable::IntValue(NumOperands) << MatchTable::LineBreak;
1771 }
1772};
1773
Daniel Sanders2c269f62017-08-24 09:11:20 +00001774/// Generates code to check that this instruction is a constant whose value
1775/// meets an immediate predicate.
1776///
1777/// Immediates are slightly odd since they are typically used like an operand
1778/// but are represented as an operator internally. We typically write simm8:$src
1779/// in a tablegen pattern, but this is just syntactic sugar for
1780/// (imm:i32)<<P:Predicate_simm8>>:$imm which more directly describes the nodes
1781/// that will be matched and the predicate (which is attached to the imm
1782/// operator) that will be tested. In SelectionDAG this describes a
1783/// ConstantSDNode whose internal value will be tested using the simm8 predicate.
1784///
1785/// The corresponding GlobalISel representation is %1 = G_CONSTANT iN Value. In
1786/// this representation, the immediate could be tested with an
1787/// InstructionMatcher, InstructionOpcodeMatcher, OperandMatcher, and a
1788/// OperandPredicateMatcher-subclass to check the Value meets the predicate but
1789/// there are two implementation issues with producing that matcher
1790/// configuration from the SelectionDAG pattern:
1791/// * ImmLeaf is a PatFrag whose root is an InstructionMatcher. This means that
1792/// were we to sink the immediate predicate to the operand we would have to
1793/// have two partial implementations of PatFrag support, one for immediates
1794/// and one for non-immediates.
1795/// * At the point we handle the predicate, the OperandMatcher hasn't been
1796/// created yet. If we were to sink the predicate to the OperandMatcher we
1797/// would also have to complicate (or duplicate) the code that descends and
1798/// creates matchers for the subtree.
1799/// Overall, it's simpler to handle it in the place it was found.
1800class InstructionImmPredicateMatcher : public InstructionPredicateMatcher {
1801protected:
1802 TreePredicateFn Predicate;
1803
1804public:
Quentin Colombetaad20be2017-12-15 23:07:42 +00001805 InstructionImmPredicateMatcher(unsigned InsnVarID,
1806 const TreePredicateFn &Predicate)
1807 : InstructionPredicateMatcher(IPM_ImmPredicate, InsnVarID),
1808 Predicate(Predicate) {}
Daniel Sanders2c269f62017-08-24 09:11:20 +00001809
Quentin Colombet893e0f12017-12-15 23:24:39 +00001810 bool isIdentical(const PredicateMatcher &B) const override {
1811 return InstructionPredicateMatcher::isIdentical(B) &&
1812 Predicate.getOrigPatFragRecord() ==
1813 cast<InstructionImmPredicateMatcher>(&B)
1814 ->Predicate.getOrigPatFragRecord();
1815 }
1816
Quentin Colombet063d7982017-12-14 23:44:07 +00001817 static bool classof(const PredicateMatcher *P) {
Daniel Sanders2c269f62017-08-24 09:11:20 +00001818 return P->getKind() == IPM_ImmPredicate;
1819 }
1820
Quentin Colombetaad20be2017-12-15 23:07:42 +00001821 void emitPredicateOpcodes(MatchTable &Table,
1822 RuleMatcher &Rule) const override {
Daniel Sanders11300ce2017-10-13 21:28:03 +00001823 Table << MatchTable::Opcode(getMatchOpcodeForPredicate(Predicate))
Daniel Sanders2c269f62017-08-24 09:11:20 +00001824 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1825 << MatchTable::Comment("Predicate")
Daniel Sanders11300ce2017-10-13 21:28:03 +00001826 << MatchTable::NamedValue(getEnumNameForPredicate(Predicate))
Daniel Sanders2c269f62017-08-24 09:11:20 +00001827 << MatchTable::LineBreak;
1828 }
1829};
1830
Daniel Sanders76664652017-11-28 22:07:05 +00001831/// Generates code to check that a memory instruction has a atomic ordering
1832/// MachineMemoryOperand.
1833class AtomicOrderingMMOPredicateMatcher : public InstructionPredicateMatcher {
Daniel Sanders0c43b3a2017-11-30 21:05:59 +00001834public:
1835 enum AOComparator {
1836 AO_Exactly,
1837 AO_OrStronger,
1838 AO_WeakerThan,
1839 };
1840
1841protected:
Daniel Sanders76664652017-11-28 22:07:05 +00001842 StringRef Order;
Daniel Sanders0c43b3a2017-11-30 21:05:59 +00001843 AOComparator Comparator;
Daniel Sanders76664652017-11-28 22:07:05 +00001844
Daniel Sanders39690bd2017-10-15 02:41:12 +00001845public:
Quentin Colombetaad20be2017-12-15 23:07:42 +00001846 AtomicOrderingMMOPredicateMatcher(unsigned InsnVarID, StringRef Order,
Daniel Sanders0c43b3a2017-11-30 21:05:59 +00001847 AOComparator Comparator = AO_Exactly)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001848 : InstructionPredicateMatcher(IPM_AtomicOrderingMMO, InsnVarID),
1849 Order(Order), Comparator(Comparator) {}
Daniel Sanders39690bd2017-10-15 02:41:12 +00001850
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001851 static bool classof(const PredicateMatcher *P) {
Daniel Sanders76664652017-11-28 22:07:05 +00001852 return P->getKind() == IPM_AtomicOrderingMMO;
Daniel Sanders39690bd2017-10-15 02:41:12 +00001853 }
1854
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001855 bool isIdentical(const PredicateMatcher &B) const override {
1856 if (!InstructionPredicateMatcher::isIdentical(B))
1857 return false;
1858 const auto &R = *cast<AtomicOrderingMMOPredicateMatcher>(&B);
1859 return Order == R.Order && Comparator == R.Comparator;
1860 }
1861
Quentin Colombetaad20be2017-12-15 23:07:42 +00001862 void emitPredicateOpcodes(MatchTable &Table,
1863 RuleMatcher &Rule) const override {
Daniel Sanders0c43b3a2017-11-30 21:05:59 +00001864 StringRef Opcode = "GIM_CheckAtomicOrdering";
1865
1866 if (Comparator == AO_OrStronger)
1867 Opcode = "GIM_CheckAtomicOrderingOrStrongerThan";
1868 if (Comparator == AO_WeakerThan)
1869 Opcode = "GIM_CheckAtomicOrderingWeakerThan";
1870
1871 Table << MatchTable::Opcode(Opcode) << MatchTable::Comment("MI")
1872 << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Order")
Daniel Sanders76664652017-11-28 22:07:05 +00001873 << MatchTable::NamedValue(("(int64_t)AtomicOrdering::" + Order).str())
Daniel Sanders39690bd2017-10-15 02:41:12 +00001874 << MatchTable::LineBreak;
1875 }
1876};
1877
Daniel Sandersf84bc372018-05-05 20:53:24 +00001878/// Generates code to check that the size of an MMO is exactly N bytes.
1879class MemorySizePredicateMatcher : public InstructionPredicateMatcher {
1880protected:
1881 unsigned MMOIdx;
1882 uint64_t Size;
1883
1884public:
1885 MemorySizePredicateMatcher(unsigned InsnVarID, unsigned MMOIdx, unsigned Size)
1886 : InstructionPredicateMatcher(IPM_MemoryLLTSize, InsnVarID),
1887 MMOIdx(MMOIdx), Size(Size) {}
1888
1889 static bool classof(const PredicateMatcher *P) {
1890 return P->getKind() == IPM_MemoryLLTSize;
1891 }
1892 bool isIdentical(const PredicateMatcher &B) const override {
1893 return InstructionPredicateMatcher::isIdentical(B) &&
1894 MMOIdx == cast<MemorySizePredicateMatcher>(&B)->MMOIdx &&
1895 Size == cast<MemorySizePredicateMatcher>(&B)->Size;
1896 }
1897
1898 void emitPredicateOpcodes(MatchTable &Table,
1899 RuleMatcher &Rule) const override {
1900 Table << MatchTable::Opcode("GIM_CheckMemorySizeEqualTo")
1901 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1902 << MatchTable::Comment("MMO") << MatchTable::IntValue(MMOIdx)
1903 << MatchTable::Comment("Size") << MatchTable::IntValue(Size)
1904 << MatchTable::LineBreak;
1905 }
1906};
1907
Matt Arsenaultd00d8572019-07-15 20:59:42 +00001908class MemoryAddressSpacePredicateMatcher : public InstructionPredicateMatcher {
1909protected:
1910 unsigned MMOIdx;
1911 SmallVector<unsigned, 4> AddrSpaces;
1912
1913public:
1914 MemoryAddressSpacePredicateMatcher(unsigned InsnVarID, unsigned MMOIdx,
1915 ArrayRef<unsigned> AddrSpaces)
1916 : InstructionPredicateMatcher(IPM_MemoryAddressSpace, InsnVarID),
1917 MMOIdx(MMOIdx), AddrSpaces(AddrSpaces.begin(), AddrSpaces.end()) {}
1918
1919 static bool classof(const PredicateMatcher *P) {
1920 return P->getKind() == IPM_MemoryAddressSpace;
1921 }
1922 bool isIdentical(const PredicateMatcher &B) const override {
1923 if (!InstructionPredicateMatcher::isIdentical(B))
1924 return false;
1925 auto *Other = cast<MemoryAddressSpacePredicateMatcher>(&B);
1926 return MMOIdx == Other->MMOIdx && AddrSpaces == Other->AddrSpaces;
1927 }
1928
1929 void emitPredicateOpcodes(MatchTable &Table,
1930 RuleMatcher &Rule) const override {
1931 Table << MatchTable::Opcode("GIM_CheckMemoryAddressSpace")
1932 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1933 << MatchTable::Comment("MMO") << MatchTable::IntValue(MMOIdx)
1934 // Encode number of address spaces to expect.
1935 << MatchTable::Comment("NumAddrSpace")
1936 << MatchTable::IntValue(AddrSpaces.size());
1937 for (unsigned AS : AddrSpaces)
1938 Table << MatchTable::Comment("AddrSpace") << MatchTable::IntValue(AS);
1939
1940 Table << MatchTable::LineBreak;
1941 }
1942};
1943
Matt Arsenault52c26242019-07-31 00:14:43 +00001944class MemoryAlignmentPredicateMatcher : public InstructionPredicateMatcher {
1945protected:
1946 unsigned MMOIdx;
1947 int MinAlign;
1948
1949public:
1950 MemoryAlignmentPredicateMatcher(unsigned InsnVarID, unsigned MMOIdx,
1951 int MinAlign)
1952 : InstructionPredicateMatcher(IPM_MemoryAlignment, InsnVarID),
1953 MMOIdx(MMOIdx), MinAlign(MinAlign) {
1954 assert(MinAlign > 0);
1955 }
1956
1957 static bool classof(const PredicateMatcher *P) {
1958 return P->getKind() == IPM_MemoryAlignment;
1959 }
1960
1961 bool isIdentical(const PredicateMatcher &B) const override {
1962 if (!InstructionPredicateMatcher::isIdentical(B))
1963 return false;
1964 auto *Other = cast<MemoryAlignmentPredicateMatcher>(&B);
1965 return MMOIdx == Other->MMOIdx && MinAlign == Other->MinAlign;
1966 }
1967
1968 void emitPredicateOpcodes(MatchTable &Table,
1969 RuleMatcher &Rule) const override {
1970 Table << MatchTable::Opcode("GIM_CheckMemoryAlignment")
1971 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1972 << MatchTable::Comment("MMO") << MatchTable::IntValue(MMOIdx)
1973 << MatchTable::Comment("MinAlign") << MatchTable::IntValue(MinAlign)
1974 << MatchTable::LineBreak;
1975 }
1976};
1977
Daniel Sandersf84bc372018-05-05 20:53:24 +00001978/// Generates code to check that the size of an MMO is less-than, equal-to, or
1979/// greater than a given LLT.
1980class MemoryVsLLTSizePredicateMatcher : public InstructionPredicateMatcher {
1981public:
1982 enum RelationKind {
1983 GreaterThan,
1984 EqualTo,
1985 LessThan,
1986 };
1987
1988protected:
1989 unsigned MMOIdx;
1990 RelationKind Relation;
1991 unsigned OpIdx;
1992
1993public:
1994 MemoryVsLLTSizePredicateMatcher(unsigned InsnVarID, unsigned MMOIdx,
1995 enum RelationKind Relation,
1996 unsigned OpIdx)
1997 : InstructionPredicateMatcher(IPM_MemoryVsLLTSize, InsnVarID),
1998 MMOIdx(MMOIdx), Relation(Relation), OpIdx(OpIdx) {}
1999
2000 static bool classof(const PredicateMatcher *P) {
2001 return P->getKind() == IPM_MemoryVsLLTSize;
2002 }
2003 bool isIdentical(const PredicateMatcher &B) const override {
2004 return InstructionPredicateMatcher::isIdentical(B) &&
2005 MMOIdx == cast<MemoryVsLLTSizePredicateMatcher>(&B)->MMOIdx &&
2006 Relation == cast<MemoryVsLLTSizePredicateMatcher>(&B)->Relation &&
2007 OpIdx == cast<MemoryVsLLTSizePredicateMatcher>(&B)->OpIdx;
2008 }
2009
2010 void emitPredicateOpcodes(MatchTable &Table,
2011 RuleMatcher &Rule) const override {
2012 Table << MatchTable::Opcode(Relation == EqualTo
2013 ? "GIM_CheckMemorySizeEqualToLLT"
2014 : Relation == GreaterThan
2015 ? "GIM_CheckMemorySizeGreaterThanLLT"
2016 : "GIM_CheckMemorySizeLessThanLLT")
2017 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
2018 << MatchTable::Comment("MMO") << MatchTable::IntValue(MMOIdx)
2019 << MatchTable::Comment("OpIdx") << MatchTable::IntValue(OpIdx)
2020 << MatchTable::LineBreak;
2021 }
2022};
2023
Daniel Sanders8ead1292018-06-15 23:13:43 +00002024/// Generates code to check an arbitrary C++ instruction predicate.
2025class GenericInstructionPredicateMatcher : public InstructionPredicateMatcher {
2026protected:
2027 TreePredicateFn Predicate;
2028
2029public:
2030 GenericInstructionPredicateMatcher(unsigned InsnVarID,
2031 TreePredicateFn Predicate)
2032 : InstructionPredicateMatcher(IPM_GenericPredicate, InsnVarID),
2033 Predicate(Predicate) {}
2034
2035 static bool classof(const InstructionPredicateMatcher *P) {
2036 return P->getKind() == IPM_GenericPredicate;
2037 }
Daniel Sanders06f4ff12018-09-25 17:59:02 +00002038 bool isIdentical(const PredicateMatcher &B) const override {
2039 return InstructionPredicateMatcher::isIdentical(B) &&
2040 Predicate ==
2041 static_cast<const GenericInstructionPredicateMatcher &>(B)
2042 .Predicate;
2043 }
Daniel Sanders8ead1292018-06-15 23:13:43 +00002044 void emitPredicateOpcodes(MatchTable &Table,
2045 RuleMatcher &Rule) const override {
2046 Table << MatchTable::Opcode("GIM_CheckCxxInsnPredicate")
2047 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
2048 << MatchTable::Comment("FnId")
2049 << MatchTable::NamedValue(getEnumNameForPredicate(Predicate))
2050 << MatchTable::LineBreak;
2051 }
2052};
2053
Daniel Sandersdc662ff2017-01-26 11:10:14 +00002054/// Generates code to check that a set of predicates and operands match for a
2055/// particular instruction.
2056///
2057/// Typical predicates include:
2058/// * Has a specific opcode.
2059/// * Has an nsw/nuw flag or doesn't.
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002060class InstructionMatcher final : public PredicateListMatcher<PredicateMatcher> {
Daniel Sandersdc662ff2017-01-26 11:10:14 +00002061protected:
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002062 typedef std::vector<std::unique_ptr<OperandMatcher>> OperandVec;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002063
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002064 RuleMatcher &Rule;
2065
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002066 /// The operands to match. All rendered operands must be present even if the
2067 /// condition is always true.
2068 OperandVec Operands;
Roman Tereshin19da6672018-05-22 04:31:50 +00002069 bool NumOperandsCheck = true;
Daniel Sandersdc662ff2017-01-26 11:10:14 +00002070
Daniel Sanders05540042017-08-08 10:44:31 +00002071 std::string SymbolicName;
Quentin Colombetaad20be2017-12-15 23:07:42 +00002072 unsigned InsnVarID;
Daniel Sanders05540042017-08-08 10:44:31 +00002073
Matt Arsenault3e45c702019-09-06 20:32:37 +00002074 /// PhysRegInputs - List list has an entry for each explicitly specified
2075 /// physreg input to the pattern. The first elt is the Register node, the
2076 /// second is the recorded slot number the input pattern match saved it in.
2077 SmallVector<std::pair<Record *, unsigned>, 2> PhysRegInputs;
2078
Daniel Sandersdc662ff2017-01-26 11:10:14 +00002079public:
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002080 InstructionMatcher(RuleMatcher &Rule, StringRef SymbolicName)
Quentin Colombetaad20be2017-12-15 23:07:42 +00002081 : Rule(Rule), SymbolicName(SymbolicName) {
2082 // We create a new instruction matcher.
2083 // Get a new ID for that instruction.
2084 InsnVarID = Rule.implicitlyDefineInsnVar(*this);
2085 }
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002086
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002087 /// Construct a new instruction predicate and add it to the matcher.
2088 template <class Kind, class... Args>
2089 Optional<Kind *> addPredicate(Args &&... args) {
2090 Predicates.emplace_back(
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00002091 std::make_unique<Kind>(getInsnVarID(), std::forward<Args>(args)...));
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002092 return static_cast<Kind *>(Predicates.back().get());
2093 }
2094
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002095 RuleMatcher &getRuleMatcher() const { return Rule; }
Daniel Sanders05540042017-08-08 10:44:31 +00002096
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002097 unsigned getInsnVarID() const { return InsnVarID; }
Quentin Colombetaad20be2017-12-15 23:07:42 +00002098
Daniel Sandersdc662ff2017-01-26 11:10:14 +00002099 /// Add an operand to the matcher.
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002100 OperandMatcher &addOperand(unsigned OpIdx, const std::string &SymbolicName,
2101 unsigned AllocatedTemporariesBaseID) {
2102 Operands.emplace_back(new OperandMatcher(*this, OpIdx, SymbolicName,
2103 AllocatedTemporariesBaseID));
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002104 if (!SymbolicName.empty())
2105 Rule.defineOperand(SymbolicName, *Operands.back());
2106
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002107 return *Operands.back();
Daniel Sandersdc662ff2017-01-26 11:10:14 +00002108 }
2109
Daniel Sandersffc7d582017-03-29 15:37:18 +00002110 OperandMatcher &getOperand(unsigned OpIdx) {
2111 auto I = std::find_if(Operands.begin(), Operands.end(),
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002112 [&OpIdx](const std::unique_ptr<OperandMatcher> &X) {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002113 return X->getOpIdx() == OpIdx;
Daniel Sandersffc7d582017-03-29 15:37:18 +00002114 });
2115 if (I != Operands.end())
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002116 return **I;
Daniel Sandersffc7d582017-03-29 15:37:18 +00002117 llvm_unreachable("Failed to lookup operand");
2118 }
2119
Matt Arsenault3e45c702019-09-06 20:32:37 +00002120 OperandMatcher &addPhysRegInput(Record *Reg, unsigned OpIdx,
2121 unsigned TempOpIdx) {
2122 assert(SymbolicName.empty());
2123 OperandMatcher *OM = new OperandMatcher(*this, OpIdx, "", TempOpIdx);
2124 Operands.emplace_back(OM);
2125 Rule.definePhysRegOperand(Reg, *OM);
2126 PhysRegInputs.emplace_back(Reg, OpIdx);
2127 return *OM;
2128 }
2129
2130 ArrayRef<std::pair<Record *, unsigned>> getPhysRegInputs() const {
2131 return PhysRegInputs;
2132 }
2133
Daniel Sanders05540042017-08-08 10:44:31 +00002134 StringRef getSymbolicName() const { return SymbolicName; }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002135 unsigned getNumOperands() const { return Operands.size(); }
Daniel Sandersbee57392017-04-04 13:25:23 +00002136 OperandVec::iterator operands_begin() { return Operands.begin(); }
2137 OperandVec::iterator operands_end() { return Operands.end(); }
2138 iterator_range<OperandVec::iterator> operands() {
2139 return make_range(operands_begin(), operands_end());
2140 }
Daniel Sandersffc7d582017-03-29 15:37:18 +00002141 OperandVec::const_iterator operands_begin() const { return Operands.begin(); }
2142 OperandVec::const_iterator operands_end() const { return Operands.end(); }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002143 iterator_range<OperandVec::const_iterator> operands() const {
2144 return make_range(operands_begin(), operands_end());
2145 }
Quentin Colombetec76d9c2017-12-18 19:47:41 +00002146 bool operands_empty() const { return Operands.empty(); }
2147
2148 void pop_front() { Operands.erase(Operands.begin()); }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002149
Roman Tereshin19da6672018-05-22 04:31:50 +00002150 void optimize();
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002151
2152 /// Emit MatchTable opcodes that test whether the instruction named in
2153 /// InsnVarName matches all the predicates and all the operands.
2154 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule) {
Roman Tereshin19da6672018-05-22 04:31:50 +00002155 if (NumOperandsCheck)
2156 InstructionNumOperandsMatcher(InsnVarID, getNumOperands())
2157 .emitPredicateOpcodes(Table, Rule);
Daniel Sandersb96f40d2017-03-20 15:20:42 +00002158
Matt Arsenault1254f6d2020-06-20 21:38:43 -04002159 // First emit all instruction level predicates need to be verified before we
2160 // can verify operands.
2161 emitFilteredPredicateListOpcodes(
2162 [](const PredicateMatcher &P) {
2163 return !P.dependsOnOperands();
2164 }, Table, Rule);
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002165
Matt Arsenault1254f6d2020-06-20 21:38:43 -04002166 // Emit all operand constraints.
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002167 for (const auto &Operand : Operands)
Quentin Colombetaad20be2017-12-15 23:07:42 +00002168 Operand->emitPredicateOpcodes(Table, Rule);
Matt Arsenault1254f6d2020-06-20 21:38:43 -04002169
2170 // All of the tablegen defined predicates should now be matched. Now emit
2171 // any custom predicates that rely on all generated checks.
2172 emitFilteredPredicateListOpcodes(
2173 [](const PredicateMatcher &P) {
2174 return P.dependsOnOperands();
2175 }, Table, Rule);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002176 }
Daniel Sanders759ff412017-02-24 13:58:11 +00002177
2178 /// Compare the priority of this object and B.
2179 ///
2180 /// Returns true if this object is more important than B.
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002181 bool isHigherPriorityThan(InstructionMatcher &B) {
Daniel Sanders759ff412017-02-24 13:58:11 +00002182 // Instruction matchers involving more operands have higher priority.
2183 if (Operands.size() > B.Operands.size())
2184 return true;
2185 if (Operands.size() < B.Operands.size())
2186 return false;
2187
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002188 for (auto &&P : zip(predicates(), B.predicates())) {
2189 auto L = static_cast<InstructionPredicateMatcher *>(std::get<0>(P).get());
2190 auto R = static_cast<InstructionPredicateMatcher *>(std::get<1>(P).get());
2191 if (L->isHigherPriorityThan(*R))
Daniel Sanders759ff412017-02-24 13:58:11 +00002192 return true;
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002193 if (R->isHigherPriorityThan(*L))
Daniel Sanders759ff412017-02-24 13:58:11 +00002194 return false;
2195 }
2196
Mark de Wevere8d448e2019-12-22 18:58:32 +01002197 for (auto Operand : zip(Operands, B.Operands)) {
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002198 if (std::get<0>(Operand)->isHigherPriorityThan(*std::get<1>(Operand)))
Daniel Sanders759ff412017-02-24 13:58:11 +00002199 return true;
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002200 if (std::get<1>(Operand)->isHigherPriorityThan(*std::get<0>(Operand)))
Daniel Sanders759ff412017-02-24 13:58:11 +00002201 return false;
2202 }
2203
2204 return false;
2205 };
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002206
2207 /// Report the maximum number of temporary operands needed by the instruction
2208 /// matcher.
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002209 unsigned countRendererFns() {
2210 return std::accumulate(
2211 predicates().begin(), predicates().end(), 0,
2212 [](unsigned A,
2213 const std::unique_ptr<PredicateMatcher> &Predicate) {
2214 return A + Predicate->countRendererFns();
2215 }) +
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002216 std::accumulate(
2217 Operands.begin(), Operands.end(), 0,
2218 [](unsigned A, const std::unique_ptr<OperandMatcher> &Operand) {
Daniel Sanders2deea182017-04-22 15:11:04 +00002219 return A + Operand->countRendererFns();
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002220 });
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002221 }
Daniel Sanders05540042017-08-08 10:44:31 +00002222
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002223 InstructionOpcodeMatcher &getOpcodeMatcher() {
2224 for (auto &P : predicates())
2225 if (auto *OpMatcher = dyn_cast<InstructionOpcodeMatcher>(P.get()))
2226 return *OpMatcher;
2227 llvm_unreachable("Didn't find an opcode matcher");
2228 }
2229
2230 bool isConstantInstruction() {
2231 return getOpcodeMatcher().isConstantInstruction();
Daniel Sanders05540042017-08-08 10:44:31 +00002232 }
Roman Tereshin19da6672018-05-22 04:31:50 +00002233
2234 StringRef getOpcode() { return getOpcodeMatcher().getOpcode(); }
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002235};
2236
Roman Tereshin19da6672018-05-22 04:31:50 +00002237StringRef RuleMatcher::getOpcode() const {
2238 return Matchers.front()->getOpcode();
2239}
2240
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002241unsigned RuleMatcher::getNumOperands() const {
2242 return Matchers.front()->getNumOperands();
2243}
2244
Roman Tereshin9a9fa492018-05-23 21:30:16 +00002245LLTCodeGen RuleMatcher::getFirstConditionAsRootType() {
2246 InstructionMatcher &InsnMatcher = *Matchers.front();
2247 if (!InsnMatcher.predicates_empty())
2248 if (const auto *TM =
2249 dyn_cast<LLTOperandMatcher>(&**InsnMatcher.predicates_begin()))
2250 if (TM->getInsnVarID() == 0 && TM->getOpIdx() == 0)
2251 return TM->getTy();
2252 return {};
2253}
2254
Daniel Sandersbee57392017-04-04 13:25:23 +00002255/// Generates code to check that the operand is a register defined by an
2256/// instruction that matches the given instruction matcher.
2257///
2258/// For example, the pattern:
2259/// (set $dst, (G_MUL (G_ADD $src1, $src2), $src3))
2260/// would use an InstructionOperandMatcher for operand 1 of the G_MUL to match
2261/// the:
2262/// (G_ADD $src1, $src2)
2263/// subpattern.
2264class InstructionOperandMatcher : public OperandPredicateMatcher {
2265protected:
2266 std::unique_ptr<InstructionMatcher> InsnMatcher;
2267
2268public:
Quentin Colombeteba10cb2017-12-18 22:12:13 +00002269 InstructionOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
2270 RuleMatcher &Rule, StringRef SymbolicName)
Quentin Colombetaad20be2017-12-15 23:07:42 +00002271 : OperandPredicateMatcher(OPM_Instruction, InsnVarID, OpIdx),
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002272 InsnMatcher(new InstructionMatcher(Rule, SymbolicName)) {}
Daniel Sandersbee57392017-04-04 13:25:23 +00002273
Quentin Colombet063d7982017-12-14 23:44:07 +00002274 static bool classof(const PredicateMatcher *P) {
Daniel Sandersbee57392017-04-04 13:25:23 +00002275 return P->getKind() == OPM_Instruction;
2276 }
2277
2278 InstructionMatcher &getInsnMatcher() const { return *InsnMatcher; }
2279
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002280 void emitCaptureOpcodes(MatchTable &Table, RuleMatcher &Rule) const {
2281 const unsigned NewInsnVarID = InsnMatcher->getInsnVarID();
2282 Table << MatchTable::Opcode("GIM_RecordInsn")
2283 << MatchTable::Comment("DefineMI")
2284 << MatchTable::IntValue(NewInsnVarID) << MatchTable::Comment("MI")
2285 << MatchTable::IntValue(getInsnVarID())
2286 << MatchTable::Comment("OpIdx") << MatchTable::IntValue(getOpIdx())
2287 << MatchTable::Comment("MIs[" + llvm::to_string(NewInsnVarID) + "]")
2288 << MatchTable::LineBreak;
Daniel Sandersbee57392017-04-04 13:25:23 +00002289 }
2290
Quentin Colombetaad20be2017-12-15 23:07:42 +00002291 void emitPredicateOpcodes(MatchTable &Table,
2292 RuleMatcher &Rule) const override {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002293 emitCaptureOpcodes(Table, Rule);
Quentin Colombetaad20be2017-12-15 23:07:42 +00002294 InsnMatcher->emitPredicateOpcodes(Table, Rule);
Daniel Sandersbee57392017-04-04 13:25:23 +00002295 }
Daniel Sanders12e6e702018-01-17 20:34:29 +00002296
2297 bool isHigherPriorityThan(const OperandPredicateMatcher &B) const override {
2298 if (OperandPredicateMatcher::isHigherPriorityThan(B))
2299 return true;
2300 if (B.OperandPredicateMatcher::isHigherPriorityThan(*this))
2301 return false;
2302
2303 if (const InstructionOperandMatcher *BP =
2304 dyn_cast<InstructionOperandMatcher>(&B))
2305 if (InsnMatcher->isHigherPriorityThan(*BP->InsnMatcher))
2306 return true;
2307 return false;
2308 }
Daniel Sandersbee57392017-04-04 13:25:23 +00002309};
2310
Roman Tereshin19da6672018-05-22 04:31:50 +00002311void InstructionMatcher::optimize() {
2312 SmallVector<std::unique_ptr<PredicateMatcher>, 8> Stash;
2313 const auto &OpcMatcher = getOpcodeMatcher();
2314
2315 Stash.push_back(predicates_pop_front());
2316 if (Stash.back().get() == &OpcMatcher) {
Roman Tereshin6082a062019-10-30 20:58:46 -07002317 if (NumOperandsCheck && OpcMatcher.isVariadicNumOperands())
Roman Tereshin19da6672018-05-22 04:31:50 +00002318 Stash.emplace_back(
2319 new InstructionNumOperandsMatcher(InsnVarID, getNumOperands()));
2320 NumOperandsCheck = false;
Roman Tereshinfedae332018-05-23 02:04:19 +00002321
2322 for (auto &OM : Operands)
2323 for (auto &OP : OM->predicates())
2324 if (isa<IntrinsicIDOperandMatcher>(OP)) {
2325 Stash.push_back(std::move(OP));
2326 OM->eraseNullPredicates();
2327 break;
2328 }
Roman Tereshin19da6672018-05-22 04:31:50 +00002329 }
2330
2331 if (InsnVarID > 0) {
2332 assert(!Operands.empty() && "Nested instruction is expected to def a vreg");
2333 for (auto &OP : Operands[0]->predicates())
2334 OP.reset();
2335 Operands[0]->eraseNullPredicates();
2336 }
Roman Tereshinb1ba1272018-05-23 19:16:59 +00002337 for (auto &OM : Operands) {
2338 for (auto &OP : OM->predicates())
2339 if (isa<LLTOperandMatcher>(OP))
2340 Stash.push_back(std::move(OP));
2341 OM->eraseNullPredicates();
2342 }
Roman Tereshin19da6672018-05-22 04:31:50 +00002343 while (!Stash.empty())
2344 prependPredicate(Stash.pop_back_val());
2345}
2346
Daniel Sanders43c882c2017-02-01 10:53:10 +00002347//===- Actions ------------------------------------------------------------===//
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002348class OperandRenderer {
2349public:
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002350 enum RendererKind {
2351 OR_Copy,
Daniel Sandersd66e0902017-10-23 18:19:24 +00002352 OR_CopyOrAddZeroReg,
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002353 OR_CopySubReg,
Matt Arsenault3e45c702019-09-06 20:32:37 +00002354 OR_CopyPhysReg,
Daniel Sanders05540042017-08-08 10:44:31 +00002355 OR_CopyConstantAsImm,
Daniel Sanders11300ce2017-10-13 21:28:03 +00002356 OR_CopyFConstantAsFPImm,
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002357 OR_Imm,
Matt Arsenault4a23ae52019-09-10 17:57:33 +00002358 OR_SubRegIndex,
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002359 OR_Register,
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002360 OR_TempRegister,
Volkan Kelesf7f25682018-01-16 18:44:05 +00002361 OR_ComplexPattern,
Matt Arsenaultb4a64742020-01-08 12:53:15 -05002362 OR_Custom,
2363 OR_CustomOperand
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002364 };
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002365
2366protected:
2367 RendererKind Kind;
2368
2369public:
2370 OperandRenderer(RendererKind Kind) : Kind(Kind) {}
2371 virtual ~OperandRenderer() {}
2372
2373 RendererKind getKind() const { return Kind; }
2374
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002375 virtual void emitRenderOpcodes(MatchTable &Table,
2376 RuleMatcher &Rule) const = 0;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002377};
2378
2379/// A CopyRenderer emits code to copy a single operand from an existing
2380/// instruction to the one being built.
2381class CopyRenderer : public OperandRenderer {
2382protected:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002383 unsigned NewInsnID;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002384 /// The name of the operand.
2385 const StringRef SymbolicName;
2386
2387public:
Daniel Sandersbd83ad42017-10-24 01:48:34 +00002388 CopyRenderer(unsigned NewInsnID, StringRef SymbolicName)
2389 : OperandRenderer(OR_Copy), NewInsnID(NewInsnID),
Daniel Sanders05540042017-08-08 10:44:31 +00002390 SymbolicName(SymbolicName) {
2391 assert(!SymbolicName.empty() && "Cannot copy from an unspecified source");
2392 }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002393
2394 static bool classof(const OperandRenderer *R) {
2395 return R->getKind() == OR_Copy;
2396 }
2397
2398 const StringRef getSymbolicName() const { return SymbolicName; }
2399
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002400 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002401 const OperandMatcher &Operand = Rule.getOperandMatcher(SymbolicName);
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002402 unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002403 Table << MatchTable::Opcode("GIR_Copy") << MatchTable::Comment("NewInsnID")
2404 << MatchTable::IntValue(NewInsnID) << MatchTable::Comment("OldInsnID")
2405 << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002406 << MatchTable::IntValue(Operand.getOpIdx())
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002407 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002408 }
2409};
2410
Matt Arsenault3e45c702019-09-06 20:32:37 +00002411/// A CopyRenderer emits code to copy a virtual register to a specific physical
2412/// register.
2413class CopyPhysRegRenderer : public OperandRenderer {
2414protected:
2415 unsigned NewInsnID;
2416 Record *PhysReg;
2417
2418public:
2419 CopyPhysRegRenderer(unsigned NewInsnID, Record *Reg)
2420 : OperandRenderer(OR_CopyPhysReg), NewInsnID(NewInsnID),
2421 PhysReg(Reg) {
2422 assert(PhysReg);
2423 }
2424
2425 static bool classof(const OperandRenderer *R) {
2426 return R->getKind() == OR_CopyPhysReg;
2427 }
2428
2429 Record *getPhysReg() const { return PhysReg; }
2430
2431 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2432 const OperandMatcher &Operand = Rule.getPhysRegOperandMatcher(PhysReg);
2433 unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
2434 Table << MatchTable::Opcode("GIR_Copy") << MatchTable::Comment("NewInsnID")
2435 << MatchTable::IntValue(NewInsnID) << MatchTable::Comment("OldInsnID")
2436 << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
2437 << MatchTable::IntValue(Operand.getOpIdx())
2438 << MatchTable::Comment(PhysReg->getName())
2439 << MatchTable::LineBreak;
2440 }
2441};
2442
Daniel Sandersd66e0902017-10-23 18:19:24 +00002443/// A CopyOrAddZeroRegRenderer emits code to copy a single operand from an
2444/// existing instruction to the one being built. If the operand turns out to be
2445/// a 'G_CONSTANT 0' then it replaces the operand with a zero register.
2446class CopyOrAddZeroRegRenderer : public OperandRenderer {
2447protected:
2448 unsigned NewInsnID;
2449 /// The name of the operand.
2450 const StringRef SymbolicName;
2451 const Record *ZeroRegisterDef;
2452
2453public:
2454 CopyOrAddZeroRegRenderer(unsigned NewInsnID,
Daniel Sandersd66e0902017-10-23 18:19:24 +00002455 StringRef SymbolicName, Record *ZeroRegisterDef)
2456 : OperandRenderer(OR_CopyOrAddZeroReg), NewInsnID(NewInsnID),
2457 SymbolicName(SymbolicName), ZeroRegisterDef(ZeroRegisterDef) {
2458 assert(!SymbolicName.empty() && "Cannot copy from an unspecified source");
2459 }
2460
2461 static bool classof(const OperandRenderer *R) {
2462 return R->getKind() == OR_CopyOrAddZeroReg;
2463 }
2464
2465 const StringRef getSymbolicName() const { return SymbolicName; }
2466
2467 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2468 const OperandMatcher &Operand = Rule.getOperandMatcher(SymbolicName);
2469 unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
2470 Table << MatchTable::Opcode("GIR_CopyOrAddZeroReg")
2471 << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
2472 << MatchTable::Comment("OldInsnID")
2473 << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002474 << MatchTable::IntValue(Operand.getOpIdx())
Daniel Sandersd66e0902017-10-23 18:19:24 +00002475 << MatchTable::NamedValue(
2476 (ZeroRegisterDef->getValue("Namespace")
2477 ? ZeroRegisterDef->getValueAsString("Namespace")
2478 : ""),
2479 ZeroRegisterDef->getName())
2480 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2481 }
2482};
2483
Daniel Sanders05540042017-08-08 10:44:31 +00002484/// A CopyConstantAsImmRenderer emits code to render a G_CONSTANT instruction to
2485/// an extended immediate operand.
2486class CopyConstantAsImmRenderer : public OperandRenderer {
2487protected:
2488 unsigned NewInsnID;
2489 /// The name of the operand.
2490 const std::string SymbolicName;
2491 bool Signed;
2492
2493public:
2494 CopyConstantAsImmRenderer(unsigned NewInsnID, StringRef SymbolicName)
2495 : OperandRenderer(OR_CopyConstantAsImm), NewInsnID(NewInsnID),
2496 SymbolicName(SymbolicName), Signed(true) {}
2497
2498 static bool classof(const OperandRenderer *R) {
2499 return R->getKind() == OR_CopyConstantAsImm;
2500 }
2501
2502 const StringRef getSymbolicName() const { return SymbolicName; }
2503
2504 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002505 InstructionMatcher &InsnMatcher = Rule.getInstructionMatcher(SymbolicName);
Daniel Sanders05540042017-08-08 10:44:31 +00002506 unsigned OldInsnVarID = Rule.getInsnVarID(InsnMatcher);
2507 Table << MatchTable::Opcode(Signed ? "GIR_CopyConstantAsSImm"
2508 : "GIR_CopyConstantAsUImm")
2509 << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
2510 << MatchTable::Comment("OldInsnID")
2511 << MatchTable::IntValue(OldInsnVarID)
2512 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2513 }
2514};
2515
Daniel Sanders11300ce2017-10-13 21:28:03 +00002516/// A CopyFConstantAsFPImmRenderer emits code to render a G_FCONSTANT
2517/// instruction to an extended immediate operand.
2518class CopyFConstantAsFPImmRenderer : public OperandRenderer {
2519protected:
2520 unsigned NewInsnID;
2521 /// The name of the operand.
2522 const std::string SymbolicName;
2523
2524public:
2525 CopyFConstantAsFPImmRenderer(unsigned NewInsnID, StringRef SymbolicName)
2526 : OperandRenderer(OR_CopyFConstantAsFPImm), NewInsnID(NewInsnID),
2527 SymbolicName(SymbolicName) {}
2528
2529 static bool classof(const OperandRenderer *R) {
2530 return R->getKind() == OR_CopyFConstantAsFPImm;
2531 }
2532
2533 const StringRef getSymbolicName() const { return SymbolicName; }
2534
2535 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002536 InstructionMatcher &InsnMatcher = Rule.getInstructionMatcher(SymbolicName);
Daniel Sanders11300ce2017-10-13 21:28:03 +00002537 unsigned OldInsnVarID = Rule.getInsnVarID(InsnMatcher);
2538 Table << MatchTable::Opcode("GIR_CopyFConstantAsFPImm")
2539 << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
2540 << MatchTable::Comment("OldInsnID")
2541 << MatchTable::IntValue(OldInsnVarID)
2542 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2543 }
2544};
2545
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002546/// A CopySubRegRenderer emits code to copy a single register operand from an
2547/// existing instruction to the one being built and indicate that only a
2548/// subregister should be copied.
2549class CopySubRegRenderer : public OperandRenderer {
2550protected:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002551 unsigned NewInsnID;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002552 /// The name of the operand.
2553 const StringRef SymbolicName;
2554 /// The subregister to extract.
2555 const CodeGenSubRegIndex *SubReg;
2556
2557public:
Daniel Sandersbd83ad42017-10-24 01:48:34 +00002558 CopySubRegRenderer(unsigned NewInsnID, StringRef SymbolicName,
2559 const CodeGenSubRegIndex *SubReg)
2560 : OperandRenderer(OR_CopySubReg), NewInsnID(NewInsnID),
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002561 SymbolicName(SymbolicName), SubReg(SubReg) {}
2562
2563 static bool classof(const OperandRenderer *R) {
2564 return R->getKind() == OR_CopySubReg;
2565 }
2566
2567 const StringRef getSymbolicName() const { return SymbolicName; }
2568
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002569 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002570 const OperandMatcher &Operand = Rule.getOperandMatcher(SymbolicName);
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002571 unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002572 Table << MatchTable::Opcode("GIR_CopySubReg")
2573 << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
2574 << MatchTable::Comment("OldInsnID")
2575 << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002576 << MatchTable::IntValue(Operand.getOpIdx())
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002577 << MatchTable::Comment("SubRegIdx")
2578 << MatchTable::IntValue(SubReg->EnumValue)
2579 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002580 }
2581};
2582
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002583/// Adds a specific physical register to the instruction being built.
2584/// This is typically useful for WZR/XZR on AArch64.
2585class AddRegisterRenderer : public OperandRenderer {
2586protected:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002587 unsigned InsnID;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002588 const Record *RegisterDef;
Matt Arsenault3e45c702019-09-06 20:32:37 +00002589 bool IsDef;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002590
2591public:
Matt Arsenault3e45c702019-09-06 20:32:37 +00002592 AddRegisterRenderer(unsigned InsnID, const Record *RegisterDef,
2593 bool IsDef = false)
2594 : OperandRenderer(OR_Register), InsnID(InsnID), RegisterDef(RegisterDef),
2595 IsDef(IsDef) {}
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002596
2597 static bool classof(const OperandRenderer *R) {
2598 return R->getKind() == OR_Register;
2599 }
2600
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002601 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2602 Table << MatchTable::Opcode("GIR_AddRegister")
2603 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2604 << MatchTable::NamedValue(
2605 (RegisterDef->getValue("Namespace")
2606 ? RegisterDef->getValueAsString("Namespace")
2607 : ""),
2608 RegisterDef->getName())
Matt Arsenault3e45c702019-09-06 20:32:37 +00002609 << MatchTable::Comment("AddRegisterRegFlags");
2610
2611 // TODO: This is encoded as a 64-bit element, but only 16 or 32-bits are
2612 // really needed for a physical register reference. We can pack the
2613 // register and flags in a single field.
2614 if (IsDef)
2615 Table << MatchTable::NamedValue("RegState::Define");
2616 else
2617 Table << MatchTable::IntValue(0);
2618 Table << MatchTable::LineBreak;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002619 }
2620};
2621
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002622/// Adds a specific temporary virtual register to the instruction being built.
2623/// This is used to chain instructions together when emitting multiple
2624/// instructions.
2625class TempRegRenderer : public OperandRenderer {
2626protected:
2627 unsigned InsnID;
2628 unsigned TempRegID;
Matt Arsenault9c346462020-01-14 16:02:02 -05002629 const CodeGenSubRegIndex *SubRegIdx;
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002630 bool IsDef;
Matt Arsenaultee3feef2020-07-13 08:59:38 -04002631 bool IsDead;
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002632
2633public:
Matt Arsenault9c346462020-01-14 16:02:02 -05002634 TempRegRenderer(unsigned InsnID, unsigned TempRegID, bool IsDef = false,
Matt Arsenaultee3feef2020-07-13 08:59:38 -04002635 const CodeGenSubRegIndex *SubReg = nullptr,
2636 bool IsDead = false)
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002637 : OperandRenderer(OR_Register), InsnID(InsnID), TempRegID(TempRegID),
Matt Arsenaultee3feef2020-07-13 08:59:38 -04002638 SubRegIdx(SubReg), IsDef(IsDef), IsDead(IsDead) {}
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002639
2640 static bool classof(const OperandRenderer *R) {
2641 return R->getKind() == OR_TempRegister;
2642 }
2643
2644 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Matt Arsenault9c346462020-01-14 16:02:02 -05002645 if (SubRegIdx) {
2646 assert(!IsDef);
2647 Table << MatchTable::Opcode("GIR_AddTempSubRegister");
2648 } else
2649 Table << MatchTable::Opcode("GIR_AddTempRegister");
2650
2651 Table << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002652 << MatchTable::Comment("TempRegID") << MatchTable::IntValue(TempRegID)
2653 << MatchTable::Comment("TempRegFlags");
Matt Arsenault9c346462020-01-14 16:02:02 -05002654
Matt Arsenaultee3feef2020-07-13 08:59:38 -04002655 if (IsDef) {
2656 SmallString<32> RegFlags;
2657 RegFlags += "RegState::Define";
2658 if (IsDead)
2659 RegFlags += "|RegState::Dead";
2660 Table << MatchTable::NamedValue(RegFlags);
2661 } else
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002662 Table << MatchTable::IntValue(0);
Matt Arsenault9c346462020-01-14 16:02:02 -05002663
2664 if (SubRegIdx)
2665 Table << MatchTable::NamedValue(SubRegIdx->getQualifiedName());
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002666 Table << MatchTable::LineBreak;
2667 }
2668};
2669
Daniel Sanders0ed28822017-04-12 08:23:08 +00002670/// Adds a specific immediate to the instruction being built.
2671class ImmRenderer : public OperandRenderer {
2672protected:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002673 unsigned InsnID;
Daniel Sanders0ed28822017-04-12 08:23:08 +00002674 int64_t Imm;
2675
2676public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002677 ImmRenderer(unsigned InsnID, int64_t Imm)
2678 : OperandRenderer(OR_Imm), InsnID(InsnID), Imm(Imm) {}
Daniel Sanders0ed28822017-04-12 08:23:08 +00002679
2680 static bool classof(const OperandRenderer *R) {
2681 return R->getKind() == OR_Imm;
2682 }
2683
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002684 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2685 Table << MatchTable::Opcode("GIR_AddImm") << MatchTable::Comment("InsnID")
2686 << MatchTable::IntValue(InsnID) << MatchTable::Comment("Imm")
2687 << MatchTable::IntValue(Imm) << MatchTable::LineBreak;
Daniel Sanders0ed28822017-04-12 08:23:08 +00002688 }
2689};
2690
Matt Arsenault4a23ae52019-09-10 17:57:33 +00002691/// Adds an enum value for a subreg index to the instruction being built.
2692class SubRegIndexRenderer : public OperandRenderer {
2693protected:
2694 unsigned InsnID;
2695 const CodeGenSubRegIndex *SubRegIdx;
2696
2697public:
2698 SubRegIndexRenderer(unsigned InsnID, const CodeGenSubRegIndex *SRI)
2699 : OperandRenderer(OR_SubRegIndex), InsnID(InsnID), SubRegIdx(SRI) {}
2700
2701 static bool classof(const OperandRenderer *R) {
2702 return R->getKind() == OR_SubRegIndex;
2703 }
2704
2705 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2706 Table << MatchTable::Opcode("GIR_AddImm") << MatchTable::Comment("InsnID")
2707 << MatchTable::IntValue(InsnID) << MatchTable::Comment("SubRegIndex")
2708 << MatchTable::IntValue(SubRegIdx->EnumValue)
2709 << MatchTable::LineBreak;
2710 }
2711};
2712
Daniel Sanders2deea182017-04-22 15:11:04 +00002713/// Adds operands by calling a renderer function supplied by the ComplexPattern
2714/// matcher function.
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002715class RenderComplexPatternOperand : public OperandRenderer {
2716private:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002717 unsigned InsnID;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002718 const Record &TheDef;
Daniel Sanders2deea182017-04-22 15:11:04 +00002719 /// The name of the operand.
2720 const StringRef SymbolicName;
2721 /// The renderer number. This must be unique within a rule since it's used to
2722 /// identify a temporary variable to hold the renderer function.
2723 unsigned RendererID;
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002724 /// When provided, this is the suboperand of the ComplexPattern operand to
2725 /// render. Otherwise all the suboperands will be rendered.
2726 Optional<unsigned> SubOperand;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002727
2728 unsigned getNumOperands() const {
2729 return TheDef.getValueAsDag("Operands")->getNumArgs();
2730 }
2731
2732public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002733 RenderComplexPatternOperand(unsigned InsnID, const Record &TheDef,
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002734 StringRef SymbolicName, unsigned RendererID,
2735 Optional<unsigned> SubOperand = None)
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002736 : OperandRenderer(OR_ComplexPattern), InsnID(InsnID), TheDef(TheDef),
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002737 SymbolicName(SymbolicName), RendererID(RendererID),
2738 SubOperand(SubOperand) {}
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002739
2740 static bool classof(const OperandRenderer *R) {
2741 return R->getKind() == OR_ComplexPattern;
2742 }
2743
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002744 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002745 Table << MatchTable::Opcode(SubOperand.hasValue() ? "GIR_ComplexSubOperandRenderer"
2746 : "GIR_ComplexRenderer")
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002747 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2748 << MatchTable::Comment("RendererID")
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002749 << MatchTable::IntValue(RendererID);
2750 if (SubOperand.hasValue())
2751 Table << MatchTable::Comment("SubOperand")
2752 << MatchTable::IntValue(SubOperand.getValue());
2753 Table << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002754 }
2755};
2756
Volkan Kelesf7f25682018-01-16 18:44:05 +00002757class CustomRenderer : public OperandRenderer {
2758protected:
2759 unsigned InsnID;
2760 const Record &Renderer;
2761 /// The name of the operand.
2762 const std::string SymbolicName;
2763
2764public:
2765 CustomRenderer(unsigned InsnID, const Record &Renderer,
2766 StringRef SymbolicName)
2767 : OperandRenderer(OR_Custom), InsnID(InsnID), Renderer(Renderer),
2768 SymbolicName(SymbolicName) {}
2769
2770 static bool classof(const OperandRenderer *R) {
2771 return R->getKind() == OR_Custom;
2772 }
2773
2774 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002775 InstructionMatcher &InsnMatcher = Rule.getInstructionMatcher(SymbolicName);
Volkan Kelesf7f25682018-01-16 18:44:05 +00002776 unsigned OldInsnVarID = Rule.getInsnVarID(InsnMatcher);
2777 Table << MatchTable::Opcode("GIR_CustomRenderer")
2778 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2779 << MatchTable::Comment("OldInsnID")
2780 << MatchTable::IntValue(OldInsnVarID)
2781 << MatchTable::Comment("Renderer")
2782 << MatchTable::NamedValue(
2783 "GICR_" + Renderer.getValueAsString("RendererFn").str())
2784 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2785 }
2786};
2787
Matt Arsenaultb4a64742020-01-08 12:53:15 -05002788class CustomOperandRenderer : public OperandRenderer {
2789protected:
2790 unsigned InsnID;
2791 const Record &Renderer;
2792 /// The name of the operand.
2793 const std::string SymbolicName;
2794
2795public:
2796 CustomOperandRenderer(unsigned InsnID, const Record &Renderer,
2797 StringRef SymbolicName)
2798 : OperandRenderer(OR_CustomOperand), InsnID(InsnID), Renderer(Renderer),
2799 SymbolicName(SymbolicName) {}
2800
2801 static bool classof(const OperandRenderer *R) {
2802 return R->getKind() == OR_CustomOperand;
2803 }
2804
2805 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2806 const OperandMatcher &OpdMatcher = Rule.getOperandMatcher(SymbolicName);
2807 Table << MatchTable::Opcode("GIR_CustomOperandRenderer")
2808 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2809 << MatchTable::Comment("OldInsnID")
2810 << MatchTable::IntValue(OpdMatcher.getInsnVarID())
2811 << MatchTable::Comment("OpIdx")
2812 << MatchTable::IntValue(OpdMatcher.getOpIdx())
2813 << MatchTable::Comment("OperandRenderer")
2814 << MatchTable::NamedValue(
2815 "GICR_" + Renderer.getValueAsString("RendererFn").str())
2816 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2817 }
2818};
2819
Ahmed Bougacha56ca3a92017-02-04 00:47:10 +00002820/// An action taken when all Matcher predicates succeeded for a parent rule.
2821///
2822/// Typical actions include:
2823/// * Changing the opcode of an instruction.
2824/// * Adding an operand to an instruction.
Daniel Sanders43c882c2017-02-01 10:53:10 +00002825class MatchAction {
2826public:
2827 virtual ~MatchAction() {}
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002828
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002829 /// Emit the MatchTable opcodes to implement the action.
Daniel Sandersa7b75262017-10-31 18:50:24 +00002830 virtual void emitActionOpcodes(MatchTable &Table,
2831 RuleMatcher &Rule) const = 0;
Daniel Sanders43c882c2017-02-01 10:53:10 +00002832};
2833
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +00002834/// Generates a comment describing the matched rule being acted upon.
2835class DebugCommentAction : public MatchAction {
2836private:
Daniel Sanders6ea17ed2017-10-31 18:07:03 +00002837 std::string S;
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +00002838
2839public:
Benjamin Krameradcd0262020-01-28 20:23:46 +01002840 DebugCommentAction(StringRef S) : S(std::string(S)) {}
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +00002841
Daniel Sandersa7b75262017-10-31 18:50:24 +00002842 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sanders6ea17ed2017-10-31 18:07:03 +00002843 Table << MatchTable::Comment(S) << MatchTable::LineBreak;
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +00002844 }
2845};
2846
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002847/// Generates code to build an instruction or mutate an existing instruction
2848/// into the desired instruction when this is possible.
2849class BuildMIAction : public MatchAction {
Daniel Sanders43c882c2017-02-01 10:53:10 +00002850private:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002851 unsigned InsnID;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002852 const CodeGenInstruction *I;
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002853 InstructionMatcher *Matched;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002854 std::vector<std::unique_ptr<OperandRenderer>> OperandRenderers;
2855
2856 /// True if the instruction can be built solely by mutating the opcode.
Daniel Sandersa7b75262017-10-31 18:50:24 +00002857 bool canMutate(RuleMatcher &Rule, const InstructionMatcher *Insn) const {
2858 if (!Insn)
Daniel Sandersab1d1192017-10-24 18:11:54 +00002859 return false;
2860
Daniel Sandersa7b75262017-10-31 18:50:24 +00002861 if (OperandRenderers.size() != Insn->getNumOperands())
Daniel Sanderse9fdba32017-04-29 17:30:09 +00002862 return false;
2863
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002864 for (const auto &Renderer : enumerate(OperandRenderers)) {
Zachary Turner309a0882017-03-13 16:24:10 +00002865 if (const auto *Copy = dyn_cast<CopyRenderer>(&*Renderer.value())) {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002866 const OperandMatcher &OM = Rule.getOperandMatcher(Copy->getSymbolicName());
Daniel Sandersa7b75262017-10-31 18:50:24 +00002867 if (Insn != &OM.getInstructionMatcher() ||
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002868 OM.getOpIdx() != Renderer.index())
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002869 return false;
2870 } else
2871 return false;
2872 }
2873
2874 return true;
2875 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002876
Daniel Sanders43c882c2017-02-01 10:53:10 +00002877public:
Daniel Sandersa7b75262017-10-31 18:50:24 +00002878 BuildMIAction(unsigned InsnID, const CodeGenInstruction *I)
2879 : InsnID(InsnID), I(I), Matched(nullptr) {}
2880
Daniel Sanders08464522018-01-29 21:09:12 +00002881 unsigned getInsnID() const { return InsnID; }
Daniel Sandersdf258e32017-10-31 19:09:29 +00002882 const CodeGenInstruction *getCGI() const { return I; }
2883
Daniel Sandersa7b75262017-10-31 18:50:24 +00002884 void chooseInsnToMutate(RuleMatcher &Rule) {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002885 for (auto *MutateCandidate : Rule.mutatable_insns()) {
Daniel Sandersa7b75262017-10-31 18:50:24 +00002886 if (canMutate(Rule, MutateCandidate)) {
2887 // Take the first one we're offered that we're able to mutate.
2888 Rule.reserveInsnMatcherForMutation(MutateCandidate);
2889 Matched = MutateCandidate;
2890 return;
2891 }
2892 }
2893 }
Daniel Sanders43c882c2017-02-01 10:53:10 +00002894
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002895 template <class Kind, class... Args>
2896 Kind &addRenderer(Args&&... args) {
2897 OperandRenderers.emplace_back(
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00002898 std::make_unique<Kind>(InsnID, std::forward<Args>(args)...));
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002899 return *static_cast<Kind *>(OperandRenderers.back().get());
2900 }
2901
Daniel Sandersa7b75262017-10-31 18:50:24 +00002902 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2903 if (Matched) {
2904 assert(canMutate(Rule, Matched) &&
2905 "Arranged to mutate an insn that isn't mutatable");
2906
2907 unsigned RecycleInsnID = Rule.getInsnVarID(*Matched);
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002908 Table << MatchTable::Opcode("GIR_MutateOpcode")
2909 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2910 << MatchTable::Comment("RecycleInsnID")
2911 << MatchTable::IntValue(RecycleInsnID)
2912 << MatchTable::Comment("Opcode")
2913 << MatchTable::NamedValue(I->Namespace, I->TheDef->getName())
2914 << MatchTable::LineBreak;
Tim Northover4340d642017-03-20 21:58:23 +00002915
2916 if (!I->ImplicitDefs.empty() || !I->ImplicitUses.empty()) {
Tim Northover4340d642017-03-20 21:58:23 +00002917 for (auto Def : I->ImplicitDefs) {
Diana Picus8abcbbb2017-05-02 09:40:49 +00002918 auto Namespace = Def->getValue("Namespace")
2919 ? Def->getValueAsString("Namespace")
2920 : "";
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002921 Table << MatchTable::Opcode("GIR_AddImplicitDef")
2922 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2923 << MatchTable::NamedValue(Namespace, Def->getName())
2924 << MatchTable::LineBreak;
Tim Northover4340d642017-03-20 21:58:23 +00002925 }
2926 for (auto Use : I->ImplicitUses) {
Diana Picus8abcbbb2017-05-02 09:40:49 +00002927 auto Namespace = Use->getValue("Namespace")
2928 ? Use->getValueAsString("Namespace")
2929 : "";
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002930 Table << MatchTable::Opcode("GIR_AddImplicitUse")
2931 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2932 << MatchTable::NamedValue(Namespace, Use->getName())
2933 << MatchTable::LineBreak;
Tim Northover4340d642017-03-20 21:58:23 +00002934 }
2935 }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002936 return;
2937 }
2938
2939 // TODO: Simple permutation looks like it could be almost as common as
2940 // mutation due to commutative operations.
2941
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002942 Table << MatchTable::Opcode("GIR_BuildMI") << MatchTable::Comment("InsnID")
2943 << MatchTable::IntValue(InsnID) << MatchTable::Comment("Opcode")
2944 << MatchTable::NamedValue(I->Namespace, I->TheDef->getName())
2945 << MatchTable::LineBreak;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002946 for (const auto &Renderer : OperandRenderers)
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002947 Renderer->emitRenderOpcodes(Table, Rule);
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002948
Florian Hahn3bc3ec62017-08-03 14:48:22 +00002949 if (I->mayLoad || I->mayStore) {
2950 Table << MatchTable::Opcode("GIR_MergeMemOperands")
2951 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2952 << MatchTable::Comment("MergeInsnID's");
2953 // Emit the ID's for all the instructions that are matched by this rule.
2954 // TODO: Limit this to matched instructions that mayLoad/mayStore or have
2955 // some other means of having a memoperand. Also limit this to
2956 // emitted instructions that expect to have a memoperand too. For
2957 // example, (G_SEXT (G_LOAD x)) that results in separate load and
2958 // sign-extend instructions shouldn't put the memoperand on the
2959 // sign-extend since it has no effect there.
2960 std::vector<unsigned> MergeInsnIDs;
2961 for (const auto &IDMatcherPair : Rule.defined_insn_vars())
2962 MergeInsnIDs.push_back(IDMatcherPair.second);
Fangrui Song0cac7262018-09-27 02:13:45 +00002963 llvm::sort(MergeInsnIDs);
Florian Hahn3bc3ec62017-08-03 14:48:22 +00002964 for (const auto &MergeInsnID : MergeInsnIDs)
2965 Table << MatchTable::IntValue(MergeInsnID);
Daniel Sanders05540042017-08-08 10:44:31 +00002966 Table << MatchTable::NamedValue("GIU_MergeMemOperands_EndOfList")
2967 << MatchTable::LineBreak;
Florian Hahn3bc3ec62017-08-03 14:48:22 +00002968 }
2969
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002970 // FIXME: This is a hack but it's sufficient for ISel. We'll need to do
2971 // better for combines. Particularly when there are multiple match
2972 // roots.
2973 if (InsnID == 0)
2974 Table << MatchTable::Opcode("GIR_EraseFromParent")
2975 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2976 << MatchTable::LineBreak;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002977 }
2978};
2979
2980/// Generates code to constrain the operands of an output instruction to the
2981/// register classes specified by the definition of that instruction.
2982class ConstrainOperandsToDefinitionAction : public MatchAction {
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002983 unsigned InsnID;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002984
2985public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002986 ConstrainOperandsToDefinitionAction(unsigned InsnID) : InsnID(InsnID) {}
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002987
Daniel Sandersa7b75262017-10-31 18:50:24 +00002988 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002989 Table << MatchTable::Opcode("GIR_ConstrainSelectedInstOperands")
2990 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2991 << MatchTable::LineBreak;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002992 }
2993};
2994
2995/// Generates code to constrain the specified operand of an output instruction
2996/// to the specified register class.
2997class ConstrainOperandToRegClassAction : public MatchAction {
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002998 unsigned InsnID;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002999 unsigned OpIdx;
3000 const CodeGenRegisterClass &RC;
3001
3002public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00003003 ConstrainOperandToRegClassAction(unsigned InsnID, unsigned OpIdx,
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003004 const CodeGenRegisterClass &RC)
Daniel Sandersd93a35a2017-07-05 09:39:33 +00003005 : InsnID(InsnID), OpIdx(OpIdx), RC(RC) {}
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003006
Daniel Sandersa7b75262017-10-31 18:50:24 +00003007 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00003008 Table << MatchTable::Opcode("GIR_ConstrainOperandRC")
3009 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
3010 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
Matt Arsenault2e2af602020-07-13 13:14:29 -04003011 << MatchTable::NamedValue(RC.getQualifiedName() + "RegClassID")
3012 << MatchTable::LineBreak;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003013 }
3014};
3015
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003016/// Generates code to create a temporary register which can be used to chain
3017/// instructions together.
3018class MakeTempRegisterAction : public MatchAction {
3019private:
3020 LLTCodeGen Ty;
3021 unsigned TempRegID;
3022
3023public:
3024 MakeTempRegisterAction(const LLTCodeGen &Ty, unsigned TempRegID)
Matt Arsenault4a23ae52019-09-10 17:57:33 +00003025 : Ty(Ty), TempRegID(TempRegID) {
3026 KnownTypes.insert(Ty);
3027 }
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003028
3029 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
3030 Table << MatchTable::Opcode("GIR_MakeTempReg")
3031 << MatchTable::Comment("TempRegID") << MatchTable::IntValue(TempRegID)
3032 << MatchTable::Comment("TypeID")
3033 << MatchTable::NamedValue(Ty.getCxxEnumValue())
3034 << MatchTable::LineBreak;
3035 }
3036};
3037
Daniel Sanders05540042017-08-08 10:44:31 +00003038InstructionMatcher &RuleMatcher::addInstructionMatcher(StringRef SymbolicName) {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003039 Matchers.emplace_back(new InstructionMatcher(*this, SymbolicName));
Daniel Sandersa7b75262017-10-31 18:50:24 +00003040 MutatableInsns.insert(Matchers.back().get());
Daniel Sandersbdfebb82017-03-15 20:18:38 +00003041 return *Matchers.back();
3042}
Ahmed Bougacha56ca3a92017-02-04 00:47:10 +00003043
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003044void RuleMatcher::addRequiredFeature(Record *Feature) {
3045 RequiredFeatures.push_back(Feature);
3046}
3047
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003048const std::vector<Record *> &RuleMatcher::getRequiredFeatures() const {
3049 return RequiredFeatures;
3050}
3051
Daniel Sanders7438b262017-10-31 23:03:18 +00003052// Emplaces an action of the specified Kind at the end of the action list.
3053//
3054// Returns a reference to the newly created action.
3055//
3056// Like std::vector::emplace_back(), may invalidate all iterators if the new
3057// size exceeds the capacity. Otherwise, only invalidates the past-the-end
3058// iterator.
Daniel Sandersbdfebb82017-03-15 20:18:38 +00003059template <class Kind, class... Args>
3060Kind &RuleMatcher::addAction(Args &&... args) {
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00003061 Actions.emplace_back(std::make_unique<Kind>(std::forward<Args>(args)...));
Daniel Sandersbdfebb82017-03-15 20:18:38 +00003062 return *static_cast<Kind *>(Actions.back().get());
3063}
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003064
Daniel Sanders7438b262017-10-31 23:03:18 +00003065// Emplaces an action of the specified Kind before the given insertion point.
3066//
3067// Returns an iterator pointing at the newly created instruction.
3068//
3069// Like std::vector::insert(), may invalidate all iterators if the new size
3070// exceeds the capacity. Otherwise, only invalidates the iterators from the
3071// insertion point onwards.
3072template <class Kind, class... Args>
3073action_iterator RuleMatcher::insertAction(action_iterator InsertPt,
3074 Args &&... args) {
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003075 return Actions.emplace(InsertPt,
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00003076 std::make_unique<Kind>(std::forward<Args>(args)...));
Daniel Sanders7438b262017-10-31 23:03:18 +00003077}
Daniel Sandersdc662ff2017-01-26 11:10:14 +00003078
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003079unsigned RuleMatcher::implicitlyDefineInsnVar(InstructionMatcher &Matcher) {
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003080 unsigned NewInsnVarID = NextInsnVarID++;
3081 InsnVariableIDs[&Matcher] = NewInsnVarID;
3082 return NewInsnVarID;
Daniel Sandersb96f40d2017-03-20 15:20:42 +00003083}
3084
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003085unsigned RuleMatcher::getInsnVarID(InstructionMatcher &InsnMatcher) const {
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003086 const auto &I = InsnVariableIDs.find(&InsnMatcher);
3087 if (I != InsnVariableIDs.end())
Daniel Sandersb96f40d2017-03-20 15:20:42 +00003088 return I->second;
3089 llvm_unreachable("Matched Insn was not captured in a local variable");
3090}
3091
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003092void RuleMatcher::defineOperand(StringRef SymbolicName, OperandMatcher &OM) {
3093 if (DefinedOperands.find(SymbolicName) == DefinedOperands.end()) {
3094 DefinedOperands[SymbolicName] = &OM;
3095 return;
3096 }
3097
3098 // If the operand is already defined, then we must ensure both references in
3099 // the matcher have the exact same node.
3100 OM.addPredicate<SameOperandMatcher>(OM.getSymbolicName());
3101}
3102
Matt Arsenault3e45c702019-09-06 20:32:37 +00003103void RuleMatcher::definePhysRegOperand(Record *Reg, OperandMatcher &OM) {
3104 if (PhysRegOperands.find(Reg) == PhysRegOperands.end()) {
3105 PhysRegOperands[Reg] = &OM;
3106 return;
3107 }
3108}
3109
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003110InstructionMatcher &
Daniel Sanders05540042017-08-08 10:44:31 +00003111RuleMatcher::getInstructionMatcher(StringRef SymbolicName) const {
3112 for (const auto &I : InsnVariableIDs)
3113 if (I.first->getSymbolicName() == SymbolicName)
3114 return *I.first;
3115 llvm_unreachable(
3116 ("Failed to lookup instruction " + SymbolicName).str().c_str());
3117}
3118
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003119const OperandMatcher &
Matt Arsenault3e45c702019-09-06 20:32:37 +00003120RuleMatcher::getPhysRegOperandMatcher(Record *Reg) const {
3121 const auto &I = PhysRegOperands.find(Reg);
3122
3123 if (I == PhysRegOperands.end()) {
3124 PrintFatalError(SrcLoc, "Register " + Reg->getName() +
3125 " was not declared in matcher");
3126 }
3127
3128 return *I->second;
3129}
3130
3131const OperandMatcher &
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003132RuleMatcher::getOperandMatcher(StringRef Name) const {
3133 const auto &I = DefinedOperands.find(Name);
3134
3135 if (I == DefinedOperands.end())
3136 PrintFatalError(SrcLoc, "Operand " + Name + " was not declared in matcher");
3137
3138 return *I->second;
3139}
3140
Daniel Sanders8e82af22017-07-27 11:03:45 +00003141void RuleMatcher::emit(MatchTable &Table) {
Daniel Sandersbdfebb82017-03-15 20:18:38 +00003142 if (Matchers.empty())
3143 llvm_unreachable("Unexpected empty matcher!");
Daniel Sandersdc662ff2017-01-26 11:10:14 +00003144
Daniel Sandersbdfebb82017-03-15 20:18:38 +00003145 // The representation supports rules that require multiple roots such as:
3146 // %ptr(p0) = ...
3147 // %elt0(s32) = G_LOAD %ptr
3148 // %1(p0) = G_ADD %ptr, 4
3149 // %elt1(s32) = G_LOAD p0 %1
3150 // which could be usefully folded into:
3151 // %ptr(p0) = ...
3152 // %elt0(s32), %elt1(s32) = TGT_LOAD_PAIR %ptr
3153 // on some targets but we don't need to make use of that yet.
3154 assert(Matchers.size() == 1 && "Cannot handle multi-root matchers yet");
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003155
Daniel Sanders8e82af22017-07-27 11:03:45 +00003156 unsigned LabelID = Table.allocateLabelID();
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00003157 Table << MatchTable::Opcode("GIM_Try", +1)
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003158 << MatchTable::Comment("On fail goto")
3159 << MatchTable::JumpTarget(LabelID)
3160 << MatchTable::Comment(("Rule ID " + Twine(RuleID) + " //").str())
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00003161 << MatchTable::LineBreak;
3162
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003163 if (!RequiredFeatures.empty()) {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00003164 Table << MatchTable::Opcode("GIM_CheckFeatures")
3165 << MatchTable::NamedValue(getNameForFeatureBitset(RequiredFeatures))
3166 << MatchTable::LineBreak;
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003167 }
Daniel Sandersb96f40d2017-03-20 15:20:42 +00003168
Quentin Colombetaad20be2017-12-15 23:07:42 +00003169 Matchers.front()->emitPredicateOpcodes(Table, *this);
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003170
Daniel Sandersbee57392017-04-04 13:25:23 +00003171 // We must also check if it's safe to fold the matched instructions.
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003172 if (InsnVariableIDs.size() >= 2) {
Galina Kistanova1754fee2017-05-25 01:51:53 +00003173 // Invert the map to create stable ordering (by var names)
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003174 SmallVector<unsigned, 2> InsnIDs;
3175 for (const auto &Pair : InsnVariableIDs) {
Daniel Sandersbee57392017-04-04 13:25:23 +00003176 // Skip the root node since it isn't moving anywhere. Everything else is
3177 // sinking to meet it.
3178 if (Pair.first == Matchers.front().get())
3179 continue;
3180
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003181 InsnIDs.push_back(Pair.second);
Galina Kistanova1754fee2017-05-25 01:51:53 +00003182 }
Fangrui Song0cac7262018-09-27 02:13:45 +00003183 llvm::sort(InsnIDs);
Galina Kistanova1754fee2017-05-25 01:51:53 +00003184
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00003185 for (const auto &InsnID : InsnIDs) {
Daniel Sandersbee57392017-04-04 13:25:23 +00003186 // Reject the difficult cases until we have a more accurate check.
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00003187 Table << MatchTable::Opcode("GIM_CheckIsSafeToFold")
3188 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
3189 << MatchTable::LineBreak;
Daniel Sandersbee57392017-04-04 13:25:23 +00003190
3191 // FIXME: Emit checks to determine it's _actually_ safe to fold and/or
3192 // account for unsafe cases.
3193 //
3194 // Example:
3195 // MI1--> %0 = ...
3196 // %1 = ... %0
3197 // MI0--> %2 = ... %0
3198 // It's not safe to erase MI1. We currently handle this by not
3199 // erasing %0 (even when it's dead).
3200 //
3201 // Example:
3202 // MI1--> %0 = load volatile @a
3203 // %1 = load volatile @a
3204 // MI0--> %2 = ... %0
3205 // It's not safe to sink %0's def past %1. We currently handle
3206 // this by rejecting all loads.
3207 //
3208 // Example:
3209 // MI1--> %0 = load @a
3210 // %1 = store @a
3211 // MI0--> %2 = ... %0
3212 // It's not safe to sink %0's def past %1. We currently handle
3213 // this by rejecting all loads.
3214 //
3215 // Example:
3216 // G_CONDBR %cond, @BB1
3217 // BB0:
3218 // MI1--> %0 = load @a
3219 // G_BR @BB1
3220 // BB1:
3221 // MI0--> %2 = ... %0
3222 // It's not always safe to sink %0 across control flow. In this
3223 // case it may introduce a memory fault. We currentl handle this
3224 // by rejecting all loads.
3225 }
3226 }
3227
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003228 for (const auto &PM : EpilogueMatchers)
3229 PM->emitPredicateOpcodes(Table, *this);
3230
Daniel Sandersd93a35a2017-07-05 09:39:33 +00003231 for (const auto &MA : Actions)
Daniel Sandersa7b75262017-10-31 18:50:24 +00003232 MA->emitActionOpcodes(Table, *this);
Daniel Sandersf76f3152017-11-16 00:46:35 +00003233
Roman Tereshinbeb39312018-05-02 20:15:11 +00003234 if (Table.isWithCoverage())
Daniel Sandersf76f3152017-11-16 00:46:35 +00003235 Table << MatchTable::Opcode("GIR_Coverage") << MatchTable::IntValue(RuleID)
3236 << MatchTable::LineBreak;
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003237 else
3238 Table << MatchTable::Comment(("GIR_Coverage, " + Twine(RuleID) + ",").str())
3239 << MatchTable::LineBreak;
Daniel Sandersf76f3152017-11-16 00:46:35 +00003240
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00003241 Table << MatchTable::Opcode("GIR_Done", -1) << MatchTable::LineBreak
Daniel Sanders8e82af22017-07-27 11:03:45 +00003242 << MatchTable::Label(LabelID);
Volkan Keles4f3fa792018-01-25 00:18:52 +00003243 ++NumPatternEmitted;
Daniel Sandersbdfebb82017-03-15 20:18:38 +00003244}
Daniel Sanders43c882c2017-02-01 10:53:10 +00003245
Daniel Sandersbdfebb82017-03-15 20:18:38 +00003246bool RuleMatcher::isHigherPriorityThan(const RuleMatcher &B) const {
3247 // Rules involving more match roots have higher priority.
3248 if (Matchers.size() > B.Matchers.size())
3249 return true;
3250 if (Matchers.size() < B.Matchers.size())
Daniel Sanders759ff412017-02-24 13:58:11 +00003251 return false;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00003252
Mark de Wevere8d448e2019-12-22 18:58:32 +01003253 for (auto Matcher : zip(Matchers, B.Matchers)) {
Daniel Sandersbdfebb82017-03-15 20:18:38 +00003254 if (std::get<0>(Matcher)->isHigherPriorityThan(*std::get<1>(Matcher)))
3255 return true;
3256 if (std::get<1>(Matcher)->isHigherPriorityThan(*std::get<0>(Matcher)))
3257 return false;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00003258 }
Daniel Sandersbdfebb82017-03-15 20:18:38 +00003259
3260 return false;
Simon Pilgrima7d1da82017-03-15 22:50:47 +00003261}
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003262
Daniel Sanders2deea182017-04-22 15:11:04 +00003263unsigned RuleMatcher::countRendererFns() const {
Daniel Sandersbdfebb82017-03-15 20:18:38 +00003264 return std::accumulate(
3265 Matchers.begin(), Matchers.end(), 0,
3266 [](unsigned A, const std::unique_ptr<InstructionMatcher> &Matcher) {
Daniel Sanders2deea182017-04-22 15:11:04 +00003267 return A + Matcher->countRendererFns();
Daniel Sandersbdfebb82017-03-15 20:18:38 +00003268 });
3269}
3270
Daniel Sanders05540042017-08-08 10:44:31 +00003271bool OperandPredicateMatcher::isHigherPriorityThan(
3272 const OperandPredicateMatcher &B) const {
3273 // Generally speaking, an instruction is more important than an Int or a
3274 // LiteralInt because it can cover more nodes but theres an exception to
3275 // this. G_CONSTANT's are less important than either of those two because they
3276 // are more permissive.
Daniel Sandersedd07842017-08-17 09:26:14 +00003277
3278 const InstructionOperandMatcher *AOM =
3279 dyn_cast<InstructionOperandMatcher>(this);
3280 const InstructionOperandMatcher *BOM =
3281 dyn_cast<InstructionOperandMatcher>(&B);
3282 bool AIsConstantInsn = AOM && AOM->getInsnMatcher().isConstantInstruction();
3283 bool BIsConstantInsn = BOM && BOM->getInsnMatcher().isConstantInstruction();
3284
3285 if (AOM && BOM) {
3286 // The relative priorities between a G_CONSTANT and any other instruction
3287 // don't actually matter but this code is needed to ensure a strict weak
3288 // ordering. This is particularly important on Windows where the rules will
3289 // be incorrectly sorted without it.
3290 if (AIsConstantInsn != BIsConstantInsn)
3291 return AIsConstantInsn < BIsConstantInsn;
3292 return false;
Daniel Sanders05540042017-08-08 10:44:31 +00003293 }
Daniel Sandersedd07842017-08-17 09:26:14 +00003294
3295 if (AOM && AIsConstantInsn && (B.Kind == OPM_Int || B.Kind == OPM_LiteralInt))
3296 return false;
3297 if (BOM && BIsConstantInsn && (Kind == OPM_Int || Kind == OPM_LiteralInt))
3298 return true;
Daniel Sanders05540042017-08-08 10:44:31 +00003299
3300 return Kind < B.Kind;
Daniel Sanders75b84fc2017-08-08 13:21:26 +00003301}
Daniel Sanders05540042017-08-08 10:44:31 +00003302
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003303void SameOperandMatcher::emitPredicateOpcodes(MatchTable &Table,
Quentin Colombetaad20be2017-12-15 23:07:42 +00003304 RuleMatcher &Rule) const {
Daniel Sanders1e4569f2017-10-20 20:55:29 +00003305 const OperandMatcher &OtherOM = Rule.getOperandMatcher(MatchingName);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003306 unsigned OtherInsnVarID = Rule.getInsnVarID(OtherOM.getInstructionMatcher());
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003307 assert(OtherInsnVarID == OtherOM.getInstructionMatcher().getInsnVarID());
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003308
3309 Table << MatchTable::Opcode("GIM_CheckIsSameOperand")
3310 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
3311 << MatchTable::Comment("OpIdx") << MatchTable::IntValue(OpIdx)
3312 << MatchTable::Comment("OtherMI")
3313 << MatchTable::IntValue(OtherInsnVarID)
3314 << MatchTable::Comment("OtherOpIdx")
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003315 << MatchTable::IntValue(OtherOM.getOpIdx())
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003316 << MatchTable::LineBreak;
3317}
3318
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003319//===- GlobalISelEmitter class --------------------------------------------===//
3320
Matt Arsenault9c346462020-01-14 16:02:02 -05003321static Expected<LLTCodeGen> getInstResultType(const TreePatternNode *Dst) {
3322 ArrayRef<TypeSetByHwMode> ChildTypes = Dst->getExtTypes();
3323 if (ChildTypes.size() != 1)
3324 return failedImport("Dst pattern child has multiple results");
3325
3326 Optional<LLTCodeGen> MaybeOpTy;
3327 if (ChildTypes.front().isMachineValueType()) {
3328 MaybeOpTy =
3329 MVTToLLT(ChildTypes.front().getMachineValueType().SimpleTy);
3330 }
3331
3332 if (!MaybeOpTy)
3333 return failedImport("Dst operand has an unsupported type");
3334 return *MaybeOpTy;
3335}
3336
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003337class GlobalISelEmitter {
3338public:
3339 explicit GlobalISelEmitter(RecordKeeper &RK);
3340 void run(raw_ostream &OS);
3341
3342private:
3343 const RecordKeeper &RK;
3344 const CodeGenDAGPatterns CGP;
3345 const CodeGenTarget &Target;
Matt Arsenault3ab7b7f2020-01-14 13:48:34 -05003346 CodeGenRegBank &CGRegs;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003347
Daniel Sanders39690bd2017-10-15 02:41:12 +00003348 /// Keep track of the equivalence between SDNodes and Instruction by mapping
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003349 /// SDNodes to the GINodeEquiv mapping. We need to map to the GINodeEquiv to
3350 /// check for attributes on the relation such as CheckMMOIsNonAtomic.
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003351 /// This is defined using 'GINodeEquiv' in the target description.
Daniel Sanders39690bd2017-10-15 02:41:12 +00003352 DenseMap<Record *, Record *> NodeEquivs;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003353
Daniel Sanders8a4bae92017-03-14 21:32:08 +00003354 /// Keep track of the equivalence between ComplexPattern's and
3355 /// GIComplexOperandMatcher. Map entries are specified by subclassing
3356 /// GIComplexPatternEquiv.
3357 DenseMap<const Record *, const Record *> ComplexPatternEquivs;
3358
Volkan Kelesf7f25682018-01-16 18:44:05 +00003359 /// Keep track of the equivalence between SDNodeXForm's and
3360 /// GICustomOperandRenderer. Map entries are specified by subclassing
3361 /// GISDNodeXFormEquiv.
3362 DenseMap<const Record *, const Record *> SDNodeXFormEquivs;
3363
Aditya Nandakumarb63e7632018-02-16 22:37:15 +00003364 /// Keep track of Scores of PatternsToMatch similar to how the DAG does.
3365 /// This adds compatibility for RuleMatchers to use this for ordering rules.
3366 DenseMap<uint64_t, int> RuleMatcherScores;
3367
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003368 // Map of predicates to their subtarget features.
Daniel Sanderse9fdba32017-04-29 17:30:09 +00003369 SubtargetFeatureInfoMap SubtargetFeatures;
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003370
Daniel Sandersf76f3152017-11-16 00:46:35 +00003371 // Rule coverage information.
3372 Optional<CodeGenCoverage> RuleCoverage;
3373
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003374 void gatherOpcodeValues();
3375 void gatherTypeIDValues();
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003376 void gatherNodeEquivs();
Daniel Sanders8ead1292018-06-15 23:13:43 +00003377
Daniel Sanders39690bd2017-10-15 02:41:12 +00003378 Record *findNodeEquiv(Record *N) const;
Daniel Sandersf84bc372018-05-05 20:53:24 +00003379 const CodeGenInstruction *getEquivNode(Record &Equiv,
Florian Hahn6b1db822018-06-14 20:32:58 +00003380 const TreePatternNode *N) const;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003381
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003382 Error importRulePredicates(RuleMatcher &M, ArrayRef<Predicate> Predicates);
Daniel Sanders8ead1292018-06-15 23:13:43 +00003383 Expected<InstructionMatcher &>
3384 createAndImportSelDAGMatcher(RuleMatcher &Rule,
3385 InstructionMatcher &InsnMatcher,
3386 const TreePatternNode *Src, unsigned &TempOpIdx);
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003387 Error importComplexPatternOperandMatcher(OperandMatcher &OM, Record *R,
3388 unsigned &TempOpIdx) const;
3389 Error importChildMatcher(RuleMatcher &Rule, InstructionMatcher &InsnMatcher,
Florian Hahn6b1db822018-06-14 20:32:58 +00003390 const TreePatternNode *SrcChild,
Matt Arsenault10edb1d2020-01-08 15:40:37 -05003391 bool OperandIsAPointer, bool OperandIsImmArg,
3392 unsigned OpIdx, unsigned &TempOpIdx);
Daniel Sandersdf258e32017-10-31 19:09:29 +00003393
Matt Arsenault3e45c702019-09-06 20:32:37 +00003394 Expected<BuildMIAction &> createAndImportInstructionRenderer(
3395 RuleMatcher &M, InstructionMatcher &InsnMatcher,
3396 const TreePatternNode *Src, const TreePatternNode *Dst);
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003397 Expected<action_iterator> createAndImportSubInstructionRenderer(
Florian Hahn6b1db822018-06-14 20:32:58 +00003398 action_iterator InsertPt, RuleMatcher &M, const TreePatternNode *Dst,
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003399 unsigned TempReg);
Daniel Sanders7438b262017-10-31 23:03:18 +00003400 Expected<action_iterator>
3401 createInstructionRenderer(action_iterator InsertPt, RuleMatcher &M,
Florian Hahn6b1db822018-06-14 20:32:58 +00003402 const TreePatternNode *Dst);
Matt Arsenaultee3feef2020-07-13 08:59:38 -04003403
3404 Expected<action_iterator>
3405 importExplicitDefRenderers(action_iterator InsertPt, RuleMatcher &M,
3406 BuildMIAction &DstMIBuilder,
3407 const TreePatternNode *Dst);
Matt Arsenault3e45c702019-09-06 20:32:37 +00003408
Daniel Sanders7438b262017-10-31 23:03:18 +00003409 Expected<action_iterator>
3410 importExplicitUseRenderers(action_iterator InsertPt, RuleMatcher &M,
3411 BuildMIAction &DstMIBuilder,
Florian Hahn6b1db822018-06-14 20:32:58 +00003412 const llvm::TreePatternNode *Dst);
Daniel Sanders7438b262017-10-31 23:03:18 +00003413 Expected<action_iterator>
3414 importExplicitUseRenderer(action_iterator InsertPt, RuleMatcher &Rule,
3415 BuildMIAction &DstMIBuilder,
Florian Hahn6b1db822018-06-14 20:32:58 +00003416 TreePatternNode *DstChild);
Sjoerd Meijerde234842019-05-30 07:30:37 +00003417 Error importDefaultOperandRenderers(action_iterator InsertPt, RuleMatcher &M,
3418 BuildMIAction &DstMIBuilder,
Diana Picus382602f2017-05-17 08:57:28 +00003419 DagInit *DefaultOps) const;
Daniel Sandersc270c502017-03-30 09:36:33 +00003420 Error
Daniel Sandersffc7d582017-03-29 15:37:18 +00003421 importImplicitDefRenderers(BuildMIAction &DstMIBuilder,
3422 const std::vector<Record *> &ImplicitDefs) const;
3423
Daniel Sanders8ead1292018-06-15 23:13:43 +00003424 void emitCxxPredicateFns(raw_ostream &OS, StringRef CodeFieldName,
3425 StringRef TypeIdentifier, StringRef ArgType,
3426 StringRef ArgName, StringRef AdditionalDeclarations,
3427 std::function<bool(const Record *R)> Filter);
3428 void emitImmPredicateFns(raw_ostream &OS, StringRef TypeIdentifier,
3429 StringRef ArgType,
3430 std::function<bool(const Record *R)> Filter);
3431 void emitMIPredicateFns(raw_ostream &OS);
Daniel Sanders649c5852017-10-13 20:42:18 +00003432
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003433 /// Analyze pattern \p P, returning a matcher for it if possible.
3434 /// Otherwise, return an Error explaining why we don't support it.
3435 Expected<RuleMatcher> runOnPattern(const PatternToMatch &P);
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003436
3437 void declareSubtargetFeature(Record *Predicate);
Daniel Sanders7e523672017-11-11 03:23:44 +00003438
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003439 MatchTable buildMatchTable(MutableArrayRef<RuleMatcher> Rules, bool Optimize,
3440 bool WithCoverage);
3441
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00003442 /// Infer a CodeGenRegisterClass for the type of \p SuperRegNode. The returned
3443 /// CodeGenRegisterClass will support the CodeGenRegisterClass of
3444 /// \p SubRegNode, and the subregister index defined by \p SubRegIdxNode.
3445 /// If no register class is found, return None.
3446 Optional<const CodeGenRegisterClass *>
Jessica Paquette7080ffa2019-08-28 20:12:31 +00003447 inferSuperRegisterClassForNode(const TypeSetByHwMode &Ty,
3448 TreePatternNode *SuperRegNode,
3449 TreePatternNode *SubRegIdxNode);
Matt Arsenault9ceb6ed2019-09-06 00:05:58 +00003450 Optional<CodeGenSubRegIndex *>
3451 inferSubRegIndexForNode(TreePatternNode *SubRegIdxNode);
Jessica Paquette7080ffa2019-08-28 20:12:31 +00003452
3453 /// Infer a CodeGenRegisterClass which suppoorts \p Ty and \p SubRegIdxNode.
3454 /// Return None if no such class exists.
3455 Optional<const CodeGenRegisterClass *>
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00003456 inferSuperRegisterClass(const TypeSetByHwMode &Ty,
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00003457 TreePatternNode *SubRegIdxNode);
3458
3459 /// Return the CodeGenRegisterClass associated with \p Leaf if it has one.
3460 Optional<const CodeGenRegisterClass *>
3461 getRegClassFromLeaf(TreePatternNode *Leaf);
3462
3463 /// Return a CodeGenRegisterClass for \p N if one can be found. Return None
3464 /// otherwise.
3465 Optional<const CodeGenRegisterClass *>
3466 inferRegClassFromPattern(TreePatternNode *N);
3467
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003468public:
Quentin Colombetec76d9c2017-12-18 19:47:41 +00003469 /// Takes a sequence of \p Rules and group them based on the predicates
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003470 /// they share. \p MatcherStorage is used as a memory container
Hiroshi Inoue501931b2018-01-24 05:04:35 +00003471 /// for the group that are created as part of this process.
Quentin Colombetec76d9c2017-12-18 19:47:41 +00003472 ///
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003473 /// What this optimization does looks like if GroupT = GroupMatcher:
Quentin Colombetec76d9c2017-12-18 19:47:41 +00003474 /// Output without optimization:
3475 /// \verbatim
3476 /// # R1
3477 /// # predicate A
3478 /// # predicate B
3479 /// ...
3480 /// # R2
3481 /// # predicate A // <-- effectively this is going to be checked twice.
3482 /// // Once in R1 and once in R2.
3483 /// # predicate C
3484 /// \endverbatim
3485 /// Output with optimization:
3486 /// \verbatim
3487 /// # Group1_2
3488 /// # predicate A // <-- Check is now shared.
3489 /// # R1
3490 /// # predicate B
3491 /// # R2
3492 /// # predicate C
3493 /// \endverbatim
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003494 template <class GroupT>
3495 static std::vector<Matcher *> optimizeRules(
Roman Tereshin2d6d3762018-05-02 20:08:14 +00003496 ArrayRef<Matcher *> Rules,
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003497 std::vector<std::unique_ptr<Matcher>> &MatcherStorage);
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003498};
3499
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003500void GlobalISelEmitter::gatherOpcodeValues() {
3501 InstructionOpcodeMatcher::initOpcodeValuesMap(Target);
3502}
3503
3504void GlobalISelEmitter::gatherTypeIDValues() {
3505 LLTOperandMatcher::initTypeIDValuesMap();
3506}
3507
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003508void GlobalISelEmitter::gatherNodeEquivs() {
3509 assert(NodeEquivs.empty());
3510 for (Record *Equiv : RK.getAllDerivedDefinitions("GINodeEquiv"))
Daniel Sanders39690bd2017-10-15 02:41:12 +00003511 NodeEquivs[Equiv->getValueAsDef("Node")] = Equiv;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00003512
3513 assert(ComplexPatternEquivs.empty());
3514 for (Record *Equiv : RK.getAllDerivedDefinitions("GIComplexPatternEquiv")) {
3515 Record *SelDAGEquiv = Equiv->getValueAsDef("SelDAGEquivalent");
3516 if (!SelDAGEquiv)
3517 continue;
3518 ComplexPatternEquivs[SelDAGEquiv] = Equiv;
3519 }
Volkan Kelesf7f25682018-01-16 18:44:05 +00003520
3521 assert(SDNodeXFormEquivs.empty());
3522 for (Record *Equiv : RK.getAllDerivedDefinitions("GISDNodeXFormEquiv")) {
3523 Record *SelDAGEquiv = Equiv->getValueAsDef("SelDAGEquivalent");
3524 if (!SelDAGEquiv)
3525 continue;
3526 SDNodeXFormEquivs[SelDAGEquiv] = Equiv;
3527 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003528}
3529
Daniel Sanders39690bd2017-10-15 02:41:12 +00003530Record *GlobalISelEmitter::findNodeEquiv(Record *N) const {
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003531 return NodeEquivs.lookup(N);
3532}
3533
Daniel Sandersf84bc372018-05-05 20:53:24 +00003534const CodeGenInstruction *
Florian Hahn6b1db822018-06-14 20:32:58 +00003535GlobalISelEmitter::getEquivNode(Record &Equiv, const TreePatternNode *N) const {
Matt Arsenault8ec5c102019-08-29 01:13:41 +00003536 if (N->getNumChildren() >= 1) {
3537 // setcc operation maps to two different G_* instructions based on the type.
3538 if (!Equiv.isValueUnset("IfFloatingPoint") &&
3539 MVT(N->getChild(0)->getSimpleType(0)).isFloatingPoint())
3540 return &Target.getInstruction(Equiv.getValueAsDef("IfFloatingPoint"));
3541 }
3542
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00003543 for (const TreePredicateCall &Call : N->getPredicateCalls()) {
3544 const TreePredicateFn &Predicate = Call.Fn;
Daniel Sandersf84bc372018-05-05 20:53:24 +00003545 if (!Equiv.isValueUnset("IfSignExtend") && Predicate.isLoad() &&
3546 Predicate.isSignExtLoad())
3547 return &Target.getInstruction(Equiv.getValueAsDef("IfSignExtend"));
3548 if (!Equiv.isValueUnset("IfZeroExtend") && Predicate.isLoad() &&
3549 Predicate.isZeroExtLoad())
3550 return &Target.getInstruction(Equiv.getValueAsDef("IfZeroExtend"));
3551 }
Matt Arsenault8ec5c102019-08-29 01:13:41 +00003552
Daniel Sandersf84bc372018-05-05 20:53:24 +00003553 return &Target.getInstruction(Equiv.getValueAsDef("I"));
3554}
3555
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003556GlobalISelEmitter::GlobalISelEmitter(RecordKeeper &RK)
Daniel Sandersf84bc372018-05-05 20:53:24 +00003557 : RK(RK), CGP(RK), Target(CGP.getTargetInfo()),
Matt Arsenault3ab7b7f2020-01-14 13:48:34 -05003558 CGRegs(Target.getRegBank()) {}
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003559
3560//===- Emitter ------------------------------------------------------------===//
3561
Daniel Sandersc270c502017-03-30 09:36:33 +00003562Error
Daniel Sandersffc7d582017-03-29 15:37:18 +00003563GlobalISelEmitter::importRulePredicates(RuleMatcher &M,
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003564 ArrayRef<Predicate> Predicates) {
3565 for (const Predicate &P : Predicates) {
Matt Arsenault57ef94f2019-07-30 15:56:43 +00003566 if (!P.Def || P.getCondString().empty())
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003567 continue;
3568 declareSubtargetFeature(P.Def);
3569 M.addRequiredFeature(P.Def);
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003570 }
3571
Daniel Sandersc270c502017-03-30 09:36:33 +00003572 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00003573}
Daniel Sanders8a4bae92017-03-14 21:32:08 +00003574
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003575Expected<InstructionMatcher &> GlobalISelEmitter::createAndImportSelDAGMatcher(
3576 RuleMatcher &Rule, InstructionMatcher &InsnMatcher,
Daniel Sanders8ead1292018-06-15 23:13:43 +00003577 const TreePatternNode *Src, unsigned &TempOpIdx) {
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003578 Record *SrcGIEquivOrNull = nullptr;
3579 const CodeGenInstruction *SrcGIOrNull = nullptr;
3580
3581 // Start with the defined operands (i.e., the results of the root operator).
Florian Hahn6b1db822018-06-14 20:32:58 +00003582 if (Src->getExtTypes().size() > 1)
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003583 return failedImport("Src pattern has multiple results");
3584
Florian Hahn6b1db822018-06-14 20:32:58 +00003585 if (Src->isLeaf()) {
3586 Init *SrcInit = Src->getLeafValue();
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003587 if (isa<IntInit>(SrcInit)) {
3588 InsnMatcher.addPredicate<InstructionOpcodeMatcher>(
3589 &Target.getInstruction(RK.getDef("G_CONSTANT")));
3590 } else
3591 return failedImport(
3592 "Unable to deduce gMIR opcode to handle Src (which is a leaf)");
3593 } else {
Florian Hahn6b1db822018-06-14 20:32:58 +00003594 SrcGIEquivOrNull = findNodeEquiv(Src->getOperator());
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003595 if (!SrcGIEquivOrNull)
3596 return failedImport("Pattern operator lacks an equivalent Instruction" +
Florian Hahn6b1db822018-06-14 20:32:58 +00003597 explainOperator(Src->getOperator()));
Daniel Sandersf84bc372018-05-05 20:53:24 +00003598 SrcGIOrNull = getEquivNode(*SrcGIEquivOrNull, Src);
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003599
3600 // The operators look good: match the opcode
3601 InsnMatcher.addPredicate<InstructionOpcodeMatcher>(SrcGIOrNull);
3602 }
3603
3604 unsigned OpIdx = 0;
Florian Hahn6b1db822018-06-14 20:32:58 +00003605 for (const TypeSetByHwMode &VTy : Src->getExtTypes()) {
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003606 // Results don't have a name unless they are the root node. The caller will
3607 // set the name if appropriate.
3608 OperandMatcher &OM = InsnMatcher.addOperand(OpIdx++, "", TempOpIdx);
3609 if (auto Error = OM.addTypeCheckPredicate(VTy, false /* OperandIsAPointer */))
3610 return failedImport(toString(std::move(Error)) +
3611 " for result of Src pattern operator");
3612 }
3613
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00003614 for (const TreePredicateCall &Call : Src->getPredicateCalls()) {
3615 const TreePredicateFn &Predicate = Call.Fn;
Daniel Sanders2c269f62017-08-24 09:11:20 +00003616 if (Predicate.isAlwaysTrue())
3617 continue;
3618
3619 if (Predicate.isImmediatePattern()) {
3620 InsnMatcher.addPredicate<InstructionImmPredicateMatcher>(Predicate);
3621 continue;
3622 }
3623
Matt Arsenaultd00d8572019-07-15 20:59:42 +00003624 // An address space check is needed in all contexts if there is one.
3625 if (Predicate.isLoad() || Predicate.isStore() || Predicate.isAtomic()) {
3626 if (const ListInit *AddrSpaces = Predicate.getAddressSpaces()) {
3627 SmallVector<unsigned, 4> ParsedAddrSpaces;
3628
3629 for (Init *Val : AddrSpaces->getValues()) {
3630 IntInit *IntVal = dyn_cast<IntInit>(Val);
3631 if (!IntVal)
3632 return failedImport("Address space is not an integer");
3633 ParsedAddrSpaces.push_back(IntVal->getValue());
3634 }
3635
3636 if (!ParsedAddrSpaces.empty()) {
3637 InsnMatcher.addPredicate<MemoryAddressSpacePredicateMatcher>(
3638 0, ParsedAddrSpaces);
3639 }
3640 }
Matt Arsenault52c26242019-07-31 00:14:43 +00003641
3642 int64_t MinAlign = Predicate.getMinAlignment();
3643 if (MinAlign > 0)
3644 InsnMatcher.addPredicate<MemoryAlignmentPredicateMatcher>(0, MinAlign);
Matt Arsenaultd00d8572019-07-15 20:59:42 +00003645 }
3646
3647 // G_LOAD is used for both non-extending and any-extending loads.
Daniel Sandersf84bc372018-05-05 20:53:24 +00003648 if (Predicate.isLoad() && Predicate.isNonExtLoad()) {
3649 InsnMatcher.addPredicate<MemoryVsLLTSizePredicateMatcher>(
3650 0, MemoryVsLLTSizePredicateMatcher::EqualTo, 0);
3651 continue;
3652 }
3653 if (Predicate.isLoad() && Predicate.isAnyExtLoad()) {
3654 InsnMatcher.addPredicate<MemoryVsLLTSizePredicateMatcher>(
3655 0, MemoryVsLLTSizePredicateMatcher::LessThan, 0);
3656 continue;
3657 }
3658
Amara Emerson52e6d522019-08-02 23:33:13 +00003659 if (Predicate.isStore()) {
3660 if (Predicate.isTruncStore()) {
3661 // FIXME: If MemoryVT is set, we end up with 2 checks for the MMO size.
3662 InsnMatcher.addPredicate<MemoryVsLLTSizePredicateMatcher>(
3663 0, MemoryVsLLTSizePredicateMatcher::LessThan, 0);
3664 continue;
3665 }
3666 if (Predicate.isNonTruncStore()) {
3667 // We need to check the sizes match here otherwise we could incorrectly
3668 // match truncating stores with non-truncating ones.
3669 InsnMatcher.addPredicate<MemoryVsLLTSizePredicateMatcher>(
3670 0, MemoryVsLLTSizePredicateMatcher::EqualTo, 0);
3671 }
Matt Arsenault02772492019-07-15 21:15:20 +00003672 }
3673
Daniel Sandersf84bc372018-05-05 20:53:24 +00003674 // No check required. We already did it by swapping the opcode.
3675 if (!SrcGIEquivOrNull->isValueUnset("IfSignExtend") &&
3676 Predicate.isSignExtLoad())
3677 continue;
3678
3679 // No check required. We already did it by swapping the opcode.
3680 if (!SrcGIEquivOrNull->isValueUnset("IfZeroExtend") &&
3681 Predicate.isZeroExtLoad())
Daniel Sandersa71f4542017-10-16 00:56:30 +00003682 continue;
3683
Daniel Sandersd66e0902017-10-23 18:19:24 +00003684 // No check required. G_STORE by itself is a non-extending store.
3685 if (Predicate.isNonTruncStore())
3686 continue;
3687
Daniel Sanders76664652017-11-28 22:07:05 +00003688 if (Predicate.isLoad() || Predicate.isStore() || Predicate.isAtomic()) {
3689 if (Predicate.getMemoryVT() != nullptr) {
3690 Optional<LLTCodeGen> MemTyOrNone =
3691 MVTToLLT(getValueType(Predicate.getMemoryVT()));
Daniel Sandersd66e0902017-10-23 18:19:24 +00003692
Daniel Sanders76664652017-11-28 22:07:05 +00003693 if (!MemTyOrNone)
3694 return failedImport("MemVT could not be converted to LLT");
Daniel Sandersd66e0902017-10-23 18:19:24 +00003695
Daniel Sandersf84bc372018-05-05 20:53:24 +00003696 // MMO's work in bytes so we must take care of unusual types like i1
3697 // don't round down.
3698 unsigned MemSizeInBits =
3699 llvm::alignTo(MemTyOrNone->get().getSizeInBits(), 8);
3700
3701 InsnMatcher.addPredicate<MemorySizePredicateMatcher>(
3702 0, MemSizeInBits / 8);
Daniel Sanders76664652017-11-28 22:07:05 +00003703 continue;
3704 }
3705 }
3706
3707 if (Predicate.isLoad() || Predicate.isStore()) {
3708 // No check required. A G_LOAD/G_STORE is an unindexed load.
3709 if (Predicate.isUnindexed())
3710 continue;
3711 }
3712
3713 if (Predicate.isAtomic()) {
3714 if (Predicate.isAtomicOrderingMonotonic()) {
3715 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3716 "Monotonic");
3717 continue;
3718 }
3719 if (Predicate.isAtomicOrderingAcquire()) {
3720 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>("Acquire");
3721 continue;
3722 }
3723 if (Predicate.isAtomicOrderingRelease()) {
3724 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>("Release");
3725 continue;
3726 }
3727 if (Predicate.isAtomicOrderingAcquireRelease()) {
3728 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3729 "AcquireRelease");
3730 continue;
3731 }
3732 if (Predicate.isAtomicOrderingSequentiallyConsistent()) {
3733 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3734 "SequentiallyConsistent");
3735 continue;
3736 }
Daniel Sanders0c43b3a2017-11-30 21:05:59 +00003737
3738 if (Predicate.isAtomicOrderingAcquireOrStronger()) {
3739 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3740 "Acquire", AtomicOrderingMMOPredicateMatcher::AO_OrStronger);
3741 continue;
3742 }
3743 if (Predicate.isAtomicOrderingWeakerThanAcquire()) {
3744 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3745 "Acquire", AtomicOrderingMMOPredicateMatcher::AO_WeakerThan);
3746 continue;
3747 }
3748
3749 if (Predicate.isAtomicOrderingReleaseOrStronger()) {
3750 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3751 "Release", AtomicOrderingMMOPredicateMatcher::AO_OrStronger);
3752 continue;
3753 }
3754 if (Predicate.isAtomicOrderingWeakerThanRelease()) {
3755 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3756 "Release", AtomicOrderingMMOPredicateMatcher::AO_WeakerThan);
3757 continue;
3758 }
Daniel Sandersd66e0902017-10-23 18:19:24 +00003759 }
3760
Daniel Sanders8ead1292018-06-15 23:13:43 +00003761 if (Predicate.hasGISelPredicateCode()) {
3762 InsnMatcher.addPredicate<GenericInstructionPredicateMatcher>(Predicate);
3763 continue;
3764 }
3765
Daniel Sanders2c269f62017-08-24 09:11:20 +00003766 return failedImport("Src pattern child has predicate (" +
3767 explainPredicates(Src) + ")");
3768 }
Matt Arsenault53f21e02020-08-02 17:23:52 -04003769
3770 bool IsAtomic = false;
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003771 if (SrcGIEquivOrNull && SrcGIEquivOrNull->getValueAsBit("CheckMMOIsNonAtomic"))
3772 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>("NotAtomic");
Matt Arsenault63e6d8d2019-09-09 16:18:07 +00003773 else if (SrcGIEquivOrNull && SrcGIEquivOrNull->getValueAsBit("CheckMMOIsAtomic")) {
Matt Arsenault53f21e02020-08-02 17:23:52 -04003774 IsAtomic = true;
Matt Arsenault63e6d8d2019-09-09 16:18:07 +00003775 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3776 "Unordered", AtomicOrderingMMOPredicateMatcher::AO_OrStronger);
3777 }
Daniel Sanders2c269f62017-08-24 09:11:20 +00003778
Florian Hahn6b1db822018-06-14 20:32:58 +00003779 if (Src->isLeaf()) {
3780 Init *SrcInit = Src->getLeafValue();
Daniel Sanders452c8ae2017-05-23 19:33:16 +00003781 if (IntInit *SrcIntInit = dyn_cast<IntInit>(SrcInit)) {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003782 OperandMatcher &OM =
Florian Hahn6b1db822018-06-14 20:32:58 +00003783 InsnMatcher.addOperand(OpIdx++, Src->getName(), TempOpIdx);
Daniel Sanders452c8ae2017-05-23 19:33:16 +00003784 OM.addPredicate<LiteralIntOperandMatcher>(SrcIntInit->getValue());
3785 } else
Daniel Sanders32291982017-06-28 13:50:04 +00003786 return failedImport(
3787 "Unable to deduce gMIR opcode to handle Src (which is a leaf)");
Daniel Sanders452c8ae2017-05-23 19:33:16 +00003788 } else {
Daniel Sanders85ffd362017-07-06 08:12:20 +00003789 assert(SrcGIOrNull &&
3790 "Expected to have already found an equivalent Instruction");
Daniel Sanders11300ce2017-10-13 21:28:03 +00003791 if (SrcGIOrNull->TheDef->getName() == "G_CONSTANT" ||
3792 SrcGIOrNull->TheDef->getName() == "G_FCONSTANT") {
3793 // imm/fpimm still have operands but we don't need to do anything with it
Daniel Sanders05540042017-08-08 10:44:31 +00003794 // here since we don't support ImmLeaf predicates yet. However, we still
3795 // need to note the hidden operand to get GIM_CheckNumOperands correct.
3796 InsnMatcher.addOperand(OpIdx++, "", TempOpIdx);
3797 return InsnMatcher;
3798 }
3799
Matt Arsenault8ec5c102019-08-29 01:13:41 +00003800 // Special case because the operand order is changed from setcc. The
3801 // predicate operand needs to be swapped from the last operand to the first
3802 // source.
3803
3804 unsigned NumChildren = Src->getNumChildren();
3805 bool IsFCmp = SrcGIOrNull->TheDef->getName() == "G_FCMP";
3806
3807 if (IsFCmp || SrcGIOrNull->TheDef->getName() == "G_ICMP") {
3808 TreePatternNode *SrcChild = Src->getChild(NumChildren - 1);
3809 if (SrcChild->isLeaf()) {
3810 DefInit *DI = dyn_cast<DefInit>(SrcChild->getLeafValue());
3811 Record *CCDef = DI ? DI->getDef() : nullptr;
3812 if (!CCDef || !CCDef->isSubClassOf("CondCode"))
3813 return failedImport("Unable to handle CondCode");
3814
3815 OperandMatcher &OM =
3816 InsnMatcher.addOperand(OpIdx++, SrcChild->getName(), TempOpIdx);
3817 StringRef PredType = IsFCmp ? CCDef->getValueAsString("FCmpPredicate") :
3818 CCDef->getValueAsString("ICmpPredicate");
3819
3820 if (!PredType.empty()) {
Benjamin Krameradcd0262020-01-28 20:23:46 +01003821 OM.addPredicate<CmpPredicateOperandMatcher>(std::string(PredType));
Matt Arsenault8ec5c102019-08-29 01:13:41 +00003822 // Process the other 2 operands normally.
3823 --NumChildren;
3824 }
3825 }
3826 }
3827
Matt Arsenault53f21e02020-08-02 17:23:52 -04003828 // Hack around an unfortunate mistake in how atomic store (and really
3829 // atomicrmw in general) operands were ordered. A ISD::STORE used the order
3830 // <stored value>, <pointer> order. ISD::ATOMIC_STORE used the opposite,
3831 // <pointer>, <stored value>. In GlobalISel there's just the one store
3832 // opcode, so we need to swap the operands here to get the right type check.
3833 if (IsAtomic && SrcGIOrNull->TheDef->getName() == "G_STORE") {
3834 assert(NumChildren == 2 && "wrong operands for atomic store");
3835
3836 TreePatternNode *PtrChild = Src->getChild(0);
3837 TreePatternNode *ValueChild = Src->getChild(1);
3838
3839 if (auto Error = importChildMatcher(Rule, InsnMatcher, PtrChild, true,
3840 false, 1, TempOpIdx))
3841 return std::move(Error);
3842
3843 if (auto Error = importChildMatcher(Rule, InsnMatcher, ValueChild, false,
3844 false, 0, TempOpIdx))
3845 return std::move(Error);
3846 return InsnMatcher;
3847 }
3848
Daniel Sanders452c8ae2017-05-23 19:33:16 +00003849 // Match the used operands (i.e. the children of the operator).
Jessica Paquette5c8a29f2019-08-20 22:04:10 +00003850 bool IsIntrinsic =
3851 SrcGIOrNull->TheDef->getName() == "G_INTRINSIC" ||
3852 SrcGIOrNull->TheDef->getName() == "G_INTRINSIC_W_SIDE_EFFECTS";
3853 const CodeGenIntrinsic *II = Src->getIntrinsicInfo(CGP);
3854 if (IsIntrinsic && !II)
3855 return failedImport("Expected IntInit containing intrinsic ID)");
3856
Matt Arsenault8ec5c102019-08-29 01:13:41 +00003857 for (unsigned i = 0; i != NumChildren; ++i) {
Florian Hahn6b1db822018-06-14 20:32:58 +00003858 TreePatternNode *SrcChild = Src->getChild(i);
Daniel Sanders85ffd362017-07-06 08:12:20 +00003859
Matt Arsenault10edb1d2020-01-08 15:40:37 -05003860 // We need to determine the meaning of a literal integer based on the
3861 // context. If this is a field required to be an immediate (such as an
3862 // immarg intrinsic argument), the required predicates are different than
3863 // a constant which may be materialized in a register. If we have an
3864 // argument that is required to be an immediate, we should not emit an LLT
3865 // type check, and should not be looking for a G_CONSTANT defined
3866 // register.
3867 bool OperandIsImmArg = SrcGIOrNull->isOperandImmArg(i);
3868
Daniel Sandersa71f4542017-10-16 00:56:30 +00003869 // SelectionDAG allows pointers to be represented with iN since it doesn't
3870 // distinguish between pointers and integers but they are different types in GlobalISel.
3871 // Coerce integers to pointers to address space 0 if the context indicates a pointer.
Matt Arsenault10edb1d2020-01-08 15:40:37 -05003872 //
Daniel Sandersc54aa9c2017-11-18 00:16:44 +00003873 bool OperandIsAPointer = SrcGIOrNull->isOperandAPointer(i);
Daniel Sandersa71f4542017-10-16 00:56:30 +00003874
Jessica Paquette5c8a29f2019-08-20 22:04:10 +00003875 if (IsIntrinsic) {
3876 // For G_INTRINSIC/G_INTRINSIC_W_SIDE_EFFECTS, the operand immediately
3877 // following the defs is an intrinsic ID.
3878 if (i == 0) {
Daniel Sanders85ffd362017-07-06 08:12:20 +00003879 OperandMatcher &OM =
Florian Hahn6b1db822018-06-14 20:32:58 +00003880 InsnMatcher.addOperand(OpIdx++, SrcChild->getName(), TempOpIdx);
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00003881 OM.addPredicate<IntrinsicIDOperandMatcher>(II);
Daniel Sanders85ffd362017-07-06 08:12:20 +00003882 continue;
3883 }
3884
Matt Arsenault10edb1d2020-01-08 15:40:37 -05003885 // We have to check intrinsics for llvm_anyptr_ty and immarg parameters.
Jessica Paquette5c8a29f2019-08-20 22:04:10 +00003886 //
3887 // Note that we have to look at the i-1th parameter, because we don't
3888 // have the intrinsic ID in the intrinsic's parameter list.
3889 OperandIsAPointer |= II->isParamAPointer(i - 1);
Matt Arsenault10edb1d2020-01-08 15:40:37 -05003890 OperandIsImmArg |= II->isParamImmArg(i - 1);
Daniel Sanders85ffd362017-07-06 08:12:20 +00003891 }
3892
Daniel Sandersa71f4542017-10-16 00:56:30 +00003893 if (auto Error =
3894 importChildMatcher(Rule, InsnMatcher, SrcChild, OperandIsAPointer,
Matt Arsenault10edb1d2020-01-08 15:40:37 -05003895 OperandIsImmArg, OpIdx++, TempOpIdx))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -08003896 return std::move(Error);
Daniel Sanders452c8ae2017-05-23 19:33:16 +00003897 }
Daniel Sandersffc7d582017-03-29 15:37:18 +00003898 }
3899
3900 return InsnMatcher;
3901}
3902
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003903Error GlobalISelEmitter::importComplexPatternOperandMatcher(
3904 OperandMatcher &OM, Record *R, unsigned &TempOpIdx) const {
3905 const auto &ComplexPattern = ComplexPatternEquivs.find(R);
3906 if (ComplexPattern == ComplexPatternEquivs.end())
3907 return failedImport("SelectionDAG ComplexPattern (" + R->getName() +
3908 ") not mapped to GlobalISel");
3909
3910 OM.addPredicate<ComplexPatternOperandMatcher>(OM, *ComplexPattern->second);
3911 TempOpIdx++;
3912 return Error::success();
3913}
3914
Matt Arsenault3e45c702019-09-06 20:32:37 +00003915// Get the name to use for a pattern operand. For an anonymous physical register
3916// input, this should use the register name.
3917static StringRef getSrcChildName(const TreePatternNode *SrcChild,
3918 Record *&PhysReg) {
3919 StringRef SrcChildName = SrcChild->getName();
3920 if (SrcChildName.empty() && SrcChild->isLeaf()) {
3921 if (auto *ChildDefInit = dyn_cast<DefInit>(SrcChild->getLeafValue())) {
3922 auto *ChildRec = ChildDefInit->getDef();
3923 if (ChildRec->isSubClassOf("Register")) {
3924 SrcChildName = ChildRec->getName();
3925 PhysReg = ChildRec;
3926 }
3927 }
3928 }
3929
3930 return SrcChildName;
3931}
3932
Matt Arsenault10edb1d2020-01-08 15:40:37 -05003933Error GlobalISelEmitter::importChildMatcher(
3934 RuleMatcher &Rule, InstructionMatcher &InsnMatcher,
3935 const TreePatternNode *SrcChild, bool OperandIsAPointer,
3936 bool OperandIsImmArg, unsigned OpIdx, unsigned &TempOpIdx) {
Matt Arsenault3e45c702019-09-06 20:32:37 +00003937
3938 Record *PhysReg = nullptr;
3939 StringRef SrcChildName = getSrcChildName(SrcChild, PhysReg);
3940
Benjamin Krameradcd0262020-01-28 20:23:46 +01003941 OperandMatcher &OM =
3942 PhysReg
3943 ? InsnMatcher.addPhysRegInput(PhysReg, OpIdx, TempOpIdx)
3944 : InsnMatcher.addOperand(OpIdx, std::string(SrcChildName), TempOpIdx);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003945 if (OM.isSameAsAnotherOperand())
3946 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00003947
Florian Hahn6b1db822018-06-14 20:32:58 +00003948 ArrayRef<TypeSetByHwMode> ChildTypes = SrcChild->getExtTypes();
Daniel Sandersffc7d582017-03-29 15:37:18 +00003949 if (ChildTypes.size() != 1)
3950 return failedImport("Src pattern child has multiple results");
3951
3952 // Check MBB's before the type check since they are not a known type.
Florian Hahn6b1db822018-06-14 20:32:58 +00003953 if (!SrcChild->isLeaf()) {
3954 if (SrcChild->getOperator()->isSubClassOf("SDNode")) {
3955 auto &ChildSDNI = CGP.getSDNodeInfo(SrcChild->getOperator());
Daniel Sandersffc7d582017-03-29 15:37:18 +00003956 if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") {
3957 OM.addPredicate<MBBOperandMatcher>();
Daniel Sandersc270c502017-03-30 09:36:33 +00003958 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00003959 }
Matt Arsenault3ecab8e2019-09-19 16:26:14 +00003960 if (SrcChild->getOperator()->getName() == "timm") {
3961 OM.addPredicate<ImmOperandMatcher>();
3962 return Error::success();
3963 }
Daniel Sandersffc7d582017-03-29 15:37:18 +00003964 }
Daniel Sandersffc7d582017-03-29 15:37:18 +00003965 }
3966
Matt Arsenault10edb1d2020-01-08 15:40:37 -05003967 // Immediate arguments have no meaningful type to check as they don't have
3968 // registers.
3969 if (!OperandIsImmArg) {
3970 if (auto Error =
3971 OM.addTypeCheckPredicate(ChildTypes.front(), OperandIsAPointer))
3972 return failedImport(toString(std::move(Error)) + " for Src operand (" +
3973 to_string(*SrcChild) + ")");
3974 }
Daniel Sandersffc7d582017-03-29 15:37:18 +00003975
Daniel Sandersbee57392017-04-04 13:25:23 +00003976 // Check for nested instructions.
Florian Hahn6b1db822018-06-14 20:32:58 +00003977 if (!SrcChild->isLeaf()) {
3978 if (SrcChild->getOperator()->isSubClassOf("ComplexPattern")) {
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003979 // When a ComplexPattern is used as an operator, it should do the same
3980 // thing as when used as a leaf. However, the children of the operator
3981 // name the sub-operands that make up the complex operand and we must
3982 // prepare to reference them in the renderer too.
3983 unsigned RendererID = TempOpIdx;
3984 if (auto Error = importComplexPatternOperandMatcher(
Florian Hahn6b1db822018-06-14 20:32:58 +00003985 OM, SrcChild->getOperator(), TempOpIdx))
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003986 return Error;
3987
Florian Hahn6b1db822018-06-14 20:32:58 +00003988 for (unsigned i = 0, e = SrcChild->getNumChildren(); i != e; ++i) {
3989 auto *SubOperand = SrcChild->getChild(i);
Jessica Paquette1ed1dd62019-02-09 00:29:13 +00003990 if (!SubOperand->getName().empty()) {
3991 if (auto Error = Rule.defineComplexSubOperand(SubOperand->getName(),
3992 SrcChild->getOperator(),
3993 RendererID, i))
3994 return Error;
3995 }
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003996 }
3997
3998 return Error::success();
3999 }
4000
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00004001 auto MaybeInsnOperand = OM.addPredicate<InstructionOperandMatcher>(
Florian Hahn6b1db822018-06-14 20:32:58 +00004002 InsnMatcher.getRuleMatcher(), SrcChild->getName());
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00004003 if (!MaybeInsnOperand.hasValue()) {
4004 // This isn't strictly true. If the user were to provide exactly the same
4005 // matchers as the original operand then we could allow it. However, it's
4006 // simpler to not permit the redundant specification.
4007 return failedImport("Nested instruction cannot be the same as another operand");
4008 }
4009
Daniel Sandersbee57392017-04-04 13:25:23 +00004010 // Map the node to a gMIR instruction.
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00004011 InstructionOperandMatcher &InsnOperand = **MaybeInsnOperand;
Daniel Sanders57938df2017-07-11 10:40:18 +00004012 auto InsnMatcherOrError = createAndImportSelDAGMatcher(
Daniel Sandersdf39cba2017-10-15 18:22:54 +00004013 Rule, InsnOperand.getInsnMatcher(), SrcChild, TempOpIdx);
Daniel Sandersbee57392017-04-04 13:25:23 +00004014 if (auto Error = InsnMatcherOrError.takeError())
4015 return Error;
4016
4017 return Error::success();
4018 }
4019
Florian Hahn6b1db822018-06-14 20:32:58 +00004020 if (SrcChild->hasAnyPredicate())
Diana Picusd1b61812017-11-03 10:30:19 +00004021 return failedImport("Src pattern child has unsupported predicate");
4022
Daniel Sandersffc7d582017-03-29 15:37:18 +00004023 // Check for constant immediates.
Florian Hahn6b1db822018-06-14 20:32:58 +00004024 if (auto *ChildInt = dyn_cast<IntInit>(SrcChild->getLeafValue())) {
Matt Arsenault10edb1d2020-01-08 15:40:37 -05004025 if (OperandIsImmArg) {
4026 // Checks for argument directly in operand list
4027 OM.addPredicate<LiteralIntOperandMatcher>(ChildInt->getValue());
4028 } else {
4029 // Checks for materialized constant
4030 OM.addPredicate<ConstantIntOperandMatcher>(ChildInt->getValue());
4031 }
Daniel Sandersc270c502017-03-30 09:36:33 +00004032 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00004033 }
4034
4035 // Check for def's like register classes or ComplexPattern's.
Florian Hahn6b1db822018-06-14 20:32:58 +00004036 if (auto *ChildDefInit = dyn_cast<DefInit>(SrcChild->getLeafValue())) {
Daniel Sandersffc7d582017-03-29 15:37:18 +00004037 auto *ChildRec = ChildDefInit->getDef();
4038
4039 // Check for register classes.
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004040 if (ChildRec->isSubClassOf("RegisterClass") ||
4041 ChildRec->isSubClassOf("RegisterOperand")) {
Daniel Sandersffc7d582017-03-29 15:37:18 +00004042 OM.addPredicate<RegisterBankOperandMatcher>(
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004043 Target.getRegisterClass(getInitValueAsRegClass(ChildDefInit)));
Daniel Sanders658541f2017-04-22 15:53:21 +00004044 return Error::success();
4045 }
4046
Matt Arsenault3e45c702019-09-06 20:32:37 +00004047 if (ChildRec->isSubClassOf("Register")) {
4048 // This just be emitted as a copy to the specific register.
4049 ValueTypeByHwMode VT = ChildTypes.front().getValueTypeByHwMode();
4050 const CodeGenRegisterClass *RC
4051 = CGRegs.getMinimalPhysRegClass(ChildRec, &VT);
4052 if (!RC) {
4053 return failedImport(
4054 "Could not determine physical register class of pattern source");
4055 }
4056
4057 OM.addPredicate<RegisterBankOperandMatcher>(*RC);
4058 return Error::success();
4059 }
4060
Daniel Sanders4d4e7652017-10-09 18:14:53 +00004061 // Check for ValueType.
4062 if (ChildRec->isSubClassOf("ValueType")) {
4063 // We already added a type check as standard practice so this doesn't need
4064 // to do anything.
4065 return Error::success();
4066 }
4067
Daniel Sandersffc7d582017-03-29 15:37:18 +00004068 // Check for ComplexPattern's.
Daniel Sandersdf39cba2017-10-15 18:22:54 +00004069 if (ChildRec->isSubClassOf("ComplexPattern"))
4070 return importComplexPatternOperandMatcher(OM, ChildRec, TempOpIdx);
Daniel Sandersffc7d582017-03-29 15:37:18 +00004071
Daniel Sandersd0656a32017-04-13 09:45:37 +00004072 if (ChildRec->isSubClassOf("ImmLeaf")) {
4073 return failedImport(
4074 "Src pattern child def is an unsupported tablegen class (ImmLeaf)");
4075 }
4076
Matt Arsenault03a592f2020-01-16 10:47:13 -05004077 // Place holder for SRCVALUE nodes. Nothing to do here.
4078 if (ChildRec->getName() == "srcvalue")
4079 return Error::success();
4080
Daniel Sandersffc7d582017-03-29 15:37:18 +00004081 return failedImport(
4082 "Src pattern child def is an unsupported tablegen class");
4083 }
4084
4085 return failedImport("Src pattern child is an unsupported kind");
4086}
4087
Daniel Sanders7438b262017-10-31 23:03:18 +00004088Expected<action_iterator> GlobalISelEmitter::importExplicitUseRenderer(
4089 action_iterator InsertPt, RuleMatcher &Rule, BuildMIAction &DstMIBuilder,
Florian Hahn6b1db822018-06-14 20:32:58 +00004090 TreePatternNode *DstChild) {
Daniel Sanders2c269f62017-08-24 09:11:20 +00004091
Florian Hahn6b1db822018-06-14 20:32:58 +00004092 const auto &SubOperand = Rule.getComplexSubOperand(DstChild->getName());
Daniel Sandersdf39cba2017-10-15 18:22:54 +00004093 if (SubOperand.hasValue()) {
4094 DstMIBuilder.addRenderer<RenderComplexPatternOperand>(
Florian Hahn6b1db822018-06-14 20:32:58 +00004095 *std::get<0>(*SubOperand), DstChild->getName(),
Daniel Sandersdf39cba2017-10-15 18:22:54 +00004096 std::get<1>(*SubOperand), std::get<2>(*SubOperand));
Daniel Sanders7438b262017-10-31 23:03:18 +00004097 return InsertPt;
Daniel Sandersdf39cba2017-10-15 18:22:54 +00004098 }
4099
Florian Hahn6b1db822018-06-14 20:32:58 +00004100 if (!DstChild->isLeaf()) {
Florian Hahn6b1db822018-06-14 20:32:58 +00004101 if (DstChild->getOperator()->isSubClassOf("SDNodeXForm")) {
4102 auto Child = DstChild->getChild(0);
4103 auto I = SDNodeXFormEquivs.find(DstChild->getOperator());
Volkan Kelesf7f25682018-01-16 18:44:05 +00004104 if (I != SDNodeXFormEquivs.end()) {
Matt Arsenaultb4a64742020-01-08 12:53:15 -05004105 Record *XFormOpc = DstChild->getOperator()->getValueAsDef("Opcode");
4106 if (XFormOpc->getName() == "timm") {
4107 // If this is a TargetConstant, there won't be a corresponding
4108 // instruction to transform. Instead, this will refer directly to an
4109 // operand in an instruction's operand list.
4110 DstMIBuilder.addRenderer<CustomOperandRenderer>(*I->second,
4111 Child->getName());
4112 } else {
4113 DstMIBuilder.addRenderer<CustomRenderer>(*I->second,
4114 Child->getName());
4115 }
4116
Volkan Kelesf7f25682018-01-16 18:44:05 +00004117 return InsertPt;
4118 }
Florian Hahn6b1db822018-06-14 20:32:58 +00004119 return failedImport("SDNodeXForm " + Child->getName() +
Volkan Kelesf7f25682018-01-16 18:44:05 +00004120 " has no custom renderer");
4121 }
4122
Daniel Sanders05540042017-08-08 10:44:31 +00004123 // We accept 'bb' here. It's an operator because BasicBlockSDNode isn't
4124 // inline, but in MI it's just another operand.
Florian Hahn6b1db822018-06-14 20:32:58 +00004125 if (DstChild->getOperator()->isSubClassOf("SDNode")) {
4126 auto &ChildSDNI = CGP.getSDNodeInfo(DstChild->getOperator());
Daniel Sandersffc7d582017-03-29 15:37:18 +00004127 if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") {
Florian Hahn6b1db822018-06-14 20:32:58 +00004128 DstMIBuilder.addRenderer<CopyRenderer>(DstChild->getName());
Daniel Sanders7438b262017-10-31 23:03:18 +00004129 return InsertPt;
Daniel Sandersffc7d582017-03-29 15:37:18 +00004130 }
4131 }
Daniel Sanders05540042017-08-08 10:44:31 +00004132
4133 // Similarly, imm is an operator in TreePatternNode's view but must be
4134 // rendered as operands.
4135 // FIXME: The target should be able to choose sign-extended when appropriate
4136 // (e.g. on Mips).
Matt Arsenault3ecab8e2019-09-19 16:26:14 +00004137 if (DstChild->getOperator()->getName() == "timm") {
4138 DstMIBuilder.addRenderer<CopyRenderer>(DstChild->getName());
4139 return InsertPt;
4140 } else if (DstChild->getOperator()->getName() == "imm") {
Florian Hahn6b1db822018-06-14 20:32:58 +00004141 DstMIBuilder.addRenderer<CopyConstantAsImmRenderer>(DstChild->getName());
Daniel Sanders7438b262017-10-31 23:03:18 +00004142 return InsertPt;
Florian Hahn6b1db822018-06-14 20:32:58 +00004143 } else if (DstChild->getOperator()->getName() == "fpimm") {
Daniel Sanders11300ce2017-10-13 21:28:03 +00004144 DstMIBuilder.addRenderer<CopyFConstantAsFPImmRenderer>(
Florian Hahn6b1db822018-06-14 20:32:58 +00004145 DstChild->getName());
Daniel Sanders7438b262017-10-31 23:03:18 +00004146 return InsertPt;
Daniel Sanders05540042017-08-08 10:44:31 +00004147 }
4148
Florian Hahn6b1db822018-06-14 20:32:58 +00004149 if (DstChild->getOperator()->isSubClassOf("Instruction")) {
Matt Arsenault9c346462020-01-14 16:02:02 -05004150 auto OpTy = getInstResultType(DstChild);
4151 if (!OpTy)
4152 return OpTy.takeError();
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00004153
4154 unsigned TempRegID = Rule.allocateTempRegID();
4155 InsertPt = Rule.insertAction<MakeTempRegisterAction>(
Matt Arsenault9c346462020-01-14 16:02:02 -05004156 InsertPt, *OpTy, TempRegID);
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00004157 DstMIBuilder.addRenderer<TempRegRenderer>(TempRegID);
4158
4159 auto InsertPtOrError = createAndImportSubInstructionRenderer(
4160 ++InsertPt, Rule, DstChild, TempRegID);
4161 if (auto Error = InsertPtOrError.takeError())
Bill Wendlingc55cf4a2020-02-10 07:06:45 -08004162 return std::move(Error);
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00004163 return InsertPtOrError.get();
4164 }
4165
Florian Hahn6b1db822018-06-14 20:32:58 +00004166 return failedImport("Dst pattern child isn't a leaf node or an MBB" + llvm::to_string(*DstChild));
Daniel Sandersffc7d582017-03-29 15:37:18 +00004167 }
4168
Daniel Sandersf499b2b2017-11-30 18:48:35 +00004169 // It could be a specific immediate in which case we should just check for
4170 // that immediate.
4171 if (const IntInit *ChildIntInit =
Florian Hahn6b1db822018-06-14 20:32:58 +00004172 dyn_cast<IntInit>(DstChild->getLeafValue())) {
Daniel Sandersf499b2b2017-11-30 18:48:35 +00004173 DstMIBuilder.addRenderer<ImmRenderer>(ChildIntInit->getValue());
4174 return InsertPt;
4175 }
4176
Daniel Sandersffc7d582017-03-29 15:37:18 +00004177 // Otherwise, we're looking for a bog-standard RegisterClass operand.
Florian Hahn6b1db822018-06-14 20:32:58 +00004178 if (auto *ChildDefInit = dyn_cast<DefInit>(DstChild->getLeafValue())) {
Daniel Sandersffc7d582017-03-29 15:37:18 +00004179 auto *ChildRec = ChildDefInit->getDef();
4180
Florian Hahn6b1db822018-06-14 20:32:58 +00004181 ArrayRef<TypeSetByHwMode> ChildTypes = DstChild->getExtTypes();
Daniel Sandersffc7d582017-03-29 15:37:18 +00004182 if (ChildTypes.size() != 1)
4183 return failedImport("Dst pattern child has multiple results");
4184
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004185 Optional<LLTCodeGen> OpTyOrNone = None;
4186 if (ChildTypes.front().isMachineValueType())
4187 OpTyOrNone = MVTToLLT(ChildTypes.front().getMachineValueType().SimpleTy);
Daniel Sandersffc7d582017-03-29 15:37:18 +00004188 if (!OpTyOrNone)
4189 return failedImport("Dst operand has an unsupported type");
4190
4191 if (ChildRec->isSubClassOf("Register")) {
Daniel Sanders198447a2017-11-01 00:29:47 +00004192 DstMIBuilder.addRenderer<AddRegisterRenderer>(ChildRec);
Daniel Sanders7438b262017-10-31 23:03:18 +00004193 return InsertPt;
Daniel Sandersffc7d582017-03-29 15:37:18 +00004194 }
4195
Daniel Sanders658541f2017-04-22 15:53:21 +00004196 if (ChildRec->isSubClassOf("RegisterClass") ||
Daniel Sanders4d4e7652017-10-09 18:14:53 +00004197 ChildRec->isSubClassOf("RegisterOperand") ||
4198 ChildRec->isSubClassOf("ValueType")) {
Daniel Sandersd66e0902017-10-23 18:19:24 +00004199 if (ChildRec->isSubClassOf("RegisterOperand") &&
4200 !ChildRec->isValueUnset("GIZeroRegister")) {
4201 DstMIBuilder.addRenderer<CopyOrAddZeroRegRenderer>(
Florian Hahn6b1db822018-06-14 20:32:58 +00004202 DstChild->getName(), ChildRec->getValueAsDef("GIZeroRegister"));
Daniel Sanders7438b262017-10-31 23:03:18 +00004203 return InsertPt;
Daniel Sandersd66e0902017-10-23 18:19:24 +00004204 }
4205
Florian Hahn6b1db822018-06-14 20:32:58 +00004206 DstMIBuilder.addRenderer<CopyRenderer>(DstChild->getName());
Daniel Sanders7438b262017-10-31 23:03:18 +00004207 return InsertPt;
Daniel Sandersffc7d582017-03-29 15:37:18 +00004208 }
4209
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004210 if (ChildRec->isSubClassOf("SubRegIndex")) {
4211 CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(ChildRec);
4212 DstMIBuilder.addRenderer<ImmRenderer>(SubIdx->EnumValue);
4213 return InsertPt;
4214 }
4215
Daniel Sandersffc7d582017-03-29 15:37:18 +00004216 if (ChildRec->isSubClassOf("ComplexPattern")) {
4217 const auto &ComplexPattern = ComplexPatternEquivs.find(ChildRec);
4218 if (ComplexPattern == ComplexPatternEquivs.end())
4219 return failedImport(
4220 "SelectionDAG ComplexPattern not mapped to GlobalISel");
4221
Florian Hahn6b1db822018-06-14 20:32:58 +00004222 const OperandMatcher &OM = Rule.getOperandMatcher(DstChild->getName());
Daniel Sandersffc7d582017-03-29 15:37:18 +00004223 DstMIBuilder.addRenderer<RenderComplexPatternOperand>(
Florian Hahn6b1db822018-06-14 20:32:58 +00004224 *ComplexPattern->second, DstChild->getName(),
Daniel Sanders2deea182017-04-22 15:11:04 +00004225 OM.getAllocatedTemporariesBaseID());
Daniel Sanders7438b262017-10-31 23:03:18 +00004226 return InsertPt;
Daniel Sandersffc7d582017-03-29 15:37:18 +00004227 }
4228
4229 return failedImport(
4230 "Dst pattern child def is an unsupported tablegen class");
4231 }
4232
4233 return failedImport("Dst pattern child is an unsupported kind");
4234}
4235
Daniel Sandersc270c502017-03-30 09:36:33 +00004236Expected<BuildMIAction &> GlobalISelEmitter::createAndImportInstructionRenderer(
Matt Arsenault3e45c702019-09-06 20:32:37 +00004237 RuleMatcher &M, InstructionMatcher &InsnMatcher, const TreePatternNode *Src,
4238 const TreePatternNode *Dst) {
Daniel Sanders7438b262017-10-31 23:03:18 +00004239 auto InsertPtOrError = createInstructionRenderer(M.actions_end(), M, Dst);
4240 if (auto Error = InsertPtOrError.takeError())
Bill Wendlingc55cf4a2020-02-10 07:06:45 -08004241 return std::move(Error);
Daniel Sandersdf258e32017-10-31 19:09:29 +00004242
Daniel Sanders7438b262017-10-31 23:03:18 +00004243 action_iterator InsertPt = InsertPtOrError.get();
4244 BuildMIAction &DstMIBuilder = *static_cast<BuildMIAction *>(InsertPt->get());
Daniel Sandersdf258e32017-10-31 19:09:29 +00004245
Matt Arsenault3e45c702019-09-06 20:32:37 +00004246 for (auto PhysInput : InsnMatcher.getPhysRegInputs()) {
4247 InsertPt = M.insertAction<BuildMIAction>(
4248 InsertPt, M.allocateOutputInsnID(),
4249 &Target.getInstruction(RK.getDef("COPY")));
4250 BuildMIAction &CopyToPhysRegMIBuilder =
4251 *static_cast<BuildMIAction *>(InsertPt->get());
4252 CopyToPhysRegMIBuilder.addRenderer<AddRegisterRenderer>(PhysInput.first,
4253 true);
4254 CopyToPhysRegMIBuilder.addRenderer<CopyPhysRegRenderer>(PhysInput.first);
4255 }
4256
Matt Arsenaultee3feef2020-07-13 08:59:38 -04004257 if (auto Error = importExplicitDefRenderers(InsertPt, M, DstMIBuilder, Dst)
4258 .takeError())
4259 return std::move(Error);
Daniel Sandersdf258e32017-10-31 19:09:29 +00004260
Daniel Sanders7438b262017-10-31 23:03:18 +00004261 if (auto Error = importExplicitUseRenderers(InsertPt, M, DstMIBuilder, Dst)
4262 .takeError())
Bill Wendlingc55cf4a2020-02-10 07:06:45 -08004263 return std::move(Error);
Daniel Sandersdf258e32017-10-31 19:09:29 +00004264
4265 return DstMIBuilder;
4266}
4267
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00004268Expected<action_iterator>
4269GlobalISelEmitter::createAndImportSubInstructionRenderer(
Florian Hahn6b1db822018-06-14 20:32:58 +00004270 const action_iterator InsertPt, RuleMatcher &M, const TreePatternNode *Dst,
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00004271 unsigned TempRegID) {
4272 auto InsertPtOrError = createInstructionRenderer(InsertPt, M, Dst);
4273
4274 // TODO: Assert there's exactly one result.
4275
4276 if (auto Error = InsertPtOrError.takeError())
Bill Wendlingc55cf4a2020-02-10 07:06:45 -08004277 return std::move(Error);
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00004278
4279 BuildMIAction &DstMIBuilder =
4280 *static_cast<BuildMIAction *>(InsertPtOrError.get()->get());
4281
4282 // Assign the result to TempReg.
4283 DstMIBuilder.addRenderer<TempRegRenderer>(TempRegID, true);
4284
Daniel Sanders08464522018-01-29 21:09:12 +00004285 InsertPtOrError =
4286 importExplicitUseRenderers(InsertPtOrError.get(), M, DstMIBuilder, Dst);
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00004287 if (auto Error = InsertPtOrError.takeError())
Bill Wendlingc55cf4a2020-02-10 07:06:45 -08004288 return std::move(Error);
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00004289
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004290 // We need to make sure that when we import an INSERT_SUBREG as a
4291 // subinstruction that it ends up being constrained to the correct super
4292 // register and subregister classes.
Matt Arsenault38fb3442019-09-04 16:19:34 +00004293 auto OpName = Target.getInstruction(Dst->getOperator()).TheDef->getName();
4294 if (OpName == "INSERT_SUBREG") {
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004295 auto SubClass = inferRegClassFromPattern(Dst->getChild(1));
4296 if (!SubClass)
4297 return failedImport(
4298 "Cannot infer register class from INSERT_SUBREG operand #1");
Jessica Paquette7080ffa2019-08-28 20:12:31 +00004299 Optional<const CodeGenRegisterClass *> SuperClass =
4300 inferSuperRegisterClassForNode(Dst->getExtType(0), Dst->getChild(0),
4301 Dst->getChild(2));
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004302 if (!SuperClass)
4303 return failedImport(
4304 "Cannot infer register class for INSERT_SUBREG operand #0");
4305 // The destination and the super register source of an INSERT_SUBREG must
4306 // be the same register class.
4307 M.insertAction<ConstrainOperandToRegClassAction>(
4308 InsertPt, DstMIBuilder.getInsnID(), 0, **SuperClass);
4309 M.insertAction<ConstrainOperandToRegClassAction>(
4310 InsertPt, DstMIBuilder.getInsnID(), 1, **SuperClass);
4311 M.insertAction<ConstrainOperandToRegClassAction>(
4312 InsertPt, DstMIBuilder.getInsnID(), 2, **SubClass);
4313 return InsertPtOrError.get();
4314 }
4315
Matt Arsenault9ceb6ed2019-09-06 00:05:58 +00004316 if (OpName == "EXTRACT_SUBREG") {
4317 // EXTRACT_SUBREG selects into a subregister COPY but unlike most
4318 // instructions, the result register class is controlled by the
4319 // subregisters of the operand. As a result, we must constrain the result
4320 // class rather than check that it's already the right one.
4321 auto SuperClass = inferRegClassFromPattern(Dst->getChild(0));
4322 if (!SuperClass)
4323 return failedImport(
4324 "Cannot infer register class from EXTRACT_SUBREG operand #0");
4325
4326 auto SubIdx = inferSubRegIndexForNode(Dst->getChild(1));
4327 if (!SubIdx)
4328 return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
4329
Matt Arsenaulteafa8db2020-01-14 14:09:06 -05004330 const auto SrcRCDstRCPair =
Matt Arsenault9ceb6ed2019-09-06 00:05:58 +00004331 (*SuperClass)->getMatchingSubClassWithSubRegs(CGRegs, *SubIdx);
4332 assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
4333 M.insertAction<ConstrainOperandToRegClassAction>(
4334 InsertPt, DstMIBuilder.getInsnID(), 0, *SrcRCDstRCPair->second);
4335 M.insertAction<ConstrainOperandToRegClassAction>(
4336 InsertPt, DstMIBuilder.getInsnID(), 1, *SrcRCDstRCPair->first);
4337
4338 // We're done with this pattern! It's eligible for GISel emission; return
4339 // it.
4340 return InsertPtOrError.get();
4341 }
4342
Jessica Paquette7080ffa2019-08-28 20:12:31 +00004343 // Similar to INSERT_SUBREG, we also have to handle SUBREG_TO_REG as a
4344 // subinstruction.
Matt Arsenault38fb3442019-09-04 16:19:34 +00004345 if (OpName == "SUBREG_TO_REG") {
4346 auto SubClass = inferRegClassFromPattern(Dst->getChild(1));
4347 if (!SubClass)
4348 return failedImport(
Jessica Paquette7080ffa2019-08-28 20:12:31 +00004349 "Cannot infer register class from SUBREG_TO_REG child #1");
Matt Arsenault38fb3442019-09-04 16:19:34 +00004350 auto SuperClass = inferSuperRegisterClass(Dst->getExtType(0),
4351 Dst->getChild(2));
4352 if (!SuperClass)
4353 return failedImport(
Jessica Paquette7080ffa2019-08-28 20:12:31 +00004354 "Cannot infer register class for SUBREG_TO_REG operand #0");
Matt Arsenault38fb3442019-09-04 16:19:34 +00004355 M.insertAction<ConstrainOperandToRegClassAction>(
Jessica Paquette7080ffa2019-08-28 20:12:31 +00004356 InsertPt, DstMIBuilder.getInsnID(), 0, **SuperClass);
Matt Arsenault38fb3442019-09-04 16:19:34 +00004357 M.insertAction<ConstrainOperandToRegClassAction>(
Jessica Paquette7080ffa2019-08-28 20:12:31 +00004358 InsertPt, DstMIBuilder.getInsnID(), 2, **SubClass);
Matt Arsenault38fb3442019-09-04 16:19:34 +00004359 return InsertPtOrError.get();
4360 }
Jessica Paquette7080ffa2019-08-28 20:12:31 +00004361
Matt Arsenaultcb5dc372020-04-07 09:32:51 -04004362 if (OpName == "REG_SEQUENCE") {
4363 auto SuperClass = inferRegClassFromPattern(Dst->getChild(0));
4364 M.insertAction<ConstrainOperandToRegClassAction>(
4365 InsertPt, DstMIBuilder.getInsnID(), 0, **SuperClass);
4366
4367 unsigned Num = Dst->getNumChildren();
4368 for (unsigned I = 1; I != Num; I += 2) {
4369 TreePatternNode *SubRegChild = Dst->getChild(I + 1);
4370
4371 auto SubIdx = inferSubRegIndexForNode(SubRegChild);
4372 if (!SubIdx)
4373 return failedImport("REG_SEQUENCE child is not a subreg index");
4374
4375 const auto SrcRCDstRCPair =
4376 (*SuperClass)->getMatchingSubClassWithSubRegs(CGRegs, *SubIdx);
4377 assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
4378 M.insertAction<ConstrainOperandToRegClassAction>(
4379 InsertPt, DstMIBuilder.getInsnID(), I, *SrcRCDstRCPair->second);
4380 }
4381
4382 return InsertPtOrError.get();
4383 }
4384
Daniel Sanders08464522018-01-29 21:09:12 +00004385 M.insertAction<ConstrainOperandsToDefinitionAction>(InsertPt,
4386 DstMIBuilder.getInsnID());
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00004387 return InsertPtOrError.get();
4388}
4389
Daniel Sanders7438b262017-10-31 23:03:18 +00004390Expected<action_iterator> GlobalISelEmitter::createInstructionRenderer(
Florian Hahn6b1db822018-06-14 20:32:58 +00004391 action_iterator InsertPt, RuleMatcher &M, const TreePatternNode *Dst) {
4392 Record *DstOp = Dst->getOperator();
Daniel Sandersd0656a32017-04-13 09:45:37 +00004393 if (!DstOp->isSubClassOf("Instruction")) {
4394 if (DstOp->isSubClassOf("ValueType"))
4395 return failedImport(
4396 "Pattern operator isn't an instruction (it's a ValueType)");
Daniel Sandersffc7d582017-03-29 15:37:18 +00004397 return failedImport("Pattern operator isn't an instruction");
Daniel Sandersd0656a32017-04-13 09:45:37 +00004398 }
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004399 CodeGenInstruction *DstI = &Target.getInstruction(DstOp);
Daniel Sandersffc7d582017-03-29 15:37:18 +00004400
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004401 // COPY_TO_REGCLASS is just a copy with a ConstrainOperandToRegClassAction
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004402 // attached. Similarly for EXTRACT_SUBREG except that's a subregister copy.
Matt Arsenault4a23ae52019-09-10 17:57:33 +00004403 StringRef Name = DstI->TheDef->getName();
4404 if (Name == "COPY_TO_REGCLASS" || Name == "EXTRACT_SUBREG")
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004405 DstI = &Target.getInstruction(RK.getDef("COPY"));
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004406
Daniel Sanders198447a2017-11-01 00:29:47 +00004407 return M.insertAction<BuildMIAction>(InsertPt, M.allocateOutputInsnID(),
4408 DstI);
Daniel Sandersdf258e32017-10-31 19:09:29 +00004409}
4410
Matt Arsenaultee3feef2020-07-13 08:59:38 -04004411Expected<action_iterator> GlobalISelEmitter::importExplicitDefRenderers(
4412 action_iterator InsertPt, RuleMatcher &M, BuildMIAction &DstMIBuilder,
4413 const TreePatternNode *Dst) {
Daniel Sandersdf258e32017-10-31 19:09:29 +00004414 const CodeGenInstruction *DstI = DstMIBuilder.getCGI();
Matt Arsenaultee3feef2020-07-13 08:59:38 -04004415 const unsigned NumDefs = DstI->Operands.NumDefs;
4416 if (NumDefs == 0)
4417 return InsertPt;
4418
4419 DstMIBuilder.addRenderer<CopyRenderer>(DstI->Operands[0].Name);
4420
Matt Arsenault930fc0b2020-07-27 20:29:53 -04004421 // Some instructions have multiple defs, but are missing a type entry
4422 // (e.g. s_cc_out operands).
4423 if (Dst->getExtTypes().size() < NumDefs)
4424 return failedImport("unhandled discarded def");
4425
Matt Arsenaultee3feef2020-07-13 08:59:38 -04004426 // Patterns only handle a single result, so any result after the first is an
4427 // implicitly dead def.
4428 for (unsigned I = 1; I < NumDefs; ++I) {
4429 const TypeSetByHwMode &ExtTy = Dst->getExtType(I);
4430 if (!ExtTy.isMachineValueType())
4431 return failedImport("unsupported typeset");
4432
4433 auto OpTy = MVTToLLT(ExtTy.getMachineValueType().SimpleTy);
4434 if (!OpTy)
4435 return failedImport("unsupported type");
4436
4437 unsigned TempRegID = M.allocateTempRegID();
4438 InsertPt =
4439 M.insertAction<MakeTempRegisterAction>(InsertPt, *OpTy, TempRegID);
4440 DstMIBuilder.addRenderer<TempRegRenderer>(TempRegID, true, nullptr, true);
Daniel Sandersffc7d582017-03-29 15:37:18 +00004441 }
Matt Arsenaultee3feef2020-07-13 08:59:38 -04004442
4443 return InsertPt;
Daniel Sandersdf258e32017-10-31 19:09:29 +00004444}
4445
Daniel Sanders7438b262017-10-31 23:03:18 +00004446Expected<action_iterator> GlobalISelEmitter::importExplicitUseRenderers(
4447 action_iterator InsertPt, RuleMatcher &M, BuildMIAction &DstMIBuilder,
Florian Hahn6b1db822018-06-14 20:32:58 +00004448 const llvm::TreePatternNode *Dst) {
Daniel Sandersdf258e32017-10-31 19:09:29 +00004449 const CodeGenInstruction *DstI = DstMIBuilder.getCGI();
Florian Hahn6b1db822018-06-14 20:32:58 +00004450 CodeGenInstruction *OrigDstI = &Target.getInstruction(Dst->getOperator());
Daniel Sandersffc7d582017-03-29 15:37:18 +00004451
Matt Arsenault4a23ae52019-09-10 17:57:33 +00004452 StringRef Name = OrigDstI->TheDef->getName();
4453 unsigned ExpectedDstINumUses = Dst->getNumChildren();
4454
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004455 // EXTRACT_SUBREG needs to use a subregister COPY.
Matt Arsenault4a23ae52019-09-10 17:57:33 +00004456 if (Name == "EXTRACT_SUBREG") {
Matt Arsenault9c346462020-01-14 16:02:02 -05004457 DefInit *SubRegInit = dyn_cast<DefInit>(Dst->getChild(1)->getLeafValue());
4458 if (!SubRegInit)
4459 return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004460
Matt Arsenault9c346462020-01-14 16:02:02 -05004461 CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef());
4462 TreePatternNode *ValChild = Dst->getChild(0);
4463 if (!ValChild->isLeaf()) {
4464 // We really have to handle the source instruction, and then insert a
4465 // copy from the subregister.
4466 auto ExtractSrcTy = getInstResultType(ValChild);
4467 if (!ExtractSrcTy)
4468 return ExtractSrcTy.takeError();
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00004469
Matt Arsenault9c346462020-01-14 16:02:02 -05004470 unsigned TempRegID = M.allocateTempRegID();
4471 InsertPt = M.insertAction<MakeTempRegisterAction>(
4472 InsertPt, *ExtractSrcTy, TempRegID);
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004473
Matt Arsenault9c346462020-01-14 16:02:02 -05004474 auto InsertPtOrError = createAndImportSubInstructionRenderer(
4475 ++InsertPt, M, ValChild, TempRegID);
4476 if (auto Error = InsertPtOrError.takeError())
Bill Wendlingc55cf4a2020-02-10 07:06:45 -08004477 return std::move(Error);
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004478
Matt Arsenault9c346462020-01-14 16:02:02 -05004479 DstMIBuilder.addRenderer<TempRegRenderer>(TempRegID, false, SubIdx);
Daniel Sanders7438b262017-10-31 23:03:18 +00004480 return InsertPt;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004481 }
4482
Matt Arsenault9c346462020-01-14 16:02:02 -05004483 // If this is a source operand, this is just a subregister copy.
4484 Record *RCDef = getInitValueAsRegClass(ValChild->getLeafValue());
4485 if (!RCDef)
4486 return failedImport("EXTRACT_SUBREG child #0 could not "
4487 "be coerced to a register class");
4488
4489 CodeGenRegisterClass *RC = CGRegs.getRegClass(RCDef);
4490
4491 const auto SrcRCDstRCPair =
4492 RC->getMatchingSubClassWithSubRegs(CGRegs, SubIdx);
4493 if (SrcRCDstRCPair.hasValue()) {
4494 assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
4495 if (SrcRCDstRCPair->first != RC)
4496 return failedImport("EXTRACT_SUBREG requires an additional COPY");
4497 }
4498
4499 DstMIBuilder.addRenderer<CopySubRegRenderer>(Dst->getChild(0)->getName(),
4500 SubIdx);
4501 return InsertPt;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004502 }
4503
Matt Arsenault4a23ae52019-09-10 17:57:33 +00004504 if (Name == "REG_SEQUENCE") {
4505 if (!Dst->getChild(0)->isLeaf())
4506 return failedImport("REG_SEQUENCE child #0 is not a leaf");
4507
4508 Record *RCDef = getInitValueAsRegClass(Dst->getChild(0)->getLeafValue());
4509 if (!RCDef)
4510 return failedImport("REG_SEQUENCE child #0 could not "
4511 "be coerced to a register class");
4512
4513 if ((ExpectedDstINumUses - 1) % 2 != 0)
4514 return failedImport("Malformed REG_SEQUENCE");
4515
4516 for (unsigned I = 1; I != ExpectedDstINumUses; I += 2) {
4517 TreePatternNode *ValChild = Dst->getChild(I);
4518 TreePatternNode *SubRegChild = Dst->getChild(I + 1);
4519
4520 if (DefInit *SubRegInit =
4521 dyn_cast<DefInit>(SubRegChild->getLeafValue())) {
4522 CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef());
4523
4524 auto InsertPtOrError =
4525 importExplicitUseRenderer(InsertPt, M, DstMIBuilder, ValChild);
4526 if (auto Error = InsertPtOrError.takeError())
Bill Wendlingc55cf4a2020-02-10 07:06:45 -08004527 return std::move(Error);
Matt Arsenault4a23ae52019-09-10 17:57:33 +00004528 InsertPt = InsertPtOrError.get();
4529 DstMIBuilder.addRenderer<SubRegIndexRenderer>(SubIdx);
4530 }
4531 }
4532
4533 return InsertPt;
4534 }
4535
Daniel Sandersffc7d582017-03-29 15:37:18 +00004536 // Render the explicit uses.
Daniel Sandersdf258e32017-10-31 19:09:29 +00004537 unsigned DstINumUses = OrigDstI->Operands.size() - OrigDstI->Operands.NumDefs;
Matt Arsenault4a23ae52019-09-10 17:57:33 +00004538 if (Name == "COPY_TO_REGCLASS") {
Daniel Sandersdf258e32017-10-31 19:09:29 +00004539 DstINumUses--; // Ignore the class constraint.
4540 ExpectedDstINumUses--;
4541 }
4542
Matt Arsenault26f714f2019-10-21 21:39:42 -07004543 // NumResults - This is the number of results produced by the instruction in
4544 // the "outs" list.
4545 unsigned NumResults = OrigDstI->Operands.NumDefs;
4546
4547 // Number of operands we know the output instruction must have. If it is
4548 // variadic, we could have more operands.
4549 unsigned NumFixedOperands = DstI->Operands.size();
4550
4551 // Loop over all of the fixed operands of the instruction pattern, emitting
4552 // code to fill them all in. The node 'N' usually has number children equal to
4553 // the number of input operands of the instruction. However, in cases where
4554 // there are predicate operands for an instruction, we need to fill in the
4555 // 'execute always' values. Match up the node operands to the instruction
4556 // operands to do this.
Daniel Sanders0ed28822017-04-12 08:23:08 +00004557 unsigned Child = 0;
Matt Arsenault26f714f2019-10-21 21:39:42 -07004558
4559 // Similarly to the code in TreePatternNode::ApplyTypeConstraints, count the
4560 // number of operands at the end of the list which have default values.
4561 // Those can come from the pattern if it provides enough arguments, or be
4562 // filled in with the default if the pattern hasn't provided them. But any
4563 // operand with a default value _before_ the last mandatory one will be
4564 // filled in with their defaults unconditionally.
4565 unsigned NonOverridableOperands = NumFixedOperands;
4566 while (NonOverridableOperands > NumResults &&
4567 CGP.operandHasDefault(DstI->Operands[NonOverridableOperands - 1].Rec))
4568 --NonOverridableOperands;
4569
Diana Picus382602f2017-05-17 08:57:28 +00004570 unsigned NumDefaultOps = 0;
Daniel Sanders0ed28822017-04-12 08:23:08 +00004571 for (unsigned I = 0; I != DstINumUses; ++I) {
Matt Arsenault26f714f2019-10-21 21:39:42 -07004572 unsigned InstOpNo = DstI->Operands.NumDefs + I;
4573
4574 // Determine what to emit for this operand.
4575 Record *OperandNode = DstI->Operands[InstOpNo].Rec;
Daniel Sanders0ed28822017-04-12 08:23:08 +00004576
Diana Picus382602f2017-05-17 08:57:28 +00004577 // If the operand has default values, introduce them now.
Matt Arsenault26f714f2019-10-21 21:39:42 -07004578 if (CGP.operandHasDefault(OperandNode) &&
4579 (InstOpNo < NonOverridableOperands || Child >= Dst->getNumChildren())) {
4580 // This is a predicate or optional def operand which the pattern has not
4581 // overridden, or which we aren't letting it override; emit the 'default
4582 // ops' operands.
4583
4584 const CGIOperandList::OperandInfo &DstIOperand = DstI->Operands[InstOpNo];
Daniel Sanders0ed28822017-04-12 08:23:08 +00004585 DagInit *DefaultOps = DstIOperand.Rec->getValueAsDag("DefaultOps");
Sjoerd Meijerde234842019-05-30 07:30:37 +00004586 if (auto Error = importDefaultOperandRenderers(
4587 InsertPt, M, DstMIBuilder, DefaultOps))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -08004588 return std::move(Error);
Diana Picus382602f2017-05-17 08:57:28 +00004589 ++NumDefaultOps;
Daniel Sanders0ed28822017-04-12 08:23:08 +00004590 continue;
4591 }
4592
Daniel Sanders7438b262017-10-31 23:03:18 +00004593 auto InsertPtOrError = importExplicitUseRenderer(InsertPt, M, DstMIBuilder,
Florian Hahn6b1db822018-06-14 20:32:58 +00004594 Dst->getChild(Child));
Daniel Sanders7438b262017-10-31 23:03:18 +00004595 if (auto Error = InsertPtOrError.takeError())
Bill Wendlingc55cf4a2020-02-10 07:06:45 -08004596 return std::move(Error);
Daniel Sanders7438b262017-10-31 23:03:18 +00004597 InsertPt = InsertPtOrError.get();
Daniel Sanders0ed28822017-04-12 08:23:08 +00004598 ++Child;
Daniel Sandersffc7d582017-03-29 15:37:18 +00004599 }
4600
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004601 if (NumDefaultOps + ExpectedDstINumUses != DstINumUses)
Diana Picuseb2057c2017-05-17 09:25:08 +00004602 return failedImport("Expected " + llvm::to_string(DstINumUses) +
Diana Picus382602f2017-05-17 08:57:28 +00004603 " used operands but found " +
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004604 llvm::to_string(ExpectedDstINumUses) +
Diana Picuseb2057c2017-05-17 09:25:08 +00004605 " explicit ones and " + llvm::to_string(NumDefaultOps) +
Diana Picus382602f2017-05-17 08:57:28 +00004606 " default ones");
4607
Daniel Sanders7438b262017-10-31 23:03:18 +00004608 return InsertPt;
Daniel Sandersffc7d582017-03-29 15:37:18 +00004609}
4610
Diana Picus382602f2017-05-17 08:57:28 +00004611Error GlobalISelEmitter::importDefaultOperandRenderers(
Sjoerd Meijerde234842019-05-30 07:30:37 +00004612 action_iterator InsertPt, RuleMatcher &M, BuildMIAction &DstMIBuilder,
4613 DagInit *DefaultOps) const {
Craig Topper481ff702017-05-29 21:49:34 +00004614 for (const auto *DefaultOp : DefaultOps->getArgs()) {
Sjoerd Meijerde234842019-05-30 07:30:37 +00004615 Optional<LLTCodeGen> OpTyOrNone = None;
4616
Diana Picus382602f2017-05-17 08:57:28 +00004617 // Look through ValueType operators.
4618 if (const DagInit *DefaultDagOp = dyn_cast<DagInit>(DefaultOp)) {
4619 if (const DefInit *DefaultDagOperator =
4620 dyn_cast<DefInit>(DefaultDagOp->getOperator())) {
Sjoerd Meijer3cac8d22019-05-31 08:39:34 +00004621 if (DefaultDagOperator->getDef()->isSubClassOf("ValueType")) {
Sjoerd Meijerde234842019-05-30 07:30:37 +00004622 OpTyOrNone = MVTToLLT(getValueType(
4623 DefaultDagOperator->getDef()));
Diana Picus382602f2017-05-17 08:57:28 +00004624 DefaultOp = DefaultDagOp->getArg(0);
Sjoerd Meijer3cac8d22019-05-31 08:39:34 +00004625 }
Diana Picus382602f2017-05-17 08:57:28 +00004626 }
4627 }
4628
4629 if (const DefInit *DefaultDefOp = dyn_cast<DefInit>(DefaultOp)) {
Sjoerd Meijerde234842019-05-30 07:30:37 +00004630 auto Def = DefaultDefOp->getDef();
4631 if (Def->getName() == "undef_tied_input") {
4632 unsigned TempRegID = M.allocateTempRegID();
4633 M.insertAction<MakeTempRegisterAction>(
4634 InsertPt, OpTyOrNone.getValue(), TempRegID);
4635 InsertPt = M.insertAction<BuildMIAction>(
4636 InsertPt, M.allocateOutputInsnID(),
4637 &Target.getInstruction(RK.getDef("IMPLICIT_DEF")));
4638 BuildMIAction &IDMIBuilder = *static_cast<BuildMIAction *>(
4639 InsertPt->get());
4640 IDMIBuilder.addRenderer<TempRegRenderer>(TempRegID);
4641 DstMIBuilder.addRenderer<TempRegRenderer>(TempRegID);
4642 } else {
4643 DstMIBuilder.addRenderer<AddRegisterRenderer>(Def);
4644 }
Diana Picus382602f2017-05-17 08:57:28 +00004645 continue;
4646 }
4647
4648 if (const IntInit *DefaultIntOp = dyn_cast<IntInit>(DefaultOp)) {
Daniel Sanders198447a2017-11-01 00:29:47 +00004649 DstMIBuilder.addRenderer<ImmRenderer>(DefaultIntOp->getValue());
Diana Picus382602f2017-05-17 08:57:28 +00004650 continue;
4651 }
4652
4653 return failedImport("Could not add default op");
4654 }
4655
4656 return Error::success();
4657}
4658
Daniel Sandersc270c502017-03-30 09:36:33 +00004659Error GlobalISelEmitter::importImplicitDefRenderers(
Daniel Sandersffc7d582017-03-29 15:37:18 +00004660 BuildMIAction &DstMIBuilder,
4661 const std::vector<Record *> &ImplicitDefs) const {
4662 if (!ImplicitDefs.empty())
4663 return failedImport("Pattern defines a physical register");
Daniel Sandersc270c502017-03-30 09:36:33 +00004664 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00004665}
4666
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004667Optional<const CodeGenRegisterClass *>
4668GlobalISelEmitter::getRegClassFromLeaf(TreePatternNode *Leaf) {
4669 assert(Leaf && "Expected node?");
4670 assert(Leaf->isLeaf() && "Expected leaf?");
4671 Record *RCRec = getInitValueAsRegClass(Leaf->getLeafValue());
4672 if (!RCRec)
4673 return None;
4674 CodeGenRegisterClass *RC = CGRegs.getRegClass(RCRec);
4675 if (!RC)
4676 return None;
4677 return RC;
4678}
4679
4680Optional<const CodeGenRegisterClass *>
4681GlobalISelEmitter::inferRegClassFromPattern(TreePatternNode *N) {
4682 if (!N)
4683 return None;
4684
4685 if (N->isLeaf())
4686 return getRegClassFromLeaf(N);
4687
4688 // We don't have a leaf node, so we have to try and infer something. Check
4689 // that we have an instruction that we an infer something from.
4690
4691 // Only handle things that produce a single type.
4692 if (N->getNumTypes() != 1)
4693 return None;
4694 Record *OpRec = N->getOperator();
4695
4696 // We only want instructions.
4697 if (!OpRec->isSubClassOf("Instruction"))
4698 return None;
4699
4700 // Don't want to try and infer things when there could potentially be more
4701 // than one candidate register class.
4702 auto &Inst = Target.getInstruction(OpRec);
4703 if (Inst.Operands.NumDefs > 1)
4704 return None;
4705
4706 // Handle any special-case instructions which we can safely infer register
4707 // classes from.
4708 StringRef InstName = Inst.TheDef->getName();
Matt Arsenault38fb3442019-09-04 16:19:34 +00004709 bool IsRegSequence = InstName == "REG_SEQUENCE";
4710 if (IsRegSequence || InstName == "COPY_TO_REGCLASS") {
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004711 // If we have a COPY_TO_REGCLASS, then we need to handle it specially. It
4712 // has the desired register class as the first child.
Matt Arsenault38fb3442019-09-04 16:19:34 +00004713 TreePatternNode *RCChild = N->getChild(IsRegSequence ? 0 : 1);
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004714 if (!RCChild->isLeaf())
4715 return None;
4716 return getRegClassFromLeaf(RCChild);
4717 }
4718
4719 // Handle destination record types that we can safely infer a register class
4720 // from.
4721 const auto &DstIOperand = Inst.Operands[0];
4722 Record *DstIOpRec = DstIOperand.Rec;
4723 if (DstIOpRec->isSubClassOf("RegisterOperand")) {
4724 DstIOpRec = DstIOpRec->getValueAsDef("RegClass");
4725 const CodeGenRegisterClass &RC = Target.getRegisterClass(DstIOpRec);
4726 return &RC;
4727 }
4728
4729 if (DstIOpRec->isSubClassOf("RegisterClass")) {
4730 const CodeGenRegisterClass &RC = Target.getRegisterClass(DstIOpRec);
4731 return &RC;
4732 }
4733
4734 return None;
4735}
4736
4737Optional<const CodeGenRegisterClass *>
4738GlobalISelEmitter::inferSuperRegisterClass(const TypeSetByHwMode &Ty,
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004739 TreePatternNode *SubRegIdxNode) {
Jessica Paquette7080ffa2019-08-28 20:12:31 +00004740 assert(SubRegIdxNode && "Expected subregister index node!");
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004741 // We need a ValueTypeByHwMode for getSuperRegForSubReg.
4742 if (!Ty.isValueTypeByHwMode(false))
4743 return None;
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004744 if (!SubRegIdxNode->isLeaf())
4745 return None;
4746 DefInit *SubRegInit = dyn_cast<DefInit>(SubRegIdxNode->getLeafValue());
4747 if (!SubRegInit)
4748 return None;
4749 CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef());
4750
4751 // Use the information we found above to find a minimal register class which
4752 // supports the subregister and type we want.
4753 auto RC =
4754 Target.getSuperRegForSubReg(Ty.getValueTypeByHwMode(), CGRegs, SubIdx);
4755 if (!RC)
4756 return None;
4757 return *RC;
4758}
4759
Jessica Paquette7080ffa2019-08-28 20:12:31 +00004760Optional<const CodeGenRegisterClass *>
4761GlobalISelEmitter::inferSuperRegisterClassForNode(
4762 const TypeSetByHwMode &Ty, TreePatternNode *SuperRegNode,
4763 TreePatternNode *SubRegIdxNode) {
4764 assert(SuperRegNode && "Expected super register node!");
4765 // Check if we already have a defined register class for the super register
4766 // node. If we do, then we should preserve that rather than inferring anything
4767 // from the subregister index node. We can assume that whoever wrote the
4768 // pattern in the first place made sure that the super register and
4769 // subregister are compatible.
4770 if (Optional<const CodeGenRegisterClass *> SuperRegisterClass =
4771 inferRegClassFromPattern(SuperRegNode))
4772 return *SuperRegisterClass;
4773 return inferSuperRegisterClass(Ty, SubRegIdxNode);
4774}
4775
Matt Arsenault9ceb6ed2019-09-06 00:05:58 +00004776Optional<CodeGenSubRegIndex *>
4777GlobalISelEmitter::inferSubRegIndexForNode(TreePatternNode *SubRegIdxNode) {
4778 if (!SubRegIdxNode->isLeaf())
4779 return None;
4780
4781 DefInit *SubRegInit = dyn_cast<DefInit>(SubRegIdxNode->getLeafValue());
4782 if (!SubRegInit)
4783 return None;
4784 return CGRegs.getSubRegIdx(SubRegInit->getDef());
4785}
4786
Daniel Sandersffc7d582017-03-29 15:37:18 +00004787Expected<RuleMatcher> GlobalISelEmitter::runOnPattern(const PatternToMatch &P) {
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004788 // Keep track of the matchers and actions to emit.
Aditya Nandakumarb63e7632018-02-16 22:37:15 +00004789 int Score = P.getPatternComplexity(CGP);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00004790 RuleMatcher M(P.getSrcRecord()->getLoc());
Aditya Nandakumarb63e7632018-02-16 22:37:15 +00004791 RuleMatcherScores[M.getRuleID()] = Score;
Daniel Sanders6ea17ed2017-10-31 18:07:03 +00004792 M.addAction<DebugCommentAction>(llvm::to_string(*P.getSrcPattern()) +
4793 " => " +
4794 llvm::to_string(*P.getDstPattern()));
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004795
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004796 if (auto Error = importRulePredicates(M, P.getPredicates()))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -08004797 return std::move(Error);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004798
4799 // Next, analyze the pattern operators.
Florian Hahn6b1db822018-06-14 20:32:58 +00004800 TreePatternNode *Src = P.getSrcPattern();
4801 TreePatternNode *Dst = P.getDstPattern();
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004802
4803 // If the root of either pattern isn't a simple operator, ignore it.
Daniel Sandersd0656a32017-04-13 09:45:37 +00004804 if (auto Err = isTrivialOperatorNode(Dst))
4805 return failedImport("Dst pattern root isn't a trivial operator (" +
4806 toString(std::move(Err)) + ")");
4807 if (auto Err = isTrivialOperatorNode(Src))
4808 return failedImport("Src pattern root isn't a trivial operator (" +
4809 toString(std::move(Err)) + ")");
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004810
Quentin Colombetaad20be2017-12-15 23:07:42 +00004811 // The different predicates and matchers created during
4812 // addInstructionMatcher use the RuleMatcher M to set up their
4813 // instruction ID (InsnVarID) that are going to be used when
4814 // M is going to be emitted.
4815 // However, the code doing the emission still relies on the IDs
4816 // returned during that process by the RuleMatcher when issuing
4817 // the recordInsn opcodes.
4818 // Because of that:
4819 // 1. The order in which we created the predicates
4820 // and such must be the same as the order in which we emit them,
4821 // and
4822 // 2. We need to reset the generation of the IDs in M somewhere between
4823 // addInstructionMatcher and emit
4824 //
4825 // FIXME: Long term, we don't want to have to rely on this implicit
4826 // naming being the same. One possible solution would be to have
4827 // explicit operator for operation capture and reference those.
4828 // The plus side is that it would expose opportunities to share
4829 // the capture accross rules. The downside is that it would
4830 // introduce a dependency between predicates (captures must happen
4831 // before their first use.)
Florian Hahn6b1db822018-06-14 20:32:58 +00004832 InstructionMatcher &InsnMatcherTemp = M.addInstructionMatcher(Src->getName());
Daniel Sandersedd07842017-08-17 09:26:14 +00004833 unsigned TempOpIdx = 0;
4834 auto InsnMatcherOrError =
Daniel Sandersdf39cba2017-10-15 18:22:54 +00004835 createAndImportSelDAGMatcher(M, InsnMatcherTemp, Src, TempOpIdx);
Daniel Sandersedd07842017-08-17 09:26:14 +00004836 if (auto Error = InsnMatcherOrError.takeError())
Bill Wendlingc55cf4a2020-02-10 07:06:45 -08004837 return std::move(Error);
Daniel Sandersedd07842017-08-17 09:26:14 +00004838 InstructionMatcher &InsnMatcher = InsnMatcherOrError.get();
4839
Florian Hahn6b1db822018-06-14 20:32:58 +00004840 if (Dst->isLeaf()) {
4841 Record *RCDef = getInitValueAsRegClass(Dst->getLeafValue());
Daniel Sandersedd07842017-08-17 09:26:14 +00004842
4843 const CodeGenRegisterClass &RC = Target.getRegisterClass(RCDef);
4844 if (RCDef) {
4845 // We need to replace the def and all its uses with the specified
4846 // operand. However, we must also insert COPY's wherever needed.
4847 // For now, emit a copy and let the register allocator clean up.
4848 auto &DstI = Target.getInstruction(RK.getDef("COPY"));
4849 const auto &DstIOperand = DstI.Operands[0];
4850
4851 OperandMatcher &OM0 = InsnMatcher.getOperand(0);
4852 OM0.setSymbolicName(DstIOperand.Name);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00004853 M.defineOperand(OM0.getSymbolicName(), OM0);
Daniel Sandersedd07842017-08-17 09:26:14 +00004854 OM0.addPredicate<RegisterBankOperandMatcher>(RC);
4855
Daniel Sanders198447a2017-11-01 00:29:47 +00004856 auto &DstMIBuilder =
4857 M.addAction<BuildMIAction>(M.allocateOutputInsnID(), &DstI);
4858 DstMIBuilder.addRenderer<CopyRenderer>(DstIOperand.Name);
Florian Hahn6b1db822018-06-14 20:32:58 +00004859 DstMIBuilder.addRenderer<CopyRenderer>(Dst->getName());
Daniel Sandersedd07842017-08-17 09:26:14 +00004860 M.addAction<ConstrainOperandToRegClassAction>(0, 0, RC);
4861
4862 // We're done with this pattern! It's eligible for GISel emission; return
4863 // it.
4864 ++NumPatternImported;
Bill Wendlingc55cf4a2020-02-10 07:06:45 -08004865 return std::move(M);
Daniel Sandersedd07842017-08-17 09:26:14 +00004866 }
4867
Daniel Sanders452c8ae2017-05-23 19:33:16 +00004868 return failedImport("Dst pattern root isn't a known leaf");
Daniel Sandersedd07842017-08-17 09:26:14 +00004869 }
Daniel Sanders452c8ae2017-05-23 19:33:16 +00004870
Daniel Sandersbee57392017-04-04 13:25:23 +00004871 // Start with the defined operands (i.e., the results of the root operator).
Florian Hahn6b1db822018-06-14 20:32:58 +00004872 Record *DstOp = Dst->getOperator();
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004873 if (!DstOp->isSubClassOf("Instruction"))
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00004874 return failedImport("Pattern operator isn't an instruction");
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004875
4876 auto &DstI = Target.getInstruction(DstOp);
Matt Arsenault38fb3442019-09-04 16:19:34 +00004877 StringRef DstIName = DstI.TheDef->getName();
4878
Matt Arsenaultee3feef2020-07-13 08:59:38 -04004879 if (DstI.Operands.NumDefs < Src->getExtTypes().size())
4880 return failedImport("Src pattern result has more defs than dst MI (" +
Florian Hahn6b1db822018-06-14 20:32:58 +00004881 to_string(Src->getExtTypes().size()) + " def(s) vs " +
Daniel Sandersd0656a32017-04-13 09:45:37 +00004882 to_string(DstI.Operands.NumDefs) + " def(s))");
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004883
Daniel Sandersffc7d582017-03-29 15:37:18 +00004884 // The root of the match also has constraints on the register bank so that it
4885 // matches the result instruction.
4886 unsigned OpIdx = 0;
Florian Hahn6b1db822018-06-14 20:32:58 +00004887 for (const TypeSetByHwMode &VTy : Src->getExtTypes()) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004888 (void)VTy;
Daniel Sandersffc7d582017-03-29 15:37:18 +00004889
Daniel Sanders066ebbf2017-02-24 15:43:30 +00004890 const auto &DstIOperand = DstI.Operands[OpIdx];
4891 Record *DstIOpRec = DstIOperand.Rec;
Matt Arsenault38fb3442019-09-04 16:19:34 +00004892 if (DstIName == "COPY_TO_REGCLASS") {
Florian Hahn6b1db822018-06-14 20:32:58 +00004893 DstIOpRec = getInitValueAsRegClass(Dst->getChild(1)->getLeafValue());
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004894
4895 if (DstIOpRec == nullptr)
4896 return failedImport(
4897 "COPY_TO_REGCLASS operand #1 isn't a register class");
Matt Arsenault38fb3442019-09-04 16:19:34 +00004898 } else if (DstIName == "REG_SEQUENCE") {
4899 DstIOpRec = getInitValueAsRegClass(Dst->getChild(0)->getLeafValue());
4900 if (DstIOpRec == nullptr)
4901 return failedImport("REG_SEQUENCE operand #0 isn't a register class");
4902 } else if (DstIName == "EXTRACT_SUBREG") {
Matt Arsenault9c346462020-01-14 16:02:02 -05004903 auto InferredClass = inferRegClassFromPattern(Dst->getChild(0));
4904 if (!InferredClass)
4905 return failedImport("Could not infer class for EXTRACT_SUBREG operand #0");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004906
Daniel Sanders32291982017-06-28 13:50:04 +00004907 // We can assume that a subregister is in the same bank as it's super
4908 // register.
Matt Arsenault9c346462020-01-14 16:02:02 -05004909 DstIOpRec = (*InferredClass)->getDef();
Matt Arsenault38fb3442019-09-04 16:19:34 +00004910 } else if (DstIName == "INSERT_SUBREG") {
Jessica Paquette7080ffa2019-08-28 20:12:31 +00004911 auto MaybeSuperClass = inferSuperRegisterClassForNode(
4912 VTy, Dst->getChild(0), Dst->getChild(2));
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004913 if (!MaybeSuperClass)
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004914 return failedImport(
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004915 "Cannot infer register class for INSERT_SUBREG operand #0");
4916 // Move to the next pattern here, because the register class we found
4917 // doesn't necessarily have a record associated with it. So, we can't
4918 // set DstIOpRec using this.
4919 OperandMatcher &OM = InsnMatcher.getOperand(OpIdx);
4920 OM.setSymbolicName(DstIOperand.Name);
4921 M.defineOperand(OM.getSymbolicName(), OM);
4922 OM.addPredicate<RegisterBankOperandMatcher>(**MaybeSuperClass);
4923 ++OpIdx;
4924 continue;
Matt Arsenault38fb3442019-09-04 16:19:34 +00004925 } else if (DstIName == "SUBREG_TO_REG") {
Jessica Paquette7080ffa2019-08-28 20:12:31 +00004926 auto MaybeRegClass = inferSuperRegisterClass(VTy, Dst->getChild(2));
4927 if (!MaybeRegClass)
4928 return failedImport(
4929 "Cannot infer register class for SUBREG_TO_REG operand #0");
4930 OperandMatcher &OM = InsnMatcher.getOperand(OpIdx);
4931 OM.setSymbolicName(DstIOperand.Name);
4932 M.defineOperand(OM.getSymbolicName(), OM);
4933 OM.addPredicate<RegisterBankOperandMatcher>(**MaybeRegClass);
4934 ++OpIdx;
4935 continue;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004936 } else if (DstIOpRec->isSubClassOf("RegisterOperand"))
Daniel Sanders658541f2017-04-22 15:53:21 +00004937 DstIOpRec = DstIOpRec->getValueAsDef("RegClass");
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004938 else if (!DstIOpRec->isSubClassOf("RegisterClass"))
Florian Hahn6b1db822018-06-14 20:32:58 +00004939 return failedImport("Dst MI def isn't a register class" +
4940 to_string(*Dst));
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004941
Daniel Sandersffc7d582017-03-29 15:37:18 +00004942 OperandMatcher &OM = InsnMatcher.getOperand(OpIdx);
4943 OM.setSymbolicName(DstIOperand.Name);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00004944 M.defineOperand(OM.getSymbolicName(), OM);
Daniel Sandersdc662ff2017-01-26 11:10:14 +00004945 OM.addPredicate<RegisterBankOperandMatcher>(
4946 Target.getRegisterClass(DstIOpRec));
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004947 ++OpIdx;
4948 }
4949
Matt Arsenault3e45c702019-09-06 20:32:37 +00004950 auto DstMIBuilderOrError =
4951 createAndImportInstructionRenderer(M, InsnMatcher, Src, Dst);
Daniel Sandersffc7d582017-03-29 15:37:18 +00004952 if (auto Error = DstMIBuilderOrError.takeError())
Bill Wendlingc55cf4a2020-02-10 07:06:45 -08004953 return std::move(Error);
Daniel Sandersffc7d582017-03-29 15:37:18 +00004954 BuildMIAction &DstMIBuilder = DstMIBuilderOrError.get();
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004955
Daniel Sandersffc7d582017-03-29 15:37:18 +00004956 // Render the implicit defs.
4957 // These are only added to the root of the result.
Daniel Sandersc270c502017-03-30 09:36:33 +00004958 if (auto Error = importImplicitDefRenderers(DstMIBuilder, P.getDstRegs()))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -08004959 return std::move(Error);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004960
Daniel Sandersa7b75262017-10-31 18:50:24 +00004961 DstMIBuilder.chooseInsnToMutate(M);
4962
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004963 // Constrain the registers to classes. This is normally derived from the
4964 // emitted instruction but a few instructions require special handling.
Matt Arsenault38fb3442019-09-04 16:19:34 +00004965 if (DstIName == "COPY_TO_REGCLASS") {
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004966 // COPY_TO_REGCLASS does not provide operand constraints itself but the
4967 // result is constrained to the class given by the second child.
4968 Record *DstIOpRec =
Florian Hahn6b1db822018-06-14 20:32:58 +00004969 getInitValueAsRegClass(Dst->getChild(1)->getLeafValue());
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004970
4971 if (DstIOpRec == nullptr)
4972 return failedImport("COPY_TO_REGCLASS operand #1 isn't a register class");
4973
4974 M.addAction<ConstrainOperandToRegClassAction>(
Daniel Sandersd93a35a2017-07-05 09:39:33 +00004975 0, 0, Target.getRegisterClass(DstIOpRec));
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004976
4977 // We're done with this pattern! It's eligible for GISel emission; return
4978 // it.
4979 ++NumPatternImported;
Bill Wendlingc55cf4a2020-02-10 07:06:45 -08004980 return std::move(M);
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004981 }
4982
Matt Arsenault38fb3442019-09-04 16:19:34 +00004983 if (DstIName == "EXTRACT_SUBREG") {
Matt Arsenault9ceb6ed2019-09-06 00:05:58 +00004984 auto SuperClass = inferRegClassFromPattern(Dst->getChild(0));
4985 if (!SuperClass)
4986 return failedImport(
4987 "Cannot infer register class from EXTRACT_SUBREG operand #0");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004988
Matt Arsenault9ceb6ed2019-09-06 00:05:58 +00004989 auto SubIdx = inferSubRegIndexForNode(Dst->getChild(1));
4990 if (!SubIdx)
Daniel Sanders320390b2017-06-28 15:16:03 +00004991 return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004992
Daniel Sanders320390b2017-06-28 15:16:03 +00004993 // It would be nice to leave this constraint implicit but we're required
4994 // to pick a register class so constrain the result to a register class
4995 // that can hold the correct MVT.
4996 //
4997 // FIXME: This may introduce an extra copy if the chosen class doesn't
4998 // actually contain the subregisters.
Florian Hahn6b1db822018-06-14 20:32:58 +00004999 assert(Src->getExtTypes().size() == 1 &&
Daniel Sanders320390b2017-06-28 15:16:03 +00005000 "Expected Src of EXTRACT_SUBREG to have one result type");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00005001
Matt Arsenaulteafa8db2020-01-14 14:09:06 -05005002 const auto SrcRCDstRCPair =
Matt Arsenault9ceb6ed2019-09-06 00:05:58 +00005003 (*SuperClass)->getMatchingSubClassWithSubRegs(CGRegs, *SubIdx);
Matt Arsenault9c346462020-01-14 16:02:02 -05005004 if (!SrcRCDstRCPair) {
5005 return failedImport("subreg index is incompatible "
5006 "with inferred reg class");
5007 }
5008
Daniel Sanders320390b2017-06-28 15:16:03 +00005009 assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
Daniel Sandersd93a35a2017-07-05 09:39:33 +00005010 M.addAction<ConstrainOperandToRegClassAction>(0, 0, *SrcRCDstRCPair->second);
5011 M.addAction<ConstrainOperandToRegClassAction>(0, 1, *SrcRCDstRCPair->first);
5012
5013 // We're done with this pattern! It's eligible for GISel emission; return
5014 // it.
5015 ++NumPatternImported;
Bill Wendlingc55cf4a2020-02-10 07:06:45 -08005016 return std::move(M);
Daniel Sandersd93a35a2017-07-05 09:39:33 +00005017 }
5018
Matt Arsenault38fb3442019-09-04 16:19:34 +00005019 if (DstIName == "INSERT_SUBREG") {
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00005020 assert(Src->getExtTypes().size() == 1 &&
5021 "Expected Src of INSERT_SUBREG to have one result type");
5022 // We need to constrain the destination, a super regsister source, and a
5023 // subregister source.
5024 auto SubClass = inferRegClassFromPattern(Dst->getChild(1));
5025 if (!SubClass)
5026 return failedImport(
5027 "Cannot infer register class from INSERT_SUBREG operand #1");
Jessica Paquette7080ffa2019-08-28 20:12:31 +00005028 auto SuperClass = inferSuperRegisterClassForNode(
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00005029 Src->getExtType(0), Dst->getChild(0), Dst->getChild(2));
5030 if (!SuperClass)
5031 return failedImport(
5032 "Cannot infer register class for INSERT_SUBREG operand #0");
5033 M.addAction<ConstrainOperandToRegClassAction>(0, 0, **SuperClass);
5034 M.addAction<ConstrainOperandToRegClassAction>(0, 1, **SuperClass);
5035 M.addAction<ConstrainOperandToRegClassAction>(0, 2, **SubClass);
5036 ++NumPatternImported;
Bill Wendlingc55cf4a2020-02-10 07:06:45 -08005037 return std::move(M);
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00005038 }
5039
Matt Arsenault38fb3442019-09-04 16:19:34 +00005040 if (DstIName == "SUBREG_TO_REG") {
Jessica Paquette7080ffa2019-08-28 20:12:31 +00005041 // We need to constrain the destination and subregister source.
5042 assert(Src->getExtTypes().size() == 1 &&
5043 "Expected Src of SUBREG_TO_REG to have one result type");
5044
5045 // Attempt to infer the subregister source from the first child. If it has
5046 // an explicitly given register class, we'll use that. Otherwise, we will
5047 // fail.
5048 auto SubClass = inferRegClassFromPattern(Dst->getChild(1));
5049 if (!SubClass)
5050 return failedImport(
5051 "Cannot infer register class from SUBREG_TO_REG child #1");
5052 // We don't have a child to look at that might have a super register node.
5053 auto SuperClass =
5054 inferSuperRegisterClass(Src->getExtType(0), Dst->getChild(2));
5055 if (!SuperClass)
5056 return failedImport(
5057 "Cannot infer register class for SUBREG_TO_REG operand #0");
5058 M.addAction<ConstrainOperandToRegClassAction>(0, 0, **SuperClass);
5059 M.addAction<ConstrainOperandToRegClassAction>(0, 2, **SubClass);
5060 ++NumPatternImported;
Bill Wendlingc55cf4a2020-02-10 07:06:45 -08005061 return std::move(M);
Jessica Paquette7080ffa2019-08-28 20:12:31 +00005062 }
5063
Matt Arsenaultcb5dc372020-04-07 09:32:51 -04005064 if (DstIName == "REG_SEQUENCE") {
5065 auto SuperClass = inferRegClassFromPattern(Dst->getChild(0));
5066
5067 M.addAction<ConstrainOperandToRegClassAction>(0, 0, **SuperClass);
5068
5069 unsigned Num = Dst->getNumChildren();
5070 for (unsigned I = 1; I != Num; I += 2) {
5071 TreePatternNode *SubRegChild = Dst->getChild(I + 1);
5072
5073 auto SubIdx = inferSubRegIndexForNode(SubRegChild);
5074 if (!SubIdx)
5075 return failedImport("REG_SEQUENCE child is not a subreg index");
5076
5077 const auto SrcRCDstRCPair =
5078 (*SuperClass)->getMatchingSubClassWithSubRegs(CGRegs, *SubIdx);
5079
5080 M.addAction<ConstrainOperandToRegClassAction>(0, I,
5081 *SrcRCDstRCPair->second);
5082 }
5083
5084 ++NumPatternImported;
5085 return std::move(M);
5086 }
5087
Daniel Sandersd93a35a2017-07-05 09:39:33 +00005088 M.addAction<ConstrainOperandsToDefinitionAction>(0);
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00005089
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00005090 // We're done with this pattern! It's eligible for GISel emission; return it.
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00005091 ++NumPatternImported;
Bill Wendlingc55cf4a2020-02-10 07:06:45 -08005092 return std::move(M);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00005093}
5094
Daniel Sanders649c5852017-10-13 20:42:18 +00005095// Emit imm predicate table and an enum to reference them with.
5096// The 'Predicate_' part of the name is redundant but eliminating it is more
5097// trouble than it's worth.
Daniel Sanders8ead1292018-06-15 23:13:43 +00005098void GlobalISelEmitter::emitCxxPredicateFns(
5099 raw_ostream &OS, StringRef CodeFieldName, StringRef TypeIdentifier,
5100 StringRef ArgType, StringRef ArgName, StringRef AdditionalDeclarations,
Daniel Sanders11300ce2017-10-13 21:28:03 +00005101 std::function<bool(const Record *R)> Filter) {
Daniel Sanders649c5852017-10-13 20:42:18 +00005102 std::vector<const Record *> MatchedRecords;
5103 const auto &Defs = RK.getAllDerivedDefinitions("PatFrag");
5104 std::copy_if(Defs.begin(), Defs.end(), std::back_inserter(MatchedRecords),
5105 [&](Record *Record) {
Daniel Sanders8ead1292018-06-15 23:13:43 +00005106 return !Record->getValueAsString(CodeFieldName).empty() &&
Daniel Sanders649c5852017-10-13 20:42:18 +00005107 Filter(Record);
5108 });
5109
Daniel Sanders11300ce2017-10-13 21:28:03 +00005110 if (!MatchedRecords.empty()) {
5111 OS << "// PatFrag predicates.\n"
5112 << "enum {\n";
Daniel Sanders2fed4ff2017-10-13 21:51:20 +00005113 std::string EnumeratorSeparator =
Daniel Sanders11300ce2017-10-13 21:28:03 +00005114 (" = GIPFP_" + TypeIdentifier + "_Invalid + 1,\n").str();
5115 for (const auto *Record : MatchedRecords) {
5116 OS << " GIPFP_" << TypeIdentifier << "_Predicate_" << Record->getName()
5117 << EnumeratorSeparator;
5118 EnumeratorSeparator = ",\n";
5119 }
5120 OS << "};\n";
Daniel Sanders649c5852017-10-13 20:42:18 +00005121 }
Daniel Sanders11300ce2017-10-13 21:28:03 +00005122
Daniel Sanders8ead1292018-06-15 23:13:43 +00005123 OS << "bool " << Target.getName() << "InstructionSelector::test" << ArgName
5124 << "Predicate_" << TypeIdentifier << "(unsigned PredicateID, " << ArgType << " "
5125 << ArgName << ") const {\n"
5126 << AdditionalDeclarations;
5127 if (!AdditionalDeclarations.empty())
5128 OS << "\n";
Aaron Ballman82e17f52017-12-20 20:09:30 +00005129 if (!MatchedRecords.empty())
5130 OS << " switch (PredicateID) {\n";
Daniel Sanders32de8bb2017-12-20 14:41:51 +00005131 for (const auto *Record : MatchedRecords) {
5132 OS << " case GIPFP_" << TypeIdentifier << "_Predicate_"
5133 << Record->getName() << ": {\n"
Daniel Sanders8ead1292018-06-15 23:13:43 +00005134 << " " << Record->getValueAsString(CodeFieldName) << "\n"
5135 << " llvm_unreachable(\"" << CodeFieldName
5136 << " should have returned\");\n"
Daniel Sanders32de8bb2017-12-20 14:41:51 +00005137 << " return false;\n"
5138 << " }\n";
5139 }
Aaron Ballman82e17f52017-12-20 20:09:30 +00005140 if (!MatchedRecords.empty())
5141 OS << " }\n";
5142 OS << " llvm_unreachable(\"Unknown predicate\");\n"
Daniel Sanders32de8bb2017-12-20 14:41:51 +00005143 << " return false;\n"
5144 << "}\n";
Daniel Sanders649c5852017-10-13 20:42:18 +00005145}
5146
Daniel Sanders8ead1292018-06-15 23:13:43 +00005147void GlobalISelEmitter::emitImmPredicateFns(
5148 raw_ostream &OS, StringRef TypeIdentifier, StringRef ArgType,
5149 std::function<bool(const Record *R)> Filter) {
5150 return emitCxxPredicateFns(OS, "ImmediateCode", TypeIdentifier, ArgType,
5151 "Imm", "", Filter);
5152}
5153
5154void GlobalISelEmitter::emitMIPredicateFns(raw_ostream &OS) {
5155 return emitCxxPredicateFns(
5156 OS, "GISelPredicateCode", "MI", "const MachineInstr &", "MI",
5157 " const MachineFunction &MF = *MI.getParent()->getParent();\n"
Andrei Elovikov36cbbff2018-06-26 07:05:08 +00005158 " const MachineRegisterInfo &MRI = MF.getRegInfo();\n"
5159 " (void)MRI;",
Daniel Sanders8ead1292018-06-15 23:13:43 +00005160 [](const Record *R) { return true; });
5161}
5162
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005163template <class GroupT>
Quentin Colombetec76d9c2017-12-18 19:47:41 +00005164std::vector<Matcher *> GlobalISelEmitter::optimizeRules(
Roman Tereshin2d6d3762018-05-02 20:08:14 +00005165 ArrayRef<Matcher *> Rules,
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005166 std::vector<std::unique_ptr<Matcher>> &MatcherStorage) {
5167
Quentin Colombetec76d9c2017-12-18 19:47:41 +00005168 std::vector<Matcher *> OptRules;
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00005169 std::unique_ptr<GroupT> CurrentGroup = std::make_unique<GroupT>();
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005170 assert(CurrentGroup->empty() && "Newly created group isn't empty!");
5171 unsigned NumGroups = 0;
5172
5173 auto ProcessCurrentGroup = [&]() {
5174 if (CurrentGroup->empty())
5175 // An empty group is good to be reused:
5176 return;
5177
5178 // If the group isn't large enough to provide any benefit, move all the
5179 // added rules out of it and make sure to re-create the group to properly
5180 // re-initialize it:
5181 if (CurrentGroup->size() < 2)
5182 for (Matcher *M : CurrentGroup->matchers())
5183 OptRules.push_back(M);
5184 else {
5185 CurrentGroup->finalize();
Roman Tereshin8bdf7be2018-05-21 22:21:24 +00005186 OptRules.push_back(CurrentGroup.get());
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005187 MatcherStorage.emplace_back(std::move(CurrentGroup));
5188 ++NumGroups;
Roman Tereshin8bdf7be2018-05-21 22:21:24 +00005189 }
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00005190 CurrentGroup = std::make_unique<GroupT>();
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005191 };
5192 for (Matcher *Rule : Rules) {
5193 // Greedily add as many matchers as possible to the current group:
5194 if (CurrentGroup->addMatcher(*Rule))
5195 continue;
5196
5197 ProcessCurrentGroup();
5198 assert(CurrentGroup->empty() && "A group wasn't properly re-initialized");
5199
5200 // Try to add the pending matcher to a newly created empty group:
5201 if (!CurrentGroup->addMatcher(*Rule))
5202 // If we couldn't add the matcher to an empty group, that group type
5203 // doesn't support that kind of matchers at all, so just skip it:
5204 OptRules.push_back(Rule);
Quentin Colombetec76d9c2017-12-18 19:47:41 +00005205 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005206 ProcessCurrentGroup();
5207
Nicola Zaghen03d0b912018-05-23 15:09:29 +00005208 LLVM_DEBUG(dbgs() << "NumGroups: " << NumGroups << "\n");
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005209 assert(CurrentGroup->empty() && "The last group wasn't properly processed");
Quentin Colombetec76d9c2017-12-18 19:47:41 +00005210 return OptRules;
5211}
5212
Roman Tereshin2d6d3762018-05-02 20:08:14 +00005213MatchTable
5214GlobalISelEmitter::buildMatchTable(MutableArrayRef<RuleMatcher> Rules,
Roman Tereshinbeb39312018-05-02 20:15:11 +00005215 bool Optimize, bool WithCoverage) {
Roman Tereshin2d6d3762018-05-02 20:08:14 +00005216 std::vector<Matcher *> InputRules;
5217 for (Matcher &Rule : Rules)
5218 InputRules.push_back(&Rule);
5219
5220 if (!Optimize)
Roman Tereshinbeb39312018-05-02 20:15:11 +00005221 return MatchTable::buildTable(InputRules, WithCoverage);
Roman Tereshin2d6d3762018-05-02 20:08:14 +00005222
Roman Tereshin77013602018-05-22 16:54:27 +00005223 unsigned CurrentOrdering = 0;
5224 StringMap<unsigned> OpcodeOrder;
5225 for (RuleMatcher &Rule : Rules) {
5226 const StringRef Opcode = Rule.getOpcode();
5227 assert(!Opcode.empty() && "Didn't expect an undefined opcode");
5228 if (OpcodeOrder.count(Opcode) == 0)
5229 OpcodeOrder[Opcode] = CurrentOrdering++;
5230 }
5231
5232 std::stable_sort(InputRules.begin(), InputRules.end(),
5233 [&OpcodeOrder](const Matcher *A, const Matcher *B) {
5234 auto *L = static_cast<const RuleMatcher *>(A);
5235 auto *R = static_cast<const RuleMatcher *>(B);
5236 return std::make_tuple(OpcodeOrder[L->getOpcode()],
5237 L->getNumOperands()) <
5238 std::make_tuple(OpcodeOrder[R->getOpcode()],
5239 R->getNumOperands());
5240 });
5241
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005242 for (Matcher *Rule : InputRules)
5243 Rule->optimize();
5244
5245 std::vector<std::unique_ptr<Matcher>> MatcherStorage;
Roman Tereshin2d6d3762018-05-02 20:08:14 +00005246 std::vector<Matcher *> OptRules =
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005247 optimizeRules<GroupMatcher>(InputRules, MatcherStorage);
5248
5249 for (Matcher *Rule : OptRules)
5250 Rule->optimize();
Roman Tereshin2d6d3762018-05-02 20:08:14 +00005251
Roman Tereshin0ee082f2018-05-22 19:37:59 +00005252 OptRules = optimizeRules<SwitchMatcher>(OptRules, MatcherStorage);
5253
Roman Tereshinbeb39312018-05-02 20:15:11 +00005254 return MatchTable::buildTable(OptRules, WithCoverage);
Roman Tereshin2d6d3762018-05-02 20:08:14 +00005255}
5256
Roman Tereshinfedae332018-05-23 02:04:19 +00005257void GroupMatcher::optimize() {
Roman Tereshin9a9fa492018-05-23 21:30:16 +00005258 // Make sure we only sort by a specific predicate within a range of rules that
5259 // all have that predicate checked against a specific value (not a wildcard):
5260 auto F = Matchers.begin();
5261 auto T = F;
5262 auto E = Matchers.end();
5263 while (T != E) {
5264 while (T != E) {
5265 auto *R = static_cast<RuleMatcher *>(*T);
5266 if (!R->getFirstConditionAsRootType().get().isValid())
5267 break;
5268 ++T;
5269 }
5270 std::stable_sort(F, T, [](Matcher *A, Matcher *B) {
5271 auto *L = static_cast<RuleMatcher *>(A);
5272 auto *R = static_cast<RuleMatcher *>(B);
5273 return L->getFirstConditionAsRootType() <
5274 R->getFirstConditionAsRootType();
5275 });
5276 if (T != E)
5277 F = ++T;
5278 }
Roman Tereshinfedae332018-05-23 02:04:19 +00005279 GlobalISelEmitter::optimizeRules<GroupMatcher>(Matchers, MatcherStorage)
5280 .swap(Matchers);
Roman Tereshina4c410d2018-05-24 00:24:15 +00005281 GlobalISelEmitter::optimizeRules<SwitchMatcher>(Matchers, MatcherStorage)
5282 .swap(Matchers);
Roman Tereshinfedae332018-05-23 02:04:19 +00005283}
5284
Ahmed Bougacha36f70352016-12-21 23:26:20 +00005285void GlobalISelEmitter::run(raw_ostream &OS) {
Daniel Sandersf76f3152017-11-16 00:46:35 +00005286 if (!UseCoverageFile.empty()) {
5287 RuleCoverage = CodeGenCoverage();
5288 auto RuleCoverageBufOrErr = MemoryBuffer::getFile(UseCoverageFile);
5289 if (!RuleCoverageBufOrErr) {
5290 PrintWarning(SMLoc(), "Missing rule coverage data");
5291 RuleCoverage = None;
5292 } else {
5293 if (!RuleCoverage->parse(*RuleCoverageBufOrErr.get(), Target.getName())) {
5294 PrintWarning(SMLoc(), "Ignoring invalid or missing rule coverage data");
5295 RuleCoverage = None;
5296 }
5297 }
5298 }
5299
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005300 // Track the run-time opcode values
5301 gatherOpcodeValues();
5302 // Track the run-time LLT ID values
5303 gatherTypeIDValues();
5304
Ahmed Bougacha36f70352016-12-21 23:26:20 +00005305 // Track the GINodeEquiv definitions.
5306 gatherNodeEquivs();
5307
5308 emitSourceFileHeader(("Global Instruction Selector for the " +
5309 Target.getName() + " target").str(), OS);
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00005310 std::vector<RuleMatcher> Rules;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00005311 // Look through the SelectionDAG patterns we found, possibly emitting some.
5312 for (const PatternToMatch &Pat : CGP.ptms()) {
5313 ++NumPatternTotal;
Daniel Sanders7e523672017-11-11 03:23:44 +00005314
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00005315 auto MatcherOrErr = runOnPattern(Pat);
5316
5317 // The pattern analysis can fail, indicating an unsupported pattern.
5318 // Report that if we've been asked to do so.
5319 if (auto Err = MatcherOrErr.takeError()) {
Ahmed Bougacha36f70352016-12-21 23:26:20 +00005320 if (WarnOnSkippedPatterns) {
5321 PrintWarning(Pat.getSrcRecord()->getLoc(),
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00005322 "Skipped pattern: " + toString(std::move(Err)));
5323 } else {
5324 consumeError(std::move(Err));
Ahmed Bougacha36f70352016-12-21 23:26:20 +00005325 }
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00005326 ++NumPatternImportsSkipped;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00005327 continue;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00005328 }
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00005329
Daniel Sandersf76f3152017-11-16 00:46:35 +00005330 if (RuleCoverage) {
5331 if (RuleCoverage->isCovered(MatcherOrErr->getRuleID()))
5332 ++NumPatternsTested;
5333 else
5334 PrintWarning(Pat.getSrcRecord()->getLoc(),
5335 "Pattern is not covered by a test");
5336 }
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00005337 Rules.push_back(std::move(MatcherOrErr.get()));
5338 }
5339
Volkan Kelesf7f25682018-01-16 18:44:05 +00005340 // Comparison function to order records by name.
5341 auto orderByName = [](const Record *A, const Record *B) {
5342 return A->getName() < B->getName();
5343 };
5344
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00005345 std::vector<Record *> ComplexPredicates =
5346 RK.getAllDerivedDefinitions("GIComplexOperandMatcher");
Fangrui Song0cac7262018-09-27 02:13:45 +00005347 llvm::sort(ComplexPredicates, orderByName);
Volkan Kelesf7f25682018-01-16 18:44:05 +00005348
5349 std::vector<Record *> CustomRendererFns =
5350 RK.getAllDerivedDefinitions("GICustomOperandRenderer");
Fangrui Song0cac7262018-09-27 02:13:45 +00005351 llvm::sort(CustomRendererFns, orderByName);
Volkan Kelesf7f25682018-01-16 18:44:05 +00005352
Daniel Sanders8a4bae92017-03-14 21:32:08 +00005353 unsigned MaxTemporaries = 0;
5354 for (const auto &Rule : Rules)
Daniel Sanders2deea182017-04-22 15:11:04 +00005355 MaxTemporaries = std::max(MaxTemporaries, Rule.countRendererFns());
Daniel Sanders8a4bae92017-03-14 21:32:08 +00005356
Daniel Sanderse7b0d662017-04-21 15:59:56 +00005357 OS << "#ifdef GET_GLOBALISEL_PREDICATE_BITSET\n"
5358 << "const unsigned MAX_SUBTARGET_PREDICATES = " << SubtargetFeatures.size()
5359 << ";\n"
5360 << "using PredicateBitset = "
5361 "llvm::PredicateBitsetImpl<MAX_SUBTARGET_PREDICATES>;\n"
5362 << "#endif // ifdef GET_GLOBALISEL_PREDICATE_BITSET\n\n";
5363
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00005364 OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n"
5365 << " mutable MatcherState State;\n"
5366 << " typedef "
Daniel Sanders1e4569f2017-10-20 20:55:29 +00005367 "ComplexRendererFns("
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00005368 << Target.getName()
5369 << "InstructionSelector::*ComplexMatcherMemFn)(MachineOperand &) const;\n"
Volkan Kelesf7f25682018-01-16 18:44:05 +00005370
5371 << " typedef void(" << Target.getName()
5372 << "InstructionSelector::*CustomRendererFn)(MachineInstrBuilder &, const "
Matt Arsenaultb4a64742020-01-08 12:53:15 -05005373 "MachineInstr&, int) "
Volkan Kelesf7f25682018-01-16 18:44:05 +00005374 "const;\n"
5375 << " const ISelInfoTy<PredicateBitset, ComplexMatcherMemFn, "
5376 "CustomRendererFn> "
5377 "ISelInfo;\n";
5378 OS << " static " << Target.getName()
Daniel Sandersea8711b2017-10-16 03:36:29 +00005379 << "InstructionSelector::ComplexMatcherMemFn ComplexPredicateFns[];\n"
Volkan Kelesf7f25682018-01-16 18:44:05 +00005380 << " static " << Target.getName()
5381 << "InstructionSelector::CustomRendererFn CustomRenderers[];\n"
Roman Tereshin2df4c222018-05-02 20:07:15 +00005382 << " bool testImmPredicate_I64(unsigned PredicateID, int64_t Imm) const "
Daniel Sanders32de8bb2017-12-20 14:41:51 +00005383 "override;\n"
Roman Tereshin2df4c222018-05-02 20:07:15 +00005384 << " bool testImmPredicate_APInt(unsigned PredicateID, const APInt &Imm) "
Daniel Sanders32de8bb2017-12-20 14:41:51 +00005385 "const override;\n"
Roman Tereshin2df4c222018-05-02 20:07:15 +00005386 << " bool testImmPredicate_APFloat(unsigned PredicateID, const APFloat "
Daniel Sanders32de8bb2017-12-20 14:41:51 +00005387 "&Imm) const override;\n"
Roman Tereshin2df4c222018-05-02 20:07:15 +00005388 << " const int64_t *getMatchTable() const override;\n"
Daniel Sanders8ead1292018-06-15 23:13:43 +00005389 << " bool testMIPredicate_MI(unsigned PredicateID, const MachineInstr &MI) "
5390 "const override;\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00005391 << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n\n";
Daniel Sanders8a4bae92017-03-14 21:32:08 +00005392
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00005393 OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n"
5394 << ", State(" << MaxTemporaries << "),\n"
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005395 << "ISelInfo(TypeObjects, NumTypeObjects, FeatureBitsets"
5396 << ", ComplexPredicateFns, CustomRenderers)\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00005397 << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n\n";
Daniel Sanders8a4bae92017-03-14 21:32:08 +00005398
Daniel Sanderse7b0d662017-04-21 15:59:56 +00005399 OS << "#ifdef GET_GLOBALISEL_IMPL\n";
5400 SubtargetFeatureInfo::emitSubtargetFeatureBitEnumeration(SubtargetFeatures,
5401 OS);
Daniel Sanderse9fdba32017-04-29 17:30:09 +00005402
5403 // Separate subtarget features by how often they must be recomputed.
5404 SubtargetFeatureInfoMap ModuleFeatures;
5405 std::copy_if(SubtargetFeatures.begin(), SubtargetFeatures.end(),
5406 std::inserter(ModuleFeatures, ModuleFeatures.end()),
5407 [](const SubtargetFeatureInfoMap::value_type &X) {
5408 return !X.second.mustRecomputePerFunction();
5409 });
5410 SubtargetFeatureInfoMap FunctionFeatures;
5411 std::copy_if(SubtargetFeatures.begin(), SubtargetFeatures.end(),
5412 std::inserter(FunctionFeatures, FunctionFeatures.end()),
5413 [](const SubtargetFeatureInfoMap::value_type &X) {
5414 return X.second.mustRecomputePerFunction();
5415 });
5416
Daniel Sanderse7b0d662017-04-21 15:59:56 +00005417 SubtargetFeatureInfo::emitComputeAvailableFeatures(
Matt Arsenaultf937b432020-01-08 19:49:30 -05005418 Target.getName(), "InstructionSelector", "computeAvailableModuleFeatures",
Daniel Sanderse9fdba32017-04-29 17:30:09 +00005419 ModuleFeatures, OS);
Hiroshi Yamauchi52e37742019-11-11 10:59:36 -08005420
Matt Arsenaultf937b432020-01-08 19:49:30 -05005421
5422 OS << "void " << Target.getName() << "InstructionSelector"
5423 "::setupGeneratedPerFunctionState(MachineFunction &MF) {\n"
5424 " AvailableFunctionFeatures = computeAvailableFunctionFeatures("
5425 "(const " << Target.getName() << "Subtarget*)&MF.getSubtarget(), &MF);\n"
5426 "}\n";
5427
Hiroshi Yamauchi52e37742019-11-11 10:59:36 -08005428 if (Target.getName() == "X86" || Target.getName() == "AArch64") {
5429 // TODO: Implement PGSO.
5430 OS << "static bool shouldOptForSize(const MachineFunction *MF) {\n";
5431 OS << " return MF->getFunction().hasOptSize();\n";
5432 OS << "}\n\n";
5433 }
5434
Daniel Sanderse9fdba32017-04-29 17:30:09 +00005435 SubtargetFeatureInfo::emitComputeAvailableFeatures(
5436 Target.getName(), "InstructionSelector",
5437 "computeAvailableFunctionFeatures", FunctionFeatures, OS,
5438 "const MachineFunction *MF");
Daniel Sanderse7b0d662017-04-21 15:59:56 +00005439
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00005440 // Emit a table containing the LLT objects needed by the matcher and an enum
5441 // for the matcher to reference them with.
Daniel Sanders032e7f22017-08-17 13:18:35 +00005442 std::vector<LLTCodeGen> TypeObjects;
Daniel Sandersf84bc372018-05-05 20:53:24 +00005443 for (const auto &Ty : KnownTypes)
Daniel Sanders032e7f22017-08-17 13:18:35 +00005444 TypeObjects.push_back(Ty);
Fangrui Song0cac7262018-09-27 02:13:45 +00005445 llvm::sort(TypeObjects);
Daniel Sanders49980702017-08-23 10:09:25 +00005446 OS << "// LLT Objects.\n"
5447 << "enum {\n";
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00005448 for (const auto &TypeObject : TypeObjects) {
5449 OS << " ";
5450 TypeObject.emitCxxEnumValue(OS);
5451 OS << ",\n";
5452 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005453 OS << "};\n";
5454 OS << "const static size_t NumTypeObjects = " << TypeObjects.size() << ";\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00005455 << "const static LLT TypeObjects[] = {\n";
5456 for (const auto &TypeObject : TypeObjects) {
5457 OS << " ";
5458 TypeObject.emitCxxConstructorCall(OS);
5459 OS << ",\n";
5460 }
5461 OS << "};\n\n";
5462
5463 // Emit a table containing the PredicateBitsets objects needed by the matcher
5464 // and an enum for the matcher to reference them with.
5465 std::vector<std::vector<Record *>> FeatureBitsets;
5466 for (auto &Rule : Rules)
5467 FeatureBitsets.push_back(Rule.getRequiredFeatures());
Fangrui Song3507c6e2018-09-30 22:31:29 +00005468 llvm::sort(FeatureBitsets, [&](const std::vector<Record *> &A,
5469 const std::vector<Record *> &B) {
5470 if (A.size() < B.size())
5471 return true;
5472 if (A.size() > B.size())
5473 return false;
Mark de Wevere8d448e2019-12-22 18:58:32 +01005474 for (auto Pair : zip(A, B)) {
Fangrui Song3507c6e2018-09-30 22:31:29 +00005475 if (std::get<0>(Pair)->getName() < std::get<1>(Pair)->getName())
5476 return true;
5477 if (std::get<0>(Pair)->getName() > std::get<1>(Pair)->getName())
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00005478 return false;
Fangrui Song3507c6e2018-09-30 22:31:29 +00005479 }
5480 return false;
5481 });
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00005482 FeatureBitsets.erase(
5483 std::unique(FeatureBitsets.begin(), FeatureBitsets.end()),
5484 FeatureBitsets.end());
Daniel Sanders49980702017-08-23 10:09:25 +00005485 OS << "// Feature bitsets.\n"
5486 << "enum {\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00005487 << " GIFBS_Invalid,\n";
5488 for (const auto &FeatureBitset : FeatureBitsets) {
5489 if (FeatureBitset.empty())
5490 continue;
5491 OS << " " << getNameForFeatureBitset(FeatureBitset) << ",\n";
5492 }
5493 OS << "};\n"
5494 << "const static PredicateBitset FeatureBitsets[] {\n"
5495 << " {}, // GIFBS_Invalid\n";
5496 for (const auto &FeatureBitset : FeatureBitsets) {
5497 if (FeatureBitset.empty())
5498 continue;
5499 OS << " {";
5500 for (const auto &Feature : FeatureBitset) {
5501 const auto &I = SubtargetFeatures.find(Feature);
5502 assert(I != SubtargetFeatures.end() && "Didn't import predicate?");
5503 OS << I->second.getEnumBitName() << ", ";
5504 }
5505 OS << "},\n";
5506 }
5507 OS << "};\n\n";
5508
5509 // Emit complex predicate table and an enum to reference them with.
Daniel Sanders49980702017-08-23 10:09:25 +00005510 OS << "// ComplexPattern predicates.\n"
5511 << "enum {\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00005512 << " GICP_Invalid,\n";
5513 for (const auto &Record : ComplexPredicates)
5514 OS << " GICP_" << Record->getName() << ",\n";
5515 OS << "};\n"
5516 << "// See constructor for table contents\n\n";
5517
Daniel Sanders8ead1292018-06-15 23:13:43 +00005518 emitImmPredicateFns(OS, "I64", "int64_t", [](const Record *R) {
Daniel Sanders649c5852017-10-13 20:42:18 +00005519 bool Unset;
5520 return !R->getValueAsBitOrUnset("IsAPFloat", Unset) &&
5521 !R->getValueAsBit("IsAPInt");
5522 });
Daniel Sanders8ead1292018-06-15 23:13:43 +00005523 emitImmPredicateFns(OS, "APFloat", "const APFloat &", [](const Record *R) {
Daniel Sanders11300ce2017-10-13 21:28:03 +00005524 bool Unset;
5525 return R->getValueAsBitOrUnset("IsAPFloat", Unset);
5526 });
Daniel Sanders8ead1292018-06-15 23:13:43 +00005527 emitImmPredicateFns(OS, "APInt", "const APInt &", [](const Record *R) {
Daniel Sanders11300ce2017-10-13 21:28:03 +00005528 return R->getValueAsBit("IsAPInt");
5529 });
Daniel Sanders8ead1292018-06-15 23:13:43 +00005530 emitMIPredicateFns(OS);
Daniel Sandersea8711b2017-10-16 03:36:29 +00005531 OS << "\n";
5532
5533 OS << Target.getName() << "InstructionSelector::ComplexMatcherMemFn\n"
5534 << Target.getName() << "InstructionSelector::ComplexPredicateFns[] = {\n"
5535 << " nullptr, // GICP_Invalid\n";
5536 for (const auto &Record : ComplexPredicates)
5537 OS << " &" << Target.getName()
5538 << "InstructionSelector::" << Record->getValueAsString("MatcherFn")
5539 << ", // " << Record->getName() << "\n";
5540 OS << "};\n\n";
Daniel Sanders2c269f62017-08-24 09:11:20 +00005541
Volkan Kelesf7f25682018-01-16 18:44:05 +00005542 OS << "// Custom renderers.\n"
5543 << "enum {\n"
5544 << " GICR_Invalid,\n";
5545 for (const auto &Record : CustomRendererFns)
5546 OS << " GICR_" << Record->getValueAsString("RendererFn") << ", \n";
5547 OS << "};\n";
5548
5549 OS << Target.getName() << "InstructionSelector::CustomRendererFn\n"
5550 << Target.getName() << "InstructionSelector::CustomRenderers[] = {\n"
Matt Arsenault0274ed92020-01-08 18:57:44 -05005551 << " nullptr, // GICR_Invalid\n";
Volkan Kelesf7f25682018-01-16 18:44:05 +00005552 for (const auto &Record : CustomRendererFns)
5553 OS << " &" << Target.getName()
5554 << "InstructionSelector::" << Record->getValueAsString("RendererFn")
5555 << ", // " << Record->getName() << "\n";
5556 OS << "};\n\n";
5557
Fangrui Songefd94c52019-04-23 14:51:27 +00005558 llvm::stable_sort(Rules, [&](const RuleMatcher &A, const RuleMatcher &B) {
Aditya Nandakumarb63e7632018-02-16 22:37:15 +00005559 int ScoreA = RuleMatcherScores[A.getRuleID()];
5560 int ScoreB = RuleMatcherScores[B.getRuleID()];
5561 if (ScoreA > ScoreB)
5562 return true;
5563 if (ScoreB > ScoreA)
5564 return false;
Quentin Colombetec76d9c2017-12-18 19:47:41 +00005565 if (A.isHigherPriorityThan(B)) {
5566 assert(!B.isHigherPriorityThan(A) && "Cannot be more important "
5567 "and less important at "
5568 "the same time");
5569 return true;
5570 }
5571 return false;
5572 });
Ahmed Bougacha36f70352016-12-21 23:26:20 +00005573
Roman Tereshin2df4c222018-05-02 20:07:15 +00005574 OS << "bool " << Target.getName()
5575 << "InstructionSelector::selectImpl(MachineInstr &I, CodeGenCoverage "
5576 "&CoverageInfo) const {\n"
5577 << " MachineFunction &MF = *I.getParent()->getParent();\n"
5578 << " MachineRegisterInfo &MRI = MF.getRegInfo();\n"
Roman Tereshin2df4c222018-05-02 20:07:15 +00005579 << " const PredicateBitset AvailableFeatures = getAvailableFeatures();\n"
5580 << " NewMIVector OutMIs;\n"
5581 << " State.MIs.clear();\n"
5582 << " State.MIs.push_back(&I);\n\n"
5583 << " if (executeMatchTable(*this, OutMIs, State, ISelInfo"
5584 << ", getMatchTable(), TII, MRI, TRI, RBI, AvailableFeatures"
5585 << ", CoverageInfo)) {\n"
5586 << " return true;\n"
5587 << " }\n\n"
5588 << " return false;\n"
5589 << "}\n\n";
5590
Roman Tereshinbeb39312018-05-02 20:15:11 +00005591 const MatchTable Table =
5592 buildMatchTable(Rules, OptimizeMatchTable, GenerateCoverage);
Roman Tereshin2df4c222018-05-02 20:07:15 +00005593 OS << "const int64_t *" << Target.getName()
5594 << "InstructionSelector::getMatchTable() const {\n";
5595 Table.emitDeclaration(OS);
5596 OS << " return ";
5597 Table.emitUse(OS);
5598 OS << ";\n}\n";
5599 OS << "#endif // ifdef GET_GLOBALISEL_IMPL\n";
Daniel Sanderse9fdba32017-04-29 17:30:09 +00005600
5601 OS << "#ifdef GET_GLOBALISEL_PREDICATES_DECL\n"
5602 << "PredicateBitset AvailableModuleFeatures;\n"
5603 << "mutable PredicateBitset AvailableFunctionFeatures;\n"
5604 << "PredicateBitset getAvailableFeatures() const {\n"
5605 << " return AvailableModuleFeatures | AvailableFunctionFeatures;\n"
5606 << "}\n"
5607 << "PredicateBitset\n"
5608 << "computeAvailableModuleFeatures(const " << Target.getName()
5609 << "Subtarget *Subtarget) const;\n"
5610 << "PredicateBitset\n"
5611 << "computeAvailableFunctionFeatures(const " << Target.getName()
5612 << "Subtarget *Subtarget,\n"
5613 << " const MachineFunction *MF) const;\n"
Matt Arsenaultf937b432020-01-08 19:49:30 -05005614 << "void setupGeneratedPerFunctionState(MachineFunction &MF) override;\n"
Daniel Sanderse9fdba32017-04-29 17:30:09 +00005615 << "#endif // ifdef GET_GLOBALISEL_PREDICATES_DECL\n";
5616
5617 OS << "#ifdef GET_GLOBALISEL_PREDICATES_INIT\n"
5618 << "AvailableModuleFeatures(computeAvailableModuleFeatures(&STI)),\n"
5619 << "AvailableFunctionFeatures()\n"
5620 << "#endif // ifdef GET_GLOBALISEL_PREDICATES_INIT\n";
Ahmed Bougacha36f70352016-12-21 23:26:20 +00005621}
5622
Daniel Sanderse7b0d662017-04-21 15:59:56 +00005623void GlobalISelEmitter::declareSubtargetFeature(Record *Predicate) {
5624 if (SubtargetFeatures.count(Predicate) == 0)
5625 SubtargetFeatures.emplace(
5626 Predicate, SubtargetFeatureInfo(Predicate, SubtargetFeatures.size()));
5627}
5628
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005629void RuleMatcher::optimize() {
5630 for (auto &Item : InsnVariableIDs) {
5631 InstructionMatcher &InsnMatcher = *Item.first;
5632 for (auto &OM : InsnMatcher.operands()) {
Roman Tereshin5f5e5502018-05-23 23:58:10 +00005633 // Complex Patterns are usually expensive and they relatively rarely fail
5634 // on their own: more often we end up throwing away all the work done by a
5635 // matching part of a complex pattern because some other part of the
5636 // enclosing pattern didn't match. All of this makes it beneficial to
5637 // delay complex patterns until the very end of the rule matching,
5638 // especially for targets having lots of complex patterns.
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005639 for (auto &OP : OM->predicates())
Roman Tereshin5f5e5502018-05-23 23:58:10 +00005640 if (isa<ComplexPatternOperandMatcher>(OP))
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005641 EpilogueMatchers.emplace_back(std::move(OP));
5642 OM->eraseNullPredicates();
5643 }
5644 InsnMatcher.optimize();
Quentin Colombetec76d9c2017-12-18 19:47:41 +00005645 }
Fangrui Song3507c6e2018-09-30 22:31:29 +00005646 llvm::sort(EpilogueMatchers, [](const std::unique_ptr<PredicateMatcher> &L,
5647 const std::unique_ptr<PredicateMatcher> &R) {
5648 return std::make_tuple(L->getKind(), L->getInsnVarID(), L->getOpIdx()) <
5649 std::make_tuple(R->getKind(), R->getInsnVarID(), R->getOpIdx());
5650 });
Quentin Colombetec76d9c2017-12-18 19:47:41 +00005651}
5652
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005653bool RuleMatcher::hasFirstCondition() const {
5654 if (insnmatchers_empty())
5655 return false;
5656 InstructionMatcher &Matcher = insnmatchers_front();
5657 if (!Matcher.predicates_empty())
5658 return true;
5659 for (auto &OM : Matcher.operands())
5660 for (auto &OP : OM->predicates())
5661 if (!isa<InstructionOperandMatcher>(OP))
5662 return true;
5663 return false;
5664}
5665
5666const PredicateMatcher &RuleMatcher::getFirstCondition() const {
5667 assert(!insnmatchers_empty() &&
5668 "Trying to get a condition from an empty RuleMatcher");
5669
5670 InstructionMatcher &Matcher = insnmatchers_front();
5671 if (!Matcher.predicates_empty())
5672 return **Matcher.predicates_begin();
5673 // If there is no more predicate on the instruction itself, look at its
5674 // operands.
5675 for (auto &OM : Matcher.operands())
5676 for (auto &OP : OM->predicates())
5677 if (!isa<InstructionOperandMatcher>(OP))
5678 return *OP;
5679
5680 llvm_unreachable("Trying to get a condition from an InstructionMatcher with "
5681 "no conditions");
5682}
5683
5684std::unique_ptr<PredicateMatcher> RuleMatcher::popFirstCondition() {
5685 assert(!insnmatchers_empty() &&
5686 "Trying to pop a condition from an empty RuleMatcher");
5687
5688 InstructionMatcher &Matcher = insnmatchers_front();
5689 if (!Matcher.predicates_empty())
5690 return Matcher.predicates_pop_front();
5691 // If there is no more predicate on the instruction itself, look at its
5692 // operands.
5693 for (auto &OM : Matcher.operands())
5694 for (auto &OP : OM->predicates())
5695 if (!isa<InstructionOperandMatcher>(OP)) {
5696 std::unique_ptr<PredicateMatcher> Result = std::move(OP);
5697 OM->eraseNullPredicates();
5698 return Result;
5699 }
5700
5701 llvm_unreachable("Trying to pop a condition from an InstructionMatcher with "
5702 "no conditions");
5703}
5704
5705bool GroupMatcher::candidateConditionMatches(
Quentin Colombetec76d9c2017-12-18 19:47:41 +00005706 const PredicateMatcher &Predicate) const {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005707
5708 if (empty()) {
5709 // Sharing predicates for nested instructions is not supported yet as we
5710 // currently don't hoist the GIM_RecordInsn's properly, therefore we can
5711 // only work on the original root instruction (InsnVarID == 0):
5712 if (Predicate.getInsnVarID() != 0)
5713 return false;
5714 // ... otherwise an empty group can handle any predicate with no specific
5715 // requirements:
5716 return true;
5717 }
5718
5719 const Matcher &Representative = **Matchers.begin();
5720 const auto &RepresentativeCondition = Representative.getFirstCondition();
5721 // ... if not empty, the group can only accomodate matchers with the exact
5722 // same first condition:
5723 return Predicate.isIdentical(RepresentativeCondition);
5724}
5725
5726bool GroupMatcher::addMatcher(Matcher &Candidate) {
5727 if (!Candidate.hasFirstCondition())
5728 return false;
5729
5730 const PredicateMatcher &Predicate = Candidate.getFirstCondition();
5731 if (!candidateConditionMatches(Predicate))
5732 return false;
5733
5734 Matchers.push_back(&Candidate);
5735 return true;
5736}
5737
5738void GroupMatcher::finalize() {
5739 assert(Conditions.empty() && "Already finalized?");
5740 if (empty())
5741 return;
5742
5743 Matcher &FirstRule = **Matchers.begin();
Roman Tereshin152fc162018-05-23 22:50:53 +00005744 for (;;) {
5745 // All the checks are expected to succeed during the first iteration:
5746 for (const auto &Rule : Matchers)
5747 if (!Rule->hasFirstCondition())
5748 return;
5749 const auto &FirstCondition = FirstRule.getFirstCondition();
5750 for (unsigned I = 1, E = Matchers.size(); I < E; ++I)
5751 if (!Matchers[I]->getFirstCondition().isIdentical(FirstCondition))
5752 return;
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005753
Roman Tereshin152fc162018-05-23 22:50:53 +00005754 Conditions.push_back(FirstRule.popFirstCondition());
5755 for (unsigned I = 1, E = Matchers.size(); I < E; ++I)
5756 Matchers[I]->popFirstCondition();
5757 }
Quentin Colombetec76d9c2017-12-18 19:47:41 +00005758}
5759
5760void GroupMatcher::emit(MatchTable &Table) {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005761 unsigned LabelID = ~0U;
5762 if (!Conditions.empty()) {
5763 LabelID = Table.allocateLabelID();
Quentin Colombetec76d9c2017-12-18 19:47:41 +00005764 Table << MatchTable::Opcode("GIM_Try", +1)
5765 << MatchTable::Comment("On fail goto")
5766 << MatchTable::JumpTarget(LabelID) << MatchTable::LineBreak;
Quentin Colombetec76d9c2017-12-18 19:47:41 +00005767 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005768 for (auto &Condition : Conditions)
5769 Condition->emitPredicateOpcodes(
5770 Table, *static_cast<RuleMatcher *>(*Matchers.begin()));
5771
5772 for (const auto &M : Matchers)
5773 M->emit(Table);
5774
5775 // Exit the group
5776 if (!Conditions.empty())
5777 Table << MatchTable::Opcode("GIM_Reject", -1) << MatchTable::LineBreak
Quentin Colombetec76d9c2017-12-18 19:47:41 +00005778 << MatchTable::Label(LabelID);
Quentin Colombetec76d9c2017-12-18 19:47:41 +00005779}
5780
Roman Tereshin0ee082f2018-05-22 19:37:59 +00005781bool SwitchMatcher::isSupportedPredicateType(const PredicateMatcher &P) {
Roman Tereshina4c410d2018-05-24 00:24:15 +00005782 return isa<InstructionOpcodeMatcher>(P) || isa<LLTOperandMatcher>(P);
Roman Tereshin0ee082f2018-05-22 19:37:59 +00005783}
5784
5785bool SwitchMatcher::candidateConditionMatches(
5786 const PredicateMatcher &Predicate) const {
5787
5788 if (empty()) {
5789 // Sharing predicates for nested instructions is not supported yet as we
5790 // currently don't hoist the GIM_RecordInsn's properly, therefore we can
5791 // only work on the original root instruction (InsnVarID == 0):
5792 if (Predicate.getInsnVarID() != 0)
5793 return false;
5794 // ... while an attempt to add even a root matcher to an empty SwitchMatcher
5795 // could fail as not all the types of conditions are supported:
5796 if (!isSupportedPredicateType(Predicate))
5797 return false;
5798 // ... or the condition might not have a proper implementation of
5799 // getValue() / isIdenticalDownToValue() yet:
5800 if (!Predicate.hasValue())
5801 return false;
5802 // ... otherwise an empty Switch can accomodate the condition with no
5803 // further requirements:
5804 return true;
5805 }
5806
5807 const Matcher &CaseRepresentative = **Matchers.begin();
5808 const auto &RepresentativeCondition = CaseRepresentative.getFirstCondition();
5809 // Switch-cases must share the same kind of condition and path to the value it
5810 // checks:
5811 if (!Predicate.isIdenticalDownToValue(RepresentativeCondition))
5812 return false;
5813
5814 const auto Value = Predicate.getValue();
5815 // ... but be unique with respect to the actual value they check:
5816 return Values.count(Value) == 0;
5817}
5818
5819bool SwitchMatcher::addMatcher(Matcher &Candidate) {
5820 if (!Candidate.hasFirstCondition())
5821 return false;
5822
5823 const PredicateMatcher &Predicate = Candidate.getFirstCondition();
5824 if (!candidateConditionMatches(Predicate))
5825 return false;
5826 const auto Value = Predicate.getValue();
5827 Values.insert(Value);
5828
5829 Matchers.push_back(&Candidate);
5830 return true;
5831}
5832
5833void SwitchMatcher::finalize() {
5834 assert(Condition == nullptr && "Already finalized");
5835 assert(Values.size() == Matchers.size() && "Broken SwitchMatcher");
5836 if (empty())
5837 return;
5838
5839 std::stable_sort(Matchers.begin(), Matchers.end(),
5840 [](const Matcher *L, const Matcher *R) {
5841 return L->getFirstCondition().getValue() <
5842 R->getFirstCondition().getValue();
5843 });
5844 Condition = Matchers[0]->popFirstCondition();
5845 for (unsigned I = 1, E = Values.size(); I < E; ++I)
5846 Matchers[I]->popFirstCondition();
5847}
5848
5849void SwitchMatcher::emitPredicateSpecificOpcodes(const PredicateMatcher &P,
5850 MatchTable &Table) {
5851 assert(isSupportedPredicateType(P) && "Predicate type is not supported");
5852
5853 if (const auto *Condition = dyn_cast<InstructionOpcodeMatcher>(&P)) {
5854 Table << MatchTable::Opcode("GIM_SwitchOpcode") << MatchTable::Comment("MI")
5855 << MatchTable::IntValue(Condition->getInsnVarID());
5856 return;
5857 }
Roman Tereshina4c410d2018-05-24 00:24:15 +00005858 if (const auto *Condition = dyn_cast<LLTOperandMatcher>(&P)) {
5859 Table << MatchTable::Opcode("GIM_SwitchType") << MatchTable::Comment("MI")
5860 << MatchTable::IntValue(Condition->getInsnVarID())
5861 << MatchTable::Comment("Op")
5862 << MatchTable::IntValue(Condition->getOpIdx());
5863 return;
5864 }
Roman Tereshin0ee082f2018-05-22 19:37:59 +00005865
5866 llvm_unreachable("emitPredicateSpecificOpcodes is broken: can not handle a "
5867 "predicate type that is claimed to be supported");
5868}
5869
5870void SwitchMatcher::emit(MatchTable &Table) {
5871 assert(Values.size() == Matchers.size() && "Broken SwitchMatcher");
5872 if (empty())
5873 return;
5874 assert(Condition != nullptr &&
5875 "Broken SwitchMatcher, hasn't been finalized?");
5876
5877 std::vector<unsigned> LabelIDs(Values.size());
5878 std::generate(LabelIDs.begin(), LabelIDs.end(),
5879 [&Table]() { return Table.allocateLabelID(); });
5880 const unsigned Default = Table.allocateLabelID();
5881
5882 const int64_t LowerBound = Values.begin()->getRawValue();
5883 const int64_t UpperBound = Values.rbegin()->getRawValue() + 1;
5884
5885 emitPredicateSpecificOpcodes(*Condition, Table);
5886
5887 Table << MatchTable::Comment("[") << MatchTable::IntValue(LowerBound)
5888 << MatchTable::IntValue(UpperBound) << MatchTable::Comment(")")
5889 << MatchTable::Comment("default:") << MatchTable::JumpTarget(Default);
5890
5891 int64_t J = LowerBound;
5892 auto VI = Values.begin();
5893 for (unsigned I = 0, E = Values.size(); I < E; ++I) {
5894 auto V = *VI++;
5895 while (J++ < V.getRawValue())
5896 Table << MatchTable::IntValue(0);
5897 V.turnIntoComment();
5898 Table << MatchTable::LineBreak << V << MatchTable::JumpTarget(LabelIDs[I]);
5899 }
5900 Table << MatchTable::LineBreak;
5901
5902 for (unsigned I = 0, E = Values.size(); I < E; ++I) {
5903 Table << MatchTable::Label(LabelIDs[I]);
5904 Matchers[I]->emit(Table);
5905 Table << MatchTable::Opcode("GIM_Reject") << MatchTable::LineBreak;
5906 }
5907 Table << MatchTable::Label(Default);
5908}
5909
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005910unsigned OperandMatcher::getInsnVarID() const { return Insn.getInsnVarID(); }
Quentin Colombetaad20be2017-12-15 23:07:42 +00005911
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00005912} // end anonymous namespace
5913
Ahmed Bougacha36f70352016-12-21 23:26:20 +00005914//===----------------------------------------------------------------------===//
5915
5916namespace llvm {
5917void EmitGlobalISel(RecordKeeper &RK, raw_ostream &OS) {
5918 GlobalISelEmitter(RK).run(OS);
5919}
5920} // End llvm namespace