blob: 0fb6a9c95e61e0916dc8268465df978ebc892bf2 [file] [log] [blame]
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001//===- GlobalISelEmitter.cpp - Generate an instruction selector -----------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Ahmed Bougacha36f70352016-12-21 23:26:20 +00006//
7//===----------------------------------------------------------------------===//
8//
9/// \file
10/// This tablegen backend emits code for use by the GlobalISel instruction
11/// selector. See include/llvm/CodeGen/TargetGlobalISel.td.
12///
13/// This file analyzes the patterns recognized by the SelectionDAGISel tablegen
14/// backend, filters out the ones that are unsupported, maps
15/// SelectionDAG-specific constructs to their GlobalISel counterpart
16/// (when applicable: MVT to LLT; SDNode to generic Instruction).
17///
18/// Not all patterns are supported: pass the tablegen invocation
19/// "-warn-on-skipped-patterns" to emit a warning when a pattern is skipped,
20/// as well as why.
21///
22/// The generated file defines a single method:
23/// bool <Target>InstructionSelector::selectImpl(MachineInstr &I) const;
24/// intended to be used in InstructionSelector::select as the first-step
25/// selector for the patterns that don't require complex C++.
26///
27/// FIXME: We'll probably want to eventually define a base
28/// "TargetGenInstructionSelector" class.
29///
30//===----------------------------------------------------------------------===//
31
32#include "CodeGenDAGPatterns.h"
Daniel Sanderse7b0d662017-04-21 15:59:56 +000033#include "SubtargetFeatureInfo.h"
Ahmed Bougacha36f70352016-12-21 23:26:20 +000034#include "llvm/ADT/Optional.h"
Daniel Sanders0ed28822017-04-12 08:23:08 +000035#include "llvm/ADT/SmallSet.h"
Ahmed Bougacha36f70352016-12-21 23:26:20 +000036#include "llvm/ADT/Statistic.h"
Daniel Sandersf76f3152017-11-16 00:46:35 +000037#include "llvm/Support/CodeGenCoverage.h"
Ahmed Bougacha36f70352016-12-21 23:26:20 +000038#include "llvm/Support/CommandLine.h"
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +000039#include "llvm/Support/Error.h"
Daniel Sanders52b4ce72017-03-07 23:20:35 +000040#include "llvm/Support/LowLevelTypeImpl.h"
David Blaikie13e77db2018-03-23 23:58:25 +000041#include "llvm/Support/MachineValueType.h"
Pavel Labath52a82e22017-02-21 09:19:41 +000042#include "llvm/Support/ScopedPrinter.h"
Ahmed Bougacha36f70352016-12-21 23:26:20 +000043#include "llvm/TableGen/Error.h"
44#include "llvm/TableGen/Record.h"
45#include "llvm/TableGen/TableGenBackend.h"
Daniel Sanders8a4bae92017-03-14 21:32:08 +000046#include <numeric>
Daniel Sandersf76f3152017-11-16 00:46:35 +000047#include <string>
Ahmed Bougacha36f70352016-12-21 23:26:20 +000048using namespace llvm;
49
50#define DEBUG_TYPE "gisel-emitter"
51
52STATISTIC(NumPatternTotal, "Total number of patterns");
Daniel Sandersb41ce2b2017-02-20 14:31:27 +000053STATISTIC(NumPatternImported, "Number of patterns imported from SelectionDAG");
54STATISTIC(NumPatternImportsSkipped, "Number of SelectionDAG imports skipped");
Daniel Sandersf76f3152017-11-16 00:46:35 +000055STATISTIC(NumPatternsTested, "Number of patterns executed according to coverage information");
Ahmed Bougacha36f70352016-12-21 23:26:20 +000056STATISTIC(NumPatternEmitted, "Number of patterns emitted");
57
Daniel Sanders0848b232017-03-27 13:15:13 +000058cl::OptionCategory GlobalISelEmitterCat("Options for -gen-global-isel");
59
Ahmed Bougacha36f70352016-12-21 23:26:20 +000060static cl::opt<bool> WarnOnSkippedPatterns(
61 "warn-on-skipped-patterns",
62 cl::desc("Explain why a pattern was skipped for inclusion "
63 "in the GlobalISel selector"),
Daniel Sanders0848b232017-03-27 13:15:13 +000064 cl::init(false), cl::cat(GlobalISelEmitterCat));
Ahmed Bougacha36f70352016-12-21 23:26:20 +000065
Daniel Sandersf76f3152017-11-16 00:46:35 +000066static cl::opt<bool> GenerateCoverage(
67 "instrument-gisel-coverage",
68 cl::desc("Generate coverage instrumentation for GlobalISel"),
69 cl::init(false), cl::cat(GlobalISelEmitterCat));
70
71static cl::opt<std::string> UseCoverageFile(
72 "gisel-coverage-file", cl::init(""),
73 cl::desc("Specify file to retrieve coverage information from"),
74 cl::cat(GlobalISelEmitterCat));
75
Quentin Colombetec76d9c2017-12-18 19:47:41 +000076static cl::opt<bool> OptimizeMatchTable(
77 "optimize-match-table",
78 cl::desc("Generate an optimized version of the match table"),
79 cl::init(true), cl::cat(GlobalISelEmitterCat));
80
Daniel Sandersbdfebb82017-03-15 20:18:38 +000081namespace {
Ahmed Bougacha36f70352016-12-21 23:26:20 +000082//===- Helper functions ---------------------------------------------------===//
83
Daniel Sanders11300ce2017-10-13 21:28:03 +000084/// Get the name of the enum value used to number the predicate function.
85std::string getEnumNameForPredicate(const TreePredicateFn &Predicate) {
Daniel Sanders8ead1292018-06-15 23:13:43 +000086 if (Predicate.hasGISelPredicateCode())
87 return "GIPFP_MI_" + Predicate.getFnName();
Simon Pilgrim6ecae9f2017-10-14 21:27:53 +000088 return "GIPFP_" + Predicate.getImmTypeIdentifier().str() + "_" +
Daniel Sanders11300ce2017-10-13 21:28:03 +000089 Predicate.getFnName();
90}
91
92/// Get the opcode used to check this predicate.
93std::string getMatchOpcodeForPredicate(const TreePredicateFn &Predicate) {
Simon Pilgrim6ecae9f2017-10-14 21:27:53 +000094 return "GIM_Check" + Predicate.getImmTypeIdentifier().str() + "ImmPredicate";
Daniel Sanders11300ce2017-10-13 21:28:03 +000095}
96
Daniel Sanders52b4ce72017-03-07 23:20:35 +000097/// This class stands in for LLT wherever we want to tablegen-erate an
98/// equivalent at compiler run-time.
99class LLTCodeGen {
100private:
101 LLT Ty;
102
103public:
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000104 LLTCodeGen() = default;
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000105 LLTCodeGen(const LLT &Ty) : Ty(Ty) {}
106
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000107 std::string getCxxEnumValue() const {
108 std::string Str;
109 raw_string_ostream OS(Str);
110
111 emitCxxEnumValue(OS);
112 return OS.str();
113 }
114
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000115 void emitCxxEnumValue(raw_ostream &OS) const {
116 if (Ty.isScalar()) {
117 OS << "GILLT_s" << Ty.getSizeInBits();
118 return;
119 }
120 if (Ty.isVector()) {
121 OS << "GILLT_v" << Ty.getNumElements() << "s" << Ty.getScalarSizeInBits();
122 return;
123 }
Daniel Sandersa71f4542017-10-16 00:56:30 +0000124 if (Ty.isPointer()) {
125 OS << "GILLT_p" << Ty.getAddressSpace();
126 if (Ty.getSizeInBits() > 0)
127 OS << "s" << Ty.getSizeInBits();
128 return;
129 }
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000130 llvm_unreachable("Unhandled LLT");
131 }
132
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000133 void emitCxxConstructorCall(raw_ostream &OS) const {
134 if (Ty.isScalar()) {
135 OS << "LLT::scalar(" << Ty.getSizeInBits() << ")";
136 return;
137 }
138 if (Ty.isVector()) {
Daniel Sanders32291982017-06-28 13:50:04 +0000139 OS << "LLT::vector(" << Ty.getNumElements() << ", "
140 << Ty.getScalarSizeInBits() << ")";
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000141 return;
142 }
Daniel Sandersa71f4542017-10-16 00:56:30 +0000143 if (Ty.isPointer() && Ty.getSizeInBits() > 0) {
144 OS << "LLT::pointer(" << Ty.getAddressSpace() << ", "
145 << Ty.getSizeInBits() << ")";
146 return;
147 }
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000148 llvm_unreachable("Unhandled LLT");
149 }
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000150
151 const LLT &get() const { return Ty; }
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000152
Mandeep Singh Grang1b0e2f22018-04-06 20:18:05 +0000153 /// This ordering is used for std::unique() and llvm::sort(). There's no
Daniel Sanders032e7f22017-08-17 13:18:35 +0000154 /// particular logic behind the order but either A < B or B < A must be
155 /// true if A != B.
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000156 bool operator<(const LLTCodeGen &Other) const {
Daniel Sanders032e7f22017-08-17 13:18:35 +0000157 if (Ty.isValid() != Other.Ty.isValid())
158 return Ty.isValid() < Other.Ty.isValid();
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000159 if (!Ty.isValid())
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000160 return false;
Daniel Sanders032e7f22017-08-17 13:18:35 +0000161
162 if (Ty.isVector() != Other.Ty.isVector())
163 return Ty.isVector() < Other.Ty.isVector();
164 if (Ty.isScalar() != Other.Ty.isScalar())
165 return Ty.isScalar() < Other.Ty.isScalar();
166 if (Ty.isPointer() != Other.Ty.isPointer())
167 return Ty.isPointer() < Other.Ty.isPointer();
168
169 if (Ty.isPointer() && Ty.getAddressSpace() != Other.Ty.getAddressSpace())
170 return Ty.getAddressSpace() < Other.Ty.getAddressSpace();
171
172 if (Ty.isVector() && Ty.getNumElements() != Other.Ty.getNumElements())
173 return Ty.getNumElements() < Other.Ty.getNumElements();
174
175 return Ty.getSizeInBits() < Other.Ty.getSizeInBits();
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000176 }
Quentin Colombet893e0f12017-12-15 23:24:39 +0000177
178 bool operator==(const LLTCodeGen &B) const { return Ty == B.Ty; }
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000179};
180
Daniel Sandersf84bc372018-05-05 20:53:24 +0000181// Track all types that are used so we can emit the corresponding enum.
182std::set<LLTCodeGen> KnownTypes;
183
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000184class InstructionMatcher;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000185/// Convert an MVT to an equivalent LLT if possible, or the invalid LLT() for
186/// MVTs that don't map cleanly to an LLT (e.g., iPTR, *any, ...).
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000187static Optional<LLTCodeGen> MVTToLLT(MVT::SimpleValueType SVT) {
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000188 MVT VT(SVT);
Daniel Sandersa71f4542017-10-16 00:56:30 +0000189
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000190 if (VT.isVector() && VT.getVectorNumElements() != 1)
Daniel Sanders32291982017-06-28 13:50:04 +0000191 return LLTCodeGen(
192 LLT::vector(VT.getVectorNumElements(), VT.getScalarSizeInBits()));
Daniel Sandersa71f4542017-10-16 00:56:30 +0000193
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000194 if (VT.isInteger() || VT.isFloatingPoint())
195 return LLTCodeGen(LLT::scalar(VT.getSizeInBits()));
196 return None;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000197}
198
Florian Hahn6b1db822018-06-14 20:32:58 +0000199static std::string explainPredicates(const TreePatternNode *N) {
Daniel Sandersd0656a32017-04-13 09:45:37 +0000200 std::string Explanation = "";
201 StringRef Separator = "";
Nicolai Haehnle445b0b62018-11-30 14:15:13 +0000202 for (const TreePredicateCall &Call : N->getPredicateCalls()) {
203 const TreePredicateFn &P = Call.Fn;
Daniel Sandersd0656a32017-04-13 09:45:37 +0000204 Explanation +=
205 (Separator + P.getOrigPatFragRecord()->getRecord()->getName()).str();
Daniel Sanders76664652017-11-28 22:07:05 +0000206 Separator = ", ";
207
Daniel Sandersd0656a32017-04-13 09:45:37 +0000208 if (P.isAlwaysTrue())
209 Explanation += " always-true";
210 if (P.isImmediatePattern())
211 Explanation += " immediate";
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000212
213 if (P.isUnindexed())
214 Explanation += " unindexed";
215
216 if (P.isNonExtLoad())
217 Explanation += " non-extload";
218 if (P.isAnyExtLoad())
219 Explanation += " extload";
220 if (P.isSignExtLoad())
221 Explanation += " sextload";
222 if (P.isZeroExtLoad())
223 Explanation += " zextload";
224
225 if (P.isNonTruncStore())
226 Explanation += " non-truncstore";
227 if (P.isTruncStore())
228 Explanation += " truncstore";
229
230 if (Record *VT = P.getMemoryVT())
231 Explanation += (" MemVT=" + VT->getName()).str();
232 if (Record *VT = P.getScalarMemoryVT())
233 Explanation += (" ScalarVT(MemVT)=" + VT->getName()).str();
Daniel Sanders76664652017-11-28 22:07:05 +0000234
Matt Arsenaultd00d8572019-07-15 20:59:42 +0000235 if (ListInit *AddrSpaces = P.getAddressSpaces()) {
236 raw_string_ostream OS(Explanation);
237 OS << " AddressSpaces=[";
238
239 StringRef AddrSpaceSeparator;
240 for (Init *Val : AddrSpaces->getValues()) {
241 IntInit *IntVal = dyn_cast<IntInit>(Val);
242 if (!IntVal)
243 continue;
244
245 OS << AddrSpaceSeparator << IntVal->getValue();
246 AddrSpaceSeparator = ", ";
247 }
248
249 OS << ']';
250 }
251
Matt Arsenault52c26242019-07-31 00:14:43 +0000252 int64_t MinAlign = P.getMinAlignment();
253 if (MinAlign > 0)
254 Explanation += " MinAlign=" + utostr(MinAlign);
255
Daniel Sanders76664652017-11-28 22:07:05 +0000256 if (P.isAtomicOrderingMonotonic())
257 Explanation += " monotonic";
258 if (P.isAtomicOrderingAcquire())
259 Explanation += " acquire";
260 if (P.isAtomicOrderingRelease())
261 Explanation += " release";
262 if (P.isAtomicOrderingAcquireRelease())
263 Explanation += " acq_rel";
264 if (P.isAtomicOrderingSequentiallyConsistent())
265 Explanation += " seq_cst";
Daniel Sanders0c43b3a2017-11-30 21:05:59 +0000266 if (P.isAtomicOrderingAcquireOrStronger())
267 Explanation += " >=acquire";
268 if (P.isAtomicOrderingWeakerThanAcquire())
269 Explanation += " <acquire";
270 if (P.isAtomicOrderingReleaseOrStronger())
271 Explanation += " >=release";
272 if (P.isAtomicOrderingWeakerThanRelease())
273 Explanation += " <release";
Daniel Sandersd0656a32017-04-13 09:45:37 +0000274 }
275 return Explanation;
276}
277
Daniel Sandersd0656a32017-04-13 09:45:37 +0000278std::string explainOperator(Record *Operator) {
279 if (Operator->isSubClassOf("SDNode"))
Craig Topper2b8419a2017-05-31 19:01:11 +0000280 return (" (" + Operator->getValueAsString("Opcode") + ")").str();
Daniel Sandersd0656a32017-04-13 09:45:37 +0000281
282 if (Operator->isSubClassOf("Intrinsic"))
283 return (" (Operator is an Intrinsic, " + Operator->getName() + ")").str();
284
Daniel Sandersdf39cba2017-10-15 18:22:54 +0000285 if (Operator->isSubClassOf("ComplexPattern"))
286 return (" (Operator is an unmapped ComplexPattern, " + Operator->getName() +
287 ")")
288 .str();
289
Volkan Kelesf7f25682018-01-16 18:44:05 +0000290 if (Operator->isSubClassOf("SDNodeXForm"))
291 return (" (Operator is an unmapped SDNodeXForm, " + Operator->getName() +
292 ")")
293 .str();
294
Daniel Sandersdf39cba2017-10-15 18:22:54 +0000295 return (" (Operator " + Operator->getName() + " not understood)").str();
Daniel Sandersd0656a32017-04-13 09:45:37 +0000296}
297
298/// Helper function to let the emitter report skip reason error messages.
299static Error failedImport(const Twine &Reason) {
300 return make_error<StringError>(Reason, inconvertibleErrorCode());
301}
302
Florian Hahn6b1db822018-06-14 20:32:58 +0000303static Error isTrivialOperatorNode(const TreePatternNode *N) {
Daniel Sandersd0656a32017-04-13 09:45:37 +0000304 std::string Explanation = "";
305 std::string Separator = "";
Daniel Sanders2c269f62017-08-24 09:11:20 +0000306
307 bool HasUnsupportedPredicate = false;
Nicolai Haehnle445b0b62018-11-30 14:15:13 +0000308 for (const TreePredicateCall &Call : N->getPredicateCalls()) {
309 const TreePredicateFn &Predicate = Call.Fn;
310
Daniel Sanders2c269f62017-08-24 09:11:20 +0000311 if (Predicate.isAlwaysTrue())
312 continue;
313
314 if (Predicate.isImmediatePattern())
315 continue;
316
Daniel Sandersf84bc372018-05-05 20:53:24 +0000317 if (Predicate.isNonExtLoad() || Predicate.isAnyExtLoad() ||
318 Predicate.isSignExtLoad() || Predicate.isZeroExtLoad())
Daniel Sandersa71f4542017-10-16 00:56:30 +0000319 continue;
Daniel Sandersd66e0902017-10-23 18:19:24 +0000320
Matt Arsenault02772492019-07-15 21:15:20 +0000321 if (Predicate.isNonTruncStore() || Predicate.isTruncStore())
Daniel Sandersd66e0902017-10-23 18:19:24 +0000322 continue;
323
Daniel Sandersf84bc372018-05-05 20:53:24 +0000324 if (Predicate.isLoad() && Predicate.getMemoryVT())
325 continue;
326
Daniel Sanders76664652017-11-28 22:07:05 +0000327 if (Predicate.isLoad() || Predicate.isStore()) {
328 if (Predicate.isUnindexed())
329 continue;
330 }
331
Matt Arsenaultd00d8572019-07-15 20:59:42 +0000332 if (Predicate.isLoad() || Predicate.isStore() || Predicate.isAtomic()) {
333 const ListInit *AddrSpaces = Predicate.getAddressSpaces();
334 if (AddrSpaces && !AddrSpaces->empty())
335 continue;
Matt Arsenault52c26242019-07-31 00:14:43 +0000336
337 if (Predicate.getMinAlignment() > 0)
338 continue;
Matt Arsenaultd00d8572019-07-15 20:59:42 +0000339 }
340
Daniel Sanders76664652017-11-28 22:07:05 +0000341 if (Predicate.isAtomic() && Predicate.getMemoryVT())
342 continue;
343
344 if (Predicate.isAtomic() &&
345 (Predicate.isAtomicOrderingMonotonic() ||
346 Predicate.isAtomicOrderingAcquire() ||
347 Predicate.isAtomicOrderingRelease() ||
348 Predicate.isAtomicOrderingAcquireRelease() ||
Daniel Sanders0c43b3a2017-11-30 21:05:59 +0000349 Predicate.isAtomicOrderingSequentiallyConsistent() ||
350 Predicate.isAtomicOrderingAcquireOrStronger() ||
351 Predicate.isAtomicOrderingWeakerThanAcquire() ||
352 Predicate.isAtomicOrderingReleaseOrStronger() ||
353 Predicate.isAtomicOrderingWeakerThanRelease()))
Daniel Sandersd66e0902017-10-23 18:19:24 +0000354 continue;
355
Daniel Sanders8ead1292018-06-15 23:13:43 +0000356 if (Predicate.hasGISelPredicateCode())
357 continue;
358
Daniel Sanders2c269f62017-08-24 09:11:20 +0000359 HasUnsupportedPredicate = true;
Daniel Sandersd0656a32017-04-13 09:45:37 +0000360 Explanation = Separator + "Has a predicate (" + explainPredicates(N) + ")";
361 Separator = ", ";
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000362 Explanation += (Separator + "first-failing:" +
363 Predicate.getOrigPatFragRecord()->getRecord()->getName())
364 .str();
Daniel Sanders2c269f62017-08-24 09:11:20 +0000365 break;
Daniel Sandersd0656a32017-04-13 09:45:37 +0000366 }
367
Volkan Kelesf7f25682018-01-16 18:44:05 +0000368 if (!HasUnsupportedPredicate)
Daniel Sandersd0656a32017-04-13 09:45:37 +0000369 return Error::success();
370
371 return failedImport(Explanation);
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000372}
373
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +0000374static Record *getInitValueAsRegClass(Init *V) {
375 if (DefInit *VDefInit = dyn_cast<DefInit>(V)) {
376 if (VDefInit->getDef()->isSubClassOf("RegisterOperand"))
377 return VDefInit->getDef()->getValueAsDef("RegClass");
378 if (VDefInit->getDef()->isSubClassOf("RegisterClass"))
379 return VDefInit->getDef();
380 }
381 return nullptr;
382}
383
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000384std::string
385getNameForFeatureBitset(const std::vector<Record *> &FeatureBitset) {
386 std::string Name = "GIFBS";
387 for (const auto &Feature : FeatureBitset)
388 Name += ("_" + Feature->getName()).str();
389 return Name;
390}
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000391
392//===- MatchTable Helpers -------------------------------------------------===//
393
394class MatchTable;
395
396/// A record to be stored in a MatchTable.
397///
398/// This class represents any and all output that may be required to emit the
399/// MatchTable. Instances are most often configured to represent an opcode or
400/// value that will be emitted to the table with some formatting but it can also
401/// represent commas, comments, and other formatting instructions.
402struct MatchTableRecord {
403 enum RecordFlagsBits {
404 MTRF_None = 0x0,
405 /// Causes EmitStr to be formatted as comment when emitted.
406 MTRF_Comment = 0x1,
407 /// Causes the record value to be followed by a comma when emitted.
408 MTRF_CommaFollows = 0x2,
409 /// Causes the record value to be followed by a line break when emitted.
410 MTRF_LineBreakFollows = 0x4,
411 /// Indicates that the record defines a label and causes an additional
412 /// comment to be emitted containing the index of the label.
413 MTRF_Label = 0x8,
414 /// Causes the record to be emitted as the index of the label specified by
415 /// LabelID along with a comment indicating where that label is.
416 MTRF_JumpTarget = 0x10,
417 /// Causes the formatter to add a level of indentation before emitting the
418 /// record.
419 MTRF_Indent = 0x20,
420 /// Causes the formatter to remove a level of indentation after emitting the
421 /// record.
422 MTRF_Outdent = 0x40,
423 };
424
425 /// When MTRF_Label or MTRF_JumpTarget is used, indicates a label id to
426 /// reference or define.
427 unsigned LabelID;
428 /// The string to emit. Depending on the MTRF_* flags it may be a comment, a
429 /// value, a label name.
430 std::string EmitStr;
431
432private:
433 /// The number of MatchTable elements described by this record. Comments are 0
434 /// while values are typically 1. Values >1 may occur when we need to emit
435 /// values that exceed the size of a MatchTable element.
436 unsigned NumElements;
437
438public:
439 /// A bitfield of RecordFlagsBits flags.
440 unsigned Flags;
441
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000442 /// The actual run-time value, if known
443 int64_t RawValue;
444
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000445 MatchTableRecord(Optional<unsigned> LabelID_, StringRef EmitStr,
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000446 unsigned NumElements, unsigned Flags,
447 int64_t RawValue = std::numeric_limits<int64_t>::min())
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000448 : LabelID(LabelID_.hasValue() ? LabelID_.getValue() : ~0u),
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000449 EmitStr(EmitStr), NumElements(NumElements), Flags(Flags),
450 RawValue(RawValue) {
451
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000452 assert((!LabelID_.hasValue() || LabelID != ~0u) &&
453 "This value is reserved for non-labels");
454 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000455 MatchTableRecord(const MatchTableRecord &Other) = default;
456 MatchTableRecord(MatchTableRecord &&Other) = default;
457
458 /// Useful if a Match Table Record gets optimized out
459 void turnIntoComment() {
460 Flags |= MTRF_Comment;
461 Flags &= ~MTRF_CommaFollows;
462 NumElements = 0;
463 }
464
465 /// For Jump Table generation purposes
466 bool operator<(const MatchTableRecord &Other) const {
467 return RawValue < Other.RawValue;
468 }
469 int64_t getRawValue() const { return RawValue; }
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000470
471 void emit(raw_ostream &OS, bool LineBreakNextAfterThis,
472 const MatchTable &Table) const;
473 unsigned size() const { return NumElements; }
474};
475
Roman Tereshin2d6d3762018-05-02 20:08:14 +0000476class Matcher;
477
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000478/// Holds the contents of a generated MatchTable to enable formatting and the
479/// necessary index tracking needed to support GIM_Try.
480class MatchTable {
481 /// An unique identifier for the table. The generated table will be named
482 /// MatchTable${ID}.
483 unsigned ID;
484 /// The records that make up the table. Also includes comments describing the
485 /// values being emitted and line breaks to format it.
486 std::vector<MatchTableRecord> Contents;
487 /// The currently defined labels.
488 DenseMap<unsigned, unsigned> LabelMap;
489 /// Tracks the sum of MatchTableRecord::NumElements as the table is built.
Roman Tereshin2d6d3762018-05-02 20:08:14 +0000490 unsigned CurrentSize = 0;
Daniel Sanders8e82af22017-07-27 11:03:45 +0000491 /// A unique identifier for a MatchTable label.
Roman Tereshin2d6d3762018-05-02 20:08:14 +0000492 unsigned CurrentLabelID = 0;
Roman Tereshinbeb39312018-05-02 20:15:11 +0000493 /// Determines if the table should be instrumented for rule coverage tracking.
494 bool IsWithCoverage;
Daniel Sanders8e82af22017-07-27 11:03:45 +0000495
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000496public:
497 static MatchTableRecord LineBreak;
498 static MatchTableRecord Comment(StringRef Comment) {
499 return MatchTableRecord(None, Comment, 0, MatchTableRecord::MTRF_Comment);
500 }
501 static MatchTableRecord Opcode(StringRef Opcode, int IndentAdjust = 0) {
502 unsigned ExtraFlags = 0;
503 if (IndentAdjust > 0)
504 ExtraFlags |= MatchTableRecord::MTRF_Indent;
505 if (IndentAdjust < 0)
506 ExtraFlags |= MatchTableRecord::MTRF_Outdent;
507
508 return MatchTableRecord(None, Opcode, 1,
509 MatchTableRecord::MTRF_CommaFollows | ExtraFlags);
510 }
511 static MatchTableRecord NamedValue(StringRef NamedValue) {
512 return MatchTableRecord(None, NamedValue, 1,
513 MatchTableRecord::MTRF_CommaFollows);
514 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000515 static MatchTableRecord NamedValue(StringRef NamedValue, int64_t RawValue) {
516 return MatchTableRecord(None, NamedValue, 1,
517 MatchTableRecord::MTRF_CommaFollows, RawValue);
518 }
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000519 static MatchTableRecord NamedValue(StringRef Namespace,
520 StringRef NamedValue) {
521 return MatchTableRecord(None, (Namespace + "::" + NamedValue).str(), 1,
522 MatchTableRecord::MTRF_CommaFollows);
523 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000524 static MatchTableRecord NamedValue(StringRef Namespace, StringRef NamedValue,
525 int64_t RawValue) {
526 return MatchTableRecord(None, (Namespace + "::" + NamedValue).str(), 1,
527 MatchTableRecord::MTRF_CommaFollows, RawValue);
528 }
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000529 static MatchTableRecord IntValue(int64_t IntValue) {
530 return MatchTableRecord(None, llvm::to_string(IntValue), 1,
531 MatchTableRecord::MTRF_CommaFollows);
532 }
533 static MatchTableRecord Label(unsigned LabelID) {
534 return MatchTableRecord(LabelID, "Label " + llvm::to_string(LabelID), 0,
535 MatchTableRecord::MTRF_Label |
536 MatchTableRecord::MTRF_Comment |
537 MatchTableRecord::MTRF_LineBreakFollows);
538 }
539 static MatchTableRecord JumpTarget(unsigned LabelID) {
Daniel Sanders8e82af22017-07-27 11:03:45 +0000540 return MatchTableRecord(LabelID, "Label " + llvm::to_string(LabelID), 1,
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000541 MatchTableRecord::MTRF_JumpTarget |
542 MatchTableRecord::MTRF_Comment |
543 MatchTableRecord::MTRF_CommaFollows);
544 }
545
Roman Tereshinbeb39312018-05-02 20:15:11 +0000546 static MatchTable buildTable(ArrayRef<Matcher *> Rules, bool WithCoverage);
Roman Tereshin2d6d3762018-05-02 20:08:14 +0000547
Roman Tereshinbeb39312018-05-02 20:15:11 +0000548 MatchTable(bool WithCoverage, unsigned ID = 0)
549 : ID(ID), IsWithCoverage(WithCoverage) {}
550
551 bool isWithCoverage() const { return IsWithCoverage; }
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000552
553 void push_back(const MatchTableRecord &Value) {
554 if (Value.Flags & MatchTableRecord::MTRF_Label)
555 defineLabel(Value.LabelID);
556 Contents.push_back(Value);
557 CurrentSize += Value.size();
558 }
559
Roman Tereshin2d6d3762018-05-02 20:08:14 +0000560 unsigned allocateLabelID() { return CurrentLabelID++; }
Daniel Sanders8e82af22017-07-27 11:03:45 +0000561
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000562 void defineLabel(unsigned LabelID) {
Daniel Sanders8e82af22017-07-27 11:03:45 +0000563 LabelMap.insert(std::make_pair(LabelID, CurrentSize));
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000564 }
565
566 unsigned getLabelIndex(unsigned LabelID) const {
567 const auto I = LabelMap.find(LabelID);
568 assert(I != LabelMap.end() && "Use of undeclared label");
569 return I->second;
570 }
571
Daniel Sanders8e82af22017-07-27 11:03:45 +0000572 void emitUse(raw_ostream &OS) const { OS << "MatchTable" << ID; }
573
574 void emitDeclaration(raw_ostream &OS) const {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000575 unsigned Indentation = 4;
Daniel Sanderscbbbfe42017-07-27 12:47:31 +0000576 OS << " constexpr static int64_t MatchTable" << ID << "[] = {";
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000577 LineBreak.emit(OS, true, *this);
578 OS << std::string(Indentation, ' ');
579
580 for (auto I = Contents.begin(), E = Contents.end(); I != E;
581 ++I) {
582 bool LineBreakIsNext = false;
583 const auto &NextI = std::next(I);
584
585 if (NextI != E) {
586 if (NextI->EmitStr == "" &&
587 NextI->Flags == MatchTableRecord::MTRF_LineBreakFollows)
588 LineBreakIsNext = true;
589 }
590
591 if (I->Flags & MatchTableRecord::MTRF_Indent)
592 Indentation += 2;
593
594 I->emit(OS, LineBreakIsNext, *this);
595 if (I->Flags & MatchTableRecord::MTRF_LineBreakFollows)
596 OS << std::string(Indentation, ' ');
597
598 if (I->Flags & MatchTableRecord::MTRF_Outdent)
599 Indentation -= 2;
600 }
601 OS << "};\n";
602 }
603};
604
605MatchTableRecord MatchTable::LineBreak = {
606 None, "" /* Emit String */, 0 /* Elements */,
607 MatchTableRecord::MTRF_LineBreakFollows};
608
609void MatchTableRecord::emit(raw_ostream &OS, bool LineBreakIsNextAfterThis,
610 const MatchTable &Table) const {
611 bool UseLineComment =
612 LineBreakIsNextAfterThis | (Flags & MTRF_LineBreakFollows);
613 if (Flags & (MTRF_JumpTarget | MTRF_CommaFollows))
614 UseLineComment = false;
615
616 if (Flags & MTRF_Comment)
617 OS << (UseLineComment ? "// " : "/*");
618
619 OS << EmitStr;
620 if (Flags & MTRF_Label)
621 OS << ": @" << Table.getLabelIndex(LabelID);
622
623 if (Flags & MTRF_Comment && !UseLineComment)
624 OS << "*/";
625
626 if (Flags & MTRF_JumpTarget) {
627 if (Flags & MTRF_Comment)
628 OS << " ";
629 OS << Table.getLabelIndex(LabelID);
630 }
631
632 if (Flags & MTRF_CommaFollows) {
633 OS << ",";
634 if (!LineBreakIsNextAfterThis && !(Flags & MTRF_LineBreakFollows))
635 OS << " ";
636 }
637
638 if (Flags & MTRF_LineBreakFollows)
639 OS << "\n";
640}
641
642MatchTable &operator<<(MatchTable &Table, const MatchTableRecord &Value) {
643 Table.push_back(Value);
644 return Table;
645}
646
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000647//===- Matchers -----------------------------------------------------------===//
648
Daniel Sandersbee57392017-04-04 13:25:23 +0000649class OperandMatcher;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000650class MatchAction;
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000651class PredicateMatcher;
652class RuleMatcher;
653
654class Matcher {
655public:
656 virtual ~Matcher() = default;
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000657 virtual void optimize() {}
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000658 virtual void emit(MatchTable &Table) = 0;
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000659
660 virtual bool hasFirstCondition() const = 0;
661 virtual const PredicateMatcher &getFirstCondition() const = 0;
662 virtual std::unique_ptr<PredicateMatcher> popFirstCondition() = 0;
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000663};
664
Roman Tereshinbeb39312018-05-02 20:15:11 +0000665MatchTable MatchTable::buildTable(ArrayRef<Matcher *> Rules,
666 bool WithCoverage) {
667 MatchTable Table(WithCoverage);
Roman Tereshin2d6d3762018-05-02 20:08:14 +0000668 for (Matcher *Rule : Rules)
669 Rule->emit(Table);
670
671 return Table << MatchTable::Opcode("GIM_Reject") << MatchTable::LineBreak;
672}
673
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000674class GroupMatcher final : public Matcher {
675 /// Conditions that form a common prefix of all the matchers contained.
676 SmallVector<std::unique_ptr<PredicateMatcher>, 1> Conditions;
677
678 /// All the nested matchers, sharing a common prefix.
679 std::vector<Matcher *> Matchers;
680
681 /// An owning collection for any auxiliary matchers created while optimizing
682 /// nested matchers contained.
683 std::vector<std::unique_ptr<Matcher>> MatcherStorage;
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000684
685public:
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000686 /// Add a matcher to the collection of nested matchers if it meets the
687 /// requirements, and return true. If it doesn't, do nothing and return false.
688 ///
689 /// Expected to preserve its argument, so it could be moved out later on.
690 bool addMatcher(Matcher &Candidate);
691
692 /// Mark the matcher as fully-built and ensure any invariants expected by both
693 /// optimize() and emit(...) methods. Generally, both sequences of calls
694 /// are expected to lead to a sensible result:
695 ///
696 /// addMatcher(...)*; finalize(); optimize(); emit(...); and
697 /// addMatcher(...)*; finalize(); emit(...);
698 ///
699 /// or generally
700 ///
701 /// addMatcher(...)*; finalize(); { optimize()*; emit(...); }*
702 ///
703 /// Multiple calls to optimize() are expected to be handled gracefully, though
704 /// optimize() is not expected to be idempotent. Multiple calls to finalize()
705 /// aren't generally supported. emit(...) is expected to be non-mutating and
706 /// producing the exact same results upon repeated calls.
707 ///
708 /// addMatcher() calls after the finalize() call are not supported.
709 ///
710 /// finalize() and optimize() are both allowed to mutate the contained
711 /// matchers, so moving them out after finalize() is not supported.
712 void finalize();
Roman Tereshinfedae332018-05-23 02:04:19 +0000713 void optimize() override;
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000714 void emit(MatchTable &Table) override;
Quentin Colombet34688b92017-12-18 21:25:53 +0000715
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000716 /// Could be used to move out the matchers added previously, unless finalize()
717 /// has been already called. If any of the matchers are moved out, the group
718 /// becomes safe to destroy, but not safe to re-use for anything else.
719 iterator_range<std::vector<Matcher *>::iterator> matchers() {
720 return make_range(Matchers.begin(), Matchers.end());
Quentin Colombet34688b92017-12-18 21:25:53 +0000721 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000722 size_t size() const { return Matchers.size(); }
723 bool empty() const { return Matchers.empty(); }
724
725 std::unique_ptr<PredicateMatcher> popFirstCondition() override {
726 assert(!Conditions.empty() &&
727 "Trying to pop a condition from a condition-less group");
728 std::unique_ptr<PredicateMatcher> P = std::move(Conditions.front());
729 Conditions.erase(Conditions.begin());
730 return P;
731 }
732 const PredicateMatcher &getFirstCondition() const override {
733 assert(!Conditions.empty() &&
734 "Trying to get a condition from a condition-less group");
735 return *Conditions.front();
736 }
737 bool hasFirstCondition() const override { return !Conditions.empty(); }
738
739private:
740 /// See if a candidate matcher could be added to this group solely by
741 /// analyzing its first condition.
742 bool candidateConditionMatches(const PredicateMatcher &Predicate) const;
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000743};
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000744
Roman Tereshin0ee082f2018-05-22 19:37:59 +0000745class SwitchMatcher : public Matcher {
746 /// All the nested matchers, representing distinct switch-cases. The first
747 /// conditions (as Matcher::getFirstCondition() reports) of all the nested
748 /// matchers must share the same type and path to a value they check, in other
749 /// words, be isIdenticalDownToValue, but have different values they check
750 /// against.
751 std::vector<Matcher *> Matchers;
752
753 /// The representative condition, with a type and a path (InsnVarID and OpIdx
754 /// in most cases) shared by all the matchers contained.
755 std::unique_ptr<PredicateMatcher> Condition = nullptr;
756
757 /// Temporary set used to check that the case values don't repeat within the
758 /// same switch.
759 std::set<MatchTableRecord> Values;
760
761 /// An owning collection for any auxiliary matchers created while optimizing
762 /// nested matchers contained.
763 std::vector<std::unique_ptr<Matcher>> MatcherStorage;
764
765public:
766 bool addMatcher(Matcher &Candidate);
767
768 void finalize();
769 void emit(MatchTable &Table) override;
770
771 iterator_range<std::vector<Matcher *>::iterator> matchers() {
772 return make_range(Matchers.begin(), Matchers.end());
773 }
774 size_t size() const { return Matchers.size(); }
775 bool empty() const { return Matchers.empty(); }
776
777 std::unique_ptr<PredicateMatcher> popFirstCondition() override {
778 // SwitchMatcher doesn't have a common first condition for its cases, as all
779 // the cases only share a kind of a value (a type and a path to it) they
780 // match, but deliberately differ in the actual value they match.
781 llvm_unreachable("Trying to pop a condition from a condition-less group");
782 }
783 const PredicateMatcher &getFirstCondition() const override {
784 llvm_unreachable("Trying to pop a condition from a condition-less group");
785 }
786 bool hasFirstCondition() const override { return false; }
787
788private:
789 /// See if the predicate type has a Switch-implementation for it.
790 static bool isSupportedPredicateType(const PredicateMatcher &Predicate);
791
792 bool candidateConditionMatches(const PredicateMatcher &Predicate) const;
793
794 /// emit()-helper
795 static void emitPredicateSpecificOpcodes(const PredicateMatcher &P,
796 MatchTable &Table);
797};
798
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000799/// Generates code to check that a match rule matches.
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000800class RuleMatcher : public Matcher {
Daniel Sanders7438b262017-10-31 23:03:18 +0000801public:
Daniel Sanders08464522018-01-29 21:09:12 +0000802 using ActionList = std::list<std::unique_ptr<MatchAction>>;
803 using action_iterator = ActionList::iterator;
Daniel Sanders7438b262017-10-31 23:03:18 +0000804
805protected:
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000806 /// A list of matchers that all need to succeed for the current rule to match.
807 /// FIXME: This currently supports a single match position but could be
808 /// extended to support multiple positions to support div/rem fusion or
809 /// load-multiple instructions.
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000810 using MatchersTy = std::vector<std::unique_ptr<InstructionMatcher>> ;
811 MatchersTy Matchers;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000812
813 /// A list of actions that need to be taken when all predicates in this rule
814 /// have succeeded.
Daniel Sanders08464522018-01-29 21:09:12 +0000815 ActionList Actions;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000816
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000817 using DefinedInsnVariablesMap = std::map<InstructionMatcher *, unsigned>;
Daniel Sandersa7b75262017-10-31 18:50:24 +0000818
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000819 /// A map of instruction matchers to the local variables
Daniel Sanders078572b2017-08-02 11:03:36 +0000820 DefinedInsnVariablesMap InsnVariableIDs;
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000821
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000822 using MutatableInsnSet = SmallPtrSet<InstructionMatcher *, 4>;
Daniel Sandersa7b75262017-10-31 18:50:24 +0000823
824 // The set of instruction matchers that have not yet been claimed for mutation
825 // by a BuildMI.
826 MutatableInsnSet MutatableInsns;
827
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000828 /// A map of named operands defined by the matchers that may be referenced by
829 /// the renderers.
830 StringMap<OperandMatcher *> DefinedOperands;
831
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000832 /// ID for the next instruction variable defined with implicitlyDefineInsnVar()
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000833 unsigned NextInsnVarID;
834
Daniel Sanders198447a2017-11-01 00:29:47 +0000835 /// ID for the next output instruction allocated with allocateOutputInsnID()
836 unsigned NextOutputInsnID;
837
Daniel Sanders9cbe7c72017-11-01 19:57:57 +0000838 /// ID for the next temporary register ID allocated with allocateTempRegID()
839 unsigned NextTempRegID;
840
Daniel Sanderse7b0d662017-04-21 15:59:56 +0000841 std::vector<Record *> RequiredFeatures;
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000842 std::vector<std::unique_ptr<PredicateMatcher>> EpilogueMatchers;
Daniel Sanderse7b0d662017-04-21 15:59:56 +0000843
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000844 ArrayRef<SMLoc> SrcLoc;
845
Daniel Sandersdf39cba2017-10-15 18:22:54 +0000846 typedef std::tuple<Record *, unsigned, unsigned>
847 DefinedComplexPatternSubOperand;
848 typedef StringMap<DefinedComplexPatternSubOperand>
849 DefinedComplexPatternSubOperandMap;
850 /// A map of Symbolic Names to ComplexPattern sub-operands.
851 DefinedComplexPatternSubOperandMap ComplexSubOperands;
852
Daniel Sandersf76f3152017-11-16 00:46:35 +0000853 uint64_t RuleID;
854 static uint64_t NextRuleID;
855
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000856public:
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000857 RuleMatcher(ArrayRef<SMLoc> SrcLoc)
Daniel Sandersa7b75262017-10-31 18:50:24 +0000858 : Matchers(), Actions(), InsnVariableIDs(), MutatableInsns(),
Daniel Sanders198447a2017-11-01 00:29:47 +0000859 DefinedOperands(), NextInsnVarID(0), NextOutputInsnID(0),
Daniel Sandersf76f3152017-11-16 00:46:35 +0000860 NextTempRegID(0), SrcLoc(SrcLoc), ComplexSubOperands(),
861 RuleID(NextRuleID++) {}
Zachary Turnerb7dbd872017-03-20 19:56:52 +0000862 RuleMatcher(RuleMatcher &&Other) = default;
863 RuleMatcher &operator=(RuleMatcher &&Other) = default;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000864
Daniel Sandersf76f3152017-11-16 00:46:35 +0000865 uint64_t getRuleID() const { return RuleID; }
866
Daniel Sanders05540042017-08-08 10:44:31 +0000867 InstructionMatcher &addInstructionMatcher(StringRef SymbolicName);
Daniel Sanderse7b0d662017-04-21 15:59:56 +0000868 void addRequiredFeature(Record *Feature);
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000869 const std::vector<Record *> &getRequiredFeatures() const;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000870
871 template <class Kind, class... Args> Kind &addAction(Args &&... args);
Daniel Sanders7438b262017-10-31 23:03:18 +0000872 template <class Kind, class... Args>
873 action_iterator insertAction(action_iterator InsertPt, Args &&... args);
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000874
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000875 /// Define an instruction without emitting any code to do so.
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000876 unsigned implicitlyDefineInsnVar(InstructionMatcher &Matcher);
877
878 unsigned getInsnVarID(InstructionMatcher &InsnMatcher) const;
Daniel Sanders078572b2017-08-02 11:03:36 +0000879 DefinedInsnVariablesMap::const_iterator defined_insn_vars_begin() const {
880 return InsnVariableIDs.begin();
881 }
882 DefinedInsnVariablesMap::const_iterator defined_insn_vars_end() const {
883 return InsnVariableIDs.end();
884 }
885 iterator_range<typename DefinedInsnVariablesMap::const_iterator>
886 defined_insn_vars() const {
887 return make_range(defined_insn_vars_begin(), defined_insn_vars_end());
888 }
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000889
Daniel Sandersa7b75262017-10-31 18:50:24 +0000890 MutatableInsnSet::const_iterator mutatable_insns_begin() const {
891 return MutatableInsns.begin();
892 }
893 MutatableInsnSet::const_iterator mutatable_insns_end() const {
894 return MutatableInsns.end();
895 }
896 iterator_range<typename MutatableInsnSet::const_iterator>
897 mutatable_insns() const {
898 return make_range(mutatable_insns_begin(), mutatable_insns_end());
899 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000900 void reserveInsnMatcherForMutation(InstructionMatcher *InsnMatcher) {
Daniel Sandersa7b75262017-10-31 18:50:24 +0000901 bool R = MutatableInsns.erase(InsnMatcher);
902 assert(R && "Reserving a mutatable insn that isn't available");
903 (void)R;
904 }
905
Daniel Sanders7438b262017-10-31 23:03:18 +0000906 action_iterator actions_begin() { return Actions.begin(); }
907 action_iterator actions_end() { return Actions.end(); }
908 iterator_range<action_iterator> actions() {
909 return make_range(actions_begin(), actions_end());
910 }
911
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000912 void defineOperand(StringRef SymbolicName, OperandMatcher &OM);
913
Jessica Paquette1ed1dd62019-02-09 00:29:13 +0000914 Error defineComplexSubOperand(StringRef SymbolicName, Record *ComplexPattern,
915 unsigned RendererID, unsigned SubOperandID) {
916 if (ComplexSubOperands.count(SymbolicName))
917 return failedImport(
918 "Complex suboperand referenced more than once (Operand: " +
919 SymbolicName + ")");
920
Daniel Sandersdf39cba2017-10-15 18:22:54 +0000921 ComplexSubOperands[SymbolicName] =
922 std::make_tuple(ComplexPattern, RendererID, SubOperandID);
Jessica Paquette1ed1dd62019-02-09 00:29:13 +0000923
924 return Error::success();
Daniel Sandersdf39cba2017-10-15 18:22:54 +0000925 }
Jessica Paquette1ed1dd62019-02-09 00:29:13 +0000926
Daniel Sandersdf39cba2017-10-15 18:22:54 +0000927 Optional<DefinedComplexPatternSubOperand>
928 getComplexSubOperand(StringRef SymbolicName) const {
929 const auto &I = ComplexSubOperands.find(SymbolicName);
930 if (I == ComplexSubOperands.end())
931 return None;
932 return I->second;
933 }
934
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000935 InstructionMatcher &getInstructionMatcher(StringRef SymbolicName) const;
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +0000936 const OperandMatcher &getOperandMatcher(StringRef Name) const;
Daniel Sanders05540042017-08-08 10:44:31 +0000937
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000938 void optimize() override;
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000939 void emit(MatchTable &Table) override;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000940
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000941 /// Compare the priority of this object and B.
942 ///
943 /// Returns true if this object is more important than B.
944 bool isHigherPriorityThan(const RuleMatcher &B) const;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000945
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000946 /// Report the maximum number of temporary operands needed by the rule
947 /// matcher.
948 unsigned countRendererFns() const;
Daniel Sanders2deea182017-04-22 15:11:04 +0000949
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000950 std::unique_ptr<PredicateMatcher> popFirstCondition() override;
951 const PredicateMatcher &getFirstCondition() const override;
Roman Tereshin9a9fa492018-05-23 21:30:16 +0000952 LLTCodeGen getFirstConditionAsRootType();
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000953 bool hasFirstCondition() const override;
954 unsigned getNumOperands() const;
Roman Tereshin19da6672018-05-22 04:31:50 +0000955 StringRef getOpcode() const;
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000956
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000957 // FIXME: Remove this as soon as possible
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000958 InstructionMatcher &insnmatchers_front() const { return *Matchers.front(); }
Daniel Sanders198447a2017-11-01 00:29:47 +0000959
960 unsigned allocateOutputInsnID() { return NextOutputInsnID++; }
Daniel Sanders9cbe7c72017-11-01 19:57:57 +0000961 unsigned allocateTempRegID() { return NextTempRegID++; }
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000962
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000963 iterator_range<MatchersTy::iterator> insnmatchers() {
964 return make_range(Matchers.begin(), Matchers.end());
965 }
Quentin Colombetec76d9c2017-12-18 19:47:41 +0000966 bool insnmatchers_empty() const { return Matchers.empty(); }
967 void insnmatchers_pop_front() { Matchers.erase(Matchers.begin()); }
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000968};
969
Daniel Sandersf76f3152017-11-16 00:46:35 +0000970uint64_t RuleMatcher::NextRuleID = 0;
971
Daniel Sanders7438b262017-10-31 23:03:18 +0000972using action_iterator = RuleMatcher::action_iterator;
973
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000974template <class PredicateTy> class PredicateListMatcher {
975private:
Daniel Sanders2c269f62017-08-24 09:11:20 +0000976 /// Template instantiations should specialize this to return a string to use
977 /// for the comment emitted when there are no predicates.
978 std::string getNoPredicateComment() const;
979
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000980protected:
981 using PredicatesTy = std::deque<std::unique_ptr<PredicateTy>>;
982 PredicatesTy Predicates;
Roman Tereshinf0dc9fa2018-05-21 22:04:39 +0000983
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000984 /// Track if the list of predicates was manipulated by one of the optimization
985 /// methods.
986 bool Optimized = false;
987
988public:
989 /// Construct a new predicate and add it to the matcher.
990 template <class Kind, class... Args>
991 Optional<Kind *> addPredicate(Args &&... args);
992
993 typename PredicatesTy::iterator predicates_begin() {
Daniel Sanders32291982017-06-28 13:50:04 +0000994 return Predicates.begin();
995 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000996 typename PredicatesTy::iterator predicates_end() {
Daniel Sanders32291982017-06-28 13:50:04 +0000997 return Predicates.end();
998 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +0000999 iterator_range<typename PredicatesTy::iterator> predicates() {
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001000 return make_range(predicates_begin(), predicates_end());
1001 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001002 typename PredicatesTy::size_type predicates_size() const {
Daniel Sanders32291982017-06-28 13:50:04 +00001003 return Predicates.size();
1004 }
Quentin Colombetec76d9c2017-12-18 19:47:41 +00001005 bool predicates_empty() const { return Predicates.empty(); }
1006
1007 std::unique_ptr<PredicateTy> predicates_pop_front() {
1008 std::unique_ptr<PredicateTy> Front = std::move(Predicates.front());
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001009 Predicates.pop_front();
1010 Optimized = true;
Quentin Colombetec76d9c2017-12-18 19:47:41 +00001011 return Front;
1012 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001013
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001014 void prependPredicate(std::unique_ptr<PredicateTy> &&Predicate) {
1015 Predicates.push_front(std::move(Predicate));
1016 }
1017
1018 void eraseNullPredicates() {
1019 const auto NewEnd =
1020 std::stable_partition(Predicates.begin(), Predicates.end(),
1021 std::logical_not<std::unique_ptr<PredicateTy>>());
1022 if (NewEnd != Predicates.begin()) {
1023 Predicates.erase(Predicates.begin(), NewEnd);
1024 Optimized = true;
1025 }
1026 }
1027
Daniel Sanders9d662d22017-07-06 10:06:12 +00001028 /// Emit MatchTable opcodes that tests whether all the predicates are met.
Ahmed Bougachab67a3ce2017-01-26 22:07:37 +00001029 template <class... Args>
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001030 void emitPredicateListOpcodes(MatchTable &Table, Args &&... args) {
1031 if (Predicates.empty() && !Optimized) {
Daniel Sanders2c269f62017-08-24 09:11:20 +00001032 Table << MatchTable::Comment(getNoPredicateComment())
1033 << MatchTable::LineBreak;
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001034 return;
1035 }
1036
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001037 for (const auto &Predicate : predicates())
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001038 Predicate->emitPredicateOpcodes(Table, std::forward<Args>(args)...);
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001039 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001040};
1041
Quentin Colombet063d7982017-12-14 23:44:07 +00001042class PredicateMatcher {
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001043public:
Daniel Sanders759ff412017-02-24 13:58:11 +00001044 /// This enum is used for RTTI and also defines the priority that is given to
1045 /// the predicate when generating the matcher code. Kinds with higher priority
1046 /// must be tested first.
1047 ///
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001048 /// The relative priority of OPM_LLT, OPM_RegBank, and OPM_MBB do not matter
1049 /// but OPM_Int must have priority over OPM_RegBank since constant integers
1050 /// are represented by a virtual register defined by a G_CONSTANT instruction.
Quentin Colombet063d7982017-12-14 23:44:07 +00001051 ///
1052 /// Note: The relative priority between IPM_ and OPM_ does not matter, they
1053 /// are currently not compared between each other.
Daniel Sanders759ff412017-02-24 13:58:11 +00001054 enum PredicateKind {
Quentin Colombet063d7982017-12-14 23:44:07 +00001055 IPM_Opcode,
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001056 IPM_NumOperands,
Quentin Colombet063d7982017-12-14 23:44:07 +00001057 IPM_ImmPredicate,
1058 IPM_AtomicOrderingMMO,
Daniel Sandersf84bc372018-05-05 20:53:24 +00001059 IPM_MemoryLLTSize,
1060 IPM_MemoryVsLLTSize,
Matt Arsenaultd00d8572019-07-15 20:59:42 +00001061 IPM_MemoryAddressSpace,
Matt Arsenault52c26242019-07-31 00:14:43 +00001062 IPM_MemoryAlignment,
Daniel Sanders8ead1292018-06-15 23:13:43 +00001063 IPM_GenericPredicate,
Daniel Sanders1e4569f2017-10-20 20:55:29 +00001064 OPM_SameOperand,
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001065 OPM_ComplexPattern,
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00001066 OPM_IntrinsicID,
Daniel Sanders05540042017-08-08 10:44:31 +00001067 OPM_Instruction,
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001068 OPM_Int,
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001069 OPM_LiteralInt,
Daniel Sanders759ff412017-02-24 13:58:11 +00001070 OPM_LLT,
Daniel Sandersa71f4542017-10-16 00:56:30 +00001071 OPM_PointerToAny,
Daniel Sanders759ff412017-02-24 13:58:11 +00001072 OPM_RegBank,
1073 OPM_MBB,
1074 };
1075
1076protected:
1077 PredicateKind Kind;
Quentin Colombetaad20be2017-12-15 23:07:42 +00001078 unsigned InsnVarID;
1079 unsigned OpIdx;
Daniel Sanders759ff412017-02-24 13:58:11 +00001080
1081public:
Quentin Colombetaad20be2017-12-15 23:07:42 +00001082 PredicateMatcher(PredicateKind Kind, unsigned InsnVarID, unsigned OpIdx = ~0)
1083 : Kind(Kind), InsnVarID(InsnVarID), OpIdx(OpIdx) {}
Quentin Colombet063d7982017-12-14 23:44:07 +00001084
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001085 unsigned getInsnVarID() const { return InsnVarID; }
Quentin Colombetaad20be2017-12-15 23:07:42 +00001086 unsigned getOpIdx() const { return OpIdx; }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001087
Quentin Colombet063d7982017-12-14 23:44:07 +00001088 virtual ~PredicateMatcher() = default;
1089 /// Emit MatchTable opcodes that check the predicate for the given operand.
Quentin Colombetaad20be2017-12-15 23:07:42 +00001090 virtual void emitPredicateOpcodes(MatchTable &Table,
1091 RuleMatcher &Rule) const = 0;
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001092
Daniel Sanders759ff412017-02-24 13:58:11 +00001093 PredicateKind getKind() const { return Kind; }
Quentin Colombet893e0f12017-12-15 23:24:39 +00001094
1095 virtual bool isIdentical(const PredicateMatcher &B) const {
Quentin Colombet893e0f12017-12-15 23:24:39 +00001096 return B.getKind() == getKind() && InsnVarID == B.InsnVarID &&
1097 OpIdx == B.OpIdx;
1098 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001099
1100 virtual bool isIdenticalDownToValue(const PredicateMatcher &B) const {
1101 return hasValue() && PredicateMatcher::isIdentical(B);
1102 }
1103
1104 virtual MatchTableRecord getValue() const {
1105 assert(hasValue() && "Can not get a value of a value-less predicate!");
1106 llvm_unreachable("Not implemented yet");
1107 }
1108 virtual bool hasValue() const { return false; }
1109
1110 /// Report the maximum number of temporary operands needed by the predicate
1111 /// matcher.
1112 virtual unsigned countRendererFns() const { return 0; }
Quentin Colombet063d7982017-12-14 23:44:07 +00001113};
1114
1115/// Generates code to check a predicate of an operand.
1116///
1117/// Typical predicates include:
1118/// * Operand is a particular register.
1119/// * Operand is assigned a particular register bank.
1120/// * Operand is an MBB.
1121class OperandPredicateMatcher : public PredicateMatcher {
1122public:
Quentin Colombetaad20be2017-12-15 23:07:42 +00001123 OperandPredicateMatcher(PredicateKind Kind, unsigned InsnVarID,
1124 unsigned OpIdx)
1125 : PredicateMatcher(Kind, InsnVarID, OpIdx) {}
Quentin Colombet063d7982017-12-14 23:44:07 +00001126 virtual ~OperandPredicateMatcher() {}
Daniel Sanders759ff412017-02-24 13:58:11 +00001127
Daniel Sanders759ff412017-02-24 13:58:11 +00001128 /// Compare the priority of this object and B.
1129 ///
1130 /// Returns true if this object is more important than B.
Daniel Sanders05540042017-08-08 10:44:31 +00001131 virtual bool isHigherPriorityThan(const OperandPredicateMatcher &B) const;
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001132};
1133
Daniel Sanders2c269f62017-08-24 09:11:20 +00001134template <>
1135std::string
1136PredicateListMatcher<OperandPredicateMatcher>::getNoPredicateComment() const {
1137 return "No operand predicates";
1138}
1139
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001140/// Generates code to check that a register operand is defined by the same exact
1141/// one as another.
1142class SameOperandMatcher : public OperandPredicateMatcher {
Daniel Sanders1e4569f2017-10-20 20:55:29 +00001143 std::string MatchingName;
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001144
1145public:
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001146 SameOperandMatcher(unsigned InsnVarID, unsigned OpIdx, StringRef MatchingName)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001147 : OperandPredicateMatcher(OPM_SameOperand, InsnVarID, OpIdx),
1148 MatchingName(MatchingName) {}
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001149
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001150 static bool classof(const PredicateMatcher *P) {
Daniel Sanders1e4569f2017-10-20 20:55:29 +00001151 return P->getKind() == OPM_SameOperand;
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001152 }
1153
Quentin Colombetaad20be2017-12-15 23:07:42 +00001154 void emitPredicateOpcodes(MatchTable &Table,
1155 RuleMatcher &Rule) const override;
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001156
1157 bool isIdentical(const PredicateMatcher &B) const override {
1158 return OperandPredicateMatcher::isIdentical(B) &&
1159 MatchingName == cast<SameOperandMatcher>(&B)->MatchingName;
1160 }
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001161};
1162
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001163/// Generates code to check that an operand is a particular LLT.
1164class LLTOperandMatcher : public OperandPredicateMatcher {
1165protected:
Daniel Sanders52b4ce72017-03-07 23:20:35 +00001166 LLTCodeGen Ty;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001167
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001168public:
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001169 static std::map<LLTCodeGen, unsigned> TypeIDValues;
1170
1171 static void initTypeIDValuesMap() {
1172 TypeIDValues.clear();
1173
1174 unsigned ID = 0;
1175 for (const LLTCodeGen LLTy : KnownTypes)
1176 TypeIDValues[LLTy] = ID++;
1177 }
1178
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001179 LLTOperandMatcher(unsigned InsnVarID, unsigned OpIdx, const LLTCodeGen &Ty)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001180 : OperandPredicateMatcher(OPM_LLT, InsnVarID, OpIdx), Ty(Ty) {
Daniel Sanders032e7f22017-08-17 13:18:35 +00001181 KnownTypes.insert(Ty);
1182 }
Daniel Sanders759ff412017-02-24 13:58:11 +00001183
Quentin Colombet063d7982017-12-14 23:44:07 +00001184 static bool classof(const PredicateMatcher *P) {
Daniel Sanders759ff412017-02-24 13:58:11 +00001185 return P->getKind() == OPM_LLT;
1186 }
Quentin Colombet893e0f12017-12-15 23:24:39 +00001187 bool isIdentical(const PredicateMatcher &B) const override {
1188 return OperandPredicateMatcher::isIdentical(B) &&
1189 Ty == cast<LLTOperandMatcher>(&B)->Ty;
1190 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001191 MatchTableRecord getValue() const override {
1192 const auto VI = TypeIDValues.find(Ty);
1193 if (VI == TypeIDValues.end())
1194 return MatchTable::NamedValue(getTy().getCxxEnumValue());
1195 return MatchTable::NamedValue(getTy().getCxxEnumValue(), VI->second);
1196 }
1197 bool hasValue() const override {
1198 if (TypeIDValues.size() != KnownTypes.size())
1199 initTypeIDValuesMap();
1200 return TypeIDValues.count(Ty);
1201 }
1202
1203 LLTCodeGen getTy() const { return Ty; }
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001204
Quentin Colombetaad20be2017-12-15 23:07:42 +00001205 void emitPredicateOpcodes(MatchTable &Table,
1206 RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001207 Table << MatchTable::Opcode("GIM_CheckType") << MatchTable::Comment("MI")
1208 << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Op")
1209 << MatchTable::IntValue(OpIdx) << MatchTable::Comment("Type")
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001210 << getValue() << MatchTable::LineBreak;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001211 }
1212};
1213
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001214std::map<LLTCodeGen, unsigned> LLTOperandMatcher::TypeIDValues;
1215
Daniel Sandersa71f4542017-10-16 00:56:30 +00001216/// Generates code to check that an operand is a pointer to any address space.
1217///
1218/// In SelectionDAG, the types did not describe pointers or address spaces. As a
1219/// result, iN is used to describe a pointer of N bits to any address space and
1220/// PatFrag predicates are typically used to constrain the address space. There's
1221/// no reliable means to derive the missing type information from the pattern so
1222/// imported rules must test the components of a pointer separately.
1223///
Daniel Sandersea8711b2017-10-16 03:36:29 +00001224/// If SizeInBits is zero, then the pointer size will be obtained from the
1225/// subtarget.
Daniel Sandersa71f4542017-10-16 00:56:30 +00001226class PointerToAnyOperandMatcher : public OperandPredicateMatcher {
1227protected:
1228 unsigned SizeInBits;
1229
1230public:
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001231 PointerToAnyOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
1232 unsigned SizeInBits)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001233 : OperandPredicateMatcher(OPM_PointerToAny, InsnVarID, OpIdx),
1234 SizeInBits(SizeInBits) {}
Daniel Sandersa71f4542017-10-16 00:56:30 +00001235
1236 static bool classof(const OperandPredicateMatcher *P) {
1237 return P->getKind() == OPM_PointerToAny;
1238 }
1239
Quentin Colombetaad20be2017-12-15 23:07:42 +00001240 void emitPredicateOpcodes(MatchTable &Table,
1241 RuleMatcher &Rule) const override {
1242 Table << MatchTable::Opcode("GIM_CheckPointerToAny")
1243 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1244 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1245 << MatchTable::Comment("SizeInBits")
Daniel Sandersa71f4542017-10-16 00:56:30 +00001246 << MatchTable::IntValue(SizeInBits) << MatchTable::LineBreak;
1247 }
1248};
1249
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001250/// Generates code to check that an operand is a particular target constant.
1251class ComplexPatternOperandMatcher : public OperandPredicateMatcher {
1252protected:
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001253 const OperandMatcher &Operand;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001254 const Record &TheDef;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001255
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001256 unsigned getAllocatedTemporariesBaseID() const;
1257
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001258public:
Quentin Colombet893e0f12017-12-15 23:24:39 +00001259 bool isIdentical(const PredicateMatcher &B) const override { return false; }
1260
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001261 ComplexPatternOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
1262 const OperandMatcher &Operand,
1263 const Record &TheDef)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001264 : OperandPredicateMatcher(OPM_ComplexPattern, InsnVarID, OpIdx),
1265 Operand(Operand), TheDef(TheDef) {}
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001266
Quentin Colombet063d7982017-12-14 23:44:07 +00001267 static bool classof(const PredicateMatcher *P) {
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001268 return P->getKind() == OPM_ComplexPattern;
1269 }
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001270
Quentin Colombetaad20be2017-12-15 23:07:42 +00001271 void emitPredicateOpcodes(MatchTable &Table,
1272 RuleMatcher &Rule) const override {
Daniel Sanders2deea182017-04-22 15:11:04 +00001273 unsigned ID = getAllocatedTemporariesBaseID();
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001274 Table << MatchTable::Opcode("GIM_CheckComplexPattern")
1275 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1276 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1277 << MatchTable::Comment("Renderer") << MatchTable::IntValue(ID)
1278 << MatchTable::NamedValue(("GICP_" + TheDef.getName()).str())
1279 << MatchTable::LineBreak;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001280 }
1281
Daniel Sanders2deea182017-04-22 15:11:04 +00001282 unsigned countRendererFns() const override {
1283 return 1;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001284 }
1285};
1286
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001287/// Generates code to check that an operand is in a particular register bank.
1288class RegisterBankOperandMatcher : public OperandPredicateMatcher {
1289protected:
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001290 const CodeGenRegisterClass &RC;
1291
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001292public:
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001293 RegisterBankOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
1294 const CodeGenRegisterClass &RC)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001295 : OperandPredicateMatcher(OPM_RegBank, InsnVarID, OpIdx), RC(RC) {}
Daniel Sanders759ff412017-02-24 13:58:11 +00001296
Quentin Colombet893e0f12017-12-15 23:24:39 +00001297 bool isIdentical(const PredicateMatcher &B) const override {
1298 return OperandPredicateMatcher::isIdentical(B) &&
1299 RC.getDef() == cast<RegisterBankOperandMatcher>(&B)->RC.getDef();
1300 }
1301
Quentin Colombet063d7982017-12-14 23:44:07 +00001302 static bool classof(const PredicateMatcher *P) {
Daniel Sanders759ff412017-02-24 13:58:11 +00001303 return P->getKind() == OPM_RegBank;
1304 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001305
Quentin Colombetaad20be2017-12-15 23:07:42 +00001306 void emitPredicateOpcodes(MatchTable &Table,
1307 RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001308 Table << MatchTable::Opcode("GIM_CheckRegBankForClass")
1309 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1310 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1311 << MatchTable::Comment("RC")
1312 << MatchTable::NamedValue(RC.getQualifiedName() + "RegClassID")
1313 << MatchTable::LineBreak;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001314 }
1315};
1316
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001317/// Generates code to check that an operand is a basic block.
1318class MBBOperandMatcher : public OperandPredicateMatcher {
1319public:
Quentin Colombetaad20be2017-12-15 23:07:42 +00001320 MBBOperandMatcher(unsigned InsnVarID, unsigned OpIdx)
1321 : OperandPredicateMatcher(OPM_MBB, InsnVarID, OpIdx) {}
Daniel Sanders759ff412017-02-24 13:58:11 +00001322
Quentin Colombet063d7982017-12-14 23:44:07 +00001323 static bool classof(const PredicateMatcher *P) {
Daniel Sanders759ff412017-02-24 13:58:11 +00001324 return P->getKind() == OPM_MBB;
1325 }
1326
Quentin Colombetaad20be2017-12-15 23:07:42 +00001327 void emitPredicateOpcodes(MatchTable &Table,
1328 RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001329 Table << MatchTable::Opcode("GIM_CheckIsMBB") << MatchTable::Comment("MI")
1330 << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Op")
1331 << MatchTable::IntValue(OpIdx) << MatchTable::LineBreak;
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001332 }
1333};
1334
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001335/// Generates code to check that an operand is a G_CONSTANT with a particular
1336/// int.
1337class ConstantIntOperandMatcher : public OperandPredicateMatcher {
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001338protected:
1339 int64_t Value;
1340
1341public:
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001342 ConstantIntOperandMatcher(unsigned InsnVarID, unsigned OpIdx, int64_t Value)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001343 : OperandPredicateMatcher(OPM_Int, InsnVarID, OpIdx), Value(Value) {}
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001344
Quentin Colombet893e0f12017-12-15 23:24:39 +00001345 bool isIdentical(const PredicateMatcher &B) const override {
1346 return OperandPredicateMatcher::isIdentical(B) &&
1347 Value == cast<ConstantIntOperandMatcher>(&B)->Value;
1348 }
1349
Quentin Colombet063d7982017-12-14 23:44:07 +00001350 static bool classof(const PredicateMatcher *P) {
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001351 return P->getKind() == OPM_Int;
1352 }
1353
Quentin Colombetaad20be2017-12-15 23:07:42 +00001354 void emitPredicateOpcodes(MatchTable &Table,
1355 RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001356 Table << MatchTable::Opcode("GIM_CheckConstantInt")
1357 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1358 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1359 << MatchTable::IntValue(Value) << MatchTable::LineBreak;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001360 }
1361};
1362
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001363/// Generates code to check that an operand is a raw int (where MO.isImm() or
1364/// MO.isCImm() is true).
1365class LiteralIntOperandMatcher : public OperandPredicateMatcher {
1366protected:
1367 int64_t Value;
1368
1369public:
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001370 LiteralIntOperandMatcher(unsigned InsnVarID, unsigned OpIdx, int64_t Value)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001371 : OperandPredicateMatcher(OPM_LiteralInt, InsnVarID, OpIdx),
1372 Value(Value) {}
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001373
Quentin Colombet893e0f12017-12-15 23:24:39 +00001374 bool isIdentical(const PredicateMatcher &B) const override {
1375 return OperandPredicateMatcher::isIdentical(B) &&
1376 Value == cast<LiteralIntOperandMatcher>(&B)->Value;
1377 }
1378
Quentin Colombet063d7982017-12-14 23:44:07 +00001379 static bool classof(const PredicateMatcher *P) {
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001380 return P->getKind() == OPM_LiteralInt;
1381 }
1382
Quentin Colombetaad20be2017-12-15 23:07:42 +00001383 void emitPredicateOpcodes(MatchTable &Table,
1384 RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001385 Table << MatchTable::Opcode("GIM_CheckLiteralInt")
1386 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1387 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1388 << MatchTable::IntValue(Value) << MatchTable::LineBreak;
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001389 }
1390};
1391
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00001392/// Generates code to check that an operand is an intrinsic ID.
1393class IntrinsicIDOperandMatcher : public OperandPredicateMatcher {
1394protected:
1395 const CodeGenIntrinsic *II;
1396
1397public:
Quentin Colombeteba10cb2017-12-18 22:12:13 +00001398 IntrinsicIDOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
1399 const CodeGenIntrinsic *II)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001400 : OperandPredicateMatcher(OPM_IntrinsicID, InsnVarID, OpIdx), II(II) {}
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00001401
Quentin Colombet893e0f12017-12-15 23:24:39 +00001402 bool isIdentical(const PredicateMatcher &B) const override {
1403 return OperandPredicateMatcher::isIdentical(B) &&
1404 II == cast<IntrinsicIDOperandMatcher>(&B)->II;
1405 }
1406
Quentin Colombet063d7982017-12-14 23:44:07 +00001407 static bool classof(const PredicateMatcher *P) {
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00001408 return P->getKind() == OPM_IntrinsicID;
1409 }
1410
Quentin Colombetaad20be2017-12-15 23:07:42 +00001411 void emitPredicateOpcodes(MatchTable &Table,
1412 RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001413 Table << MatchTable::Opcode("GIM_CheckIntrinsicID")
1414 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1415 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1416 << MatchTable::NamedValue("Intrinsic::" + II->EnumName)
1417 << MatchTable::LineBreak;
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00001418 }
1419};
1420
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001421/// Generates code to check that a set of predicates match for a particular
1422/// operand.
1423class OperandMatcher : public PredicateListMatcher<OperandPredicateMatcher> {
1424protected:
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001425 InstructionMatcher &Insn;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001426 unsigned OpIdx;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001427 std::string SymbolicName;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001428
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001429 /// The index of the first temporary variable allocated to this operand. The
1430 /// number of allocated temporaries can be found with
Daniel Sanders2deea182017-04-22 15:11:04 +00001431 /// countRendererFns().
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001432 unsigned AllocatedTemporariesBaseID;
1433
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001434public:
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001435 OperandMatcher(InstructionMatcher &Insn, unsigned OpIdx,
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001436 const std::string &SymbolicName,
1437 unsigned AllocatedTemporariesBaseID)
1438 : Insn(Insn), OpIdx(OpIdx), SymbolicName(SymbolicName),
1439 AllocatedTemporariesBaseID(AllocatedTemporariesBaseID) {}
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001440
1441 bool hasSymbolicName() const { return !SymbolicName.empty(); }
1442 const StringRef getSymbolicName() const { return SymbolicName; }
Daniel Sandersffc7d582017-03-29 15:37:18 +00001443 void setSymbolicName(StringRef Name) {
1444 assert(SymbolicName.empty() && "Operand already has a symbolic name");
1445 SymbolicName = Name;
1446 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001447
1448 /// Construct a new operand predicate and add it to the matcher.
1449 template <class Kind, class... Args>
1450 Optional<Kind *> addPredicate(Args &&... args) {
1451 if (isSameAsAnotherOperand())
1452 return None;
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00001453 Predicates.emplace_back(std::make_unique<Kind>(
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001454 getInsnVarID(), getOpIdx(), std::forward<Args>(args)...));
1455 return static_cast<Kind *>(Predicates.back().get());
1456 }
1457
1458 unsigned getOpIdx() const { return OpIdx; }
Quentin Colombetaad20be2017-12-15 23:07:42 +00001459 unsigned getInsnVarID() const;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001460
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001461 std::string getOperandExpr(unsigned InsnVarID) const {
1462 return "State.MIs[" + llvm::to_string(InsnVarID) + "]->getOperand(" +
1463 llvm::to_string(OpIdx) + ")";
Daniel Sanderse604ef52017-02-20 15:30:43 +00001464 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001465
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001466 InstructionMatcher &getInstructionMatcher() const { return Insn; }
1467
Daniel Sandersa71f4542017-10-16 00:56:30 +00001468 Error addTypeCheckPredicate(const TypeSetByHwMode &VTy,
Reid Klecknercfdd4a22017-10-16 20:31:16 +00001469 bool OperandIsAPointer);
Daniel Sandersa71f4542017-10-16 00:56:30 +00001470
Daniel Sanders9d662d22017-07-06 10:06:12 +00001471 /// Emit MatchTable opcodes that test whether the instruction named in
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001472 /// InsnVarID matches all the predicates and all the operands.
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001473 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule) {
1474 if (!Optimized) {
1475 std::string Comment;
1476 raw_string_ostream CommentOS(Comment);
1477 CommentOS << "MIs[" << getInsnVarID() << "] ";
1478 if (SymbolicName.empty())
1479 CommentOS << "Operand " << OpIdx;
1480 else
1481 CommentOS << SymbolicName;
1482 Table << MatchTable::Comment(CommentOS.str()) << MatchTable::LineBreak;
1483 }
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001484
Quentin Colombetaad20be2017-12-15 23:07:42 +00001485 emitPredicateListOpcodes(Table, Rule);
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001486 }
Daniel Sanders759ff412017-02-24 13:58:11 +00001487
1488 /// Compare the priority of this object and B.
1489 ///
1490 /// Returns true if this object is more important than B.
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001491 bool isHigherPriorityThan(OperandMatcher &B) {
Daniel Sanders759ff412017-02-24 13:58:11 +00001492 // Operand matchers involving more predicates have higher priority.
1493 if (predicates_size() > B.predicates_size())
1494 return true;
1495 if (predicates_size() < B.predicates_size())
1496 return false;
1497
1498 // This assumes that predicates are added in a consistent order.
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001499 for (auto &&Predicate : zip(predicates(), B.predicates())) {
Daniel Sanders759ff412017-02-24 13:58:11 +00001500 if (std::get<0>(Predicate)->isHigherPriorityThan(*std::get<1>(Predicate)))
1501 return true;
1502 if (std::get<1>(Predicate)->isHigherPriorityThan(*std::get<0>(Predicate)))
1503 return false;
1504 }
1505
1506 return false;
1507 };
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001508
1509 /// Report the maximum number of temporary operands needed by the operand
1510 /// matcher.
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001511 unsigned countRendererFns() {
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001512 return std::accumulate(
1513 predicates().begin(), predicates().end(), 0,
1514 [](unsigned A,
1515 const std::unique_ptr<OperandPredicateMatcher> &Predicate) {
Daniel Sanders2deea182017-04-22 15:11:04 +00001516 return A + Predicate->countRendererFns();
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001517 });
1518 }
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001519
1520 unsigned getAllocatedTemporariesBaseID() const {
1521 return AllocatedTemporariesBaseID;
1522 }
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001523
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001524 bool isSameAsAnotherOperand() {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001525 for (const auto &Predicate : predicates())
1526 if (isa<SameOperandMatcher>(Predicate))
1527 return true;
1528 return false;
1529 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001530};
1531
Reid Klecknercfdd4a22017-10-16 20:31:16 +00001532Error OperandMatcher::addTypeCheckPredicate(const TypeSetByHwMode &VTy,
Quentin Colombetaad20be2017-12-15 23:07:42 +00001533 bool OperandIsAPointer) {
Reid Klecknercfdd4a22017-10-16 20:31:16 +00001534 if (!VTy.isMachineValueType())
1535 return failedImport("unsupported typeset");
1536
1537 if (VTy.getMachineValueType() == MVT::iPTR && OperandIsAPointer) {
1538 addPredicate<PointerToAnyOperandMatcher>(0);
1539 return Error::success();
1540 }
1541
1542 auto OpTyOrNone = MVTToLLT(VTy.getMachineValueType().SimpleTy);
1543 if (!OpTyOrNone)
1544 return failedImport("unsupported type");
1545
1546 if (OperandIsAPointer)
1547 addPredicate<PointerToAnyOperandMatcher>(OpTyOrNone->get().getSizeInBits());
Tom Stellard9ad714f2019-02-20 19:43:47 +00001548 else if (VTy.isPointer())
1549 addPredicate<LLTOperandMatcher>(LLT::pointer(VTy.getPtrAddrSpace(),
1550 OpTyOrNone->get().getSizeInBits()));
Reid Klecknercfdd4a22017-10-16 20:31:16 +00001551 else
1552 addPredicate<LLTOperandMatcher>(*OpTyOrNone);
1553 return Error::success();
1554}
1555
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001556unsigned ComplexPatternOperandMatcher::getAllocatedTemporariesBaseID() const {
1557 return Operand.getAllocatedTemporariesBaseID();
1558}
1559
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001560/// Generates code to check a predicate on an instruction.
1561///
1562/// Typical predicates include:
1563/// * The opcode of the instruction is a particular value.
1564/// * The nsw/nuw flag is/isn't set.
Quentin Colombet063d7982017-12-14 23:44:07 +00001565class InstructionPredicateMatcher : public PredicateMatcher {
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001566public:
Quentin Colombetaad20be2017-12-15 23:07:42 +00001567 InstructionPredicateMatcher(PredicateKind Kind, unsigned InsnVarID)
1568 : PredicateMatcher(Kind, InsnVarID) {}
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001569 virtual ~InstructionPredicateMatcher() {}
1570
Daniel Sanders759ff412017-02-24 13:58:11 +00001571 /// Compare the priority of this object and B.
1572 ///
1573 /// Returns true if this object is more important than B.
Daniel Sanders32291982017-06-28 13:50:04 +00001574 virtual bool
1575 isHigherPriorityThan(const InstructionPredicateMatcher &B) const {
Daniel Sanders759ff412017-02-24 13:58:11 +00001576 return Kind < B.Kind;
1577 };
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001578};
1579
Daniel Sanders2c269f62017-08-24 09:11:20 +00001580template <>
1581std::string
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001582PredicateListMatcher<PredicateMatcher>::getNoPredicateComment() const {
Daniel Sanders2c269f62017-08-24 09:11:20 +00001583 return "No instruction predicates";
1584}
1585
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001586/// Generates code to check the opcode of an instruction.
1587class InstructionOpcodeMatcher : public InstructionPredicateMatcher {
1588protected:
1589 const CodeGenInstruction *I;
1590
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001591 static DenseMap<const CodeGenInstruction *, unsigned> OpcodeValues;
1592
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001593public:
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001594 static void initOpcodeValuesMap(const CodeGenTarget &Target) {
1595 OpcodeValues.clear();
1596
1597 unsigned OpcodeValue = 0;
1598 for (const CodeGenInstruction *I : Target.getInstructionsByEnumValue())
1599 OpcodeValues[I] = OpcodeValue++;
1600 }
1601
Quentin Colombetaad20be2017-12-15 23:07:42 +00001602 InstructionOpcodeMatcher(unsigned InsnVarID, const CodeGenInstruction *I)
1603 : InstructionPredicateMatcher(IPM_Opcode, InsnVarID), I(I) {}
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001604
Quentin Colombet063d7982017-12-14 23:44:07 +00001605 static bool classof(const PredicateMatcher *P) {
Daniel Sanders759ff412017-02-24 13:58:11 +00001606 return P->getKind() == IPM_Opcode;
1607 }
1608
Quentin Colombet893e0f12017-12-15 23:24:39 +00001609 bool isIdentical(const PredicateMatcher &B) const override {
1610 return InstructionPredicateMatcher::isIdentical(B) &&
1611 I == cast<InstructionOpcodeMatcher>(&B)->I;
1612 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001613 MatchTableRecord getValue() const override {
1614 const auto VI = OpcodeValues.find(I);
1615 if (VI != OpcodeValues.end())
1616 return MatchTable::NamedValue(I->Namespace, I->TheDef->getName(),
1617 VI->second);
1618 return MatchTable::NamedValue(I->Namespace, I->TheDef->getName());
1619 }
1620 bool hasValue() const override { return OpcodeValues.count(I); }
Quentin Colombet893e0f12017-12-15 23:24:39 +00001621
Quentin Colombetaad20be2017-12-15 23:07:42 +00001622 void emitPredicateOpcodes(MatchTable &Table,
1623 RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001624 Table << MatchTable::Opcode("GIM_CheckOpcode") << MatchTable::Comment("MI")
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001625 << MatchTable::IntValue(InsnVarID) << getValue()
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001626 << MatchTable::LineBreak;
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001627 }
Daniel Sanders759ff412017-02-24 13:58:11 +00001628
1629 /// Compare the priority of this object and B.
1630 ///
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001631 /// Returns true if this object is more important than B.
Daniel Sanders32291982017-06-28 13:50:04 +00001632 bool
1633 isHigherPriorityThan(const InstructionPredicateMatcher &B) const override {
Daniel Sanders759ff412017-02-24 13:58:11 +00001634 if (InstructionPredicateMatcher::isHigherPriorityThan(B))
1635 return true;
1636 if (B.InstructionPredicateMatcher::isHigherPriorityThan(*this))
1637 return false;
1638
1639 // Prioritize opcodes for cosmetic reasons in the generated source. Although
1640 // this is cosmetic at the moment, we may want to drive a similar ordering
1641 // using instruction frequency information to improve compile time.
1642 if (const InstructionOpcodeMatcher *BO =
1643 dyn_cast<InstructionOpcodeMatcher>(&B))
1644 return I->TheDef->getName() < BO->I->TheDef->getName();
1645
1646 return false;
1647 };
Daniel Sanders05540042017-08-08 10:44:31 +00001648
1649 bool isConstantInstruction() const {
1650 return I->TheDef->getName() == "G_CONSTANT";
1651 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001652
Roman Tereshin19da6672018-05-22 04:31:50 +00001653 StringRef getOpcode() const { return I->TheDef->getName(); }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001654 unsigned getNumOperands() const { return I->Operands.size(); }
1655
1656 StringRef getOperandType(unsigned OpIdx) const {
1657 return I->Operands[OpIdx].OperandType;
1658 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001659};
1660
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001661DenseMap<const CodeGenInstruction *, unsigned>
1662 InstructionOpcodeMatcher::OpcodeValues;
1663
Roman Tereshin19da6672018-05-22 04:31:50 +00001664class InstructionNumOperandsMatcher final : public InstructionPredicateMatcher {
1665 unsigned NumOperands = 0;
1666
1667public:
1668 InstructionNumOperandsMatcher(unsigned InsnVarID, unsigned NumOperands)
1669 : InstructionPredicateMatcher(IPM_NumOperands, InsnVarID),
1670 NumOperands(NumOperands) {}
1671
1672 static bool classof(const PredicateMatcher *P) {
1673 return P->getKind() == IPM_NumOperands;
1674 }
1675
1676 bool isIdentical(const PredicateMatcher &B) const override {
1677 return InstructionPredicateMatcher::isIdentical(B) &&
1678 NumOperands == cast<InstructionNumOperandsMatcher>(&B)->NumOperands;
1679 }
1680
1681 void emitPredicateOpcodes(MatchTable &Table,
1682 RuleMatcher &Rule) const override {
1683 Table << MatchTable::Opcode("GIM_CheckNumOperands")
1684 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1685 << MatchTable::Comment("Expected")
1686 << MatchTable::IntValue(NumOperands) << MatchTable::LineBreak;
1687 }
1688};
1689
Daniel Sanders2c269f62017-08-24 09:11:20 +00001690/// Generates code to check that this instruction is a constant whose value
1691/// meets an immediate predicate.
1692///
1693/// Immediates are slightly odd since they are typically used like an operand
1694/// but are represented as an operator internally. We typically write simm8:$src
1695/// in a tablegen pattern, but this is just syntactic sugar for
1696/// (imm:i32)<<P:Predicate_simm8>>:$imm which more directly describes the nodes
1697/// that will be matched and the predicate (which is attached to the imm
1698/// operator) that will be tested. In SelectionDAG this describes a
1699/// ConstantSDNode whose internal value will be tested using the simm8 predicate.
1700///
1701/// The corresponding GlobalISel representation is %1 = G_CONSTANT iN Value. In
1702/// this representation, the immediate could be tested with an
1703/// InstructionMatcher, InstructionOpcodeMatcher, OperandMatcher, and a
1704/// OperandPredicateMatcher-subclass to check the Value meets the predicate but
1705/// there are two implementation issues with producing that matcher
1706/// configuration from the SelectionDAG pattern:
1707/// * ImmLeaf is a PatFrag whose root is an InstructionMatcher. This means that
1708/// were we to sink the immediate predicate to the operand we would have to
1709/// have two partial implementations of PatFrag support, one for immediates
1710/// and one for non-immediates.
1711/// * At the point we handle the predicate, the OperandMatcher hasn't been
1712/// created yet. If we were to sink the predicate to the OperandMatcher we
1713/// would also have to complicate (or duplicate) the code that descends and
1714/// creates matchers for the subtree.
1715/// Overall, it's simpler to handle it in the place it was found.
1716class InstructionImmPredicateMatcher : public InstructionPredicateMatcher {
1717protected:
1718 TreePredicateFn Predicate;
1719
1720public:
Quentin Colombetaad20be2017-12-15 23:07:42 +00001721 InstructionImmPredicateMatcher(unsigned InsnVarID,
1722 const TreePredicateFn &Predicate)
1723 : InstructionPredicateMatcher(IPM_ImmPredicate, InsnVarID),
1724 Predicate(Predicate) {}
Daniel Sanders2c269f62017-08-24 09:11:20 +00001725
Quentin Colombet893e0f12017-12-15 23:24:39 +00001726 bool isIdentical(const PredicateMatcher &B) const override {
1727 return InstructionPredicateMatcher::isIdentical(B) &&
1728 Predicate.getOrigPatFragRecord() ==
1729 cast<InstructionImmPredicateMatcher>(&B)
1730 ->Predicate.getOrigPatFragRecord();
1731 }
1732
Quentin Colombet063d7982017-12-14 23:44:07 +00001733 static bool classof(const PredicateMatcher *P) {
Daniel Sanders2c269f62017-08-24 09:11:20 +00001734 return P->getKind() == IPM_ImmPredicate;
1735 }
1736
Quentin Colombetaad20be2017-12-15 23:07:42 +00001737 void emitPredicateOpcodes(MatchTable &Table,
1738 RuleMatcher &Rule) const override {
Daniel Sanders11300ce2017-10-13 21:28:03 +00001739 Table << MatchTable::Opcode(getMatchOpcodeForPredicate(Predicate))
Daniel Sanders2c269f62017-08-24 09:11:20 +00001740 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1741 << MatchTable::Comment("Predicate")
Daniel Sanders11300ce2017-10-13 21:28:03 +00001742 << MatchTable::NamedValue(getEnumNameForPredicate(Predicate))
Daniel Sanders2c269f62017-08-24 09:11:20 +00001743 << MatchTable::LineBreak;
1744 }
1745};
1746
Daniel Sanders76664652017-11-28 22:07:05 +00001747/// Generates code to check that a memory instruction has a atomic ordering
1748/// MachineMemoryOperand.
1749class AtomicOrderingMMOPredicateMatcher : public InstructionPredicateMatcher {
Daniel Sanders0c43b3a2017-11-30 21:05:59 +00001750public:
1751 enum AOComparator {
1752 AO_Exactly,
1753 AO_OrStronger,
1754 AO_WeakerThan,
1755 };
1756
1757protected:
Daniel Sanders76664652017-11-28 22:07:05 +00001758 StringRef Order;
Daniel Sanders0c43b3a2017-11-30 21:05:59 +00001759 AOComparator Comparator;
Daniel Sanders76664652017-11-28 22:07:05 +00001760
Daniel Sanders39690bd2017-10-15 02:41:12 +00001761public:
Quentin Colombetaad20be2017-12-15 23:07:42 +00001762 AtomicOrderingMMOPredicateMatcher(unsigned InsnVarID, StringRef Order,
Daniel Sanders0c43b3a2017-11-30 21:05:59 +00001763 AOComparator Comparator = AO_Exactly)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001764 : InstructionPredicateMatcher(IPM_AtomicOrderingMMO, InsnVarID),
1765 Order(Order), Comparator(Comparator) {}
Daniel Sanders39690bd2017-10-15 02:41:12 +00001766
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001767 static bool classof(const PredicateMatcher *P) {
Daniel Sanders76664652017-11-28 22:07:05 +00001768 return P->getKind() == IPM_AtomicOrderingMMO;
Daniel Sanders39690bd2017-10-15 02:41:12 +00001769 }
1770
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001771 bool isIdentical(const PredicateMatcher &B) const override {
1772 if (!InstructionPredicateMatcher::isIdentical(B))
1773 return false;
1774 const auto &R = *cast<AtomicOrderingMMOPredicateMatcher>(&B);
1775 return Order == R.Order && Comparator == R.Comparator;
1776 }
1777
Quentin Colombetaad20be2017-12-15 23:07:42 +00001778 void emitPredicateOpcodes(MatchTable &Table,
1779 RuleMatcher &Rule) const override {
Daniel Sanders0c43b3a2017-11-30 21:05:59 +00001780 StringRef Opcode = "GIM_CheckAtomicOrdering";
1781
1782 if (Comparator == AO_OrStronger)
1783 Opcode = "GIM_CheckAtomicOrderingOrStrongerThan";
1784 if (Comparator == AO_WeakerThan)
1785 Opcode = "GIM_CheckAtomicOrderingWeakerThan";
1786
1787 Table << MatchTable::Opcode(Opcode) << MatchTable::Comment("MI")
1788 << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Order")
Daniel Sanders76664652017-11-28 22:07:05 +00001789 << MatchTable::NamedValue(("(int64_t)AtomicOrdering::" + Order).str())
Daniel Sanders39690bd2017-10-15 02:41:12 +00001790 << MatchTable::LineBreak;
1791 }
1792};
1793
Daniel Sandersf84bc372018-05-05 20:53:24 +00001794/// Generates code to check that the size of an MMO is exactly N bytes.
1795class MemorySizePredicateMatcher : public InstructionPredicateMatcher {
1796protected:
1797 unsigned MMOIdx;
1798 uint64_t Size;
1799
1800public:
1801 MemorySizePredicateMatcher(unsigned InsnVarID, unsigned MMOIdx, unsigned Size)
1802 : InstructionPredicateMatcher(IPM_MemoryLLTSize, InsnVarID),
1803 MMOIdx(MMOIdx), Size(Size) {}
1804
1805 static bool classof(const PredicateMatcher *P) {
1806 return P->getKind() == IPM_MemoryLLTSize;
1807 }
1808 bool isIdentical(const PredicateMatcher &B) const override {
1809 return InstructionPredicateMatcher::isIdentical(B) &&
1810 MMOIdx == cast<MemorySizePredicateMatcher>(&B)->MMOIdx &&
1811 Size == cast<MemorySizePredicateMatcher>(&B)->Size;
1812 }
1813
1814 void emitPredicateOpcodes(MatchTable &Table,
1815 RuleMatcher &Rule) const override {
1816 Table << MatchTable::Opcode("GIM_CheckMemorySizeEqualTo")
1817 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1818 << MatchTable::Comment("MMO") << MatchTable::IntValue(MMOIdx)
1819 << MatchTable::Comment("Size") << MatchTable::IntValue(Size)
1820 << MatchTable::LineBreak;
1821 }
1822};
1823
Matt Arsenaultd00d8572019-07-15 20:59:42 +00001824class MemoryAddressSpacePredicateMatcher : public InstructionPredicateMatcher {
1825protected:
1826 unsigned MMOIdx;
1827 SmallVector<unsigned, 4> AddrSpaces;
1828
1829public:
1830 MemoryAddressSpacePredicateMatcher(unsigned InsnVarID, unsigned MMOIdx,
1831 ArrayRef<unsigned> AddrSpaces)
1832 : InstructionPredicateMatcher(IPM_MemoryAddressSpace, InsnVarID),
1833 MMOIdx(MMOIdx), AddrSpaces(AddrSpaces.begin(), AddrSpaces.end()) {}
1834
1835 static bool classof(const PredicateMatcher *P) {
1836 return P->getKind() == IPM_MemoryAddressSpace;
1837 }
1838 bool isIdentical(const PredicateMatcher &B) const override {
1839 if (!InstructionPredicateMatcher::isIdentical(B))
1840 return false;
1841 auto *Other = cast<MemoryAddressSpacePredicateMatcher>(&B);
1842 return MMOIdx == Other->MMOIdx && AddrSpaces == Other->AddrSpaces;
1843 }
1844
1845 void emitPredicateOpcodes(MatchTable &Table,
1846 RuleMatcher &Rule) const override {
1847 Table << MatchTable::Opcode("GIM_CheckMemoryAddressSpace")
1848 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1849 << MatchTable::Comment("MMO") << MatchTable::IntValue(MMOIdx)
1850 // Encode number of address spaces to expect.
1851 << MatchTable::Comment("NumAddrSpace")
1852 << MatchTable::IntValue(AddrSpaces.size());
1853 for (unsigned AS : AddrSpaces)
1854 Table << MatchTable::Comment("AddrSpace") << MatchTable::IntValue(AS);
1855
1856 Table << MatchTable::LineBreak;
1857 }
1858};
1859
Matt Arsenault52c26242019-07-31 00:14:43 +00001860class MemoryAlignmentPredicateMatcher : public InstructionPredicateMatcher {
1861protected:
1862 unsigned MMOIdx;
1863 int MinAlign;
1864
1865public:
1866 MemoryAlignmentPredicateMatcher(unsigned InsnVarID, unsigned MMOIdx,
1867 int MinAlign)
1868 : InstructionPredicateMatcher(IPM_MemoryAlignment, InsnVarID),
1869 MMOIdx(MMOIdx), MinAlign(MinAlign) {
1870 assert(MinAlign > 0);
1871 }
1872
1873 static bool classof(const PredicateMatcher *P) {
1874 return P->getKind() == IPM_MemoryAlignment;
1875 }
1876
1877 bool isIdentical(const PredicateMatcher &B) const override {
1878 if (!InstructionPredicateMatcher::isIdentical(B))
1879 return false;
1880 auto *Other = cast<MemoryAlignmentPredicateMatcher>(&B);
1881 return MMOIdx == Other->MMOIdx && MinAlign == Other->MinAlign;
1882 }
1883
1884 void emitPredicateOpcodes(MatchTable &Table,
1885 RuleMatcher &Rule) const override {
1886 Table << MatchTable::Opcode("GIM_CheckMemoryAlignment")
1887 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1888 << MatchTable::Comment("MMO") << MatchTable::IntValue(MMOIdx)
1889 << MatchTable::Comment("MinAlign") << MatchTable::IntValue(MinAlign)
1890 << MatchTable::LineBreak;
1891 }
1892};
1893
Daniel Sandersf84bc372018-05-05 20:53:24 +00001894/// Generates code to check that the size of an MMO is less-than, equal-to, or
1895/// greater than a given LLT.
1896class MemoryVsLLTSizePredicateMatcher : public InstructionPredicateMatcher {
1897public:
1898 enum RelationKind {
1899 GreaterThan,
1900 EqualTo,
1901 LessThan,
1902 };
1903
1904protected:
1905 unsigned MMOIdx;
1906 RelationKind Relation;
1907 unsigned OpIdx;
1908
1909public:
1910 MemoryVsLLTSizePredicateMatcher(unsigned InsnVarID, unsigned MMOIdx,
1911 enum RelationKind Relation,
1912 unsigned OpIdx)
1913 : InstructionPredicateMatcher(IPM_MemoryVsLLTSize, InsnVarID),
1914 MMOIdx(MMOIdx), Relation(Relation), OpIdx(OpIdx) {}
1915
1916 static bool classof(const PredicateMatcher *P) {
1917 return P->getKind() == IPM_MemoryVsLLTSize;
1918 }
1919 bool isIdentical(const PredicateMatcher &B) const override {
1920 return InstructionPredicateMatcher::isIdentical(B) &&
1921 MMOIdx == cast<MemoryVsLLTSizePredicateMatcher>(&B)->MMOIdx &&
1922 Relation == cast<MemoryVsLLTSizePredicateMatcher>(&B)->Relation &&
1923 OpIdx == cast<MemoryVsLLTSizePredicateMatcher>(&B)->OpIdx;
1924 }
1925
1926 void emitPredicateOpcodes(MatchTable &Table,
1927 RuleMatcher &Rule) const override {
1928 Table << MatchTable::Opcode(Relation == EqualTo
1929 ? "GIM_CheckMemorySizeEqualToLLT"
1930 : Relation == GreaterThan
1931 ? "GIM_CheckMemorySizeGreaterThanLLT"
1932 : "GIM_CheckMemorySizeLessThanLLT")
1933 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1934 << MatchTable::Comment("MMO") << MatchTable::IntValue(MMOIdx)
1935 << MatchTable::Comment("OpIdx") << MatchTable::IntValue(OpIdx)
1936 << MatchTable::LineBreak;
1937 }
1938};
1939
Daniel Sanders8ead1292018-06-15 23:13:43 +00001940/// Generates code to check an arbitrary C++ instruction predicate.
1941class GenericInstructionPredicateMatcher : public InstructionPredicateMatcher {
1942protected:
1943 TreePredicateFn Predicate;
1944
1945public:
1946 GenericInstructionPredicateMatcher(unsigned InsnVarID,
1947 TreePredicateFn Predicate)
1948 : InstructionPredicateMatcher(IPM_GenericPredicate, InsnVarID),
1949 Predicate(Predicate) {}
1950
1951 static bool classof(const InstructionPredicateMatcher *P) {
1952 return P->getKind() == IPM_GenericPredicate;
1953 }
Daniel Sanders06f4ff12018-09-25 17:59:02 +00001954 bool isIdentical(const PredicateMatcher &B) const override {
1955 return InstructionPredicateMatcher::isIdentical(B) &&
1956 Predicate ==
1957 static_cast<const GenericInstructionPredicateMatcher &>(B)
1958 .Predicate;
1959 }
Daniel Sanders8ead1292018-06-15 23:13:43 +00001960 void emitPredicateOpcodes(MatchTable &Table,
1961 RuleMatcher &Rule) const override {
1962 Table << MatchTable::Opcode("GIM_CheckCxxInsnPredicate")
1963 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
1964 << MatchTable::Comment("FnId")
1965 << MatchTable::NamedValue(getEnumNameForPredicate(Predicate))
1966 << MatchTable::LineBreak;
1967 }
1968};
1969
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001970/// Generates code to check that a set of predicates and operands match for a
1971/// particular instruction.
1972///
1973/// Typical predicates include:
1974/// * Has a specific opcode.
1975/// * Has an nsw/nuw flag or doesn't.
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001976class InstructionMatcher final : public PredicateListMatcher<PredicateMatcher> {
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001977protected:
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001978 typedef std::vector<std::unique_ptr<OperandMatcher>> OperandVec;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001979
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001980 RuleMatcher &Rule;
1981
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001982 /// The operands to match. All rendered operands must be present even if the
1983 /// condition is always true.
1984 OperandVec Operands;
Roman Tereshin19da6672018-05-22 04:31:50 +00001985 bool NumOperandsCheck = true;
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001986
Daniel Sanders05540042017-08-08 10:44:31 +00001987 std::string SymbolicName;
Quentin Colombetaad20be2017-12-15 23:07:42 +00001988 unsigned InsnVarID;
Daniel Sanders05540042017-08-08 10:44:31 +00001989
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001990public:
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001991 InstructionMatcher(RuleMatcher &Rule, StringRef SymbolicName)
Quentin Colombetaad20be2017-12-15 23:07:42 +00001992 : Rule(Rule), SymbolicName(SymbolicName) {
1993 // We create a new instruction matcher.
1994 // Get a new ID for that instruction.
1995 InsnVarID = Rule.implicitlyDefineInsnVar(*this);
1996 }
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00001997
Roman Tereshinf1aa3482018-05-21 23:28:51 +00001998 /// Construct a new instruction predicate and add it to the matcher.
1999 template <class Kind, class... Args>
2000 Optional<Kind *> addPredicate(Args &&... args) {
2001 Predicates.emplace_back(
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00002002 std::make_unique<Kind>(getInsnVarID(), std::forward<Args>(args)...));
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002003 return static_cast<Kind *>(Predicates.back().get());
2004 }
2005
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002006 RuleMatcher &getRuleMatcher() const { return Rule; }
Daniel Sanders05540042017-08-08 10:44:31 +00002007
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002008 unsigned getInsnVarID() const { return InsnVarID; }
Quentin Colombetaad20be2017-12-15 23:07:42 +00002009
Daniel Sandersdc662ff2017-01-26 11:10:14 +00002010 /// Add an operand to the matcher.
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002011 OperandMatcher &addOperand(unsigned OpIdx, const std::string &SymbolicName,
2012 unsigned AllocatedTemporariesBaseID) {
2013 Operands.emplace_back(new OperandMatcher(*this, OpIdx, SymbolicName,
2014 AllocatedTemporariesBaseID));
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002015 if (!SymbolicName.empty())
2016 Rule.defineOperand(SymbolicName, *Operands.back());
2017
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002018 return *Operands.back();
Daniel Sandersdc662ff2017-01-26 11:10:14 +00002019 }
2020
Daniel Sandersffc7d582017-03-29 15:37:18 +00002021 OperandMatcher &getOperand(unsigned OpIdx) {
2022 auto I = std::find_if(Operands.begin(), Operands.end(),
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002023 [&OpIdx](const std::unique_ptr<OperandMatcher> &X) {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002024 return X->getOpIdx() == OpIdx;
Daniel Sandersffc7d582017-03-29 15:37:18 +00002025 });
2026 if (I != Operands.end())
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002027 return **I;
Daniel Sandersffc7d582017-03-29 15:37:18 +00002028 llvm_unreachable("Failed to lookup operand");
2029 }
2030
Daniel Sanders05540042017-08-08 10:44:31 +00002031 StringRef getSymbolicName() const { return SymbolicName; }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002032 unsigned getNumOperands() const { return Operands.size(); }
Daniel Sandersbee57392017-04-04 13:25:23 +00002033 OperandVec::iterator operands_begin() { return Operands.begin(); }
2034 OperandVec::iterator operands_end() { return Operands.end(); }
2035 iterator_range<OperandVec::iterator> operands() {
2036 return make_range(operands_begin(), operands_end());
2037 }
Daniel Sandersffc7d582017-03-29 15:37:18 +00002038 OperandVec::const_iterator operands_begin() const { return Operands.begin(); }
2039 OperandVec::const_iterator operands_end() const { return Operands.end(); }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002040 iterator_range<OperandVec::const_iterator> operands() const {
2041 return make_range(operands_begin(), operands_end());
2042 }
Quentin Colombetec76d9c2017-12-18 19:47:41 +00002043 bool operands_empty() const { return Operands.empty(); }
2044
2045 void pop_front() { Operands.erase(Operands.begin()); }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002046
Roman Tereshin19da6672018-05-22 04:31:50 +00002047 void optimize();
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002048
2049 /// Emit MatchTable opcodes that test whether the instruction named in
2050 /// InsnVarName matches all the predicates and all the operands.
2051 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule) {
Roman Tereshin19da6672018-05-22 04:31:50 +00002052 if (NumOperandsCheck)
2053 InstructionNumOperandsMatcher(InsnVarID, getNumOperands())
2054 .emitPredicateOpcodes(Table, Rule);
Daniel Sandersb96f40d2017-03-20 15:20:42 +00002055
Quentin Colombetaad20be2017-12-15 23:07:42 +00002056 emitPredicateListOpcodes(Table, Rule);
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002057
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002058 for (const auto &Operand : Operands)
Quentin Colombetaad20be2017-12-15 23:07:42 +00002059 Operand->emitPredicateOpcodes(Table, Rule);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002060 }
Daniel Sanders759ff412017-02-24 13:58:11 +00002061
2062 /// Compare the priority of this object and B.
2063 ///
2064 /// Returns true if this object is more important than B.
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002065 bool isHigherPriorityThan(InstructionMatcher &B) {
Daniel Sanders759ff412017-02-24 13:58:11 +00002066 // Instruction matchers involving more operands have higher priority.
2067 if (Operands.size() > B.Operands.size())
2068 return true;
2069 if (Operands.size() < B.Operands.size())
2070 return false;
2071
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002072 for (auto &&P : zip(predicates(), B.predicates())) {
2073 auto L = static_cast<InstructionPredicateMatcher *>(std::get<0>(P).get());
2074 auto R = static_cast<InstructionPredicateMatcher *>(std::get<1>(P).get());
2075 if (L->isHigherPriorityThan(*R))
Daniel Sanders759ff412017-02-24 13:58:11 +00002076 return true;
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002077 if (R->isHigherPriorityThan(*L))
Daniel Sanders759ff412017-02-24 13:58:11 +00002078 return false;
2079 }
2080
2081 for (const auto &Operand : zip(Operands, B.Operands)) {
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002082 if (std::get<0>(Operand)->isHigherPriorityThan(*std::get<1>(Operand)))
Daniel Sanders759ff412017-02-24 13:58:11 +00002083 return true;
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002084 if (std::get<1>(Operand)->isHigherPriorityThan(*std::get<0>(Operand)))
Daniel Sanders759ff412017-02-24 13:58:11 +00002085 return false;
2086 }
2087
2088 return false;
2089 };
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002090
2091 /// Report the maximum number of temporary operands needed by the instruction
2092 /// matcher.
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002093 unsigned countRendererFns() {
2094 return std::accumulate(
2095 predicates().begin(), predicates().end(), 0,
2096 [](unsigned A,
2097 const std::unique_ptr<PredicateMatcher> &Predicate) {
2098 return A + Predicate->countRendererFns();
2099 }) +
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002100 std::accumulate(
2101 Operands.begin(), Operands.end(), 0,
2102 [](unsigned A, const std::unique_ptr<OperandMatcher> &Operand) {
Daniel Sanders2deea182017-04-22 15:11:04 +00002103 return A + Operand->countRendererFns();
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002104 });
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002105 }
Daniel Sanders05540042017-08-08 10:44:31 +00002106
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002107 InstructionOpcodeMatcher &getOpcodeMatcher() {
2108 for (auto &P : predicates())
2109 if (auto *OpMatcher = dyn_cast<InstructionOpcodeMatcher>(P.get()))
2110 return *OpMatcher;
2111 llvm_unreachable("Didn't find an opcode matcher");
2112 }
2113
2114 bool isConstantInstruction() {
2115 return getOpcodeMatcher().isConstantInstruction();
Daniel Sanders05540042017-08-08 10:44:31 +00002116 }
Roman Tereshin19da6672018-05-22 04:31:50 +00002117
2118 StringRef getOpcode() { return getOpcodeMatcher().getOpcode(); }
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002119};
2120
Roman Tereshin19da6672018-05-22 04:31:50 +00002121StringRef RuleMatcher::getOpcode() const {
2122 return Matchers.front()->getOpcode();
2123}
2124
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002125unsigned RuleMatcher::getNumOperands() const {
2126 return Matchers.front()->getNumOperands();
2127}
2128
Roman Tereshin9a9fa492018-05-23 21:30:16 +00002129LLTCodeGen RuleMatcher::getFirstConditionAsRootType() {
2130 InstructionMatcher &InsnMatcher = *Matchers.front();
2131 if (!InsnMatcher.predicates_empty())
2132 if (const auto *TM =
2133 dyn_cast<LLTOperandMatcher>(&**InsnMatcher.predicates_begin()))
2134 if (TM->getInsnVarID() == 0 && TM->getOpIdx() == 0)
2135 return TM->getTy();
2136 return {};
2137}
2138
Daniel Sandersbee57392017-04-04 13:25:23 +00002139/// Generates code to check that the operand is a register defined by an
2140/// instruction that matches the given instruction matcher.
2141///
2142/// For example, the pattern:
2143/// (set $dst, (G_MUL (G_ADD $src1, $src2), $src3))
2144/// would use an InstructionOperandMatcher for operand 1 of the G_MUL to match
2145/// the:
2146/// (G_ADD $src1, $src2)
2147/// subpattern.
2148class InstructionOperandMatcher : public OperandPredicateMatcher {
2149protected:
2150 std::unique_ptr<InstructionMatcher> InsnMatcher;
2151
2152public:
Quentin Colombeteba10cb2017-12-18 22:12:13 +00002153 InstructionOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
2154 RuleMatcher &Rule, StringRef SymbolicName)
Quentin Colombetaad20be2017-12-15 23:07:42 +00002155 : OperandPredicateMatcher(OPM_Instruction, InsnVarID, OpIdx),
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002156 InsnMatcher(new InstructionMatcher(Rule, SymbolicName)) {}
Daniel Sandersbee57392017-04-04 13:25:23 +00002157
Quentin Colombet063d7982017-12-14 23:44:07 +00002158 static bool classof(const PredicateMatcher *P) {
Daniel Sandersbee57392017-04-04 13:25:23 +00002159 return P->getKind() == OPM_Instruction;
2160 }
2161
2162 InstructionMatcher &getInsnMatcher() const { return *InsnMatcher; }
2163
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002164 void emitCaptureOpcodes(MatchTable &Table, RuleMatcher &Rule) const {
2165 const unsigned NewInsnVarID = InsnMatcher->getInsnVarID();
2166 Table << MatchTable::Opcode("GIM_RecordInsn")
2167 << MatchTable::Comment("DefineMI")
2168 << MatchTable::IntValue(NewInsnVarID) << MatchTable::Comment("MI")
2169 << MatchTable::IntValue(getInsnVarID())
2170 << MatchTable::Comment("OpIdx") << MatchTable::IntValue(getOpIdx())
2171 << MatchTable::Comment("MIs[" + llvm::to_string(NewInsnVarID) + "]")
2172 << MatchTable::LineBreak;
Daniel Sandersbee57392017-04-04 13:25:23 +00002173 }
2174
Quentin Colombetaad20be2017-12-15 23:07:42 +00002175 void emitPredicateOpcodes(MatchTable &Table,
2176 RuleMatcher &Rule) const override {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002177 emitCaptureOpcodes(Table, Rule);
Quentin Colombetaad20be2017-12-15 23:07:42 +00002178 InsnMatcher->emitPredicateOpcodes(Table, Rule);
Daniel Sandersbee57392017-04-04 13:25:23 +00002179 }
Daniel Sanders12e6e702018-01-17 20:34:29 +00002180
2181 bool isHigherPriorityThan(const OperandPredicateMatcher &B) const override {
2182 if (OperandPredicateMatcher::isHigherPriorityThan(B))
2183 return true;
2184 if (B.OperandPredicateMatcher::isHigherPriorityThan(*this))
2185 return false;
2186
2187 if (const InstructionOperandMatcher *BP =
2188 dyn_cast<InstructionOperandMatcher>(&B))
2189 if (InsnMatcher->isHigherPriorityThan(*BP->InsnMatcher))
2190 return true;
2191 return false;
2192 }
Daniel Sandersbee57392017-04-04 13:25:23 +00002193};
2194
Roman Tereshin19da6672018-05-22 04:31:50 +00002195void InstructionMatcher::optimize() {
2196 SmallVector<std::unique_ptr<PredicateMatcher>, 8> Stash;
2197 const auto &OpcMatcher = getOpcodeMatcher();
2198
2199 Stash.push_back(predicates_pop_front());
2200 if (Stash.back().get() == &OpcMatcher) {
2201 if (NumOperandsCheck && OpcMatcher.getNumOperands() < getNumOperands())
2202 Stash.emplace_back(
2203 new InstructionNumOperandsMatcher(InsnVarID, getNumOperands()));
2204 NumOperandsCheck = false;
Roman Tereshinfedae332018-05-23 02:04:19 +00002205
2206 for (auto &OM : Operands)
2207 for (auto &OP : OM->predicates())
2208 if (isa<IntrinsicIDOperandMatcher>(OP)) {
2209 Stash.push_back(std::move(OP));
2210 OM->eraseNullPredicates();
2211 break;
2212 }
Roman Tereshin19da6672018-05-22 04:31:50 +00002213 }
2214
2215 if (InsnVarID > 0) {
2216 assert(!Operands.empty() && "Nested instruction is expected to def a vreg");
2217 for (auto &OP : Operands[0]->predicates())
2218 OP.reset();
2219 Operands[0]->eraseNullPredicates();
2220 }
Roman Tereshinb1ba1272018-05-23 19:16:59 +00002221 for (auto &OM : Operands) {
2222 for (auto &OP : OM->predicates())
2223 if (isa<LLTOperandMatcher>(OP))
2224 Stash.push_back(std::move(OP));
2225 OM->eraseNullPredicates();
2226 }
Roman Tereshin19da6672018-05-22 04:31:50 +00002227 while (!Stash.empty())
2228 prependPredicate(Stash.pop_back_val());
2229}
2230
Daniel Sanders43c882c2017-02-01 10:53:10 +00002231//===- Actions ------------------------------------------------------------===//
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002232class OperandRenderer {
2233public:
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002234 enum RendererKind {
2235 OR_Copy,
Daniel Sandersd66e0902017-10-23 18:19:24 +00002236 OR_CopyOrAddZeroReg,
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002237 OR_CopySubReg,
Daniel Sanders05540042017-08-08 10:44:31 +00002238 OR_CopyConstantAsImm,
Daniel Sanders11300ce2017-10-13 21:28:03 +00002239 OR_CopyFConstantAsFPImm,
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002240 OR_Imm,
2241 OR_Register,
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002242 OR_TempRegister,
Volkan Kelesf7f25682018-01-16 18:44:05 +00002243 OR_ComplexPattern,
2244 OR_Custom
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002245 };
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002246
2247protected:
2248 RendererKind Kind;
2249
2250public:
2251 OperandRenderer(RendererKind Kind) : Kind(Kind) {}
2252 virtual ~OperandRenderer() {}
2253
2254 RendererKind getKind() const { return Kind; }
2255
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002256 virtual void emitRenderOpcodes(MatchTable &Table,
2257 RuleMatcher &Rule) const = 0;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002258};
2259
2260/// A CopyRenderer emits code to copy a single operand from an existing
2261/// instruction to the one being built.
2262class CopyRenderer : public OperandRenderer {
2263protected:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002264 unsigned NewInsnID;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002265 /// The name of the operand.
2266 const StringRef SymbolicName;
2267
2268public:
Daniel Sandersbd83ad42017-10-24 01:48:34 +00002269 CopyRenderer(unsigned NewInsnID, StringRef SymbolicName)
2270 : OperandRenderer(OR_Copy), NewInsnID(NewInsnID),
Daniel Sanders05540042017-08-08 10:44:31 +00002271 SymbolicName(SymbolicName) {
2272 assert(!SymbolicName.empty() && "Cannot copy from an unspecified source");
2273 }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002274
2275 static bool classof(const OperandRenderer *R) {
2276 return R->getKind() == OR_Copy;
2277 }
2278
2279 const StringRef getSymbolicName() const { return SymbolicName; }
2280
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002281 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002282 const OperandMatcher &Operand = Rule.getOperandMatcher(SymbolicName);
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002283 unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002284 Table << MatchTable::Opcode("GIR_Copy") << MatchTable::Comment("NewInsnID")
2285 << MatchTable::IntValue(NewInsnID) << MatchTable::Comment("OldInsnID")
2286 << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002287 << MatchTable::IntValue(Operand.getOpIdx())
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002288 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002289 }
2290};
2291
Daniel Sandersd66e0902017-10-23 18:19:24 +00002292/// A CopyOrAddZeroRegRenderer emits code to copy a single operand from an
2293/// existing instruction to the one being built. If the operand turns out to be
2294/// a 'G_CONSTANT 0' then it replaces the operand with a zero register.
2295class CopyOrAddZeroRegRenderer : public OperandRenderer {
2296protected:
2297 unsigned NewInsnID;
2298 /// The name of the operand.
2299 const StringRef SymbolicName;
2300 const Record *ZeroRegisterDef;
2301
2302public:
2303 CopyOrAddZeroRegRenderer(unsigned NewInsnID,
Daniel Sandersd66e0902017-10-23 18:19:24 +00002304 StringRef SymbolicName, Record *ZeroRegisterDef)
2305 : OperandRenderer(OR_CopyOrAddZeroReg), NewInsnID(NewInsnID),
2306 SymbolicName(SymbolicName), ZeroRegisterDef(ZeroRegisterDef) {
2307 assert(!SymbolicName.empty() && "Cannot copy from an unspecified source");
2308 }
2309
2310 static bool classof(const OperandRenderer *R) {
2311 return R->getKind() == OR_CopyOrAddZeroReg;
2312 }
2313
2314 const StringRef getSymbolicName() const { return SymbolicName; }
2315
2316 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2317 const OperandMatcher &Operand = Rule.getOperandMatcher(SymbolicName);
2318 unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
2319 Table << MatchTable::Opcode("GIR_CopyOrAddZeroReg")
2320 << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
2321 << MatchTable::Comment("OldInsnID")
2322 << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002323 << MatchTable::IntValue(Operand.getOpIdx())
Daniel Sandersd66e0902017-10-23 18:19:24 +00002324 << MatchTable::NamedValue(
2325 (ZeroRegisterDef->getValue("Namespace")
2326 ? ZeroRegisterDef->getValueAsString("Namespace")
2327 : ""),
2328 ZeroRegisterDef->getName())
2329 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2330 }
2331};
2332
Daniel Sanders05540042017-08-08 10:44:31 +00002333/// A CopyConstantAsImmRenderer emits code to render a G_CONSTANT instruction to
2334/// an extended immediate operand.
2335class CopyConstantAsImmRenderer : public OperandRenderer {
2336protected:
2337 unsigned NewInsnID;
2338 /// The name of the operand.
2339 const std::string SymbolicName;
2340 bool Signed;
2341
2342public:
2343 CopyConstantAsImmRenderer(unsigned NewInsnID, StringRef SymbolicName)
2344 : OperandRenderer(OR_CopyConstantAsImm), NewInsnID(NewInsnID),
2345 SymbolicName(SymbolicName), Signed(true) {}
2346
2347 static bool classof(const OperandRenderer *R) {
2348 return R->getKind() == OR_CopyConstantAsImm;
2349 }
2350
2351 const StringRef getSymbolicName() const { return SymbolicName; }
2352
2353 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002354 InstructionMatcher &InsnMatcher = Rule.getInstructionMatcher(SymbolicName);
Daniel Sanders05540042017-08-08 10:44:31 +00002355 unsigned OldInsnVarID = Rule.getInsnVarID(InsnMatcher);
2356 Table << MatchTable::Opcode(Signed ? "GIR_CopyConstantAsSImm"
2357 : "GIR_CopyConstantAsUImm")
2358 << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
2359 << MatchTable::Comment("OldInsnID")
2360 << MatchTable::IntValue(OldInsnVarID)
2361 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2362 }
2363};
2364
Daniel Sanders11300ce2017-10-13 21:28:03 +00002365/// A CopyFConstantAsFPImmRenderer emits code to render a G_FCONSTANT
2366/// instruction to an extended immediate operand.
2367class CopyFConstantAsFPImmRenderer : public OperandRenderer {
2368protected:
2369 unsigned NewInsnID;
2370 /// The name of the operand.
2371 const std::string SymbolicName;
2372
2373public:
2374 CopyFConstantAsFPImmRenderer(unsigned NewInsnID, StringRef SymbolicName)
2375 : OperandRenderer(OR_CopyFConstantAsFPImm), NewInsnID(NewInsnID),
2376 SymbolicName(SymbolicName) {}
2377
2378 static bool classof(const OperandRenderer *R) {
2379 return R->getKind() == OR_CopyFConstantAsFPImm;
2380 }
2381
2382 const StringRef getSymbolicName() const { return SymbolicName; }
2383
2384 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002385 InstructionMatcher &InsnMatcher = Rule.getInstructionMatcher(SymbolicName);
Daniel Sanders11300ce2017-10-13 21:28:03 +00002386 unsigned OldInsnVarID = Rule.getInsnVarID(InsnMatcher);
2387 Table << MatchTable::Opcode("GIR_CopyFConstantAsFPImm")
2388 << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
2389 << MatchTable::Comment("OldInsnID")
2390 << MatchTable::IntValue(OldInsnVarID)
2391 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2392 }
2393};
2394
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002395/// A CopySubRegRenderer emits code to copy a single register operand from an
2396/// existing instruction to the one being built and indicate that only a
2397/// subregister should be copied.
2398class CopySubRegRenderer : public OperandRenderer {
2399protected:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002400 unsigned NewInsnID;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002401 /// The name of the operand.
2402 const StringRef SymbolicName;
2403 /// The subregister to extract.
2404 const CodeGenSubRegIndex *SubReg;
2405
2406public:
Daniel Sandersbd83ad42017-10-24 01:48:34 +00002407 CopySubRegRenderer(unsigned NewInsnID, StringRef SymbolicName,
2408 const CodeGenSubRegIndex *SubReg)
2409 : OperandRenderer(OR_CopySubReg), NewInsnID(NewInsnID),
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002410 SymbolicName(SymbolicName), SubReg(SubReg) {}
2411
2412 static bool classof(const OperandRenderer *R) {
2413 return R->getKind() == OR_CopySubReg;
2414 }
2415
2416 const StringRef getSymbolicName() const { return SymbolicName; }
2417
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002418 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002419 const OperandMatcher &Operand = Rule.getOperandMatcher(SymbolicName);
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002420 unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002421 Table << MatchTable::Opcode("GIR_CopySubReg")
2422 << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
2423 << MatchTable::Comment("OldInsnID")
2424 << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002425 << MatchTable::IntValue(Operand.getOpIdx())
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002426 << MatchTable::Comment("SubRegIdx")
2427 << MatchTable::IntValue(SubReg->EnumValue)
2428 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002429 }
2430};
2431
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002432/// Adds a specific physical register to the instruction being built.
2433/// This is typically useful for WZR/XZR on AArch64.
2434class AddRegisterRenderer : public OperandRenderer {
2435protected:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002436 unsigned InsnID;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002437 const Record *RegisterDef;
2438
2439public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002440 AddRegisterRenderer(unsigned InsnID, const Record *RegisterDef)
2441 : OperandRenderer(OR_Register), InsnID(InsnID), RegisterDef(RegisterDef) {
2442 }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002443
2444 static bool classof(const OperandRenderer *R) {
2445 return R->getKind() == OR_Register;
2446 }
2447
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002448 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2449 Table << MatchTable::Opcode("GIR_AddRegister")
2450 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2451 << MatchTable::NamedValue(
2452 (RegisterDef->getValue("Namespace")
2453 ? RegisterDef->getValueAsString("Namespace")
2454 : ""),
2455 RegisterDef->getName())
2456 << MatchTable::LineBreak;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002457 }
2458};
2459
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002460/// Adds a specific temporary virtual register to the instruction being built.
2461/// This is used to chain instructions together when emitting multiple
2462/// instructions.
2463class TempRegRenderer : public OperandRenderer {
2464protected:
2465 unsigned InsnID;
2466 unsigned TempRegID;
2467 bool IsDef;
2468
2469public:
2470 TempRegRenderer(unsigned InsnID, unsigned TempRegID, bool IsDef = false)
2471 : OperandRenderer(OR_Register), InsnID(InsnID), TempRegID(TempRegID),
2472 IsDef(IsDef) {}
2473
2474 static bool classof(const OperandRenderer *R) {
2475 return R->getKind() == OR_TempRegister;
2476 }
2477
2478 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2479 Table << MatchTable::Opcode("GIR_AddTempRegister")
2480 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2481 << MatchTable::Comment("TempRegID") << MatchTable::IntValue(TempRegID)
2482 << MatchTable::Comment("TempRegFlags");
2483 if (IsDef)
2484 Table << MatchTable::NamedValue("RegState::Define");
2485 else
2486 Table << MatchTable::IntValue(0);
2487 Table << MatchTable::LineBreak;
2488 }
2489};
2490
Daniel Sanders0ed28822017-04-12 08:23:08 +00002491/// Adds a specific immediate to the instruction being built.
2492class ImmRenderer : public OperandRenderer {
2493protected:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002494 unsigned InsnID;
Daniel Sanders0ed28822017-04-12 08:23:08 +00002495 int64_t Imm;
2496
2497public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002498 ImmRenderer(unsigned InsnID, int64_t Imm)
2499 : OperandRenderer(OR_Imm), InsnID(InsnID), Imm(Imm) {}
Daniel Sanders0ed28822017-04-12 08:23:08 +00002500
2501 static bool classof(const OperandRenderer *R) {
2502 return R->getKind() == OR_Imm;
2503 }
2504
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002505 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2506 Table << MatchTable::Opcode("GIR_AddImm") << MatchTable::Comment("InsnID")
2507 << MatchTable::IntValue(InsnID) << MatchTable::Comment("Imm")
2508 << MatchTable::IntValue(Imm) << MatchTable::LineBreak;
Daniel Sanders0ed28822017-04-12 08:23:08 +00002509 }
2510};
2511
Daniel Sanders2deea182017-04-22 15:11:04 +00002512/// Adds operands by calling a renderer function supplied by the ComplexPattern
2513/// matcher function.
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002514class RenderComplexPatternOperand : public OperandRenderer {
2515private:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002516 unsigned InsnID;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002517 const Record &TheDef;
Daniel Sanders2deea182017-04-22 15:11:04 +00002518 /// The name of the operand.
2519 const StringRef SymbolicName;
2520 /// The renderer number. This must be unique within a rule since it's used to
2521 /// identify a temporary variable to hold the renderer function.
2522 unsigned RendererID;
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002523 /// When provided, this is the suboperand of the ComplexPattern operand to
2524 /// render. Otherwise all the suboperands will be rendered.
2525 Optional<unsigned> SubOperand;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002526
2527 unsigned getNumOperands() const {
2528 return TheDef.getValueAsDag("Operands")->getNumArgs();
2529 }
2530
2531public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002532 RenderComplexPatternOperand(unsigned InsnID, const Record &TheDef,
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002533 StringRef SymbolicName, unsigned RendererID,
2534 Optional<unsigned> SubOperand = None)
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002535 : OperandRenderer(OR_ComplexPattern), InsnID(InsnID), TheDef(TheDef),
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002536 SymbolicName(SymbolicName), RendererID(RendererID),
2537 SubOperand(SubOperand) {}
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002538
2539 static bool classof(const OperandRenderer *R) {
2540 return R->getKind() == OR_ComplexPattern;
2541 }
2542
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002543 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002544 Table << MatchTable::Opcode(SubOperand.hasValue() ? "GIR_ComplexSubOperandRenderer"
2545 : "GIR_ComplexRenderer")
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002546 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2547 << MatchTable::Comment("RendererID")
Daniel Sandersdf39cba2017-10-15 18:22:54 +00002548 << MatchTable::IntValue(RendererID);
2549 if (SubOperand.hasValue())
2550 Table << MatchTable::Comment("SubOperand")
2551 << MatchTable::IntValue(SubOperand.getValue());
2552 Table << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002553 }
2554};
2555
Volkan Kelesf7f25682018-01-16 18:44:05 +00002556class CustomRenderer : public OperandRenderer {
2557protected:
2558 unsigned InsnID;
2559 const Record &Renderer;
2560 /// The name of the operand.
2561 const std::string SymbolicName;
2562
2563public:
2564 CustomRenderer(unsigned InsnID, const Record &Renderer,
2565 StringRef SymbolicName)
2566 : OperandRenderer(OR_Custom), InsnID(InsnID), Renderer(Renderer),
2567 SymbolicName(SymbolicName) {}
2568
2569 static bool classof(const OperandRenderer *R) {
2570 return R->getKind() == OR_Custom;
2571 }
2572
2573 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002574 InstructionMatcher &InsnMatcher = Rule.getInstructionMatcher(SymbolicName);
Volkan Kelesf7f25682018-01-16 18:44:05 +00002575 unsigned OldInsnVarID = Rule.getInsnVarID(InsnMatcher);
2576 Table << MatchTable::Opcode("GIR_CustomRenderer")
2577 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2578 << MatchTable::Comment("OldInsnID")
2579 << MatchTable::IntValue(OldInsnVarID)
2580 << MatchTable::Comment("Renderer")
2581 << MatchTable::NamedValue(
2582 "GICR_" + Renderer.getValueAsString("RendererFn").str())
2583 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
2584 }
2585};
2586
Ahmed Bougacha56ca3a92017-02-04 00:47:10 +00002587/// An action taken when all Matcher predicates succeeded for a parent rule.
2588///
2589/// Typical actions include:
2590/// * Changing the opcode of an instruction.
2591/// * Adding an operand to an instruction.
Daniel Sanders43c882c2017-02-01 10:53:10 +00002592class MatchAction {
2593public:
2594 virtual ~MatchAction() {}
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002595
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002596 /// Emit the MatchTable opcodes to implement the action.
Daniel Sandersa7b75262017-10-31 18:50:24 +00002597 virtual void emitActionOpcodes(MatchTable &Table,
2598 RuleMatcher &Rule) const = 0;
Daniel Sanders43c882c2017-02-01 10:53:10 +00002599};
2600
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +00002601/// Generates a comment describing the matched rule being acted upon.
2602class DebugCommentAction : public MatchAction {
2603private:
Daniel Sanders6ea17ed2017-10-31 18:07:03 +00002604 std::string S;
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +00002605
2606public:
Daniel Sanders6ea17ed2017-10-31 18:07:03 +00002607 DebugCommentAction(StringRef S) : S(S) {}
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +00002608
Daniel Sandersa7b75262017-10-31 18:50:24 +00002609 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sanders6ea17ed2017-10-31 18:07:03 +00002610 Table << MatchTable::Comment(S) << MatchTable::LineBreak;
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +00002611 }
2612};
2613
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002614/// Generates code to build an instruction or mutate an existing instruction
2615/// into the desired instruction when this is possible.
2616class BuildMIAction : public MatchAction {
Daniel Sanders43c882c2017-02-01 10:53:10 +00002617private:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002618 unsigned InsnID;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002619 const CodeGenInstruction *I;
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002620 InstructionMatcher *Matched;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002621 std::vector<std::unique_ptr<OperandRenderer>> OperandRenderers;
2622
2623 /// True if the instruction can be built solely by mutating the opcode.
Daniel Sandersa7b75262017-10-31 18:50:24 +00002624 bool canMutate(RuleMatcher &Rule, const InstructionMatcher *Insn) const {
2625 if (!Insn)
Daniel Sandersab1d1192017-10-24 18:11:54 +00002626 return false;
2627
Daniel Sandersa7b75262017-10-31 18:50:24 +00002628 if (OperandRenderers.size() != Insn->getNumOperands())
Daniel Sanderse9fdba32017-04-29 17:30:09 +00002629 return false;
2630
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002631 for (const auto &Renderer : enumerate(OperandRenderers)) {
Zachary Turner309a0882017-03-13 16:24:10 +00002632 if (const auto *Copy = dyn_cast<CopyRenderer>(&*Renderer.value())) {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002633 const OperandMatcher &OM = Rule.getOperandMatcher(Copy->getSymbolicName());
Daniel Sandersa7b75262017-10-31 18:50:24 +00002634 if (Insn != &OM.getInstructionMatcher() ||
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002635 OM.getOpIdx() != Renderer.index())
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002636 return false;
2637 } else
2638 return false;
2639 }
2640
2641 return true;
2642 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002643
Daniel Sanders43c882c2017-02-01 10:53:10 +00002644public:
Daniel Sandersa7b75262017-10-31 18:50:24 +00002645 BuildMIAction(unsigned InsnID, const CodeGenInstruction *I)
2646 : InsnID(InsnID), I(I), Matched(nullptr) {}
2647
Daniel Sanders08464522018-01-29 21:09:12 +00002648 unsigned getInsnID() const { return InsnID; }
Daniel Sandersdf258e32017-10-31 19:09:29 +00002649 const CodeGenInstruction *getCGI() const { return I; }
2650
Daniel Sandersa7b75262017-10-31 18:50:24 +00002651 void chooseInsnToMutate(RuleMatcher &Rule) {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002652 for (auto *MutateCandidate : Rule.mutatable_insns()) {
Daniel Sandersa7b75262017-10-31 18:50:24 +00002653 if (canMutate(Rule, MutateCandidate)) {
2654 // Take the first one we're offered that we're able to mutate.
2655 Rule.reserveInsnMatcherForMutation(MutateCandidate);
2656 Matched = MutateCandidate;
2657 return;
2658 }
2659 }
2660 }
Daniel Sanders43c882c2017-02-01 10:53:10 +00002661
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002662 template <class Kind, class... Args>
2663 Kind &addRenderer(Args&&... args) {
2664 OperandRenderers.emplace_back(
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00002665 std::make_unique<Kind>(InsnID, std::forward<Args>(args)...));
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002666 return *static_cast<Kind *>(OperandRenderers.back().get());
2667 }
2668
Daniel Sandersa7b75262017-10-31 18:50:24 +00002669 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2670 if (Matched) {
2671 assert(canMutate(Rule, Matched) &&
2672 "Arranged to mutate an insn that isn't mutatable");
2673
2674 unsigned RecycleInsnID = Rule.getInsnVarID(*Matched);
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002675 Table << MatchTable::Opcode("GIR_MutateOpcode")
2676 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2677 << MatchTable::Comment("RecycleInsnID")
2678 << MatchTable::IntValue(RecycleInsnID)
2679 << MatchTable::Comment("Opcode")
2680 << MatchTable::NamedValue(I->Namespace, I->TheDef->getName())
2681 << MatchTable::LineBreak;
Tim Northover4340d642017-03-20 21:58:23 +00002682
2683 if (!I->ImplicitDefs.empty() || !I->ImplicitUses.empty()) {
Tim Northover4340d642017-03-20 21:58:23 +00002684 for (auto Def : I->ImplicitDefs) {
Diana Picus8abcbbb2017-05-02 09:40:49 +00002685 auto Namespace = Def->getValue("Namespace")
2686 ? Def->getValueAsString("Namespace")
2687 : "";
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002688 Table << MatchTable::Opcode("GIR_AddImplicitDef")
2689 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2690 << MatchTable::NamedValue(Namespace, Def->getName())
2691 << MatchTable::LineBreak;
Tim Northover4340d642017-03-20 21:58:23 +00002692 }
2693 for (auto Use : I->ImplicitUses) {
Diana Picus8abcbbb2017-05-02 09:40:49 +00002694 auto Namespace = Use->getValue("Namespace")
2695 ? Use->getValueAsString("Namespace")
2696 : "";
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002697 Table << MatchTable::Opcode("GIR_AddImplicitUse")
2698 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2699 << MatchTable::NamedValue(Namespace, Use->getName())
2700 << MatchTable::LineBreak;
Tim Northover4340d642017-03-20 21:58:23 +00002701 }
2702 }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002703 return;
2704 }
2705
2706 // TODO: Simple permutation looks like it could be almost as common as
2707 // mutation due to commutative operations.
2708
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002709 Table << MatchTable::Opcode("GIR_BuildMI") << MatchTable::Comment("InsnID")
2710 << MatchTable::IntValue(InsnID) << MatchTable::Comment("Opcode")
2711 << MatchTable::NamedValue(I->Namespace, I->TheDef->getName())
2712 << MatchTable::LineBreak;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002713 for (const auto &Renderer : OperandRenderers)
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002714 Renderer->emitRenderOpcodes(Table, Rule);
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002715
Florian Hahn3bc3ec62017-08-03 14:48:22 +00002716 if (I->mayLoad || I->mayStore) {
2717 Table << MatchTable::Opcode("GIR_MergeMemOperands")
2718 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2719 << MatchTable::Comment("MergeInsnID's");
2720 // Emit the ID's for all the instructions that are matched by this rule.
2721 // TODO: Limit this to matched instructions that mayLoad/mayStore or have
2722 // some other means of having a memoperand. Also limit this to
2723 // emitted instructions that expect to have a memoperand too. For
2724 // example, (G_SEXT (G_LOAD x)) that results in separate load and
2725 // sign-extend instructions shouldn't put the memoperand on the
2726 // sign-extend since it has no effect there.
2727 std::vector<unsigned> MergeInsnIDs;
2728 for (const auto &IDMatcherPair : Rule.defined_insn_vars())
2729 MergeInsnIDs.push_back(IDMatcherPair.second);
Fangrui Song0cac7262018-09-27 02:13:45 +00002730 llvm::sort(MergeInsnIDs);
Florian Hahn3bc3ec62017-08-03 14:48:22 +00002731 for (const auto &MergeInsnID : MergeInsnIDs)
2732 Table << MatchTable::IntValue(MergeInsnID);
Daniel Sanders05540042017-08-08 10:44:31 +00002733 Table << MatchTable::NamedValue("GIU_MergeMemOperands_EndOfList")
2734 << MatchTable::LineBreak;
Florian Hahn3bc3ec62017-08-03 14:48:22 +00002735 }
2736
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002737 // FIXME: This is a hack but it's sufficient for ISel. We'll need to do
2738 // better for combines. Particularly when there are multiple match
2739 // roots.
2740 if (InsnID == 0)
2741 Table << MatchTable::Opcode("GIR_EraseFromParent")
2742 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2743 << MatchTable::LineBreak;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002744 }
2745};
2746
2747/// Generates code to constrain the operands of an output instruction to the
2748/// register classes specified by the definition of that instruction.
2749class ConstrainOperandsToDefinitionAction : public MatchAction {
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002750 unsigned InsnID;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002751
2752public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002753 ConstrainOperandsToDefinitionAction(unsigned InsnID) : InsnID(InsnID) {}
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002754
Daniel Sandersa7b75262017-10-31 18:50:24 +00002755 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002756 Table << MatchTable::Opcode("GIR_ConstrainSelectedInstOperands")
2757 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2758 << MatchTable::LineBreak;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002759 }
2760};
2761
2762/// Generates code to constrain the specified operand of an output instruction
2763/// to the specified register class.
2764class ConstrainOperandToRegClassAction : public MatchAction {
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002765 unsigned InsnID;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002766 unsigned OpIdx;
2767 const CodeGenRegisterClass &RC;
2768
2769public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002770 ConstrainOperandToRegClassAction(unsigned InsnID, unsigned OpIdx,
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002771 const CodeGenRegisterClass &RC)
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002772 : InsnID(InsnID), OpIdx(OpIdx), RC(RC) {}
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002773
Daniel Sandersa7b75262017-10-31 18:50:24 +00002774 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002775 Table << MatchTable::Opcode("GIR_ConstrainOperandRC")
2776 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2777 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
2778 << MatchTable::Comment("RC " + RC.getName())
2779 << MatchTable::IntValue(RC.EnumValue) << MatchTable::LineBreak;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002780 }
2781};
2782
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002783/// Generates code to create a temporary register which can be used to chain
2784/// instructions together.
2785class MakeTempRegisterAction : public MatchAction {
2786private:
2787 LLTCodeGen Ty;
2788 unsigned TempRegID;
2789
2790public:
2791 MakeTempRegisterAction(const LLTCodeGen &Ty, unsigned TempRegID)
2792 : Ty(Ty), TempRegID(TempRegID) {}
2793
2794 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
2795 Table << MatchTable::Opcode("GIR_MakeTempReg")
2796 << MatchTable::Comment("TempRegID") << MatchTable::IntValue(TempRegID)
2797 << MatchTable::Comment("TypeID")
2798 << MatchTable::NamedValue(Ty.getCxxEnumValue())
2799 << MatchTable::LineBreak;
2800 }
2801};
2802
Daniel Sanders05540042017-08-08 10:44:31 +00002803InstructionMatcher &RuleMatcher::addInstructionMatcher(StringRef SymbolicName) {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002804 Matchers.emplace_back(new InstructionMatcher(*this, SymbolicName));
Daniel Sandersa7b75262017-10-31 18:50:24 +00002805 MutatableInsns.insert(Matchers.back().get());
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002806 return *Matchers.back();
2807}
Ahmed Bougacha56ca3a92017-02-04 00:47:10 +00002808
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002809void RuleMatcher::addRequiredFeature(Record *Feature) {
2810 RequiredFeatures.push_back(Feature);
2811}
2812
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002813const std::vector<Record *> &RuleMatcher::getRequiredFeatures() const {
2814 return RequiredFeatures;
2815}
2816
Daniel Sanders7438b262017-10-31 23:03:18 +00002817// Emplaces an action of the specified Kind at the end of the action list.
2818//
2819// Returns a reference to the newly created action.
2820//
2821// Like std::vector::emplace_back(), may invalidate all iterators if the new
2822// size exceeds the capacity. Otherwise, only invalidates the past-the-end
2823// iterator.
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002824template <class Kind, class... Args>
2825Kind &RuleMatcher::addAction(Args &&... args) {
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00002826 Actions.emplace_back(std::make_unique<Kind>(std::forward<Args>(args)...));
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002827 return *static_cast<Kind *>(Actions.back().get());
2828}
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002829
Daniel Sanders7438b262017-10-31 23:03:18 +00002830// Emplaces an action of the specified Kind before the given insertion point.
2831//
2832// Returns an iterator pointing at the newly created instruction.
2833//
2834// Like std::vector::insert(), may invalidate all iterators if the new size
2835// exceeds the capacity. Otherwise, only invalidates the iterators from the
2836// insertion point onwards.
2837template <class Kind, class... Args>
2838action_iterator RuleMatcher::insertAction(action_iterator InsertPt,
2839 Args &&... args) {
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00002840 return Actions.emplace(InsertPt,
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00002841 std::make_unique<Kind>(std::forward<Args>(args)...));
Daniel Sanders7438b262017-10-31 23:03:18 +00002842}
Daniel Sandersdc662ff2017-01-26 11:10:14 +00002843
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002844unsigned RuleMatcher::implicitlyDefineInsnVar(InstructionMatcher &Matcher) {
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002845 unsigned NewInsnVarID = NextInsnVarID++;
2846 InsnVariableIDs[&Matcher] = NewInsnVarID;
2847 return NewInsnVarID;
Daniel Sandersb96f40d2017-03-20 15:20:42 +00002848}
2849
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002850unsigned RuleMatcher::getInsnVarID(InstructionMatcher &InsnMatcher) const {
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002851 const auto &I = InsnVariableIDs.find(&InsnMatcher);
2852 if (I != InsnVariableIDs.end())
Daniel Sandersb96f40d2017-03-20 15:20:42 +00002853 return I->second;
2854 llvm_unreachable("Matched Insn was not captured in a local variable");
2855}
2856
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002857void RuleMatcher::defineOperand(StringRef SymbolicName, OperandMatcher &OM) {
2858 if (DefinedOperands.find(SymbolicName) == DefinedOperands.end()) {
2859 DefinedOperands[SymbolicName] = &OM;
2860 return;
2861 }
2862
2863 // If the operand is already defined, then we must ensure both references in
2864 // the matcher have the exact same node.
2865 OM.addPredicate<SameOperandMatcher>(OM.getSymbolicName());
2866}
2867
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002868InstructionMatcher &
Daniel Sanders05540042017-08-08 10:44:31 +00002869RuleMatcher::getInstructionMatcher(StringRef SymbolicName) const {
2870 for (const auto &I : InsnVariableIDs)
2871 if (I.first->getSymbolicName() == SymbolicName)
2872 return *I.first;
2873 llvm_unreachable(
2874 ("Failed to lookup instruction " + SymbolicName).str().c_str());
2875}
2876
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00002877const OperandMatcher &
2878RuleMatcher::getOperandMatcher(StringRef Name) const {
2879 const auto &I = DefinedOperands.find(Name);
2880
2881 if (I == DefinedOperands.end())
2882 PrintFatalError(SrcLoc, "Operand " + Name + " was not declared in matcher");
2883
2884 return *I->second;
2885}
2886
Daniel Sanders8e82af22017-07-27 11:03:45 +00002887void RuleMatcher::emit(MatchTable &Table) {
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002888 if (Matchers.empty())
2889 llvm_unreachable("Unexpected empty matcher!");
Daniel Sandersdc662ff2017-01-26 11:10:14 +00002890
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002891 // The representation supports rules that require multiple roots such as:
2892 // %ptr(p0) = ...
2893 // %elt0(s32) = G_LOAD %ptr
2894 // %1(p0) = G_ADD %ptr, 4
2895 // %elt1(s32) = G_LOAD p0 %1
2896 // which could be usefully folded into:
2897 // %ptr(p0) = ...
2898 // %elt0(s32), %elt1(s32) = TGT_LOAD_PAIR %ptr
2899 // on some targets but we don't need to make use of that yet.
2900 assert(Matchers.size() == 1 && "Cannot handle multi-root matchers yet");
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002901
Daniel Sanders8e82af22017-07-27 11:03:45 +00002902 unsigned LabelID = Table.allocateLabelID();
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002903 Table << MatchTable::Opcode("GIM_Try", +1)
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002904 << MatchTable::Comment("On fail goto")
2905 << MatchTable::JumpTarget(LabelID)
2906 << MatchTable::Comment(("Rule ID " + Twine(RuleID) + " //").str())
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002907 << MatchTable::LineBreak;
2908
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002909 if (!RequiredFeatures.empty()) {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002910 Table << MatchTable::Opcode("GIM_CheckFeatures")
2911 << MatchTable::NamedValue(getNameForFeatureBitset(RequiredFeatures))
2912 << MatchTable::LineBreak;
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002913 }
Daniel Sandersb96f40d2017-03-20 15:20:42 +00002914
Quentin Colombetaad20be2017-12-15 23:07:42 +00002915 Matchers.front()->emitPredicateOpcodes(Table, *this);
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002916
Daniel Sandersbee57392017-04-04 13:25:23 +00002917 // We must also check if it's safe to fold the matched instructions.
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002918 if (InsnVariableIDs.size() >= 2) {
Galina Kistanova1754fee2017-05-25 01:51:53 +00002919 // Invert the map to create stable ordering (by var names)
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002920 SmallVector<unsigned, 2> InsnIDs;
2921 for (const auto &Pair : InsnVariableIDs) {
Daniel Sandersbee57392017-04-04 13:25:23 +00002922 // Skip the root node since it isn't moving anywhere. Everything else is
2923 // sinking to meet it.
2924 if (Pair.first == Matchers.front().get())
2925 continue;
2926
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002927 InsnIDs.push_back(Pair.second);
Galina Kistanova1754fee2017-05-25 01:51:53 +00002928 }
Fangrui Song0cac7262018-09-27 02:13:45 +00002929 llvm::sort(InsnIDs);
Galina Kistanova1754fee2017-05-25 01:51:53 +00002930
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002931 for (const auto &InsnID : InsnIDs) {
Daniel Sandersbee57392017-04-04 13:25:23 +00002932 // Reject the difficult cases until we have a more accurate check.
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002933 Table << MatchTable::Opcode("GIM_CheckIsSafeToFold")
2934 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
2935 << MatchTable::LineBreak;
Daniel Sandersbee57392017-04-04 13:25:23 +00002936
2937 // FIXME: Emit checks to determine it's _actually_ safe to fold and/or
2938 // account for unsafe cases.
2939 //
2940 // Example:
2941 // MI1--> %0 = ...
2942 // %1 = ... %0
2943 // MI0--> %2 = ... %0
2944 // It's not safe to erase MI1. We currently handle this by not
2945 // erasing %0 (even when it's dead).
2946 //
2947 // Example:
2948 // MI1--> %0 = load volatile @a
2949 // %1 = load volatile @a
2950 // MI0--> %2 = ... %0
2951 // It's not safe to sink %0's def past %1. We currently handle
2952 // this by rejecting all loads.
2953 //
2954 // Example:
2955 // MI1--> %0 = load @a
2956 // %1 = store @a
2957 // MI0--> %2 = ... %0
2958 // It's not safe to sink %0's def past %1. We currently handle
2959 // this by rejecting all loads.
2960 //
2961 // Example:
2962 // G_CONDBR %cond, @BB1
2963 // BB0:
2964 // MI1--> %0 = load @a
2965 // G_BR @BB1
2966 // BB1:
2967 // MI0--> %2 = ... %0
2968 // It's not always safe to sink %0 across control flow. In this
2969 // case it may introduce a memory fault. We currentl handle this
2970 // by rejecting all loads.
2971 }
2972 }
2973
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002974 for (const auto &PM : EpilogueMatchers)
2975 PM->emitPredicateOpcodes(Table, *this);
2976
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002977 for (const auto &MA : Actions)
Daniel Sandersa7b75262017-10-31 18:50:24 +00002978 MA->emitActionOpcodes(Table, *this);
Daniel Sandersf76f3152017-11-16 00:46:35 +00002979
Roman Tereshinbeb39312018-05-02 20:15:11 +00002980 if (Table.isWithCoverage())
Daniel Sandersf76f3152017-11-16 00:46:35 +00002981 Table << MatchTable::Opcode("GIR_Coverage") << MatchTable::IntValue(RuleID)
2982 << MatchTable::LineBreak;
Roman Tereshinf1aa3482018-05-21 23:28:51 +00002983 else
2984 Table << MatchTable::Comment(("GIR_Coverage, " + Twine(RuleID) + ",").str())
2985 << MatchTable::LineBreak;
Daniel Sandersf76f3152017-11-16 00:46:35 +00002986
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00002987 Table << MatchTable::Opcode("GIR_Done", -1) << MatchTable::LineBreak
Daniel Sanders8e82af22017-07-27 11:03:45 +00002988 << MatchTable::Label(LabelID);
Volkan Keles4f3fa792018-01-25 00:18:52 +00002989 ++NumPatternEmitted;
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002990}
Daniel Sanders43c882c2017-02-01 10:53:10 +00002991
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002992bool RuleMatcher::isHigherPriorityThan(const RuleMatcher &B) const {
2993 // Rules involving more match roots have higher priority.
2994 if (Matchers.size() > B.Matchers.size())
2995 return true;
2996 if (Matchers.size() < B.Matchers.size())
Daniel Sanders759ff412017-02-24 13:58:11 +00002997 return false;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002998
Daniel Sandersbdfebb82017-03-15 20:18:38 +00002999 for (const auto &Matcher : zip(Matchers, B.Matchers)) {
3000 if (std::get<0>(Matcher)->isHigherPriorityThan(*std::get<1>(Matcher)))
3001 return true;
3002 if (std::get<1>(Matcher)->isHigherPriorityThan(*std::get<0>(Matcher)))
3003 return false;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00003004 }
Daniel Sandersbdfebb82017-03-15 20:18:38 +00003005
3006 return false;
Simon Pilgrima7d1da82017-03-15 22:50:47 +00003007}
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003008
Daniel Sanders2deea182017-04-22 15:11:04 +00003009unsigned RuleMatcher::countRendererFns() const {
Daniel Sandersbdfebb82017-03-15 20:18:38 +00003010 return std::accumulate(
3011 Matchers.begin(), Matchers.end(), 0,
3012 [](unsigned A, const std::unique_ptr<InstructionMatcher> &Matcher) {
Daniel Sanders2deea182017-04-22 15:11:04 +00003013 return A + Matcher->countRendererFns();
Daniel Sandersbdfebb82017-03-15 20:18:38 +00003014 });
3015}
3016
Daniel Sanders05540042017-08-08 10:44:31 +00003017bool OperandPredicateMatcher::isHigherPriorityThan(
3018 const OperandPredicateMatcher &B) const {
3019 // Generally speaking, an instruction is more important than an Int or a
3020 // LiteralInt because it can cover more nodes but theres an exception to
3021 // this. G_CONSTANT's are less important than either of those two because they
3022 // are more permissive.
Daniel Sandersedd07842017-08-17 09:26:14 +00003023
3024 const InstructionOperandMatcher *AOM =
3025 dyn_cast<InstructionOperandMatcher>(this);
3026 const InstructionOperandMatcher *BOM =
3027 dyn_cast<InstructionOperandMatcher>(&B);
3028 bool AIsConstantInsn = AOM && AOM->getInsnMatcher().isConstantInstruction();
3029 bool BIsConstantInsn = BOM && BOM->getInsnMatcher().isConstantInstruction();
3030
3031 if (AOM && BOM) {
3032 // The relative priorities between a G_CONSTANT and any other instruction
3033 // don't actually matter but this code is needed to ensure a strict weak
3034 // ordering. This is particularly important on Windows where the rules will
3035 // be incorrectly sorted without it.
3036 if (AIsConstantInsn != BIsConstantInsn)
3037 return AIsConstantInsn < BIsConstantInsn;
3038 return false;
Daniel Sanders05540042017-08-08 10:44:31 +00003039 }
Daniel Sandersedd07842017-08-17 09:26:14 +00003040
3041 if (AOM && AIsConstantInsn && (B.Kind == OPM_Int || B.Kind == OPM_LiteralInt))
3042 return false;
3043 if (BOM && BIsConstantInsn && (Kind == OPM_Int || Kind == OPM_LiteralInt))
3044 return true;
Daniel Sanders05540042017-08-08 10:44:31 +00003045
3046 return Kind < B.Kind;
Daniel Sanders75b84fc2017-08-08 13:21:26 +00003047}
Daniel Sanders05540042017-08-08 10:44:31 +00003048
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003049void SameOperandMatcher::emitPredicateOpcodes(MatchTable &Table,
Quentin Colombetaad20be2017-12-15 23:07:42 +00003050 RuleMatcher &Rule) const {
Daniel Sanders1e4569f2017-10-20 20:55:29 +00003051 const OperandMatcher &OtherOM = Rule.getOperandMatcher(MatchingName);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003052 unsigned OtherInsnVarID = Rule.getInsnVarID(OtherOM.getInstructionMatcher());
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003053 assert(OtherInsnVarID == OtherOM.getInstructionMatcher().getInsnVarID());
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003054
3055 Table << MatchTable::Opcode("GIM_CheckIsSameOperand")
3056 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
3057 << MatchTable::Comment("OpIdx") << MatchTable::IntValue(OpIdx)
3058 << MatchTable::Comment("OtherMI")
3059 << MatchTable::IntValue(OtherInsnVarID)
3060 << MatchTable::Comment("OtherOpIdx")
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003061 << MatchTable::IntValue(OtherOM.getOpIdx())
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003062 << MatchTable::LineBreak;
3063}
3064
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003065//===- GlobalISelEmitter class --------------------------------------------===//
3066
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003067class GlobalISelEmitter {
3068public:
3069 explicit GlobalISelEmitter(RecordKeeper &RK);
3070 void run(raw_ostream &OS);
3071
3072private:
3073 const RecordKeeper &RK;
3074 const CodeGenDAGPatterns CGP;
3075 const CodeGenTarget &Target;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00003076 CodeGenRegBank CGRegs;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003077
Daniel Sanders39690bd2017-10-15 02:41:12 +00003078 /// Keep track of the equivalence between SDNodes and Instruction by mapping
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003079 /// SDNodes to the GINodeEquiv mapping. We need to map to the GINodeEquiv to
3080 /// check for attributes on the relation such as CheckMMOIsNonAtomic.
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003081 /// This is defined using 'GINodeEquiv' in the target description.
Daniel Sanders39690bd2017-10-15 02:41:12 +00003082 DenseMap<Record *, Record *> NodeEquivs;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003083
Daniel Sanders8a4bae92017-03-14 21:32:08 +00003084 /// Keep track of the equivalence between ComplexPattern's and
3085 /// GIComplexOperandMatcher. Map entries are specified by subclassing
3086 /// GIComplexPatternEquiv.
3087 DenseMap<const Record *, const Record *> ComplexPatternEquivs;
3088
Volkan Kelesf7f25682018-01-16 18:44:05 +00003089 /// Keep track of the equivalence between SDNodeXForm's and
3090 /// GICustomOperandRenderer. Map entries are specified by subclassing
3091 /// GISDNodeXFormEquiv.
3092 DenseMap<const Record *, const Record *> SDNodeXFormEquivs;
3093
Aditya Nandakumarb63e7632018-02-16 22:37:15 +00003094 /// Keep track of Scores of PatternsToMatch similar to how the DAG does.
3095 /// This adds compatibility for RuleMatchers to use this for ordering rules.
3096 DenseMap<uint64_t, int> RuleMatcherScores;
3097
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003098 // Map of predicates to their subtarget features.
Daniel Sanderse9fdba32017-04-29 17:30:09 +00003099 SubtargetFeatureInfoMap SubtargetFeatures;
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003100
Daniel Sandersf76f3152017-11-16 00:46:35 +00003101 // Rule coverage information.
3102 Optional<CodeGenCoverage> RuleCoverage;
3103
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003104 void gatherOpcodeValues();
3105 void gatherTypeIDValues();
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003106 void gatherNodeEquivs();
Daniel Sanders8ead1292018-06-15 23:13:43 +00003107
Daniel Sanders39690bd2017-10-15 02:41:12 +00003108 Record *findNodeEquiv(Record *N) const;
Daniel Sandersf84bc372018-05-05 20:53:24 +00003109 const CodeGenInstruction *getEquivNode(Record &Equiv,
Florian Hahn6b1db822018-06-14 20:32:58 +00003110 const TreePatternNode *N) const;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003111
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003112 Error importRulePredicates(RuleMatcher &M, ArrayRef<Predicate> Predicates);
Daniel Sanders8ead1292018-06-15 23:13:43 +00003113 Expected<InstructionMatcher &>
3114 createAndImportSelDAGMatcher(RuleMatcher &Rule,
3115 InstructionMatcher &InsnMatcher,
3116 const TreePatternNode *Src, unsigned &TempOpIdx);
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003117 Error importComplexPatternOperandMatcher(OperandMatcher &OM, Record *R,
3118 unsigned &TempOpIdx) const;
3119 Error importChildMatcher(RuleMatcher &Rule, InstructionMatcher &InsnMatcher,
Florian Hahn6b1db822018-06-14 20:32:58 +00003120 const TreePatternNode *SrcChild,
Daniel Sandersa71f4542017-10-16 00:56:30 +00003121 bool OperandIsAPointer, unsigned OpIdx,
Daniel Sanders8ead1292018-06-15 23:13:43 +00003122 unsigned &TempOpIdx);
Daniel Sandersdf258e32017-10-31 19:09:29 +00003123
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00003124 Expected<BuildMIAction &>
Daniel Sandersa7b75262017-10-31 18:50:24 +00003125 createAndImportInstructionRenderer(RuleMatcher &M,
Florian Hahn6b1db822018-06-14 20:32:58 +00003126 const TreePatternNode *Dst);
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003127 Expected<action_iterator> createAndImportSubInstructionRenderer(
Florian Hahn6b1db822018-06-14 20:32:58 +00003128 action_iterator InsertPt, RuleMatcher &M, const TreePatternNode *Dst,
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003129 unsigned TempReg);
Daniel Sanders7438b262017-10-31 23:03:18 +00003130 Expected<action_iterator>
3131 createInstructionRenderer(action_iterator InsertPt, RuleMatcher &M,
Florian Hahn6b1db822018-06-14 20:32:58 +00003132 const TreePatternNode *Dst);
Daniel Sandersdf258e32017-10-31 19:09:29 +00003133 void importExplicitDefRenderers(BuildMIAction &DstMIBuilder);
Daniel Sanders7438b262017-10-31 23:03:18 +00003134 Expected<action_iterator>
3135 importExplicitUseRenderers(action_iterator InsertPt, RuleMatcher &M,
3136 BuildMIAction &DstMIBuilder,
Florian Hahn6b1db822018-06-14 20:32:58 +00003137 const llvm::TreePatternNode *Dst);
Daniel Sanders7438b262017-10-31 23:03:18 +00003138 Expected<action_iterator>
3139 importExplicitUseRenderer(action_iterator InsertPt, RuleMatcher &Rule,
3140 BuildMIAction &DstMIBuilder,
Florian Hahn6b1db822018-06-14 20:32:58 +00003141 TreePatternNode *DstChild);
Sjoerd Meijerde234842019-05-30 07:30:37 +00003142 Error importDefaultOperandRenderers(action_iterator InsertPt, RuleMatcher &M,
3143 BuildMIAction &DstMIBuilder,
Diana Picus382602f2017-05-17 08:57:28 +00003144 DagInit *DefaultOps) const;
Daniel Sandersc270c502017-03-30 09:36:33 +00003145 Error
Daniel Sandersffc7d582017-03-29 15:37:18 +00003146 importImplicitDefRenderers(BuildMIAction &DstMIBuilder,
3147 const std::vector<Record *> &ImplicitDefs) const;
3148
Daniel Sanders8ead1292018-06-15 23:13:43 +00003149 void emitCxxPredicateFns(raw_ostream &OS, StringRef CodeFieldName,
3150 StringRef TypeIdentifier, StringRef ArgType,
3151 StringRef ArgName, StringRef AdditionalDeclarations,
3152 std::function<bool(const Record *R)> Filter);
3153 void emitImmPredicateFns(raw_ostream &OS, StringRef TypeIdentifier,
3154 StringRef ArgType,
3155 std::function<bool(const Record *R)> Filter);
3156 void emitMIPredicateFns(raw_ostream &OS);
Daniel Sanders649c5852017-10-13 20:42:18 +00003157
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003158 /// Analyze pattern \p P, returning a matcher for it if possible.
3159 /// Otherwise, return an Error explaining why we don't support it.
3160 Expected<RuleMatcher> runOnPattern(const PatternToMatch &P);
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003161
3162 void declareSubtargetFeature(Record *Predicate);
Daniel Sanders7e523672017-11-11 03:23:44 +00003163
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003164 MatchTable buildMatchTable(MutableArrayRef<RuleMatcher> Rules, bool Optimize,
3165 bool WithCoverage);
3166
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00003167 /// Infer a CodeGenRegisterClass for the type of \p SuperRegNode. The returned
3168 /// CodeGenRegisterClass will support the CodeGenRegisterClass of
3169 /// \p SubRegNode, and the subregister index defined by \p SubRegIdxNode.
3170 /// If no register class is found, return None.
3171 Optional<const CodeGenRegisterClass *>
3172 inferSuperRegisterClass(const TypeSetByHwMode &Ty,
3173 TreePatternNode *SuperRegNode,
3174 TreePatternNode *SubRegIdxNode);
3175
3176 /// Return the CodeGenRegisterClass associated with \p Leaf if it has one.
3177 Optional<const CodeGenRegisterClass *>
3178 getRegClassFromLeaf(TreePatternNode *Leaf);
3179
3180 /// Return a CodeGenRegisterClass for \p N if one can be found. Return None
3181 /// otherwise.
3182 Optional<const CodeGenRegisterClass *>
3183 inferRegClassFromPattern(TreePatternNode *N);
3184
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003185public:
Quentin Colombetec76d9c2017-12-18 19:47:41 +00003186 /// Takes a sequence of \p Rules and group them based on the predicates
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003187 /// they share. \p MatcherStorage is used as a memory container
Hiroshi Inoue501931b2018-01-24 05:04:35 +00003188 /// for the group that are created as part of this process.
Quentin Colombetec76d9c2017-12-18 19:47:41 +00003189 ///
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003190 /// What this optimization does looks like if GroupT = GroupMatcher:
Quentin Colombetec76d9c2017-12-18 19:47:41 +00003191 /// Output without optimization:
3192 /// \verbatim
3193 /// # R1
3194 /// # predicate A
3195 /// # predicate B
3196 /// ...
3197 /// # R2
3198 /// # predicate A // <-- effectively this is going to be checked twice.
3199 /// // Once in R1 and once in R2.
3200 /// # predicate C
3201 /// \endverbatim
3202 /// Output with optimization:
3203 /// \verbatim
3204 /// # Group1_2
3205 /// # predicate A // <-- Check is now shared.
3206 /// # R1
3207 /// # predicate B
3208 /// # R2
3209 /// # predicate C
3210 /// \endverbatim
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003211 template <class GroupT>
3212 static std::vector<Matcher *> optimizeRules(
Roman Tereshin2d6d3762018-05-02 20:08:14 +00003213 ArrayRef<Matcher *> Rules,
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003214 std::vector<std::unique_ptr<Matcher>> &MatcherStorage);
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00003215};
3216
Roman Tereshinf1aa3482018-05-21 23:28:51 +00003217void GlobalISelEmitter::gatherOpcodeValues() {
3218 InstructionOpcodeMatcher::initOpcodeValuesMap(Target);
3219}
3220
3221void GlobalISelEmitter::gatherTypeIDValues() {
3222 LLTOperandMatcher::initTypeIDValuesMap();
3223}
3224
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003225void GlobalISelEmitter::gatherNodeEquivs() {
3226 assert(NodeEquivs.empty());
3227 for (Record *Equiv : RK.getAllDerivedDefinitions("GINodeEquiv"))
Daniel Sanders39690bd2017-10-15 02:41:12 +00003228 NodeEquivs[Equiv->getValueAsDef("Node")] = Equiv;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00003229
3230 assert(ComplexPatternEquivs.empty());
3231 for (Record *Equiv : RK.getAllDerivedDefinitions("GIComplexPatternEquiv")) {
3232 Record *SelDAGEquiv = Equiv->getValueAsDef("SelDAGEquivalent");
3233 if (!SelDAGEquiv)
3234 continue;
3235 ComplexPatternEquivs[SelDAGEquiv] = Equiv;
3236 }
Volkan Kelesf7f25682018-01-16 18:44:05 +00003237
3238 assert(SDNodeXFormEquivs.empty());
3239 for (Record *Equiv : RK.getAllDerivedDefinitions("GISDNodeXFormEquiv")) {
3240 Record *SelDAGEquiv = Equiv->getValueAsDef("SelDAGEquivalent");
3241 if (!SelDAGEquiv)
3242 continue;
3243 SDNodeXFormEquivs[SelDAGEquiv] = Equiv;
3244 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003245}
3246
Daniel Sanders39690bd2017-10-15 02:41:12 +00003247Record *GlobalISelEmitter::findNodeEquiv(Record *N) const {
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003248 return NodeEquivs.lookup(N);
3249}
3250
Daniel Sandersf84bc372018-05-05 20:53:24 +00003251const CodeGenInstruction *
Florian Hahn6b1db822018-06-14 20:32:58 +00003252GlobalISelEmitter::getEquivNode(Record &Equiv, const TreePatternNode *N) const {
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00003253 for (const TreePredicateCall &Call : N->getPredicateCalls()) {
3254 const TreePredicateFn &Predicate = Call.Fn;
Daniel Sandersf84bc372018-05-05 20:53:24 +00003255 if (!Equiv.isValueUnset("IfSignExtend") && Predicate.isLoad() &&
3256 Predicate.isSignExtLoad())
3257 return &Target.getInstruction(Equiv.getValueAsDef("IfSignExtend"));
3258 if (!Equiv.isValueUnset("IfZeroExtend") && Predicate.isLoad() &&
3259 Predicate.isZeroExtLoad())
3260 return &Target.getInstruction(Equiv.getValueAsDef("IfZeroExtend"));
3261 }
3262 return &Target.getInstruction(Equiv.getValueAsDef("I"));
3263}
3264
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003265GlobalISelEmitter::GlobalISelEmitter(RecordKeeper &RK)
Daniel Sandersf84bc372018-05-05 20:53:24 +00003266 : RK(RK), CGP(RK), Target(CGP.getTargetInfo()),
3267 CGRegs(RK, Target.getHwModes()) {}
Ahmed Bougacha36f70352016-12-21 23:26:20 +00003268
3269//===- Emitter ------------------------------------------------------------===//
3270
Daniel Sandersc270c502017-03-30 09:36:33 +00003271Error
Daniel Sandersffc7d582017-03-29 15:37:18 +00003272GlobalISelEmitter::importRulePredicates(RuleMatcher &M,
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003273 ArrayRef<Predicate> Predicates) {
3274 for (const Predicate &P : Predicates) {
Matt Arsenault57ef94f2019-07-30 15:56:43 +00003275 if (!P.Def || P.getCondString().empty())
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003276 continue;
3277 declareSubtargetFeature(P.Def);
3278 M.addRequiredFeature(P.Def);
Daniel Sanderse7b0d662017-04-21 15:59:56 +00003279 }
3280
Daniel Sandersc270c502017-03-30 09:36:33 +00003281 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00003282}
Daniel Sanders8a4bae92017-03-14 21:32:08 +00003283
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003284Expected<InstructionMatcher &> GlobalISelEmitter::createAndImportSelDAGMatcher(
3285 RuleMatcher &Rule, InstructionMatcher &InsnMatcher,
Daniel Sanders8ead1292018-06-15 23:13:43 +00003286 const TreePatternNode *Src, unsigned &TempOpIdx) {
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003287 Record *SrcGIEquivOrNull = nullptr;
3288 const CodeGenInstruction *SrcGIOrNull = nullptr;
3289
3290 // Start with the defined operands (i.e., the results of the root operator).
Florian Hahn6b1db822018-06-14 20:32:58 +00003291 if (Src->getExtTypes().size() > 1)
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003292 return failedImport("Src pattern has multiple results");
3293
Florian Hahn6b1db822018-06-14 20:32:58 +00003294 if (Src->isLeaf()) {
3295 Init *SrcInit = Src->getLeafValue();
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003296 if (isa<IntInit>(SrcInit)) {
3297 InsnMatcher.addPredicate<InstructionOpcodeMatcher>(
3298 &Target.getInstruction(RK.getDef("G_CONSTANT")));
3299 } else
3300 return failedImport(
3301 "Unable to deduce gMIR opcode to handle Src (which is a leaf)");
3302 } else {
Florian Hahn6b1db822018-06-14 20:32:58 +00003303 SrcGIEquivOrNull = findNodeEquiv(Src->getOperator());
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003304 if (!SrcGIEquivOrNull)
3305 return failedImport("Pattern operator lacks an equivalent Instruction" +
Florian Hahn6b1db822018-06-14 20:32:58 +00003306 explainOperator(Src->getOperator()));
Daniel Sandersf84bc372018-05-05 20:53:24 +00003307 SrcGIOrNull = getEquivNode(*SrcGIEquivOrNull, Src);
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003308
3309 // The operators look good: match the opcode
3310 InsnMatcher.addPredicate<InstructionOpcodeMatcher>(SrcGIOrNull);
3311 }
3312
3313 unsigned OpIdx = 0;
Florian Hahn6b1db822018-06-14 20:32:58 +00003314 for (const TypeSetByHwMode &VTy : Src->getExtTypes()) {
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003315 // Results don't have a name unless they are the root node. The caller will
3316 // set the name if appropriate.
3317 OperandMatcher &OM = InsnMatcher.addOperand(OpIdx++, "", TempOpIdx);
3318 if (auto Error = OM.addTypeCheckPredicate(VTy, false /* OperandIsAPointer */))
3319 return failedImport(toString(std::move(Error)) +
3320 " for result of Src pattern operator");
3321 }
3322
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00003323 for (const TreePredicateCall &Call : Src->getPredicateCalls()) {
3324 const TreePredicateFn &Predicate = Call.Fn;
Daniel Sanders2c269f62017-08-24 09:11:20 +00003325 if (Predicate.isAlwaysTrue())
3326 continue;
3327
3328 if (Predicate.isImmediatePattern()) {
3329 InsnMatcher.addPredicate<InstructionImmPredicateMatcher>(Predicate);
3330 continue;
3331 }
3332
Matt Arsenaultd00d8572019-07-15 20:59:42 +00003333 // An address space check is needed in all contexts if there is one.
3334 if (Predicate.isLoad() || Predicate.isStore() || Predicate.isAtomic()) {
3335 if (const ListInit *AddrSpaces = Predicate.getAddressSpaces()) {
3336 SmallVector<unsigned, 4> ParsedAddrSpaces;
3337
3338 for (Init *Val : AddrSpaces->getValues()) {
3339 IntInit *IntVal = dyn_cast<IntInit>(Val);
3340 if (!IntVal)
3341 return failedImport("Address space is not an integer");
3342 ParsedAddrSpaces.push_back(IntVal->getValue());
3343 }
3344
3345 if (!ParsedAddrSpaces.empty()) {
3346 InsnMatcher.addPredicate<MemoryAddressSpacePredicateMatcher>(
3347 0, ParsedAddrSpaces);
3348 }
3349 }
Matt Arsenault52c26242019-07-31 00:14:43 +00003350
3351 int64_t MinAlign = Predicate.getMinAlignment();
3352 if (MinAlign > 0)
3353 InsnMatcher.addPredicate<MemoryAlignmentPredicateMatcher>(0, MinAlign);
Matt Arsenaultd00d8572019-07-15 20:59:42 +00003354 }
3355
3356 // G_LOAD is used for both non-extending and any-extending loads.
Daniel Sandersf84bc372018-05-05 20:53:24 +00003357 if (Predicate.isLoad() && Predicate.isNonExtLoad()) {
3358 InsnMatcher.addPredicate<MemoryVsLLTSizePredicateMatcher>(
3359 0, MemoryVsLLTSizePredicateMatcher::EqualTo, 0);
3360 continue;
3361 }
3362 if (Predicate.isLoad() && Predicate.isAnyExtLoad()) {
3363 InsnMatcher.addPredicate<MemoryVsLLTSizePredicateMatcher>(
3364 0, MemoryVsLLTSizePredicateMatcher::LessThan, 0);
3365 continue;
3366 }
3367
Amara Emerson52e6d522019-08-02 23:33:13 +00003368 if (Predicate.isStore()) {
3369 if (Predicate.isTruncStore()) {
3370 // FIXME: If MemoryVT is set, we end up with 2 checks for the MMO size.
3371 InsnMatcher.addPredicate<MemoryVsLLTSizePredicateMatcher>(
3372 0, MemoryVsLLTSizePredicateMatcher::LessThan, 0);
3373 continue;
3374 }
3375 if (Predicate.isNonTruncStore()) {
3376 // We need to check the sizes match here otherwise we could incorrectly
3377 // match truncating stores with non-truncating ones.
3378 InsnMatcher.addPredicate<MemoryVsLLTSizePredicateMatcher>(
3379 0, MemoryVsLLTSizePredicateMatcher::EqualTo, 0);
3380 }
Matt Arsenault02772492019-07-15 21:15:20 +00003381 }
3382
Daniel Sandersf84bc372018-05-05 20:53:24 +00003383 // No check required. We already did it by swapping the opcode.
3384 if (!SrcGIEquivOrNull->isValueUnset("IfSignExtend") &&
3385 Predicate.isSignExtLoad())
3386 continue;
3387
3388 // No check required. We already did it by swapping the opcode.
3389 if (!SrcGIEquivOrNull->isValueUnset("IfZeroExtend") &&
3390 Predicate.isZeroExtLoad())
Daniel Sandersa71f4542017-10-16 00:56:30 +00003391 continue;
3392
Daniel Sandersd66e0902017-10-23 18:19:24 +00003393 // No check required. G_STORE by itself is a non-extending store.
3394 if (Predicate.isNonTruncStore())
3395 continue;
3396
Daniel Sanders76664652017-11-28 22:07:05 +00003397 if (Predicate.isLoad() || Predicate.isStore() || Predicate.isAtomic()) {
3398 if (Predicate.getMemoryVT() != nullptr) {
3399 Optional<LLTCodeGen> MemTyOrNone =
3400 MVTToLLT(getValueType(Predicate.getMemoryVT()));
Daniel Sandersd66e0902017-10-23 18:19:24 +00003401
Daniel Sanders76664652017-11-28 22:07:05 +00003402 if (!MemTyOrNone)
3403 return failedImport("MemVT could not be converted to LLT");
Daniel Sandersd66e0902017-10-23 18:19:24 +00003404
Daniel Sandersf84bc372018-05-05 20:53:24 +00003405 // MMO's work in bytes so we must take care of unusual types like i1
3406 // don't round down.
3407 unsigned MemSizeInBits =
3408 llvm::alignTo(MemTyOrNone->get().getSizeInBits(), 8);
3409
3410 InsnMatcher.addPredicate<MemorySizePredicateMatcher>(
3411 0, MemSizeInBits / 8);
Daniel Sanders76664652017-11-28 22:07:05 +00003412 continue;
3413 }
3414 }
3415
3416 if (Predicate.isLoad() || Predicate.isStore()) {
3417 // No check required. A G_LOAD/G_STORE is an unindexed load.
3418 if (Predicate.isUnindexed())
3419 continue;
3420 }
3421
3422 if (Predicate.isAtomic()) {
3423 if (Predicate.isAtomicOrderingMonotonic()) {
3424 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3425 "Monotonic");
3426 continue;
3427 }
3428 if (Predicate.isAtomicOrderingAcquire()) {
3429 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>("Acquire");
3430 continue;
3431 }
3432 if (Predicate.isAtomicOrderingRelease()) {
3433 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>("Release");
3434 continue;
3435 }
3436 if (Predicate.isAtomicOrderingAcquireRelease()) {
3437 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3438 "AcquireRelease");
3439 continue;
3440 }
3441 if (Predicate.isAtomicOrderingSequentiallyConsistent()) {
3442 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3443 "SequentiallyConsistent");
3444 continue;
3445 }
Daniel Sanders0c43b3a2017-11-30 21:05:59 +00003446
3447 if (Predicate.isAtomicOrderingAcquireOrStronger()) {
3448 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3449 "Acquire", AtomicOrderingMMOPredicateMatcher::AO_OrStronger);
3450 continue;
3451 }
3452 if (Predicate.isAtomicOrderingWeakerThanAcquire()) {
3453 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3454 "Acquire", AtomicOrderingMMOPredicateMatcher::AO_WeakerThan);
3455 continue;
3456 }
3457
3458 if (Predicate.isAtomicOrderingReleaseOrStronger()) {
3459 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3460 "Release", AtomicOrderingMMOPredicateMatcher::AO_OrStronger);
3461 continue;
3462 }
3463 if (Predicate.isAtomicOrderingWeakerThanRelease()) {
3464 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
3465 "Release", AtomicOrderingMMOPredicateMatcher::AO_WeakerThan);
3466 continue;
3467 }
Daniel Sandersd66e0902017-10-23 18:19:24 +00003468 }
3469
Daniel Sanders8ead1292018-06-15 23:13:43 +00003470 if (Predicate.hasGISelPredicateCode()) {
3471 InsnMatcher.addPredicate<GenericInstructionPredicateMatcher>(Predicate);
3472 continue;
3473 }
3474
Daniel Sanders2c269f62017-08-24 09:11:20 +00003475 return failedImport("Src pattern child has predicate (" +
3476 explainPredicates(Src) + ")");
3477 }
Daniel Sanders3c1c4c02017-12-05 05:52:07 +00003478 if (SrcGIEquivOrNull && SrcGIEquivOrNull->getValueAsBit("CheckMMOIsNonAtomic"))
3479 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>("NotAtomic");
Daniel Sanders2c269f62017-08-24 09:11:20 +00003480
Florian Hahn6b1db822018-06-14 20:32:58 +00003481 if (Src->isLeaf()) {
3482 Init *SrcInit = Src->getLeafValue();
Daniel Sanders452c8ae2017-05-23 19:33:16 +00003483 if (IntInit *SrcIntInit = dyn_cast<IntInit>(SrcInit)) {
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003484 OperandMatcher &OM =
Florian Hahn6b1db822018-06-14 20:32:58 +00003485 InsnMatcher.addOperand(OpIdx++, Src->getName(), TempOpIdx);
Daniel Sanders452c8ae2017-05-23 19:33:16 +00003486 OM.addPredicate<LiteralIntOperandMatcher>(SrcIntInit->getValue());
3487 } else
Daniel Sanders32291982017-06-28 13:50:04 +00003488 return failedImport(
3489 "Unable to deduce gMIR opcode to handle Src (which is a leaf)");
Daniel Sanders452c8ae2017-05-23 19:33:16 +00003490 } else {
Daniel Sanders85ffd362017-07-06 08:12:20 +00003491 assert(SrcGIOrNull &&
3492 "Expected to have already found an equivalent Instruction");
Daniel Sanders11300ce2017-10-13 21:28:03 +00003493 if (SrcGIOrNull->TheDef->getName() == "G_CONSTANT" ||
3494 SrcGIOrNull->TheDef->getName() == "G_FCONSTANT") {
3495 // imm/fpimm still have operands but we don't need to do anything with it
Daniel Sanders05540042017-08-08 10:44:31 +00003496 // here since we don't support ImmLeaf predicates yet. However, we still
3497 // need to note the hidden operand to get GIM_CheckNumOperands correct.
3498 InsnMatcher.addOperand(OpIdx++, "", TempOpIdx);
3499 return InsnMatcher;
3500 }
3501
Daniel Sanders452c8ae2017-05-23 19:33:16 +00003502 // Match the used operands (i.e. the children of the operator).
Jessica Paquette5c8a29f2019-08-20 22:04:10 +00003503 bool IsIntrinsic =
3504 SrcGIOrNull->TheDef->getName() == "G_INTRINSIC" ||
3505 SrcGIOrNull->TheDef->getName() == "G_INTRINSIC_W_SIDE_EFFECTS";
3506 const CodeGenIntrinsic *II = Src->getIntrinsicInfo(CGP);
3507 if (IsIntrinsic && !II)
3508 return failedImport("Expected IntInit containing intrinsic ID)");
3509
Florian Hahn6b1db822018-06-14 20:32:58 +00003510 for (unsigned i = 0, e = Src->getNumChildren(); i != e; ++i) {
3511 TreePatternNode *SrcChild = Src->getChild(i);
Daniel Sanders85ffd362017-07-06 08:12:20 +00003512
Daniel Sandersa71f4542017-10-16 00:56:30 +00003513 // SelectionDAG allows pointers to be represented with iN since it doesn't
3514 // distinguish between pointers and integers but they are different types in GlobalISel.
3515 // Coerce integers to pointers to address space 0 if the context indicates a pointer.
Daniel Sandersc54aa9c2017-11-18 00:16:44 +00003516 bool OperandIsAPointer = SrcGIOrNull->isOperandAPointer(i);
Daniel Sandersa71f4542017-10-16 00:56:30 +00003517
Jessica Paquette5c8a29f2019-08-20 22:04:10 +00003518 if (IsIntrinsic) {
3519 // For G_INTRINSIC/G_INTRINSIC_W_SIDE_EFFECTS, the operand immediately
3520 // following the defs is an intrinsic ID.
3521 if (i == 0) {
Daniel Sanders85ffd362017-07-06 08:12:20 +00003522 OperandMatcher &OM =
Florian Hahn6b1db822018-06-14 20:32:58 +00003523 InsnMatcher.addOperand(OpIdx++, SrcChild->getName(), TempOpIdx);
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00003524 OM.addPredicate<IntrinsicIDOperandMatcher>(II);
Daniel Sanders85ffd362017-07-06 08:12:20 +00003525 continue;
3526 }
3527
Jessica Paquette5c8a29f2019-08-20 22:04:10 +00003528 // We have to check intrinsics for llvm_anyptr_ty parameters.
3529 //
3530 // Note that we have to look at the i-1th parameter, because we don't
3531 // have the intrinsic ID in the intrinsic's parameter list.
3532 OperandIsAPointer |= II->isParamAPointer(i - 1);
Daniel Sanders85ffd362017-07-06 08:12:20 +00003533 }
3534
Daniel Sandersa71f4542017-10-16 00:56:30 +00003535 if (auto Error =
3536 importChildMatcher(Rule, InsnMatcher, SrcChild, OperandIsAPointer,
3537 OpIdx++, TempOpIdx))
Daniel Sanders452c8ae2017-05-23 19:33:16 +00003538 return std::move(Error);
3539 }
Daniel Sandersffc7d582017-03-29 15:37:18 +00003540 }
3541
3542 return InsnMatcher;
3543}
3544
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003545Error GlobalISelEmitter::importComplexPatternOperandMatcher(
3546 OperandMatcher &OM, Record *R, unsigned &TempOpIdx) const {
3547 const auto &ComplexPattern = ComplexPatternEquivs.find(R);
3548 if (ComplexPattern == ComplexPatternEquivs.end())
3549 return failedImport("SelectionDAG ComplexPattern (" + R->getName() +
3550 ") not mapped to GlobalISel");
3551
3552 OM.addPredicate<ComplexPatternOperandMatcher>(OM, *ComplexPattern->second);
3553 TempOpIdx++;
3554 return Error::success();
3555}
3556
3557Error GlobalISelEmitter::importChildMatcher(RuleMatcher &Rule,
3558 InstructionMatcher &InsnMatcher,
Florian Hahn6b1db822018-06-14 20:32:58 +00003559 const TreePatternNode *SrcChild,
Daniel Sandersa71f4542017-10-16 00:56:30 +00003560 bool OperandIsAPointer,
Daniel Sandersc270c502017-03-30 09:36:33 +00003561 unsigned OpIdx,
Daniel Sanders8ead1292018-06-15 23:13:43 +00003562 unsigned &TempOpIdx) {
Daniel Sanders4f3eb242017-04-05 13:14:03 +00003563 OperandMatcher &OM =
Florian Hahn6b1db822018-06-14 20:32:58 +00003564 InsnMatcher.addOperand(OpIdx, SrcChild->getName(), TempOpIdx);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003565 if (OM.isSameAsAnotherOperand())
3566 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00003567
Florian Hahn6b1db822018-06-14 20:32:58 +00003568 ArrayRef<TypeSetByHwMode> ChildTypes = SrcChild->getExtTypes();
Daniel Sandersffc7d582017-03-29 15:37:18 +00003569 if (ChildTypes.size() != 1)
3570 return failedImport("Src pattern child has multiple results");
3571
3572 // Check MBB's before the type check since they are not a known type.
Florian Hahn6b1db822018-06-14 20:32:58 +00003573 if (!SrcChild->isLeaf()) {
3574 if (SrcChild->getOperator()->isSubClassOf("SDNode")) {
3575 auto &ChildSDNI = CGP.getSDNodeInfo(SrcChild->getOperator());
Daniel Sandersffc7d582017-03-29 15:37:18 +00003576 if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") {
3577 OM.addPredicate<MBBOperandMatcher>();
Daniel Sandersc270c502017-03-30 09:36:33 +00003578 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00003579 }
3580 }
Daniel Sandersffc7d582017-03-29 15:37:18 +00003581 }
3582
Daniel Sandersa71f4542017-10-16 00:56:30 +00003583 if (auto Error =
3584 OM.addTypeCheckPredicate(ChildTypes.front(), OperandIsAPointer))
3585 return failedImport(toString(std::move(Error)) + " for Src operand (" +
Florian Hahn6b1db822018-06-14 20:32:58 +00003586 to_string(*SrcChild) + ")");
Daniel Sandersffc7d582017-03-29 15:37:18 +00003587
Daniel Sandersbee57392017-04-04 13:25:23 +00003588 // Check for nested instructions.
Florian Hahn6b1db822018-06-14 20:32:58 +00003589 if (!SrcChild->isLeaf()) {
3590 if (SrcChild->getOperator()->isSubClassOf("ComplexPattern")) {
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003591 // When a ComplexPattern is used as an operator, it should do the same
3592 // thing as when used as a leaf. However, the children of the operator
3593 // name the sub-operands that make up the complex operand and we must
3594 // prepare to reference them in the renderer too.
3595 unsigned RendererID = TempOpIdx;
3596 if (auto Error = importComplexPatternOperandMatcher(
Florian Hahn6b1db822018-06-14 20:32:58 +00003597 OM, SrcChild->getOperator(), TempOpIdx))
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003598 return Error;
3599
Florian Hahn6b1db822018-06-14 20:32:58 +00003600 for (unsigned i = 0, e = SrcChild->getNumChildren(); i != e; ++i) {
3601 auto *SubOperand = SrcChild->getChild(i);
Jessica Paquette1ed1dd62019-02-09 00:29:13 +00003602 if (!SubOperand->getName().empty()) {
3603 if (auto Error = Rule.defineComplexSubOperand(SubOperand->getName(),
3604 SrcChild->getOperator(),
3605 RendererID, i))
3606 return Error;
3607 }
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003608 }
3609
3610 return Error::success();
3611 }
3612
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003613 auto MaybeInsnOperand = OM.addPredicate<InstructionOperandMatcher>(
Florian Hahn6b1db822018-06-14 20:32:58 +00003614 InsnMatcher.getRuleMatcher(), SrcChild->getName());
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003615 if (!MaybeInsnOperand.hasValue()) {
3616 // This isn't strictly true. If the user were to provide exactly the same
3617 // matchers as the original operand then we could allow it. However, it's
3618 // simpler to not permit the redundant specification.
3619 return failedImport("Nested instruction cannot be the same as another operand");
3620 }
3621
Daniel Sandersbee57392017-04-04 13:25:23 +00003622 // Map the node to a gMIR instruction.
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00003623 InstructionOperandMatcher &InsnOperand = **MaybeInsnOperand;
Daniel Sanders57938df2017-07-11 10:40:18 +00003624 auto InsnMatcherOrError = createAndImportSelDAGMatcher(
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003625 Rule, InsnOperand.getInsnMatcher(), SrcChild, TempOpIdx);
Daniel Sandersbee57392017-04-04 13:25:23 +00003626 if (auto Error = InsnMatcherOrError.takeError())
3627 return Error;
3628
3629 return Error::success();
3630 }
3631
Florian Hahn6b1db822018-06-14 20:32:58 +00003632 if (SrcChild->hasAnyPredicate())
Diana Picusd1b61812017-11-03 10:30:19 +00003633 return failedImport("Src pattern child has unsupported predicate");
3634
Daniel Sandersffc7d582017-03-29 15:37:18 +00003635 // Check for constant immediates.
Florian Hahn6b1db822018-06-14 20:32:58 +00003636 if (auto *ChildInt = dyn_cast<IntInit>(SrcChild->getLeafValue())) {
Daniel Sanders452c8ae2017-05-23 19:33:16 +00003637 OM.addPredicate<ConstantIntOperandMatcher>(ChildInt->getValue());
Daniel Sandersc270c502017-03-30 09:36:33 +00003638 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00003639 }
3640
3641 // Check for def's like register classes or ComplexPattern's.
Florian Hahn6b1db822018-06-14 20:32:58 +00003642 if (auto *ChildDefInit = dyn_cast<DefInit>(SrcChild->getLeafValue())) {
Daniel Sandersffc7d582017-03-29 15:37:18 +00003643 auto *ChildRec = ChildDefInit->getDef();
3644
3645 // Check for register classes.
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003646 if (ChildRec->isSubClassOf("RegisterClass") ||
3647 ChildRec->isSubClassOf("RegisterOperand")) {
Daniel Sandersffc7d582017-03-29 15:37:18 +00003648 OM.addPredicate<RegisterBankOperandMatcher>(
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003649 Target.getRegisterClass(getInitValueAsRegClass(ChildDefInit)));
Daniel Sanders658541f2017-04-22 15:53:21 +00003650 return Error::success();
3651 }
3652
Daniel Sanders4d4e7652017-10-09 18:14:53 +00003653 // Check for ValueType.
3654 if (ChildRec->isSubClassOf("ValueType")) {
3655 // We already added a type check as standard practice so this doesn't need
3656 // to do anything.
3657 return Error::success();
3658 }
3659
Daniel Sandersffc7d582017-03-29 15:37:18 +00003660 // Check for ComplexPattern's.
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003661 if (ChildRec->isSubClassOf("ComplexPattern"))
3662 return importComplexPatternOperandMatcher(OM, ChildRec, TempOpIdx);
Daniel Sandersffc7d582017-03-29 15:37:18 +00003663
Daniel Sandersd0656a32017-04-13 09:45:37 +00003664 if (ChildRec->isSubClassOf("ImmLeaf")) {
3665 return failedImport(
3666 "Src pattern child def is an unsupported tablegen class (ImmLeaf)");
3667 }
3668
Daniel Sandersffc7d582017-03-29 15:37:18 +00003669 return failedImport(
3670 "Src pattern child def is an unsupported tablegen class");
3671 }
3672
3673 return failedImport("Src pattern child is an unsupported kind");
3674}
3675
Daniel Sanders7438b262017-10-31 23:03:18 +00003676Expected<action_iterator> GlobalISelEmitter::importExplicitUseRenderer(
3677 action_iterator InsertPt, RuleMatcher &Rule, BuildMIAction &DstMIBuilder,
Florian Hahn6b1db822018-06-14 20:32:58 +00003678 TreePatternNode *DstChild) {
Daniel Sanders2c269f62017-08-24 09:11:20 +00003679
Florian Hahn6b1db822018-06-14 20:32:58 +00003680 const auto &SubOperand = Rule.getComplexSubOperand(DstChild->getName());
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003681 if (SubOperand.hasValue()) {
3682 DstMIBuilder.addRenderer<RenderComplexPatternOperand>(
Florian Hahn6b1db822018-06-14 20:32:58 +00003683 *std::get<0>(*SubOperand), DstChild->getName(),
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003684 std::get<1>(*SubOperand), std::get<2>(*SubOperand));
Daniel Sanders7438b262017-10-31 23:03:18 +00003685 return InsertPt;
Daniel Sandersdf39cba2017-10-15 18:22:54 +00003686 }
3687
Florian Hahn6b1db822018-06-14 20:32:58 +00003688 if (!DstChild->isLeaf()) {
Volkan Kelesf7f25682018-01-16 18:44:05 +00003689
Florian Hahn6b1db822018-06-14 20:32:58 +00003690 if (DstChild->getOperator()->isSubClassOf("SDNodeXForm")) {
3691 auto Child = DstChild->getChild(0);
3692 auto I = SDNodeXFormEquivs.find(DstChild->getOperator());
Volkan Kelesf7f25682018-01-16 18:44:05 +00003693 if (I != SDNodeXFormEquivs.end()) {
Florian Hahn6b1db822018-06-14 20:32:58 +00003694 DstMIBuilder.addRenderer<CustomRenderer>(*I->second, Child->getName());
Volkan Kelesf7f25682018-01-16 18:44:05 +00003695 return InsertPt;
3696 }
Florian Hahn6b1db822018-06-14 20:32:58 +00003697 return failedImport("SDNodeXForm " + Child->getName() +
Volkan Kelesf7f25682018-01-16 18:44:05 +00003698 " has no custom renderer");
3699 }
3700
Daniel Sanders05540042017-08-08 10:44:31 +00003701 // We accept 'bb' here. It's an operator because BasicBlockSDNode isn't
3702 // inline, but in MI it's just another operand.
Florian Hahn6b1db822018-06-14 20:32:58 +00003703 if (DstChild->getOperator()->isSubClassOf("SDNode")) {
3704 auto &ChildSDNI = CGP.getSDNodeInfo(DstChild->getOperator());
Daniel Sandersffc7d582017-03-29 15:37:18 +00003705 if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") {
Florian Hahn6b1db822018-06-14 20:32:58 +00003706 DstMIBuilder.addRenderer<CopyRenderer>(DstChild->getName());
Daniel Sanders7438b262017-10-31 23:03:18 +00003707 return InsertPt;
Daniel Sandersffc7d582017-03-29 15:37:18 +00003708 }
3709 }
Daniel Sanders05540042017-08-08 10:44:31 +00003710
3711 // Similarly, imm is an operator in TreePatternNode's view but must be
3712 // rendered as operands.
3713 // FIXME: The target should be able to choose sign-extended when appropriate
3714 // (e.g. on Mips).
Florian Hahn6b1db822018-06-14 20:32:58 +00003715 if (DstChild->getOperator()->getName() == "imm") {
3716 DstMIBuilder.addRenderer<CopyConstantAsImmRenderer>(DstChild->getName());
Daniel Sanders7438b262017-10-31 23:03:18 +00003717 return InsertPt;
Florian Hahn6b1db822018-06-14 20:32:58 +00003718 } else if (DstChild->getOperator()->getName() == "fpimm") {
Daniel Sanders11300ce2017-10-13 21:28:03 +00003719 DstMIBuilder.addRenderer<CopyFConstantAsFPImmRenderer>(
Florian Hahn6b1db822018-06-14 20:32:58 +00003720 DstChild->getName());
Daniel Sanders7438b262017-10-31 23:03:18 +00003721 return InsertPt;
Daniel Sanders05540042017-08-08 10:44:31 +00003722 }
3723
Florian Hahn6b1db822018-06-14 20:32:58 +00003724 if (DstChild->getOperator()->isSubClassOf("Instruction")) {
3725 ArrayRef<TypeSetByHwMode> ChildTypes = DstChild->getExtTypes();
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003726 if (ChildTypes.size() != 1)
3727 return failedImport("Dst pattern child has multiple results");
3728
3729 Optional<LLTCodeGen> OpTyOrNone = None;
3730 if (ChildTypes.front().isMachineValueType())
3731 OpTyOrNone =
3732 MVTToLLT(ChildTypes.front().getMachineValueType().SimpleTy);
3733 if (!OpTyOrNone)
3734 return failedImport("Dst operand has an unsupported type");
3735
3736 unsigned TempRegID = Rule.allocateTempRegID();
3737 InsertPt = Rule.insertAction<MakeTempRegisterAction>(
3738 InsertPt, OpTyOrNone.getValue(), TempRegID);
3739 DstMIBuilder.addRenderer<TempRegRenderer>(TempRegID);
3740
3741 auto InsertPtOrError = createAndImportSubInstructionRenderer(
3742 ++InsertPt, Rule, DstChild, TempRegID);
3743 if (auto Error = InsertPtOrError.takeError())
3744 return std::move(Error);
3745 return InsertPtOrError.get();
3746 }
3747
Florian Hahn6b1db822018-06-14 20:32:58 +00003748 return failedImport("Dst pattern child isn't a leaf node or an MBB" + llvm::to_string(*DstChild));
Daniel Sandersffc7d582017-03-29 15:37:18 +00003749 }
3750
Daniel Sandersf499b2b2017-11-30 18:48:35 +00003751 // It could be a specific immediate in which case we should just check for
3752 // that immediate.
3753 if (const IntInit *ChildIntInit =
Florian Hahn6b1db822018-06-14 20:32:58 +00003754 dyn_cast<IntInit>(DstChild->getLeafValue())) {
Daniel Sandersf499b2b2017-11-30 18:48:35 +00003755 DstMIBuilder.addRenderer<ImmRenderer>(ChildIntInit->getValue());
3756 return InsertPt;
3757 }
3758
Daniel Sandersffc7d582017-03-29 15:37:18 +00003759 // Otherwise, we're looking for a bog-standard RegisterClass operand.
Florian Hahn6b1db822018-06-14 20:32:58 +00003760 if (auto *ChildDefInit = dyn_cast<DefInit>(DstChild->getLeafValue())) {
Daniel Sandersffc7d582017-03-29 15:37:18 +00003761 auto *ChildRec = ChildDefInit->getDef();
3762
Florian Hahn6b1db822018-06-14 20:32:58 +00003763 ArrayRef<TypeSetByHwMode> ChildTypes = DstChild->getExtTypes();
Daniel Sandersffc7d582017-03-29 15:37:18 +00003764 if (ChildTypes.size() != 1)
3765 return failedImport("Dst pattern child has multiple results");
3766
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003767 Optional<LLTCodeGen> OpTyOrNone = None;
3768 if (ChildTypes.front().isMachineValueType())
3769 OpTyOrNone = MVTToLLT(ChildTypes.front().getMachineValueType().SimpleTy);
Daniel Sandersffc7d582017-03-29 15:37:18 +00003770 if (!OpTyOrNone)
3771 return failedImport("Dst operand has an unsupported type");
3772
3773 if (ChildRec->isSubClassOf("Register")) {
Daniel Sanders198447a2017-11-01 00:29:47 +00003774 DstMIBuilder.addRenderer<AddRegisterRenderer>(ChildRec);
Daniel Sanders7438b262017-10-31 23:03:18 +00003775 return InsertPt;
Daniel Sandersffc7d582017-03-29 15:37:18 +00003776 }
3777
Daniel Sanders658541f2017-04-22 15:53:21 +00003778 if (ChildRec->isSubClassOf("RegisterClass") ||
Daniel Sanders4d4e7652017-10-09 18:14:53 +00003779 ChildRec->isSubClassOf("RegisterOperand") ||
3780 ChildRec->isSubClassOf("ValueType")) {
Daniel Sandersd66e0902017-10-23 18:19:24 +00003781 if (ChildRec->isSubClassOf("RegisterOperand") &&
3782 !ChildRec->isValueUnset("GIZeroRegister")) {
3783 DstMIBuilder.addRenderer<CopyOrAddZeroRegRenderer>(
Florian Hahn6b1db822018-06-14 20:32:58 +00003784 DstChild->getName(), ChildRec->getValueAsDef("GIZeroRegister"));
Daniel Sanders7438b262017-10-31 23:03:18 +00003785 return InsertPt;
Daniel Sandersd66e0902017-10-23 18:19:24 +00003786 }
3787
Florian Hahn6b1db822018-06-14 20:32:58 +00003788 DstMIBuilder.addRenderer<CopyRenderer>(DstChild->getName());
Daniel Sanders7438b262017-10-31 23:03:18 +00003789 return InsertPt;
Daniel Sandersffc7d582017-03-29 15:37:18 +00003790 }
3791
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00003792 if (ChildRec->isSubClassOf("SubRegIndex")) {
3793 CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(ChildRec);
3794 DstMIBuilder.addRenderer<ImmRenderer>(SubIdx->EnumValue);
3795 return InsertPt;
3796 }
3797
Daniel Sandersffc7d582017-03-29 15:37:18 +00003798 if (ChildRec->isSubClassOf("ComplexPattern")) {
3799 const auto &ComplexPattern = ComplexPatternEquivs.find(ChildRec);
3800 if (ComplexPattern == ComplexPatternEquivs.end())
3801 return failedImport(
3802 "SelectionDAG ComplexPattern not mapped to GlobalISel");
3803
Florian Hahn6b1db822018-06-14 20:32:58 +00003804 const OperandMatcher &OM = Rule.getOperandMatcher(DstChild->getName());
Daniel Sandersffc7d582017-03-29 15:37:18 +00003805 DstMIBuilder.addRenderer<RenderComplexPatternOperand>(
Florian Hahn6b1db822018-06-14 20:32:58 +00003806 *ComplexPattern->second, DstChild->getName(),
Daniel Sanders2deea182017-04-22 15:11:04 +00003807 OM.getAllocatedTemporariesBaseID());
Daniel Sanders7438b262017-10-31 23:03:18 +00003808 return InsertPt;
Daniel Sandersffc7d582017-03-29 15:37:18 +00003809 }
3810
3811 return failedImport(
3812 "Dst pattern child def is an unsupported tablegen class");
3813 }
3814
3815 return failedImport("Dst pattern child is an unsupported kind");
3816}
3817
Daniel Sandersc270c502017-03-30 09:36:33 +00003818Expected<BuildMIAction &> GlobalISelEmitter::createAndImportInstructionRenderer(
Florian Hahn6b1db822018-06-14 20:32:58 +00003819 RuleMatcher &M, const TreePatternNode *Dst) {
Daniel Sanders7438b262017-10-31 23:03:18 +00003820 auto InsertPtOrError = createInstructionRenderer(M.actions_end(), M, Dst);
3821 if (auto Error = InsertPtOrError.takeError())
Daniel Sandersdf258e32017-10-31 19:09:29 +00003822 return std::move(Error);
3823
Daniel Sanders7438b262017-10-31 23:03:18 +00003824 action_iterator InsertPt = InsertPtOrError.get();
3825 BuildMIAction &DstMIBuilder = *static_cast<BuildMIAction *>(InsertPt->get());
Daniel Sandersdf258e32017-10-31 19:09:29 +00003826
3827 importExplicitDefRenderers(DstMIBuilder);
3828
Daniel Sanders7438b262017-10-31 23:03:18 +00003829 if (auto Error = importExplicitUseRenderers(InsertPt, M, DstMIBuilder, Dst)
3830 .takeError())
Daniel Sandersdf258e32017-10-31 19:09:29 +00003831 return std::move(Error);
3832
3833 return DstMIBuilder;
3834}
3835
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003836Expected<action_iterator>
3837GlobalISelEmitter::createAndImportSubInstructionRenderer(
Florian Hahn6b1db822018-06-14 20:32:58 +00003838 const action_iterator InsertPt, RuleMatcher &M, const TreePatternNode *Dst,
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003839 unsigned TempRegID) {
3840 auto InsertPtOrError = createInstructionRenderer(InsertPt, M, Dst);
3841
3842 // TODO: Assert there's exactly one result.
3843
3844 if (auto Error = InsertPtOrError.takeError())
3845 return std::move(Error);
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003846
3847 BuildMIAction &DstMIBuilder =
3848 *static_cast<BuildMIAction *>(InsertPtOrError.get()->get());
3849
3850 // Assign the result to TempReg.
3851 DstMIBuilder.addRenderer<TempRegRenderer>(TempRegID, true);
3852
Daniel Sanders08464522018-01-29 21:09:12 +00003853 InsertPtOrError =
3854 importExplicitUseRenderers(InsertPtOrError.get(), M, DstMIBuilder, Dst);
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003855 if (auto Error = InsertPtOrError.takeError())
3856 return std::move(Error);
3857
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00003858 // We need to make sure that when we import an INSERT_SUBREG as a
3859 // subinstruction that it ends up being constrained to the correct super
3860 // register and subregister classes.
3861 if (Target.getInstruction(Dst->getOperator()).TheDef->getName() ==
3862 "INSERT_SUBREG") {
3863 auto SubClass = inferRegClassFromPattern(Dst->getChild(1));
3864 if (!SubClass)
3865 return failedImport(
3866 "Cannot infer register class from INSERT_SUBREG operand #1");
3867 Optional<const CodeGenRegisterClass *> SuperClass = inferSuperRegisterClass(
3868 Dst->getExtType(0), Dst->getChild(0), Dst->getChild(2));
3869 if (!SuperClass)
3870 return failedImport(
3871 "Cannot infer register class for INSERT_SUBREG operand #0");
3872 // The destination and the super register source of an INSERT_SUBREG must
3873 // be the same register class.
3874 M.insertAction<ConstrainOperandToRegClassAction>(
3875 InsertPt, DstMIBuilder.getInsnID(), 0, **SuperClass);
3876 M.insertAction<ConstrainOperandToRegClassAction>(
3877 InsertPt, DstMIBuilder.getInsnID(), 1, **SuperClass);
3878 M.insertAction<ConstrainOperandToRegClassAction>(
3879 InsertPt, DstMIBuilder.getInsnID(), 2, **SubClass);
3880 return InsertPtOrError.get();
3881 }
3882
Daniel Sanders08464522018-01-29 21:09:12 +00003883 M.insertAction<ConstrainOperandsToDefinitionAction>(InsertPt,
3884 DstMIBuilder.getInsnID());
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003885 return InsertPtOrError.get();
3886}
3887
Daniel Sanders7438b262017-10-31 23:03:18 +00003888Expected<action_iterator> GlobalISelEmitter::createInstructionRenderer(
Florian Hahn6b1db822018-06-14 20:32:58 +00003889 action_iterator InsertPt, RuleMatcher &M, const TreePatternNode *Dst) {
3890 Record *DstOp = Dst->getOperator();
Daniel Sandersd0656a32017-04-13 09:45:37 +00003891 if (!DstOp->isSubClassOf("Instruction")) {
3892 if (DstOp->isSubClassOf("ValueType"))
3893 return failedImport(
3894 "Pattern operator isn't an instruction (it's a ValueType)");
Daniel Sandersffc7d582017-03-29 15:37:18 +00003895 return failedImport("Pattern operator isn't an instruction");
Daniel Sandersd0656a32017-04-13 09:45:37 +00003896 }
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003897 CodeGenInstruction *DstI = &Target.getInstruction(DstOp);
Daniel Sandersffc7d582017-03-29 15:37:18 +00003898
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003899 // COPY_TO_REGCLASS is just a copy with a ConstrainOperandToRegClassAction
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00003900 // attached. Similarly for EXTRACT_SUBREG except that's a subregister copy.
Daniel Sandersdf258e32017-10-31 19:09:29 +00003901 if (DstI->TheDef->getName() == "COPY_TO_REGCLASS")
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003902 DstI = &Target.getInstruction(RK.getDef("COPY"));
Daniel Sandersdf258e32017-10-31 19:09:29 +00003903 else if (DstI->TheDef->getName() == "EXTRACT_SUBREG")
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00003904 DstI = &Target.getInstruction(RK.getDef("COPY"));
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003905 else if (DstI->TheDef->getName() == "REG_SEQUENCE")
3906 return failedImport("Unable to emit REG_SEQUENCE");
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003907
Daniel Sanders198447a2017-11-01 00:29:47 +00003908 return M.insertAction<BuildMIAction>(InsertPt, M.allocateOutputInsnID(),
3909 DstI);
Daniel Sandersdf258e32017-10-31 19:09:29 +00003910}
3911
3912void GlobalISelEmitter::importExplicitDefRenderers(
3913 BuildMIAction &DstMIBuilder) {
3914 const CodeGenInstruction *DstI = DstMIBuilder.getCGI();
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003915 for (unsigned I = 0; I < DstI->Operands.NumDefs; ++I) {
3916 const CGIOperandList::OperandInfo &DstIOperand = DstI->Operands[I];
Daniel Sanders198447a2017-11-01 00:29:47 +00003917 DstMIBuilder.addRenderer<CopyRenderer>(DstIOperand.Name);
Daniel Sandersffc7d582017-03-29 15:37:18 +00003918 }
Daniel Sandersdf258e32017-10-31 19:09:29 +00003919}
3920
Daniel Sanders7438b262017-10-31 23:03:18 +00003921Expected<action_iterator> GlobalISelEmitter::importExplicitUseRenderers(
3922 action_iterator InsertPt, RuleMatcher &M, BuildMIAction &DstMIBuilder,
Florian Hahn6b1db822018-06-14 20:32:58 +00003923 const llvm::TreePatternNode *Dst) {
Daniel Sandersdf258e32017-10-31 19:09:29 +00003924 const CodeGenInstruction *DstI = DstMIBuilder.getCGI();
Florian Hahn6b1db822018-06-14 20:32:58 +00003925 CodeGenInstruction *OrigDstI = &Target.getInstruction(Dst->getOperator());
Daniel Sandersffc7d582017-03-29 15:37:18 +00003926
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00003927 // EXTRACT_SUBREG needs to use a subregister COPY.
Daniel Sandersdf258e32017-10-31 19:09:29 +00003928 if (OrigDstI->TheDef->getName() == "EXTRACT_SUBREG") {
Florian Hahn6b1db822018-06-14 20:32:58 +00003929 if (!Dst->getChild(0)->isLeaf())
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00003930 return failedImport("EXTRACT_SUBREG child #1 is not a leaf");
3931
Daniel Sanders32291982017-06-28 13:50:04 +00003932 if (DefInit *SubRegInit =
Florian Hahn6b1db822018-06-14 20:32:58 +00003933 dyn_cast<DefInit>(Dst->getChild(1)->getLeafValue())) {
3934 Record *RCDef = getInitValueAsRegClass(Dst->getChild(0)->getLeafValue());
Daniel Sanders9cbe7c72017-11-01 19:57:57 +00003935 if (!RCDef)
3936 return failedImport("EXTRACT_SUBREG child #0 could not "
3937 "be coerced to a register class");
3938
3939 CodeGenRegisterClass *RC = CGRegs.getRegClass(RCDef);
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00003940 CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef());
3941
3942 const auto &SrcRCDstRCPair =
3943 RC->getMatchingSubClassWithSubRegs(CGRegs, SubIdx);
3944 if (SrcRCDstRCPair.hasValue()) {
3945 assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
3946 if (SrcRCDstRCPair->first != RC)
3947 return failedImport("EXTRACT_SUBREG requires an additional COPY");
3948 }
3949
Florian Hahn6b1db822018-06-14 20:32:58 +00003950 DstMIBuilder.addRenderer<CopySubRegRenderer>(Dst->getChild(0)->getName(),
Daniel Sanders198447a2017-11-01 00:29:47 +00003951 SubIdx);
Daniel Sanders7438b262017-10-31 23:03:18 +00003952 return InsertPt;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00003953 }
3954
3955 return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
3956 }
3957
Daniel Sandersffc7d582017-03-29 15:37:18 +00003958 // Render the explicit uses.
Daniel Sandersdf258e32017-10-31 19:09:29 +00003959 unsigned DstINumUses = OrigDstI->Operands.size() - OrigDstI->Operands.NumDefs;
Florian Hahn6b1db822018-06-14 20:32:58 +00003960 unsigned ExpectedDstINumUses = Dst->getNumChildren();
Daniel Sandersdf258e32017-10-31 19:09:29 +00003961 if (OrigDstI->TheDef->getName() == "COPY_TO_REGCLASS") {
3962 DstINumUses--; // Ignore the class constraint.
3963 ExpectedDstINumUses--;
3964 }
3965
Daniel Sanders0ed28822017-04-12 08:23:08 +00003966 unsigned Child = 0;
Diana Picus382602f2017-05-17 08:57:28 +00003967 unsigned NumDefaultOps = 0;
Daniel Sanders0ed28822017-04-12 08:23:08 +00003968 for (unsigned I = 0; I != DstINumUses; ++I) {
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003969 const CGIOperandList::OperandInfo &DstIOperand =
3970 DstI->Operands[DstI->Operands.NumDefs + I];
Daniel Sanders0ed28822017-04-12 08:23:08 +00003971
Diana Picus382602f2017-05-17 08:57:28 +00003972 // If the operand has default values, introduce them now.
3973 // FIXME: Until we have a decent test case that dictates we should do
3974 // otherwise, we're going to assume that operands with default values cannot
3975 // be specified in the patterns. Therefore, adding them will not cause us to
3976 // end up with too many rendered operands.
3977 if (DstIOperand.Rec->isSubClassOf("OperandWithDefaultOps")) {
Daniel Sanders0ed28822017-04-12 08:23:08 +00003978 DagInit *DefaultOps = DstIOperand.Rec->getValueAsDag("DefaultOps");
Sjoerd Meijerde234842019-05-30 07:30:37 +00003979 if (auto Error = importDefaultOperandRenderers(
3980 InsertPt, M, DstMIBuilder, DefaultOps))
Diana Picus382602f2017-05-17 08:57:28 +00003981 return std::move(Error);
3982 ++NumDefaultOps;
Daniel Sanders0ed28822017-04-12 08:23:08 +00003983 continue;
3984 }
3985
Daniel Sanders7438b262017-10-31 23:03:18 +00003986 auto InsertPtOrError = importExplicitUseRenderer(InsertPt, M, DstMIBuilder,
Florian Hahn6b1db822018-06-14 20:32:58 +00003987 Dst->getChild(Child));
Daniel Sanders7438b262017-10-31 23:03:18 +00003988 if (auto Error = InsertPtOrError.takeError())
Daniel Sandersffc7d582017-03-29 15:37:18 +00003989 return std::move(Error);
Daniel Sanders7438b262017-10-31 23:03:18 +00003990 InsertPt = InsertPtOrError.get();
Daniel Sanders0ed28822017-04-12 08:23:08 +00003991 ++Child;
Daniel Sandersffc7d582017-03-29 15:37:18 +00003992 }
3993
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003994 if (NumDefaultOps + ExpectedDstINumUses != DstINumUses)
Diana Picuseb2057c2017-05-17 09:25:08 +00003995 return failedImport("Expected " + llvm::to_string(DstINumUses) +
Diana Picus382602f2017-05-17 08:57:28 +00003996 " used operands but found " +
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00003997 llvm::to_string(ExpectedDstINumUses) +
Diana Picuseb2057c2017-05-17 09:25:08 +00003998 " explicit ones and " + llvm::to_string(NumDefaultOps) +
Diana Picus382602f2017-05-17 08:57:28 +00003999 " default ones");
4000
Daniel Sanders7438b262017-10-31 23:03:18 +00004001 return InsertPt;
Daniel Sandersffc7d582017-03-29 15:37:18 +00004002}
4003
Diana Picus382602f2017-05-17 08:57:28 +00004004Error GlobalISelEmitter::importDefaultOperandRenderers(
Sjoerd Meijerde234842019-05-30 07:30:37 +00004005 action_iterator InsertPt, RuleMatcher &M, BuildMIAction &DstMIBuilder,
4006 DagInit *DefaultOps) const {
Craig Topper481ff702017-05-29 21:49:34 +00004007 for (const auto *DefaultOp : DefaultOps->getArgs()) {
Sjoerd Meijerde234842019-05-30 07:30:37 +00004008 Optional<LLTCodeGen> OpTyOrNone = None;
4009
Diana Picus382602f2017-05-17 08:57:28 +00004010 // Look through ValueType operators.
4011 if (const DagInit *DefaultDagOp = dyn_cast<DagInit>(DefaultOp)) {
4012 if (const DefInit *DefaultDagOperator =
4013 dyn_cast<DefInit>(DefaultDagOp->getOperator())) {
Sjoerd Meijer3cac8d22019-05-31 08:39:34 +00004014 if (DefaultDagOperator->getDef()->isSubClassOf("ValueType")) {
Sjoerd Meijerde234842019-05-30 07:30:37 +00004015 OpTyOrNone = MVTToLLT(getValueType(
4016 DefaultDagOperator->getDef()));
Diana Picus382602f2017-05-17 08:57:28 +00004017 DefaultOp = DefaultDagOp->getArg(0);
Sjoerd Meijer3cac8d22019-05-31 08:39:34 +00004018 }
Diana Picus382602f2017-05-17 08:57:28 +00004019 }
4020 }
4021
4022 if (const DefInit *DefaultDefOp = dyn_cast<DefInit>(DefaultOp)) {
Sjoerd Meijerde234842019-05-30 07:30:37 +00004023 auto Def = DefaultDefOp->getDef();
4024 if (Def->getName() == "undef_tied_input") {
4025 unsigned TempRegID = M.allocateTempRegID();
4026 M.insertAction<MakeTempRegisterAction>(
4027 InsertPt, OpTyOrNone.getValue(), TempRegID);
4028 InsertPt = M.insertAction<BuildMIAction>(
4029 InsertPt, M.allocateOutputInsnID(),
4030 &Target.getInstruction(RK.getDef("IMPLICIT_DEF")));
4031 BuildMIAction &IDMIBuilder = *static_cast<BuildMIAction *>(
4032 InsertPt->get());
4033 IDMIBuilder.addRenderer<TempRegRenderer>(TempRegID);
4034 DstMIBuilder.addRenderer<TempRegRenderer>(TempRegID);
4035 } else {
4036 DstMIBuilder.addRenderer<AddRegisterRenderer>(Def);
4037 }
Diana Picus382602f2017-05-17 08:57:28 +00004038 continue;
4039 }
4040
4041 if (const IntInit *DefaultIntOp = dyn_cast<IntInit>(DefaultOp)) {
Daniel Sanders198447a2017-11-01 00:29:47 +00004042 DstMIBuilder.addRenderer<ImmRenderer>(DefaultIntOp->getValue());
Diana Picus382602f2017-05-17 08:57:28 +00004043 continue;
4044 }
4045
4046 return failedImport("Could not add default op");
4047 }
4048
4049 return Error::success();
4050}
4051
Daniel Sandersc270c502017-03-30 09:36:33 +00004052Error GlobalISelEmitter::importImplicitDefRenderers(
Daniel Sandersffc7d582017-03-29 15:37:18 +00004053 BuildMIAction &DstMIBuilder,
4054 const std::vector<Record *> &ImplicitDefs) const {
4055 if (!ImplicitDefs.empty())
4056 return failedImport("Pattern defines a physical register");
Daniel Sandersc270c502017-03-30 09:36:33 +00004057 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00004058}
4059
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004060Optional<const CodeGenRegisterClass *>
4061GlobalISelEmitter::getRegClassFromLeaf(TreePatternNode *Leaf) {
4062 assert(Leaf && "Expected node?");
4063 assert(Leaf->isLeaf() && "Expected leaf?");
4064 Record *RCRec = getInitValueAsRegClass(Leaf->getLeafValue());
4065 if (!RCRec)
4066 return None;
4067 CodeGenRegisterClass *RC = CGRegs.getRegClass(RCRec);
4068 if (!RC)
4069 return None;
4070 return RC;
4071}
4072
4073Optional<const CodeGenRegisterClass *>
4074GlobalISelEmitter::inferRegClassFromPattern(TreePatternNode *N) {
4075 if (!N)
4076 return None;
4077
4078 if (N->isLeaf())
4079 return getRegClassFromLeaf(N);
4080
4081 // We don't have a leaf node, so we have to try and infer something. Check
4082 // that we have an instruction that we an infer something from.
4083
4084 // Only handle things that produce a single type.
4085 if (N->getNumTypes() != 1)
4086 return None;
4087 Record *OpRec = N->getOperator();
4088
4089 // We only want instructions.
4090 if (!OpRec->isSubClassOf("Instruction"))
4091 return None;
4092
4093 // Don't want to try and infer things when there could potentially be more
4094 // than one candidate register class.
4095 auto &Inst = Target.getInstruction(OpRec);
4096 if (Inst.Operands.NumDefs > 1)
4097 return None;
4098
4099 // Handle any special-case instructions which we can safely infer register
4100 // classes from.
4101 StringRef InstName = Inst.TheDef->getName();
4102 if (InstName == "COPY_TO_REGCLASS") {
4103 // If we have a COPY_TO_REGCLASS, then we need to handle it specially. It
4104 // has the desired register class as the first child.
4105 TreePatternNode *RCChild = N->getChild(1);
4106 if (!RCChild->isLeaf())
4107 return None;
4108 return getRegClassFromLeaf(RCChild);
4109 }
4110
4111 // Handle destination record types that we can safely infer a register class
4112 // from.
4113 const auto &DstIOperand = Inst.Operands[0];
4114 Record *DstIOpRec = DstIOperand.Rec;
4115 if (DstIOpRec->isSubClassOf("RegisterOperand")) {
4116 DstIOpRec = DstIOpRec->getValueAsDef("RegClass");
4117 const CodeGenRegisterClass &RC = Target.getRegisterClass(DstIOpRec);
4118 return &RC;
4119 }
4120
4121 if (DstIOpRec->isSubClassOf("RegisterClass")) {
4122 const CodeGenRegisterClass &RC = Target.getRegisterClass(DstIOpRec);
4123 return &RC;
4124 }
4125
4126 return None;
4127}
4128
4129Optional<const CodeGenRegisterClass *>
4130GlobalISelEmitter::inferSuperRegisterClass(const TypeSetByHwMode &Ty,
4131 TreePatternNode *SuperRegNode,
4132 TreePatternNode *SubRegIdxNode) {
4133 // Check if we already have a defined register class for the super register
4134 // node. If we do, then we should preserve that rather than inferring anything
4135 // from the subregister index node. We can assume that whoever wrote the
4136 // pattern in the first place made sure that the super register and
4137 // subregister are compatible.
4138 if (Optional<const CodeGenRegisterClass *> SuperRegisterClass =
4139 inferRegClassFromPattern(SuperRegNode))
4140 return SuperRegisterClass;
4141
4142 // We need a ValueTypeByHwMode for getSuperRegForSubReg.
4143 if (!Ty.isValueTypeByHwMode(false))
4144 return None;
4145
4146 // We don't know anything about the super register. Try to use the subregister
4147 // index to infer an appropriate register class.
4148 if (!SubRegIdxNode->isLeaf())
4149 return None;
4150 DefInit *SubRegInit = dyn_cast<DefInit>(SubRegIdxNode->getLeafValue());
4151 if (!SubRegInit)
4152 return None;
4153 CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef());
4154
4155 // Use the information we found above to find a minimal register class which
4156 // supports the subregister and type we want.
4157 auto RC =
4158 Target.getSuperRegForSubReg(Ty.getValueTypeByHwMode(), CGRegs, SubIdx);
4159 if (!RC)
4160 return None;
4161 return *RC;
4162}
4163
Daniel Sandersffc7d582017-03-29 15:37:18 +00004164Expected<RuleMatcher> GlobalISelEmitter::runOnPattern(const PatternToMatch &P) {
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004165 // Keep track of the matchers and actions to emit.
Aditya Nandakumarb63e7632018-02-16 22:37:15 +00004166 int Score = P.getPatternComplexity(CGP);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00004167 RuleMatcher M(P.getSrcRecord()->getLoc());
Aditya Nandakumarb63e7632018-02-16 22:37:15 +00004168 RuleMatcherScores[M.getRuleID()] = Score;
Daniel Sanders6ea17ed2017-10-31 18:07:03 +00004169 M.addAction<DebugCommentAction>(llvm::to_string(*P.getSrcPattern()) +
4170 " => " +
4171 llvm::to_string(*P.getDstPattern()));
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004172
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004173 if (auto Error = importRulePredicates(M, P.getPredicates()))
Daniel Sandersffc7d582017-03-29 15:37:18 +00004174 return std::move(Error);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004175
4176 // Next, analyze the pattern operators.
Florian Hahn6b1db822018-06-14 20:32:58 +00004177 TreePatternNode *Src = P.getSrcPattern();
4178 TreePatternNode *Dst = P.getDstPattern();
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004179
4180 // If the root of either pattern isn't a simple operator, ignore it.
Daniel Sandersd0656a32017-04-13 09:45:37 +00004181 if (auto Err = isTrivialOperatorNode(Dst))
4182 return failedImport("Dst pattern root isn't a trivial operator (" +
4183 toString(std::move(Err)) + ")");
4184 if (auto Err = isTrivialOperatorNode(Src))
4185 return failedImport("Src pattern root isn't a trivial operator (" +
4186 toString(std::move(Err)) + ")");
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004187
Quentin Colombetaad20be2017-12-15 23:07:42 +00004188 // The different predicates and matchers created during
4189 // addInstructionMatcher use the RuleMatcher M to set up their
4190 // instruction ID (InsnVarID) that are going to be used when
4191 // M is going to be emitted.
4192 // However, the code doing the emission still relies on the IDs
4193 // returned during that process by the RuleMatcher when issuing
4194 // the recordInsn opcodes.
4195 // Because of that:
4196 // 1. The order in which we created the predicates
4197 // and such must be the same as the order in which we emit them,
4198 // and
4199 // 2. We need to reset the generation of the IDs in M somewhere between
4200 // addInstructionMatcher and emit
4201 //
4202 // FIXME: Long term, we don't want to have to rely on this implicit
4203 // naming being the same. One possible solution would be to have
4204 // explicit operator for operation capture and reference those.
4205 // The plus side is that it would expose opportunities to share
4206 // the capture accross rules. The downside is that it would
4207 // introduce a dependency between predicates (captures must happen
4208 // before their first use.)
Florian Hahn6b1db822018-06-14 20:32:58 +00004209 InstructionMatcher &InsnMatcherTemp = M.addInstructionMatcher(Src->getName());
Daniel Sandersedd07842017-08-17 09:26:14 +00004210 unsigned TempOpIdx = 0;
4211 auto InsnMatcherOrError =
Daniel Sandersdf39cba2017-10-15 18:22:54 +00004212 createAndImportSelDAGMatcher(M, InsnMatcherTemp, Src, TempOpIdx);
Daniel Sandersedd07842017-08-17 09:26:14 +00004213 if (auto Error = InsnMatcherOrError.takeError())
4214 return std::move(Error);
4215 InstructionMatcher &InsnMatcher = InsnMatcherOrError.get();
4216
Florian Hahn6b1db822018-06-14 20:32:58 +00004217 if (Dst->isLeaf()) {
4218 Record *RCDef = getInitValueAsRegClass(Dst->getLeafValue());
Daniel Sandersedd07842017-08-17 09:26:14 +00004219
4220 const CodeGenRegisterClass &RC = Target.getRegisterClass(RCDef);
4221 if (RCDef) {
4222 // We need to replace the def and all its uses with the specified
4223 // operand. However, we must also insert COPY's wherever needed.
4224 // For now, emit a copy and let the register allocator clean up.
4225 auto &DstI = Target.getInstruction(RK.getDef("COPY"));
4226 const auto &DstIOperand = DstI.Operands[0];
4227
4228 OperandMatcher &OM0 = InsnMatcher.getOperand(0);
4229 OM0.setSymbolicName(DstIOperand.Name);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00004230 M.defineOperand(OM0.getSymbolicName(), OM0);
Daniel Sandersedd07842017-08-17 09:26:14 +00004231 OM0.addPredicate<RegisterBankOperandMatcher>(RC);
4232
Daniel Sanders198447a2017-11-01 00:29:47 +00004233 auto &DstMIBuilder =
4234 M.addAction<BuildMIAction>(M.allocateOutputInsnID(), &DstI);
4235 DstMIBuilder.addRenderer<CopyRenderer>(DstIOperand.Name);
Florian Hahn6b1db822018-06-14 20:32:58 +00004236 DstMIBuilder.addRenderer<CopyRenderer>(Dst->getName());
Daniel Sandersedd07842017-08-17 09:26:14 +00004237 M.addAction<ConstrainOperandToRegClassAction>(0, 0, RC);
4238
4239 // We're done with this pattern! It's eligible for GISel emission; return
4240 // it.
4241 ++NumPatternImported;
4242 return std::move(M);
4243 }
4244
Daniel Sanders452c8ae2017-05-23 19:33:16 +00004245 return failedImport("Dst pattern root isn't a known leaf");
Daniel Sandersedd07842017-08-17 09:26:14 +00004246 }
Daniel Sanders452c8ae2017-05-23 19:33:16 +00004247
Daniel Sandersbee57392017-04-04 13:25:23 +00004248 // Start with the defined operands (i.e., the results of the root operator).
Florian Hahn6b1db822018-06-14 20:32:58 +00004249 Record *DstOp = Dst->getOperator();
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004250 if (!DstOp->isSubClassOf("Instruction"))
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00004251 return failedImport("Pattern operator isn't an instruction");
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004252
4253 auto &DstI = Target.getInstruction(DstOp);
Florian Hahn6b1db822018-06-14 20:32:58 +00004254 if (DstI.Operands.NumDefs != Src->getExtTypes().size())
Daniel Sandersd0656a32017-04-13 09:45:37 +00004255 return failedImport("Src pattern results and dst MI defs are different (" +
Florian Hahn6b1db822018-06-14 20:32:58 +00004256 to_string(Src->getExtTypes().size()) + " def(s) vs " +
Daniel Sandersd0656a32017-04-13 09:45:37 +00004257 to_string(DstI.Operands.NumDefs) + " def(s))");
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004258
Daniel Sandersffc7d582017-03-29 15:37:18 +00004259 // The root of the match also has constraints on the register bank so that it
4260 // matches the result instruction.
4261 unsigned OpIdx = 0;
Florian Hahn6b1db822018-06-14 20:32:58 +00004262 for (const TypeSetByHwMode &VTy : Src->getExtTypes()) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004263 (void)VTy;
Daniel Sandersffc7d582017-03-29 15:37:18 +00004264
Daniel Sanders066ebbf2017-02-24 15:43:30 +00004265 const auto &DstIOperand = DstI.Operands[OpIdx];
4266 Record *DstIOpRec = DstIOperand.Rec;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004267 if (DstI.TheDef->getName() == "COPY_TO_REGCLASS") {
Florian Hahn6b1db822018-06-14 20:32:58 +00004268 DstIOpRec = getInitValueAsRegClass(Dst->getChild(1)->getLeafValue());
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004269
4270 if (DstIOpRec == nullptr)
4271 return failedImport(
4272 "COPY_TO_REGCLASS operand #1 isn't a register class");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004273 } else if (DstI.TheDef->getName() == "EXTRACT_SUBREG") {
Florian Hahn6b1db822018-06-14 20:32:58 +00004274 if (!Dst->getChild(0)->isLeaf())
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004275 return failedImport("EXTRACT_SUBREG operand #0 isn't a leaf");
4276
Daniel Sanders32291982017-06-28 13:50:04 +00004277 // We can assume that a subregister is in the same bank as it's super
4278 // register.
Florian Hahn6b1db822018-06-14 20:32:58 +00004279 DstIOpRec = getInitValueAsRegClass(Dst->getChild(0)->getLeafValue());
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004280
4281 if (DstIOpRec == nullptr)
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004282 return failedImport("EXTRACT_SUBREG operand #0 isn't a register class");
4283 } else if (DstI.TheDef->getName() == "INSERT_SUBREG") {
4284 auto MaybeSuperClass =
4285 inferSuperRegisterClass(VTy, Dst->getChild(0), Dst->getChild(2));
4286 if (!MaybeSuperClass)
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004287 return failedImport(
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004288 "Cannot infer register class for INSERT_SUBREG operand #0");
4289 // Move to the next pattern here, because the register class we found
4290 // doesn't necessarily have a record associated with it. So, we can't
4291 // set DstIOpRec using this.
4292 OperandMatcher &OM = InsnMatcher.getOperand(OpIdx);
4293 OM.setSymbolicName(DstIOperand.Name);
4294 M.defineOperand(OM.getSymbolicName(), OM);
4295 OM.addPredicate<RegisterBankOperandMatcher>(**MaybeSuperClass);
4296 ++OpIdx;
4297 continue;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004298 } else if (DstIOpRec->isSubClassOf("RegisterOperand"))
Daniel Sanders658541f2017-04-22 15:53:21 +00004299 DstIOpRec = DstIOpRec->getValueAsDef("RegClass");
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004300 else if (!DstIOpRec->isSubClassOf("RegisterClass"))
Florian Hahn6b1db822018-06-14 20:32:58 +00004301 return failedImport("Dst MI def isn't a register class" +
4302 to_string(*Dst));
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004303
Daniel Sandersffc7d582017-03-29 15:37:18 +00004304 OperandMatcher &OM = InsnMatcher.getOperand(OpIdx);
4305 OM.setSymbolicName(DstIOperand.Name);
Daniel Sandersbfa9e2c2017-10-14 00:31:58 +00004306 M.defineOperand(OM.getSymbolicName(), OM);
Daniel Sandersdc662ff2017-01-26 11:10:14 +00004307 OM.addPredicate<RegisterBankOperandMatcher>(
4308 Target.getRegisterClass(DstIOpRec));
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004309 ++OpIdx;
4310 }
4311
Daniel Sandersa7b75262017-10-31 18:50:24 +00004312 auto DstMIBuilderOrError = createAndImportInstructionRenderer(M, Dst);
Daniel Sandersffc7d582017-03-29 15:37:18 +00004313 if (auto Error = DstMIBuilderOrError.takeError())
4314 return std::move(Error);
4315 BuildMIAction &DstMIBuilder = DstMIBuilderOrError.get();
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004316
Daniel Sandersffc7d582017-03-29 15:37:18 +00004317 // Render the implicit defs.
4318 // These are only added to the root of the result.
Daniel Sandersc270c502017-03-30 09:36:33 +00004319 if (auto Error = importImplicitDefRenderers(DstMIBuilder, P.getDstRegs()))
Daniel Sandersffc7d582017-03-29 15:37:18 +00004320 return std::move(Error);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004321
Daniel Sandersa7b75262017-10-31 18:50:24 +00004322 DstMIBuilder.chooseInsnToMutate(M);
4323
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004324 // Constrain the registers to classes. This is normally derived from the
4325 // emitted instruction but a few instructions require special handling.
4326 if (DstI.TheDef->getName() == "COPY_TO_REGCLASS") {
4327 // COPY_TO_REGCLASS does not provide operand constraints itself but the
4328 // result is constrained to the class given by the second child.
4329 Record *DstIOpRec =
Florian Hahn6b1db822018-06-14 20:32:58 +00004330 getInitValueAsRegClass(Dst->getChild(1)->getLeafValue());
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004331
4332 if (DstIOpRec == nullptr)
4333 return failedImport("COPY_TO_REGCLASS operand #1 isn't a register class");
4334
4335 M.addAction<ConstrainOperandToRegClassAction>(
Daniel Sandersd93a35a2017-07-05 09:39:33 +00004336 0, 0, Target.getRegisterClass(DstIOpRec));
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004337
4338 // We're done with this pattern! It's eligible for GISel emission; return
4339 // it.
4340 ++NumPatternImported;
4341 return std::move(M);
4342 }
4343
4344 if (DstI.TheDef->getName() == "EXTRACT_SUBREG") {
4345 // EXTRACT_SUBREG selects into a subregister COPY but unlike most
4346 // instructions, the result register class is controlled by the
4347 // subregisters of the operand. As a result, we must constrain the result
4348 // class rather than check that it's already the right one.
Florian Hahn6b1db822018-06-14 20:32:58 +00004349 if (!Dst->getChild(0)->isLeaf())
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004350 return failedImport("EXTRACT_SUBREG child #1 is not a leaf");
4351
Florian Hahn6b1db822018-06-14 20:32:58 +00004352 DefInit *SubRegInit = dyn_cast<DefInit>(Dst->getChild(1)->getLeafValue());
Daniel Sanders320390b2017-06-28 15:16:03 +00004353 if (!SubRegInit)
4354 return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004355
Daniel Sanders320390b2017-06-28 15:16:03 +00004356 // Constrain the result to the same register bank as the operand.
4357 Record *DstIOpRec =
Florian Hahn6b1db822018-06-14 20:32:58 +00004358 getInitValueAsRegClass(Dst->getChild(0)->getLeafValue());
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004359
Daniel Sanders320390b2017-06-28 15:16:03 +00004360 if (DstIOpRec == nullptr)
4361 return failedImport("EXTRACT_SUBREG operand #1 isn't a register class");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004362
Daniel Sanders320390b2017-06-28 15:16:03 +00004363 CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef());
Daniel Sandersd93a35a2017-07-05 09:39:33 +00004364 CodeGenRegisterClass *SrcRC = CGRegs.getRegClass(DstIOpRec);
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004365
Daniel Sanders320390b2017-06-28 15:16:03 +00004366 // It would be nice to leave this constraint implicit but we're required
4367 // to pick a register class so constrain the result to a register class
4368 // that can hold the correct MVT.
4369 //
4370 // FIXME: This may introduce an extra copy if the chosen class doesn't
4371 // actually contain the subregisters.
Florian Hahn6b1db822018-06-14 20:32:58 +00004372 assert(Src->getExtTypes().size() == 1 &&
Daniel Sanders320390b2017-06-28 15:16:03 +00004373 "Expected Src of EXTRACT_SUBREG to have one result type");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00004374
Daniel Sanders320390b2017-06-28 15:16:03 +00004375 const auto &SrcRCDstRCPair =
4376 SrcRC->getMatchingSubClassWithSubRegs(CGRegs, SubIdx);
4377 assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
Daniel Sandersd93a35a2017-07-05 09:39:33 +00004378 M.addAction<ConstrainOperandToRegClassAction>(0, 0, *SrcRCDstRCPair->second);
4379 M.addAction<ConstrainOperandToRegClassAction>(0, 1, *SrcRCDstRCPair->first);
4380
4381 // We're done with this pattern! It's eligible for GISel emission; return
4382 // it.
4383 ++NumPatternImported;
4384 return std::move(M);
4385 }
4386
Jessica Paquettea2ea8a12019-08-27 17:47:06 +00004387 if (DstI.TheDef->getName() == "INSERT_SUBREG") {
4388 assert(Src->getExtTypes().size() == 1 &&
4389 "Expected Src of INSERT_SUBREG to have one result type");
4390 // We need to constrain the destination, a super regsister source, and a
4391 // subregister source.
4392 auto SubClass = inferRegClassFromPattern(Dst->getChild(1));
4393 if (!SubClass)
4394 return failedImport(
4395 "Cannot infer register class from INSERT_SUBREG operand #1");
4396 auto SuperClass = inferSuperRegisterClass(
4397 Src->getExtType(0), Dst->getChild(0), Dst->getChild(2));
4398 if (!SuperClass)
4399 return failedImport(
4400 "Cannot infer register class for INSERT_SUBREG operand #0");
4401 M.addAction<ConstrainOperandToRegClassAction>(0, 0, **SuperClass);
4402 M.addAction<ConstrainOperandToRegClassAction>(0, 1, **SuperClass);
4403 M.addAction<ConstrainOperandToRegClassAction>(0, 2, **SubClass);
4404 ++NumPatternImported;
4405 return std::move(M);
4406 }
4407
Daniel Sandersd93a35a2017-07-05 09:39:33 +00004408 M.addAction<ConstrainOperandsToDefinitionAction>(0);
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00004409
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00004410 // We're done with this pattern! It's eligible for GISel emission; return it.
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00004411 ++NumPatternImported;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00004412 return std::move(M);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004413}
4414
Daniel Sanders649c5852017-10-13 20:42:18 +00004415// Emit imm predicate table and an enum to reference them with.
4416// The 'Predicate_' part of the name is redundant but eliminating it is more
4417// trouble than it's worth.
Daniel Sanders8ead1292018-06-15 23:13:43 +00004418void GlobalISelEmitter::emitCxxPredicateFns(
4419 raw_ostream &OS, StringRef CodeFieldName, StringRef TypeIdentifier,
4420 StringRef ArgType, StringRef ArgName, StringRef AdditionalDeclarations,
Daniel Sanders11300ce2017-10-13 21:28:03 +00004421 std::function<bool(const Record *R)> Filter) {
Daniel Sanders649c5852017-10-13 20:42:18 +00004422 std::vector<const Record *> MatchedRecords;
4423 const auto &Defs = RK.getAllDerivedDefinitions("PatFrag");
4424 std::copy_if(Defs.begin(), Defs.end(), std::back_inserter(MatchedRecords),
4425 [&](Record *Record) {
Daniel Sanders8ead1292018-06-15 23:13:43 +00004426 return !Record->getValueAsString(CodeFieldName).empty() &&
Daniel Sanders649c5852017-10-13 20:42:18 +00004427 Filter(Record);
4428 });
4429
Daniel Sanders11300ce2017-10-13 21:28:03 +00004430 if (!MatchedRecords.empty()) {
4431 OS << "// PatFrag predicates.\n"
4432 << "enum {\n";
Daniel Sanders2fed4ff2017-10-13 21:51:20 +00004433 std::string EnumeratorSeparator =
Daniel Sanders11300ce2017-10-13 21:28:03 +00004434 (" = GIPFP_" + TypeIdentifier + "_Invalid + 1,\n").str();
4435 for (const auto *Record : MatchedRecords) {
4436 OS << " GIPFP_" << TypeIdentifier << "_Predicate_" << Record->getName()
4437 << EnumeratorSeparator;
4438 EnumeratorSeparator = ",\n";
4439 }
4440 OS << "};\n";
Daniel Sanders649c5852017-10-13 20:42:18 +00004441 }
Daniel Sanders11300ce2017-10-13 21:28:03 +00004442
Daniel Sanders8ead1292018-06-15 23:13:43 +00004443 OS << "bool " << Target.getName() << "InstructionSelector::test" << ArgName
4444 << "Predicate_" << TypeIdentifier << "(unsigned PredicateID, " << ArgType << " "
4445 << ArgName << ") const {\n"
4446 << AdditionalDeclarations;
4447 if (!AdditionalDeclarations.empty())
4448 OS << "\n";
Aaron Ballman82e17f52017-12-20 20:09:30 +00004449 if (!MatchedRecords.empty())
4450 OS << " switch (PredicateID) {\n";
Daniel Sanders32de8bb2017-12-20 14:41:51 +00004451 for (const auto *Record : MatchedRecords) {
4452 OS << " case GIPFP_" << TypeIdentifier << "_Predicate_"
4453 << Record->getName() << ": {\n"
Daniel Sanders8ead1292018-06-15 23:13:43 +00004454 << " " << Record->getValueAsString(CodeFieldName) << "\n"
4455 << " llvm_unreachable(\"" << CodeFieldName
4456 << " should have returned\");\n"
Daniel Sanders32de8bb2017-12-20 14:41:51 +00004457 << " return false;\n"
4458 << " }\n";
4459 }
Aaron Ballman82e17f52017-12-20 20:09:30 +00004460 if (!MatchedRecords.empty())
4461 OS << " }\n";
4462 OS << " llvm_unreachable(\"Unknown predicate\");\n"
Daniel Sanders32de8bb2017-12-20 14:41:51 +00004463 << " return false;\n"
4464 << "}\n";
Daniel Sanders649c5852017-10-13 20:42:18 +00004465}
4466
Daniel Sanders8ead1292018-06-15 23:13:43 +00004467void GlobalISelEmitter::emitImmPredicateFns(
4468 raw_ostream &OS, StringRef TypeIdentifier, StringRef ArgType,
4469 std::function<bool(const Record *R)> Filter) {
4470 return emitCxxPredicateFns(OS, "ImmediateCode", TypeIdentifier, ArgType,
4471 "Imm", "", Filter);
4472}
4473
4474void GlobalISelEmitter::emitMIPredicateFns(raw_ostream &OS) {
4475 return emitCxxPredicateFns(
4476 OS, "GISelPredicateCode", "MI", "const MachineInstr &", "MI",
4477 " const MachineFunction &MF = *MI.getParent()->getParent();\n"
Andrei Elovikov36cbbff2018-06-26 07:05:08 +00004478 " const MachineRegisterInfo &MRI = MF.getRegInfo();\n"
4479 " (void)MRI;",
Daniel Sanders8ead1292018-06-15 23:13:43 +00004480 [](const Record *R) { return true; });
4481}
4482
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004483template <class GroupT>
Quentin Colombetec76d9c2017-12-18 19:47:41 +00004484std::vector<Matcher *> GlobalISelEmitter::optimizeRules(
Roman Tereshin2d6d3762018-05-02 20:08:14 +00004485 ArrayRef<Matcher *> Rules,
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004486 std::vector<std::unique_ptr<Matcher>> &MatcherStorage) {
4487
Quentin Colombetec76d9c2017-12-18 19:47:41 +00004488 std::vector<Matcher *> OptRules;
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00004489 std::unique_ptr<GroupT> CurrentGroup = std::make_unique<GroupT>();
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004490 assert(CurrentGroup->empty() && "Newly created group isn't empty!");
4491 unsigned NumGroups = 0;
4492
4493 auto ProcessCurrentGroup = [&]() {
4494 if (CurrentGroup->empty())
4495 // An empty group is good to be reused:
4496 return;
4497
4498 // If the group isn't large enough to provide any benefit, move all the
4499 // added rules out of it and make sure to re-create the group to properly
4500 // re-initialize it:
4501 if (CurrentGroup->size() < 2)
4502 for (Matcher *M : CurrentGroup->matchers())
4503 OptRules.push_back(M);
4504 else {
4505 CurrentGroup->finalize();
Roman Tereshin8bdf7be2018-05-21 22:21:24 +00004506 OptRules.push_back(CurrentGroup.get());
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004507 MatcherStorage.emplace_back(std::move(CurrentGroup));
4508 ++NumGroups;
Roman Tereshin8bdf7be2018-05-21 22:21:24 +00004509 }
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00004510 CurrentGroup = std::make_unique<GroupT>();
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004511 };
4512 for (Matcher *Rule : Rules) {
4513 // Greedily add as many matchers as possible to the current group:
4514 if (CurrentGroup->addMatcher(*Rule))
4515 continue;
4516
4517 ProcessCurrentGroup();
4518 assert(CurrentGroup->empty() && "A group wasn't properly re-initialized");
4519
4520 // Try to add the pending matcher to a newly created empty group:
4521 if (!CurrentGroup->addMatcher(*Rule))
4522 // If we couldn't add the matcher to an empty group, that group type
4523 // doesn't support that kind of matchers at all, so just skip it:
4524 OptRules.push_back(Rule);
Quentin Colombetec76d9c2017-12-18 19:47:41 +00004525 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004526 ProcessCurrentGroup();
4527
Nicola Zaghen03d0b912018-05-23 15:09:29 +00004528 LLVM_DEBUG(dbgs() << "NumGroups: " << NumGroups << "\n");
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004529 assert(CurrentGroup->empty() && "The last group wasn't properly processed");
Quentin Colombetec76d9c2017-12-18 19:47:41 +00004530 return OptRules;
4531}
4532
Roman Tereshin2d6d3762018-05-02 20:08:14 +00004533MatchTable
4534GlobalISelEmitter::buildMatchTable(MutableArrayRef<RuleMatcher> Rules,
Roman Tereshinbeb39312018-05-02 20:15:11 +00004535 bool Optimize, bool WithCoverage) {
Roman Tereshin2d6d3762018-05-02 20:08:14 +00004536 std::vector<Matcher *> InputRules;
4537 for (Matcher &Rule : Rules)
4538 InputRules.push_back(&Rule);
4539
4540 if (!Optimize)
Roman Tereshinbeb39312018-05-02 20:15:11 +00004541 return MatchTable::buildTable(InputRules, WithCoverage);
Roman Tereshin2d6d3762018-05-02 20:08:14 +00004542
Roman Tereshin77013602018-05-22 16:54:27 +00004543 unsigned CurrentOrdering = 0;
4544 StringMap<unsigned> OpcodeOrder;
4545 for (RuleMatcher &Rule : Rules) {
4546 const StringRef Opcode = Rule.getOpcode();
4547 assert(!Opcode.empty() && "Didn't expect an undefined opcode");
4548 if (OpcodeOrder.count(Opcode) == 0)
4549 OpcodeOrder[Opcode] = CurrentOrdering++;
4550 }
4551
4552 std::stable_sort(InputRules.begin(), InputRules.end(),
4553 [&OpcodeOrder](const Matcher *A, const Matcher *B) {
4554 auto *L = static_cast<const RuleMatcher *>(A);
4555 auto *R = static_cast<const RuleMatcher *>(B);
4556 return std::make_tuple(OpcodeOrder[L->getOpcode()],
4557 L->getNumOperands()) <
4558 std::make_tuple(OpcodeOrder[R->getOpcode()],
4559 R->getNumOperands());
4560 });
4561
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004562 for (Matcher *Rule : InputRules)
4563 Rule->optimize();
4564
4565 std::vector<std::unique_ptr<Matcher>> MatcherStorage;
Roman Tereshin2d6d3762018-05-02 20:08:14 +00004566 std::vector<Matcher *> OptRules =
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004567 optimizeRules<GroupMatcher>(InputRules, MatcherStorage);
4568
4569 for (Matcher *Rule : OptRules)
4570 Rule->optimize();
Roman Tereshin2d6d3762018-05-02 20:08:14 +00004571
Roman Tereshin0ee082f2018-05-22 19:37:59 +00004572 OptRules = optimizeRules<SwitchMatcher>(OptRules, MatcherStorage);
4573
Roman Tereshinbeb39312018-05-02 20:15:11 +00004574 return MatchTable::buildTable(OptRules, WithCoverage);
Roman Tereshin2d6d3762018-05-02 20:08:14 +00004575}
4576
Roman Tereshinfedae332018-05-23 02:04:19 +00004577void GroupMatcher::optimize() {
Roman Tereshin9a9fa492018-05-23 21:30:16 +00004578 // Make sure we only sort by a specific predicate within a range of rules that
4579 // all have that predicate checked against a specific value (not a wildcard):
4580 auto F = Matchers.begin();
4581 auto T = F;
4582 auto E = Matchers.end();
4583 while (T != E) {
4584 while (T != E) {
4585 auto *R = static_cast<RuleMatcher *>(*T);
4586 if (!R->getFirstConditionAsRootType().get().isValid())
4587 break;
4588 ++T;
4589 }
4590 std::stable_sort(F, T, [](Matcher *A, Matcher *B) {
4591 auto *L = static_cast<RuleMatcher *>(A);
4592 auto *R = static_cast<RuleMatcher *>(B);
4593 return L->getFirstConditionAsRootType() <
4594 R->getFirstConditionAsRootType();
4595 });
4596 if (T != E)
4597 F = ++T;
4598 }
Roman Tereshinfedae332018-05-23 02:04:19 +00004599 GlobalISelEmitter::optimizeRules<GroupMatcher>(Matchers, MatcherStorage)
4600 .swap(Matchers);
Roman Tereshina4c410d2018-05-24 00:24:15 +00004601 GlobalISelEmitter::optimizeRules<SwitchMatcher>(Matchers, MatcherStorage)
4602 .swap(Matchers);
Roman Tereshinfedae332018-05-23 02:04:19 +00004603}
4604
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004605void GlobalISelEmitter::run(raw_ostream &OS) {
Daniel Sandersf76f3152017-11-16 00:46:35 +00004606 if (!UseCoverageFile.empty()) {
4607 RuleCoverage = CodeGenCoverage();
4608 auto RuleCoverageBufOrErr = MemoryBuffer::getFile(UseCoverageFile);
4609 if (!RuleCoverageBufOrErr) {
4610 PrintWarning(SMLoc(), "Missing rule coverage data");
4611 RuleCoverage = None;
4612 } else {
4613 if (!RuleCoverage->parse(*RuleCoverageBufOrErr.get(), Target.getName())) {
4614 PrintWarning(SMLoc(), "Ignoring invalid or missing rule coverage data");
4615 RuleCoverage = None;
4616 }
4617 }
4618 }
4619
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004620 // Track the run-time opcode values
4621 gatherOpcodeValues();
4622 // Track the run-time LLT ID values
4623 gatherTypeIDValues();
4624
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004625 // Track the GINodeEquiv definitions.
4626 gatherNodeEquivs();
4627
4628 emitSourceFileHeader(("Global Instruction Selector for the " +
4629 Target.getName() + " target").str(), OS);
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00004630 std::vector<RuleMatcher> Rules;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004631 // Look through the SelectionDAG patterns we found, possibly emitting some.
4632 for (const PatternToMatch &Pat : CGP.ptms()) {
4633 ++NumPatternTotal;
Daniel Sanders7e523672017-11-11 03:23:44 +00004634
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00004635 auto MatcherOrErr = runOnPattern(Pat);
4636
4637 // The pattern analysis can fail, indicating an unsupported pattern.
4638 // Report that if we've been asked to do so.
4639 if (auto Err = MatcherOrErr.takeError()) {
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004640 if (WarnOnSkippedPatterns) {
4641 PrintWarning(Pat.getSrcRecord()->getLoc(),
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00004642 "Skipped pattern: " + toString(std::move(Err)));
4643 } else {
4644 consumeError(std::move(Err));
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004645 }
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00004646 ++NumPatternImportsSkipped;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00004647 continue;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004648 }
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00004649
Daniel Sandersf76f3152017-11-16 00:46:35 +00004650 if (RuleCoverage) {
4651 if (RuleCoverage->isCovered(MatcherOrErr->getRuleID()))
4652 ++NumPatternsTested;
4653 else
4654 PrintWarning(Pat.getSrcRecord()->getLoc(),
4655 "Pattern is not covered by a test");
4656 }
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00004657 Rules.push_back(std::move(MatcherOrErr.get()));
4658 }
4659
Volkan Kelesf7f25682018-01-16 18:44:05 +00004660 // Comparison function to order records by name.
4661 auto orderByName = [](const Record *A, const Record *B) {
4662 return A->getName() < B->getName();
4663 };
4664
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00004665 std::vector<Record *> ComplexPredicates =
4666 RK.getAllDerivedDefinitions("GIComplexOperandMatcher");
Fangrui Song0cac7262018-09-27 02:13:45 +00004667 llvm::sort(ComplexPredicates, orderByName);
Volkan Kelesf7f25682018-01-16 18:44:05 +00004668
4669 std::vector<Record *> CustomRendererFns =
4670 RK.getAllDerivedDefinitions("GICustomOperandRenderer");
Fangrui Song0cac7262018-09-27 02:13:45 +00004671 llvm::sort(CustomRendererFns, orderByName);
Volkan Kelesf7f25682018-01-16 18:44:05 +00004672
Daniel Sanders8a4bae92017-03-14 21:32:08 +00004673 unsigned MaxTemporaries = 0;
4674 for (const auto &Rule : Rules)
Daniel Sanders2deea182017-04-22 15:11:04 +00004675 MaxTemporaries = std::max(MaxTemporaries, Rule.countRendererFns());
Daniel Sanders8a4bae92017-03-14 21:32:08 +00004676
Daniel Sanderse7b0d662017-04-21 15:59:56 +00004677 OS << "#ifdef GET_GLOBALISEL_PREDICATE_BITSET\n"
4678 << "const unsigned MAX_SUBTARGET_PREDICATES = " << SubtargetFeatures.size()
4679 << ";\n"
4680 << "using PredicateBitset = "
4681 "llvm::PredicateBitsetImpl<MAX_SUBTARGET_PREDICATES>;\n"
4682 << "#endif // ifdef GET_GLOBALISEL_PREDICATE_BITSET\n\n";
4683
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00004684 OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n"
4685 << " mutable MatcherState State;\n"
4686 << " typedef "
Daniel Sanders1e4569f2017-10-20 20:55:29 +00004687 "ComplexRendererFns("
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00004688 << Target.getName()
4689 << "InstructionSelector::*ComplexMatcherMemFn)(MachineOperand &) const;\n"
Volkan Kelesf7f25682018-01-16 18:44:05 +00004690
4691 << " typedef void(" << Target.getName()
4692 << "InstructionSelector::*CustomRendererFn)(MachineInstrBuilder &, const "
4693 "MachineInstr&) "
4694 "const;\n"
4695 << " const ISelInfoTy<PredicateBitset, ComplexMatcherMemFn, "
4696 "CustomRendererFn> "
4697 "ISelInfo;\n";
4698 OS << " static " << Target.getName()
Daniel Sandersea8711b2017-10-16 03:36:29 +00004699 << "InstructionSelector::ComplexMatcherMemFn ComplexPredicateFns[];\n"
Volkan Kelesf7f25682018-01-16 18:44:05 +00004700 << " static " << Target.getName()
4701 << "InstructionSelector::CustomRendererFn CustomRenderers[];\n"
Roman Tereshin2df4c222018-05-02 20:07:15 +00004702 << " bool testImmPredicate_I64(unsigned PredicateID, int64_t Imm) const "
Daniel Sanders32de8bb2017-12-20 14:41:51 +00004703 "override;\n"
Roman Tereshin2df4c222018-05-02 20:07:15 +00004704 << " bool testImmPredicate_APInt(unsigned PredicateID, const APInt &Imm) "
Daniel Sanders32de8bb2017-12-20 14:41:51 +00004705 "const override;\n"
Roman Tereshin2df4c222018-05-02 20:07:15 +00004706 << " bool testImmPredicate_APFloat(unsigned PredicateID, const APFloat "
Daniel Sanders32de8bb2017-12-20 14:41:51 +00004707 "&Imm) const override;\n"
Roman Tereshin2df4c222018-05-02 20:07:15 +00004708 << " const int64_t *getMatchTable() const override;\n"
Daniel Sanders8ead1292018-06-15 23:13:43 +00004709 << " bool testMIPredicate_MI(unsigned PredicateID, const MachineInstr &MI) "
4710 "const override;\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00004711 << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n\n";
Daniel Sanders8a4bae92017-03-14 21:32:08 +00004712
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00004713 OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n"
4714 << ", State(" << MaxTemporaries << "),\n"
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004715 << "ISelInfo(TypeObjects, NumTypeObjects, FeatureBitsets"
4716 << ", ComplexPredicateFns, CustomRenderers)\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00004717 << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n\n";
Daniel Sanders8a4bae92017-03-14 21:32:08 +00004718
Daniel Sanderse7b0d662017-04-21 15:59:56 +00004719 OS << "#ifdef GET_GLOBALISEL_IMPL\n";
4720 SubtargetFeatureInfo::emitSubtargetFeatureBitEnumeration(SubtargetFeatures,
4721 OS);
Daniel Sanderse9fdba32017-04-29 17:30:09 +00004722
4723 // Separate subtarget features by how often they must be recomputed.
4724 SubtargetFeatureInfoMap ModuleFeatures;
4725 std::copy_if(SubtargetFeatures.begin(), SubtargetFeatures.end(),
4726 std::inserter(ModuleFeatures, ModuleFeatures.end()),
4727 [](const SubtargetFeatureInfoMap::value_type &X) {
4728 return !X.second.mustRecomputePerFunction();
4729 });
4730 SubtargetFeatureInfoMap FunctionFeatures;
4731 std::copy_if(SubtargetFeatures.begin(), SubtargetFeatures.end(),
4732 std::inserter(FunctionFeatures, FunctionFeatures.end()),
4733 [](const SubtargetFeatureInfoMap::value_type &X) {
4734 return X.second.mustRecomputePerFunction();
4735 });
4736
Daniel Sanderse7b0d662017-04-21 15:59:56 +00004737 SubtargetFeatureInfo::emitComputeAvailableFeatures(
Daniel Sanderse9fdba32017-04-29 17:30:09 +00004738 Target.getName(), "InstructionSelector", "computeAvailableModuleFeatures",
4739 ModuleFeatures, OS);
4740 SubtargetFeatureInfo::emitComputeAvailableFeatures(
4741 Target.getName(), "InstructionSelector",
4742 "computeAvailableFunctionFeatures", FunctionFeatures, OS,
4743 "const MachineFunction *MF");
Daniel Sanderse7b0d662017-04-21 15:59:56 +00004744
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00004745 // Emit a table containing the LLT objects needed by the matcher and an enum
4746 // for the matcher to reference them with.
Daniel Sanders032e7f22017-08-17 13:18:35 +00004747 std::vector<LLTCodeGen> TypeObjects;
Daniel Sandersf84bc372018-05-05 20:53:24 +00004748 for (const auto &Ty : KnownTypes)
Daniel Sanders032e7f22017-08-17 13:18:35 +00004749 TypeObjects.push_back(Ty);
Fangrui Song0cac7262018-09-27 02:13:45 +00004750 llvm::sort(TypeObjects);
Daniel Sanders49980702017-08-23 10:09:25 +00004751 OS << "// LLT Objects.\n"
4752 << "enum {\n";
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00004753 for (const auto &TypeObject : TypeObjects) {
4754 OS << " ";
4755 TypeObject.emitCxxEnumValue(OS);
4756 OS << ",\n";
4757 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004758 OS << "};\n";
4759 OS << "const static size_t NumTypeObjects = " << TypeObjects.size() << ";\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00004760 << "const static LLT TypeObjects[] = {\n";
4761 for (const auto &TypeObject : TypeObjects) {
4762 OS << " ";
4763 TypeObject.emitCxxConstructorCall(OS);
4764 OS << ",\n";
4765 }
4766 OS << "};\n\n";
4767
4768 // Emit a table containing the PredicateBitsets objects needed by the matcher
4769 // and an enum for the matcher to reference them with.
4770 std::vector<std::vector<Record *>> FeatureBitsets;
4771 for (auto &Rule : Rules)
4772 FeatureBitsets.push_back(Rule.getRequiredFeatures());
Fangrui Song3507c6e2018-09-30 22:31:29 +00004773 llvm::sort(FeatureBitsets, [&](const std::vector<Record *> &A,
4774 const std::vector<Record *> &B) {
4775 if (A.size() < B.size())
4776 return true;
4777 if (A.size() > B.size())
4778 return false;
4779 for (const auto &Pair : zip(A, B)) {
4780 if (std::get<0>(Pair)->getName() < std::get<1>(Pair)->getName())
4781 return true;
4782 if (std::get<0>(Pair)->getName() > std::get<1>(Pair)->getName())
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00004783 return false;
Fangrui Song3507c6e2018-09-30 22:31:29 +00004784 }
4785 return false;
4786 });
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00004787 FeatureBitsets.erase(
4788 std::unique(FeatureBitsets.begin(), FeatureBitsets.end()),
4789 FeatureBitsets.end());
Daniel Sanders49980702017-08-23 10:09:25 +00004790 OS << "// Feature bitsets.\n"
4791 << "enum {\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00004792 << " GIFBS_Invalid,\n";
4793 for (const auto &FeatureBitset : FeatureBitsets) {
4794 if (FeatureBitset.empty())
4795 continue;
4796 OS << " " << getNameForFeatureBitset(FeatureBitset) << ",\n";
4797 }
4798 OS << "};\n"
4799 << "const static PredicateBitset FeatureBitsets[] {\n"
4800 << " {}, // GIFBS_Invalid\n";
4801 for (const auto &FeatureBitset : FeatureBitsets) {
4802 if (FeatureBitset.empty())
4803 continue;
4804 OS << " {";
4805 for (const auto &Feature : FeatureBitset) {
4806 const auto &I = SubtargetFeatures.find(Feature);
4807 assert(I != SubtargetFeatures.end() && "Didn't import predicate?");
4808 OS << I->second.getEnumBitName() << ", ";
4809 }
4810 OS << "},\n";
4811 }
4812 OS << "};\n\n";
4813
4814 // Emit complex predicate table and an enum to reference them with.
Daniel Sanders49980702017-08-23 10:09:25 +00004815 OS << "// ComplexPattern predicates.\n"
4816 << "enum {\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00004817 << " GICP_Invalid,\n";
4818 for (const auto &Record : ComplexPredicates)
4819 OS << " GICP_" << Record->getName() << ",\n";
4820 OS << "};\n"
4821 << "// See constructor for table contents\n\n";
4822
Daniel Sanders8ead1292018-06-15 23:13:43 +00004823 emitImmPredicateFns(OS, "I64", "int64_t", [](const Record *R) {
Daniel Sanders649c5852017-10-13 20:42:18 +00004824 bool Unset;
4825 return !R->getValueAsBitOrUnset("IsAPFloat", Unset) &&
4826 !R->getValueAsBit("IsAPInt");
4827 });
Daniel Sanders8ead1292018-06-15 23:13:43 +00004828 emitImmPredicateFns(OS, "APFloat", "const APFloat &", [](const Record *R) {
Daniel Sanders11300ce2017-10-13 21:28:03 +00004829 bool Unset;
4830 return R->getValueAsBitOrUnset("IsAPFloat", Unset);
4831 });
Daniel Sanders8ead1292018-06-15 23:13:43 +00004832 emitImmPredicateFns(OS, "APInt", "const APInt &", [](const Record *R) {
Daniel Sanders11300ce2017-10-13 21:28:03 +00004833 return R->getValueAsBit("IsAPInt");
4834 });
Daniel Sanders8ead1292018-06-15 23:13:43 +00004835 emitMIPredicateFns(OS);
Daniel Sandersea8711b2017-10-16 03:36:29 +00004836 OS << "\n";
4837
4838 OS << Target.getName() << "InstructionSelector::ComplexMatcherMemFn\n"
4839 << Target.getName() << "InstructionSelector::ComplexPredicateFns[] = {\n"
4840 << " nullptr, // GICP_Invalid\n";
4841 for (const auto &Record : ComplexPredicates)
4842 OS << " &" << Target.getName()
4843 << "InstructionSelector::" << Record->getValueAsString("MatcherFn")
4844 << ", // " << Record->getName() << "\n";
4845 OS << "};\n\n";
Daniel Sanders2c269f62017-08-24 09:11:20 +00004846
Volkan Kelesf7f25682018-01-16 18:44:05 +00004847 OS << "// Custom renderers.\n"
4848 << "enum {\n"
4849 << " GICR_Invalid,\n";
4850 for (const auto &Record : CustomRendererFns)
4851 OS << " GICR_" << Record->getValueAsString("RendererFn") << ", \n";
4852 OS << "};\n";
4853
4854 OS << Target.getName() << "InstructionSelector::CustomRendererFn\n"
4855 << Target.getName() << "InstructionSelector::CustomRenderers[] = {\n"
4856 << " nullptr, // GICP_Invalid\n";
4857 for (const auto &Record : CustomRendererFns)
4858 OS << " &" << Target.getName()
4859 << "InstructionSelector::" << Record->getValueAsString("RendererFn")
4860 << ", // " << Record->getName() << "\n";
4861 OS << "};\n\n";
4862
Fangrui Songefd94c52019-04-23 14:51:27 +00004863 llvm::stable_sort(Rules, [&](const RuleMatcher &A, const RuleMatcher &B) {
Aditya Nandakumarb63e7632018-02-16 22:37:15 +00004864 int ScoreA = RuleMatcherScores[A.getRuleID()];
4865 int ScoreB = RuleMatcherScores[B.getRuleID()];
4866 if (ScoreA > ScoreB)
4867 return true;
4868 if (ScoreB > ScoreA)
4869 return false;
Quentin Colombetec76d9c2017-12-18 19:47:41 +00004870 if (A.isHigherPriorityThan(B)) {
4871 assert(!B.isHigherPriorityThan(A) && "Cannot be more important "
4872 "and less important at "
4873 "the same time");
4874 return true;
4875 }
4876 return false;
4877 });
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004878
Roman Tereshin2df4c222018-05-02 20:07:15 +00004879 OS << "bool " << Target.getName()
4880 << "InstructionSelector::selectImpl(MachineInstr &I, CodeGenCoverage "
4881 "&CoverageInfo) const {\n"
4882 << " MachineFunction &MF = *I.getParent()->getParent();\n"
4883 << " MachineRegisterInfo &MRI = MF.getRegInfo();\n"
4884 << " // FIXME: This should be computed on a per-function basis rather "
4885 "than per-insn.\n"
4886 << " AvailableFunctionFeatures = computeAvailableFunctionFeatures(&STI, "
4887 "&MF);\n"
4888 << " const PredicateBitset AvailableFeatures = getAvailableFeatures();\n"
4889 << " NewMIVector OutMIs;\n"
4890 << " State.MIs.clear();\n"
4891 << " State.MIs.push_back(&I);\n\n"
4892 << " if (executeMatchTable(*this, OutMIs, State, ISelInfo"
4893 << ", getMatchTable(), TII, MRI, TRI, RBI, AvailableFeatures"
4894 << ", CoverageInfo)) {\n"
4895 << " return true;\n"
4896 << " }\n\n"
4897 << " return false;\n"
4898 << "}\n\n";
4899
Roman Tereshinbeb39312018-05-02 20:15:11 +00004900 const MatchTable Table =
4901 buildMatchTable(Rules, OptimizeMatchTable, GenerateCoverage);
Roman Tereshin2df4c222018-05-02 20:07:15 +00004902 OS << "const int64_t *" << Target.getName()
4903 << "InstructionSelector::getMatchTable() const {\n";
4904 Table.emitDeclaration(OS);
4905 OS << " return ";
4906 Table.emitUse(OS);
4907 OS << ";\n}\n";
4908 OS << "#endif // ifdef GET_GLOBALISEL_IMPL\n";
Daniel Sanderse9fdba32017-04-29 17:30:09 +00004909
4910 OS << "#ifdef GET_GLOBALISEL_PREDICATES_DECL\n"
4911 << "PredicateBitset AvailableModuleFeatures;\n"
4912 << "mutable PredicateBitset AvailableFunctionFeatures;\n"
4913 << "PredicateBitset getAvailableFeatures() const {\n"
4914 << " return AvailableModuleFeatures | AvailableFunctionFeatures;\n"
4915 << "}\n"
4916 << "PredicateBitset\n"
4917 << "computeAvailableModuleFeatures(const " << Target.getName()
4918 << "Subtarget *Subtarget) const;\n"
4919 << "PredicateBitset\n"
4920 << "computeAvailableFunctionFeatures(const " << Target.getName()
4921 << "Subtarget *Subtarget,\n"
4922 << " const MachineFunction *MF) const;\n"
4923 << "#endif // ifdef GET_GLOBALISEL_PREDICATES_DECL\n";
4924
4925 OS << "#ifdef GET_GLOBALISEL_PREDICATES_INIT\n"
4926 << "AvailableModuleFeatures(computeAvailableModuleFeatures(&STI)),\n"
4927 << "AvailableFunctionFeatures()\n"
4928 << "#endif // ifdef GET_GLOBALISEL_PREDICATES_INIT\n";
Ahmed Bougacha36f70352016-12-21 23:26:20 +00004929}
4930
Daniel Sanderse7b0d662017-04-21 15:59:56 +00004931void GlobalISelEmitter::declareSubtargetFeature(Record *Predicate) {
4932 if (SubtargetFeatures.count(Predicate) == 0)
4933 SubtargetFeatures.emplace(
4934 Predicate, SubtargetFeatureInfo(Predicate, SubtargetFeatures.size()));
4935}
4936
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004937void RuleMatcher::optimize() {
4938 for (auto &Item : InsnVariableIDs) {
4939 InstructionMatcher &InsnMatcher = *Item.first;
4940 for (auto &OM : InsnMatcher.operands()) {
Roman Tereshin5f5e5502018-05-23 23:58:10 +00004941 // Complex Patterns are usually expensive and they relatively rarely fail
4942 // on their own: more often we end up throwing away all the work done by a
4943 // matching part of a complex pattern because some other part of the
4944 // enclosing pattern didn't match. All of this makes it beneficial to
4945 // delay complex patterns until the very end of the rule matching,
4946 // especially for targets having lots of complex patterns.
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004947 for (auto &OP : OM->predicates())
Roman Tereshin5f5e5502018-05-23 23:58:10 +00004948 if (isa<ComplexPatternOperandMatcher>(OP))
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004949 EpilogueMatchers.emplace_back(std::move(OP));
4950 OM->eraseNullPredicates();
4951 }
4952 InsnMatcher.optimize();
Quentin Colombetec76d9c2017-12-18 19:47:41 +00004953 }
Fangrui Song3507c6e2018-09-30 22:31:29 +00004954 llvm::sort(EpilogueMatchers, [](const std::unique_ptr<PredicateMatcher> &L,
4955 const std::unique_ptr<PredicateMatcher> &R) {
4956 return std::make_tuple(L->getKind(), L->getInsnVarID(), L->getOpIdx()) <
4957 std::make_tuple(R->getKind(), R->getInsnVarID(), R->getOpIdx());
4958 });
Quentin Colombetec76d9c2017-12-18 19:47:41 +00004959}
4960
Roman Tereshinf1aa3482018-05-21 23:28:51 +00004961bool RuleMatcher::hasFirstCondition() const {
4962 if (insnmatchers_empty())
4963 return false;
4964 InstructionMatcher &Matcher = insnmatchers_front();
4965 if (!Matcher.predicates_empty())
4966 return true;
4967 for (auto &OM : Matcher.operands())
4968 for (auto &OP : OM->predicates())
4969 if (!isa<InstructionOperandMatcher>(OP))
4970 return true;
4971 return false;
4972}
4973
4974const PredicateMatcher &RuleMatcher::getFirstCondition() const {
4975 assert(!insnmatchers_empty() &&
4976 "Trying to get a condition from an empty RuleMatcher");
4977
4978 InstructionMatcher &Matcher = insnmatchers_front();
4979 if (!Matcher.predicates_empty())
4980 return **Matcher.predicates_begin();
4981 // If there is no more predicate on the instruction itself, look at its
4982 // operands.
4983 for (auto &OM : Matcher.operands())
4984 for (auto &OP : OM->predicates())
4985 if (!isa<InstructionOperandMatcher>(OP))
4986 return *OP;
4987
4988 llvm_unreachable("Trying to get a condition from an InstructionMatcher with "
4989 "no conditions");
4990}
4991
4992std::unique_ptr<PredicateMatcher> RuleMatcher::popFirstCondition() {
4993 assert(!insnmatchers_empty() &&
4994 "Trying to pop a condition from an empty RuleMatcher");
4995
4996 InstructionMatcher &Matcher = insnmatchers_front();
4997 if (!Matcher.predicates_empty())
4998 return Matcher.predicates_pop_front();
4999 // If there is no more predicate on the instruction itself, look at its
5000 // operands.
5001 for (auto &OM : Matcher.operands())
5002 for (auto &OP : OM->predicates())
5003 if (!isa<InstructionOperandMatcher>(OP)) {
5004 std::unique_ptr<PredicateMatcher> Result = std::move(OP);
5005 OM->eraseNullPredicates();
5006 return Result;
5007 }
5008
5009 llvm_unreachable("Trying to pop a condition from an InstructionMatcher with "
5010 "no conditions");
5011}
5012
5013bool GroupMatcher::candidateConditionMatches(
Quentin Colombetec76d9c2017-12-18 19:47:41 +00005014 const PredicateMatcher &Predicate) const {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005015
5016 if (empty()) {
5017 // Sharing predicates for nested instructions is not supported yet as we
5018 // currently don't hoist the GIM_RecordInsn's properly, therefore we can
5019 // only work on the original root instruction (InsnVarID == 0):
5020 if (Predicate.getInsnVarID() != 0)
5021 return false;
5022 // ... otherwise an empty group can handle any predicate with no specific
5023 // requirements:
5024 return true;
5025 }
5026
5027 const Matcher &Representative = **Matchers.begin();
5028 const auto &RepresentativeCondition = Representative.getFirstCondition();
5029 // ... if not empty, the group can only accomodate matchers with the exact
5030 // same first condition:
5031 return Predicate.isIdentical(RepresentativeCondition);
5032}
5033
5034bool GroupMatcher::addMatcher(Matcher &Candidate) {
5035 if (!Candidate.hasFirstCondition())
5036 return false;
5037
5038 const PredicateMatcher &Predicate = Candidate.getFirstCondition();
5039 if (!candidateConditionMatches(Predicate))
5040 return false;
5041
5042 Matchers.push_back(&Candidate);
5043 return true;
5044}
5045
5046void GroupMatcher::finalize() {
5047 assert(Conditions.empty() && "Already finalized?");
5048 if (empty())
5049 return;
5050
5051 Matcher &FirstRule = **Matchers.begin();
Roman Tereshin152fc162018-05-23 22:50:53 +00005052 for (;;) {
5053 // All the checks are expected to succeed during the first iteration:
5054 for (const auto &Rule : Matchers)
5055 if (!Rule->hasFirstCondition())
5056 return;
5057 const auto &FirstCondition = FirstRule.getFirstCondition();
5058 for (unsigned I = 1, E = Matchers.size(); I < E; ++I)
5059 if (!Matchers[I]->getFirstCondition().isIdentical(FirstCondition))
5060 return;
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005061
Roman Tereshin152fc162018-05-23 22:50:53 +00005062 Conditions.push_back(FirstRule.popFirstCondition());
5063 for (unsigned I = 1, E = Matchers.size(); I < E; ++I)
5064 Matchers[I]->popFirstCondition();
5065 }
Quentin Colombetec76d9c2017-12-18 19:47:41 +00005066}
5067
5068void GroupMatcher::emit(MatchTable &Table) {
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005069 unsigned LabelID = ~0U;
5070 if (!Conditions.empty()) {
5071 LabelID = Table.allocateLabelID();
Quentin Colombetec76d9c2017-12-18 19:47:41 +00005072 Table << MatchTable::Opcode("GIM_Try", +1)
5073 << MatchTable::Comment("On fail goto")
5074 << MatchTable::JumpTarget(LabelID) << MatchTable::LineBreak;
Quentin Colombetec76d9c2017-12-18 19:47:41 +00005075 }
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005076 for (auto &Condition : Conditions)
5077 Condition->emitPredicateOpcodes(
5078 Table, *static_cast<RuleMatcher *>(*Matchers.begin()));
5079
5080 for (const auto &M : Matchers)
5081 M->emit(Table);
5082
5083 // Exit the group
5084 if (!Conditions.empty())
5085 Table << MatchTable::Opcode("GIM_Reject", -1) << MatchTable::LineBreak
Quentin Colombetec76d9c2017-12-18 19:47:41 +00005086 << MatchTable::Label(LabelID);
Quentin Colombetec76d9c2017-12-18 19:47:41 +00005087}
5088
Roman Tereshin0ee082f2018-05-22 19:37:59 +00005089bool SwitchMatcher::isSupportedPredicateType(const PredicateMatcher &P) {
Roman Tereshina4c410d2018-05-24 00:24:15 +00005090 return isa<InstructionOpcodeMatcher>(P) || isa<LLTOperandMatcher>(P);
Roman Tereshin0ee082f2018-05-22 19:37:59 +00005091}
5092
5093bool SwitchMatcher::candidateConditionMatches(
5094 const PredicateMatcher &Predicate) const {
5095
5096 if (empty()) {
5097 // Sharing predicates for nested instructions is not supported yet as we
5098 // currently don't hoist the GIM_RecordInsn's properly, therefore we can
5099 // only work on the original root instruction (InsnVarID == 0):
5100 if (Predicate.getInsnVarID() != 0)
5101 return false;
5102 // ... while an attempt to add even a root matcher to an empty SwitchMatcher
5103 // could fail as not all the types of conditions are supported:
5104 if (!isSupportedPredicateType(Predicate))
5105 return false;
5106 // ... or the condition might not have a proper implementation of
5107 // getValue() / isIdenticalDownToValue() yet:
5108 if (!Predicate.hasValue())
5109 return false;
5110 // ... otherwise an empty Switch can accomodate the condition with no
5111 // further requirements:
5112 return true;
5113 }
5114
5115 const Matcher &CaseRepresentative = **Matchers.begin();
5116 const auto &RepresentativeCondition = CaseRepresentative.getFirstCondition();
5117 // Switch-cases must share the same kind of condition and path to the value it
5118 // checks:
5119 if (!Predicate.isIdenticalDownToValue(RepresentativeCondition))
5120 return false;
5121
5122 const auto Value = Predicate.getValue();
5123 // ... but be unique with respect to the actual value they check:
5124 return Values.count(Value) == 0;
5125}
5126
5127bool SwitchMatcher::addMatcher(Matcher &Candidate) {
5128 if (!Candidate.hasFirstCondition())
5129 return false;
5130
5131 const PredicateMatcher &Predicate = Candidate.getFirstCondition();
5132 if (!candidateConditionMatches(Predicate))
5133 return false;
5134 const auto Value = Predicate.getValue();
5135 Values.insert(Value);
5136
5137 Matchers.push_back(&Candidate);
5138 return true;
5139}
5140
5141void SwitchMatcher::finalize() {
5142 assert(Condition == nullptr && "Already finalized");
5143 assert(Values.size() == Matchers.size() && "Broken SwitchMatcher");
5144 if (empty())
5145 return;
5146
5147 std::stable_sort(Matchers.begin(), Matchers.end(),
5148 [](const Matcher *L, const Matcher *R) {
5149 return L->getFirstCondition().getValue() <
5150 R->getFirstCondition().getValue();
5151 });
5152 Condition = Matchers[0]->popFirstCondition();
5153 for (unsigned I = 1, E = Values.size(); I < E; ++I)
5154 Matchers[I]->popFirstCondition();
5155}
5156
5157void SwitchMatcher::emitPredicateSpecificOpcodes(const PredicateMatcher &P,
5158 MatchTable &Table) {
5159 assert(isSupportedPredicateType(P) && "Predicate type is not supported");
5160
5161 if (const auto *Condition = dyn_cast<InstructionOpcodeMatcher>(&P)) {
5162 Table << MatchTable::Opcode("GIM_SwitchOpcode") << MatchTable::Comment("MI")
5163 << MatchTable::IntValue(Condition->getInsnVarID());
5164 return;
5165 }
Roman Tereshina4c410d2018-05-24 00:24:15 +00005166 if (const auto *Condition = dyn_cast<LLTOperandMatcher>(&P)) {
5167 Table << MatchTable::Opcode("GIM_SwitchType") << MatchTable::Comment("MI")
5168 << MatchTable::IntValue(Condition->getInsnVarID())
5169 << MatchTable::Comment("Op")
5170 << MatchTable::IntValue(Condition->getOpIdx());
5171 return;
5172 }
Roman Tereshin0ee082f2018-05-22 19:37:59 +00005173
5174 llvm_unreachable("emitPredicateSpecificOpcodes is broken: can not handle a "
5175 "predicate type that is claimed to be supported");
5176}
5177
5178void SwitchMatcher::emit(MatchTable &Table) {
5179 assert(Values.size() == Matchers.size() && "Broken SwitchMatcher");
5180 if (empty())
5181 return;
5182 assert(Condition != nullptr &&
5183 "Broken SwitchMatcher, hasn't been finalized?");
5184
5185 std::vector<unsigned> LabelIDs(Values.size());
5186 std::generate(LabelIDs.begin(), LabelIDs.end(),
5187 [&Table]() { return Table.allocateLabelID(); });
5188 const unsigned Default = Table.allocateLabelID();
5189
5190 const int64_t LowerBound = Values.begin()->getRawValue();
5191 const int64_t UpperBound = Values.rbegin()->getRawValue() + 1;
5192
5193 emitPredicateSpecificOpcodes(*Condition, Table);
5194
5195 Table << MatchTable::Comment("[") << MatchTable::IntValue(LowerBound)
5196 << MatchTable::IntValue(UpperBound) << MatchTable::Comment(")")
5197 << MatchTable::Comment("default:") << MatchTable::JumpTarget(Default);
5198
5199 int64_t J = LowerBound;
5200 auto VI = Values.begin();
5201 for (unsigned I = 0, E = Values.size(); I < E; ++I) {
5202 auto V = *VI++;
5203 while (J++ < V.getRawValue())
5204 Table << MatchTable::IntValue(0);
5205 V.turnIntoComment();
5206 Table << MatchTable::LineBreak << V << MatchTable::JumpTarget(LabelIDs[I]);
5207 }
5208 Table << MatchTable::LineBreak;
5209
5210 for (unsigned I = 0, E = Values.size(); I < E; ++I) {
5211 Table << MatchTable::Label(LabelIDs[I]);
5212 Matchers[I]->emit(Table);
5213 Table << MatchTable::Opcode("GIM_Reject") << MatchTable::LineBreak;
5214 }
5215 Table << MatchTable::Label(Default);
5216}
5217
Roman Tereshinf1aa3482018-05-21 23:28:51 +00005218unsigned OperandMatcher::getInsnVarID() const { return Insn.getInsnVarID(); }
Quentin Colombetaad20be2017-12-15 23:07:42 +00005219
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00005220} // end anonymous namespace
5221
Ahmed Bougacha36f70352016-12-21 23:26:20 +00005222//===----------------------------------------------------------------------===//
5223
5224namespace llvm {
5225void EmitGlobalISel(RecordKeeper &RK, raw_ostream &OS) {
5226 GlobalISelEmitter(RK).run(OS);
5227}
5228} // End llvm namespace