blob: 1a0490507de343a485a1a4fca6cbc117b228ae64 [file] [log] [blame]
Chris Lattnerb02cdaa2010-02-15 08:04:42 +00001//===- DAGISelMatcherGen.cpp - Matcher generator --------------------------===//
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
Chris Lattnerb02cdaa2010-02-15 08:04:42 +00006//
7//===----------------------------------------------------------------------===//
8
9#include "DAGISelMatcher.h"
10#include "CodeGenDAGPatterns.h"
Jim Grosbachf17b0032011-03-11 02:19:02 +000011#include "CodeGenRegisters.h"
Chris Lattner469cfb92010-02-17 02:16:19 +000012#include "llvm/ADT/SmallVector.h"
Chris Lattnerb02cdaa2010-02-15 08:04:42 +000013#include "llvm/ADT/StringMap.h"
Chandler Carruth91d19d82012-12-04 10:37:14 +000014#include "llvm/TableGen/Error.h"
15#include "llvm/TableGen/Record.h"
Chris Lattner132df652010-02-21 03:22:59 +000016#include <utility>
Chris Lattnerb02cdaa2010-02-15 08:04:42 +000017using namespace llvm;
18
Chris Lattner16cd8cd2010-02-19 00:27:40 +000019
Chris Lattner132df652010-02-21 03:22:59 +000020/// getRegisterValueType - Look up and return the ValueType of the specified
21/// register. If the register is a member of multiple register classes which
22/// have different associated types, return MVT::Other.
23static MVT::SimpleValueType getRegisterValueType(Record *R,
24 const CodeGenTarget &T) {
25 bool FoundRC = false;
26 MVT::SimpleValueType VT = MVT::Other;
Jakob Stoklund Olesend7bc5c22011-06-15 04:50:36 +000027 const CodeGenRegister *Reg = T.getRegBank().getReg(R);
Jim Grosbach65586fe2010-12-21 16:16:00 +000028
David Blaikiedacea4b2014-12-03 19:58:45 +000029 for (const auto &RC : T.getRegBank().getRegClasses()) {
30 if (!RC.contains(Reg))
Chris Lattner132df652010-02-21 03:22:59 +000031 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +000032
Chris Lattner132df652010-02-21 03:22:59 +000033 if (!FoundRC) {
34 FoundRC = true;
Simon Pilgrima9d64122018-08-16 15:29:24 +000035 const ValueTypeByHwMode &VVT = RC.getValueTypeNum(0);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000036 if (VVT.isSimple())
37 VT = VVT.getSimple().SimpleTy;
Chris Lattner132df652010-02-21 03:22:59 +000038 continue;
Chris Lattner16cd8cd2010-02-19 00:27:40 +000039 }
Chris Lattner3d869722010-03-01 22:49:06 +000040
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000041#ifndef NDEBUG
Simon Pilgrima9d64122018-08-16 15:29:24 +000042 // If this occurs in multiple register classes, they all have to agree.
43 const ValueTypeByHwMode &T = RC.getValueTypeNum(0);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000044 assert((!T.isSimple() || T.getSimple().SimpleTy == VT) &&
45 "ValueType mismatch between register classes for this register");
46#endif
Chris Lattner132df652010-02-21 03:22:59 +000047 }
48 return VT;
49}
50
51
52namespace {
Chris Lattnerb02cdaa2010-02-15 08:04:42 +000053 class MatcherGen {
54 const PatternToMatch &Pattern;
55 const CodeGenDAGPatterns &CGP;
Jim Grosbach65586fe2010-12-21 16:16:00 +000056
Chris Lattnerb02cdaa2010-02-15 08:04:42 +000057 /// PatWithNoTypes - This is a clone of Pattern.getSrcPattern() that starts
58 /// out with all of the types removed. This allows us to insert type checks
59 /// as we scan the tree.
Florian Hahn75e87c32018-05-30 21:00:18 +000060 TreePatternNodePtr PatWithNoTypes;
Jim Grosbach65586fe2010-12-21 16:16:00 +000061
Chris Lattnerb02cdaa2010-02-15 08:04:42 +000062 /// VariableMap - A map from variable names ('$dst') to the recorded operand
63 /// number that they were captured as. These are biased by 1 to make
64 /// insertion easier.
65 StringMap<unsigned> VariableMap;
Jim Grosbach65586fe2010-12-21 16:16:00 +000066
Tim Northoverc807a172014-05-20 11:52:46 +000067 /// This maintains the recorded operand number that OPC_CheckComplexPattern
68 /// drops each sub-operand into. We don't want to insert these into
69 /// VariableMap because that leads to identity checking if they are
70 /// encountered multiple times. Biased by 1 like VariableMap for
71 /// consistency.
72 StringMap<unsigned> NamedComplexPatternOperands;
73
Chris Lattner16cd8cd2010-02-19 00:27:40 +000074 /// NextRecordedOperandNo - As we emit opcodes to record matched values in
75 /// the RecordedNodes array, this keeps track of which slot will be next to
76 /// record into.
Chris Lattnerb02cdaa2010-02-15 08:04:42 +000077 unsigned NextRecordedOperandNo;
Jim Grosbach65586fe2010-12-21 16:16:00 +000078
Chris Lattner132df652010-02-21 03:22:59 +000079 /// MatchedChainNodes - This maintains the position in the recorded nodes
80 /// array of all of the recorded input nodes that have chains.
81 SmallVector<unsigned, 2> MatchedChainNodes;
Chris Lattner29364372010-02-24 05:33:42 +000082
Chris Lattner0acbb712010-03-04 01:23:08 +000083 /// MatchedComplexPatterns - This maintains a list of all of the
Tim Northoverc807a172014-05-20 11:52:46 +000084 /// ComplexPatterns that we need to check. The second element of each pair
85 /// is the recorded operand number of the input node.
Chris Lattner0acbb712010-03-04 01:23:08 +000086 SmallVector<std::pair<const TreePatternNode*,
87 unsigned>, 2> MatchedComplexPatterns;
Jim Grosbach65586fe2010-12-21 16:16:00 +000088
Chris Lattner132df652010-02-21 03:22:59 +000089 /// PhysRegInputs - List list has an entry for each explicitly specified
90 /// physreg input to the pattern. The first elt is the Register node, the
91 /// second is the recorded slot number the input pattern match saved it in.
92 SmallVector<std::pair<Record*, unsigned>, 2> PhysRegInputs;
Jim Grosbach65586fe2010-12-21 16:16:00 +000093
Chris Lattner469cfb92010-02-17 02:16:19 +000094 /// Matcher - This is the top level of the generated matcher, the result.
Chris Lattner2c3f6492010-02-25 02:04:40 +000095 Matcher *TheMatcher;
Jim Grosbach65586fe2010-12-21 16:16:00 +000096
Chris Lattner469cfb92010-02-17 02:16:19 +000097 /// CurPredicate - As we emit matcher nodes, this points to the latest check
Chris Lattner186ad802010-02-18 02:53:41 +000098 /// which should have future checks stuck into its Next position.
Chris Lattner2c3f6492010-02-25 02:04:40 +000099 Matcher *CurPredicate;
Chris Lattnerb02cdaa2010-02-15 08:04:42 +0000100 public:
101 MatcherGen(const PatternToMatch &pattern, const CodeGenDAGPatterns &cgp);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000102
Chris Lattner053a28a2010-03-01 07:17:40 +0000103 bool EmitMatcherCode(unsigned Variant);
Chris Lattner7ed81692010-02-18 06:47:49 +0000104 void EmitResultCode();
Jim Grosbach65586fe2010-12-21 16:16:00 +0000105
Chris Lattner2c3f6492010-02-25 02:04:40 +0000106 Matcher *GetMatcher() const { return TheMatcher; }
Chris Lattnerb02cdaa2010-02-15 08:04:42 +0000107 private:
Chris Lattner2c3f6492010-02-25 02:04:40 +0000108 void AddMatcher(Matcher *NewNode);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000109 void InferPossibleTypes(unsigned ForceMode);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000110
Chris Lattner7ed81692010-02-18 06:47:49 +0000111 // Matcher Generation.
Florian Hahn6b1db822018-06-14 20:32:58 +0000112 void EmitMatchCode(const TreePatternNode *N, TreePatternNode *NodeNoTypes,
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000113 unsigned ForceMode);
Florian Hahn6b1db822018-06-14 20:32:58 +0000114 void EmitLeafMatchCode(const TreePatternNode *N);
115 void EmitOperatorMatchCode(const TreePatternNode *N,
116 TreePatternNode *NodeNoTypes,
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000117 unsigned ForceMode);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000118
Tim Northoverc807a172014-05-20 11:52:46 +0000119 /// If this is the first time a node with unique identifier Name has been
120 /// seen, record it. Otherwise, emit a check to make sure this is the same
121 /// node. Returns true if this is the first encounter.
Nicolai Haehnle445b0b62018-11-30 14:15:13 +0000122 bool recordUniqueNode(ArrayRef<std::string> Names);
Tim Northoverc807a172014-05-20 11:52:46 +0000123
Chris Lattner7ed81692010-02-18 06:47:49 +0000124 // Result Code Generation.
Chris Lattner132df652010-02-21 03:22:59 +0000125 unsigned getNamedArgumentSlot(StringRef Name) {
126 unsigned VarMapEntry = VariableMap[Name];
127 assert(VarMapEntry != 0 &&
128 "Variable referenced but not defined and not caught earlier!");
129 return VarMapEntry-1;
130 }
131
Florian Hahn6b1db822018-06-14 20:32:58 +0000132 void EmitResultOperand(const TreePatternNode *N,
Chris Lattner132df652010-02-21 03:22:59 +0000133 SmallVectorImpl<unsigned> &ResultOps);
Florian Hahn6b1db822018-06-14 20:32:58 +0000134 void EmitResultOfNamedOperand(const TreePatternNode *N,
Chris Lattner132df652010-02-21 03:22:59 +0000135 SmallVectorImpl<unsigned> &ResultOps);
Florian Hahn6b1db822018-06-14 20:32:58 +0000136 void EmitResultLeafAsOperand(const TreePatternNode *N,
Chris Lattner132df652010-02-21 03:22:59 +0000137 SmallVectorImpl<unsigned> &ResultOps);
Florian Hahn6b1db822018-06-14 20:32:58 +0000138 void EmitResultInstructionAsOperand(const TreePatternNode *N,
Chris Lattner132df652010-02-21 03:22:59 +0000139 SmallVectorImpl<unsigned> &ResultOps);
Florian Hahn6b1db822018-06-14 20:32:58 +0000140 void EmitResultSDNodeXFormAsOperand(const TreePatternNode *N,
Chris Lattner132df652010-02-21 03:22:59 +0000141 SmallVectorImpl<unsigned> &ResultOps);
142 };
Jim Grosbach65586fe2010-12-21 16:16:00 +0000143
Chris Lattnerb02cdaa2010-02-15 08:04:42 +0000144} // end anon namespace.
145
146MatcherGen::MatcherGen(const PatternToMatch &pattern,
147 const CodeGenDAGPatterns &cgp)
Chris Lattnerdc61962e2010-02-19 00:33:13 +0000148: Pattern(pattern), CGP(cgp), NextRecordedOperandNo(0),
Craig Topper24064772014-04-15 07:20:03 +0000149 TheMatcher(nullptr), CurPredicate(nullptr) {
Chris Lattnerb02cdaa2010-02-15 08:04:42 +0000150 // We need to produce the matcher tree for the patterns source pattern. To do
151 // this we need to match the structure as well as the types. To do the type
152 // matching, we want to figure out the fewest number of type checks we need to
153 // emit. For example, if there is only one integer type supported by a
154 // target, there should be no type comparisons at all for integer patterns!
155 //
156 // To figure out the fewest number of type checks needed, clone the pattern,
157 // remove the types, then perform type inference on the pattern as a whole.
158 // If there are unresolved types, emit an explicit check for those types,
159 // apply the type to the tree, then rerun type inference. Iterate until all
160 // types are resolved.
161 //
162 PatWithNoTypes = Pattern.getSrcPattern()->clone();
163 PatWithNoTypes->RemoveAllTypes();
Jim Grosbach65586fe2010-12-21 16:16:00 +0000164
Chris Lattnerb02cdaa2010-02-15 08:04:42 +0000165 // If there are types that are manifestly known, infer them.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000166 InferPossibleTypes(Pattern.ForceMode);
Chris Lattnerb02cdaa2010-02-15 08:04:42 +0000167}
168
169/// InferPossibleTypes - As we emit the pattern, we end up generating type
170/// checks and applying them to the 'PatWithNoTypes' tree. As we do this, we
171/// want to propagate implied types as far throughout the tree as possible so
172/// that we avoid doing redundant type checks. This does the type propagation.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000173void MatcherGen::InferPossibleTypes(unsigned ForceMode) {
Chris Lattnerb02cdaa2010-02-15 08:04:42 +0000174 // TP - Get *SOME* tree pattern, we don't care which. It is only used for
175 // diagnostics, which we know are impossible at this point.
176 TreePattern &TP = *CGP.pf_begin()->second;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000177 TP.getInfer().CodeGen = true;
178 TP.getInfer().ForceMode = ForceMode;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000179
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000180 bool MadeChange = true;
181 while (MadeChange)
182 MadeChange = PatWithNoTypes->ApplyTypeConstraints(TP,
183 true/*Ignore reg constraints*/);
Chris Lattnerb02cdaa2010-02-15 08:04:42 +0000184}
185
186
Jim Grosbach65586fe2010-12-21 16:16:00 +0000187/// AddMatcher - Add a matcher node to the current graph we're building.
Chris Lattner2c3f6492010-02-25 02:04:40 +0000188void MatcherGen::AddMatcher(Matcher *NewNode) {
Craig Topper24064772014-04-15 07:20:03 +0000189 if (CurPredicate)
Chris Lattner186ad802010-02-18 02:53:41 +0000190 CurPredicate->setNext(NewNode);
Chris Lattnerb02cdaa2010-02-15 08:04:42 +0000191 else
Chris Lattner2c3f6492010-02-25 02:04:40 +0000192 TheMatcher = NewNode;
Chris Lattnerb02cdaa2010-02-15 08:04:42 +0000193 CurPredicate = NewNode;
194}
195
196
Chris Lattner7ed81692010-02-18 06:47:49 +0000197//===----------------------------------------------------------------------===//
198// Pattern Match Generation
199//===----------------------------------------------------------------------===//
Chris Lattnerb02cdaa2010-02-15 08:04:42 +0000200
201/// EmitLeafMatchCode - Generate matching code for leaf nodes.
Florian Hahn6b1db822018-06-14 20:32:58 +0000202void MatcherGen::EmitLeafMatchCode(const TreePatternNode *N) {
203 assert(N->isLeaf() && "Not a leaf?");
Jim Grosbach65586fe2010-12-21 16:16:00 +0000204
Chris Lattnerb02cdaa2010-02-15 08:04:42 +0000205 // Direct match against an integer constant.
Florian Hahn6b1db822018-06-14 20:32:58 +0000206 if (IntInit *II = dyn_cast<IntInit>(N->getLeafValue())) {
Chris Lattnera44697c2010-03-01 07:27:07 +0000207 // If this is the root of the dag we're matching, we emit a redundant opcode
208 // check to ensure that this gets folded into the normal top-level
209 // OpcodeSwitch.
Florian Hahn6b1db822018-06-14 20:32:58 +0000210 if (N == Pattern.getSrcPattern()) {
Chris Lattnera44697c2010-03-01 07:27:07 +0000211 const SDNodeInfo &NI = CGP.getSDNodeInfo(CGP.getSDNodeNamed("imm"));
212 AddMatcher(new CheckOpcodeMatcher(NI));
213 }
214
Chris Lattner2c3f6492010-02-25 02:04:40 +0000215 return AddMatcher(new CheckIntegerMatcher(II->getValue()));
Chris Lattnera44697c2010-03-01 07:27:07 +0000216 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000217
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +0000218 // An UnsetInit represents a named node without any constraints.
Florian Hahn6b1db822018-06-14 20:32:58 +0000219 if (isa<UnsetInit>(N->getLeafValue())) {
220 assert(N->hasName() && "Unnamed ? leaf");
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +0000221 return;
222 }
223
Florian Hahn6b1db822018-06-14 20:32:58 +0000224 DefInit *DI = dyn_cast<DefInit>(N->getLeafValue());
Craig Topper24064772014-04-15 07:20:03 +0000225 if (!DI) {
Florian Hahn6b1db822018-06-14 20:32:58 +0000226 errs() << "Unknown leaf kind: " << *N << "\n";
Chris Lattnerb02cdaa2010-02-15 08:04:42 +0000227 abort();
228 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000229
Chris Lattnerb02cdaa2010-02-15 08:04:42 +0000230 Record *LeafRec = DI->getDef();
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +0000231
232 // A ValueType leaf node can represent a register when named, or itself when
233 // unnamed.
234 if (LeafRec->isSubClassOf("ValueType")) {
235 // A named ValueType leaf always matches: (add i32:$a, i32:$b).
Florian Hahn6b1db822018-06-14 20:32:58 +0000236 if (N->hasName())
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +0000237 return;
238 // An unnamed ValueType as in (sext_inreg GPR:$foo, i8).
239 return AddMatcher(new CheckValueTypeMatcher(LeafRec->getName()));
240 }
241
Chris Lattnerb02cdaa2010-02-15 08:04:42 +0000242 if (// Handle register references. Nothing to do here, they always match.
Jim Grosbach65586fe2010-12-21 16:16:00 +0000243 LeafRec->isSubClassOf("RegisterClass") ||
Owen Andersona84be6c2011-06-27 21:06:21 +0000244 LeafRec->isSubClassOf("RegisterOperand") ||
Chris Lattnerb02cdaa2010-02-15 08:04:42 +0000245 LeafRec->isSubClassOf("PointerLikeRegClass") ||
Jakob Stoklund Olesen1c696462010-05-24 14:48:12 +0000246 LeafRec->isSubClassOf("SubRegIndex") ||
Chris Lattnerb02cdaa2010-02-15 08:04:42 +0000247 // Place holder for SRCVALUE nodes. Nothing to do here.
248 LeafRec->getName() == "srcvalue")
249 return;
Chris Lattner132df652010-02-21 03:22:59 +0000250
251 // If we have a physreg reference like (mul gpr:$src, EAX) then we need to
Jim Grosbach65586fe2010-12-21 16:16:00 +0000252 // record the register
Chris Lattner132df652010-02-21 03:22:59 +0000253 if (LeafRec->isSubClassOf("Register")) {
Matthias Braun4a86d452016-12-04 05:48:16 +0000254 AddMatcher(new RecordMatcher("physreg input "+LeafRec->getName().str(),
Chris Lattner4634d9b2010-03-01 02:24:17 +0000255 NextRecordedOperandNo));
Chris Lattner132df652010-02-21 03:22:59 +0000256 PhysRegInputs.push_back(std::make_pair(LeafRec, NextRecordedOperandNo++));
257 return;
258 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000259
Chris Lattnerb02cdaa2010-02-15 08:04:42 +0000260 if (LeafRec->isSubClassOf("CondCode"))
Chris Lattner2c3f6492010-02-25 02:04:40 +0000261 return AddMatcher(new CheckCondCodeMatcher(LeafRec->getName()));
Jim Grosbach65586fe2010-12-21 16:16:00 +0000262
Chris Lattnerb02cdaa2010-02-15 08:04:42 +0000263 if (LeafRec->isSubClassOf("ComplexPattern")) {
Chris Lattner7b390142010-02-17 00:11:30 +0000264 // We can't model ComplexPattern uses that don't have their name taken yet.
265 // The OPC_CheckComplexPattern operation implicitly records the results.
Florian Hahn6b1db822018-06-14 20:32:58 +0000266 if (N->getName().empty()) {
James Y Knighte452e272015-05-11 22:17:13 +0000267 std::string S;
268 raw_string_ostream OS(S);
Florian Hahn6b1db822018-06-14 20:32:58 +0000269 OS << "We expect complex pattern uses to have names: " << *N;
James Y Knighte452e272015-05-11 22:17:13 +0000270 PrintFatalError(OS.str());
Chris Lattnere2347aa2010-02-16 23:16:25 +0000271 }
Chris Lattnera5a29852010-02-22 22:18:05 +0000272
Chris Lattner0acbb712010-03-04 01:23:08 +0000273 // Remember this ComplexPattern so that we can emit it after all the other
274 // structural matches are done.
Florian Hahn6b1db822018-06-14 20:32:58 +0000275 unsigned InputOperand = VariableMap[N->getName()] - 1;
276 MatchedComplexPatterns.push_back(std::make_pair(N, InputOperand));
Chris Lattner8ad29342010-02-17 06:08:25 +0000277 return;
Chris Lattnerb02cdaa2010-02-15 08:04:42 +0000278 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000279
Florian Hahn6b1db822018-06-14 20:32:58 +0000280 errs() << "Unknown leaf kind: " << *N << "\n";
Chris Lattnerb02cdaa2010-02-15 08:04:42 +0000281 abort();
282}
283
Florian Hahn6b1db822018-06-14 20:32:58 +0000284void MatcherGen::EmitOperatorMatchCode(const TreePatternNode *N,
285 TreePatternNode *NodeNoTypes,
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000286 unsigned ForceMode) {
Florian Hahn6b1db822018-06-14 20:32:58 +0000287 assert(!N->isLeaf() && "Not an operator?");
Tim Northoverc807a172014-05-20 11:52:46 +0000288
Florian Hahn6b1db822018-06-14 20:32:58 +0000289 if (N->getOperator()->isSubClassOf("ComplexPattern")) {
Tim Northoverc807a172014-05-20 11:52:46 +0000290 // The "name" of a non-leaf complex pattern (MY_PAT $op1, $op2) is
291 // "MY_PAT:op1:op2". We should already have validated that the uses are
292 // consistent.
Florian Hahn6b1db822018-06-14 20:32:58 +0000293 std::string PatternName = N->getOperator()->getName();
294 for (unsigned i = 0; i < N->getNumChildren(); ++i) {
Tim Northoverc807a172014-05-20 11:52:46 +0000295 PatternName += ":";
Florian Hahn6b1db822018-06-14 20:32:58 +0000296 PatternName += N->getChild(i)->getName();
Tim Northoverc807a172014-05-20 11:52:46 +0000297 }
298
299 if (recordUniqueNode(PatternName)) {
Florian Hahn6b1db822018-06-14 20:32:58 +0000300 auto NodeAndOpNum = std::make_pair(N, NextRecordedOperandNo - 1);
Tim Northoverc807a172014-05-20 11:52:46 +0000301 MatchedComplexPatterns.push_back(NodeAndOpNum);
302 }
303
304 return;
305 }
306
Florian Hahn6b1db822018-06-14 20:32:58 +0000307 const SDNodeInfo &CInfo = CGP.getSDNodeInfo(N->getOperator());
Jim Grosbach65586fe2010-12-21 16:16:00 +0000308
Chris Lattnerb02cdaa2010-02-15 08:04:42 +0000309 // If this is an 'and R, 1234' where the operation is AND/OR and the RHS is
Lama Saba880e8782017-07-30 20:12:17 +0000310 // a constant without a predicate fn that has more than one bit set, handle
Chris Lattnerb02cdaa2010-02-15 08:04:42 +0000311 // this as a special case. This is usually for targets that have special
312 // handling of certain large constants (e.g. alpha with it's 8/16/32-bit
313 // handling stuff). Using these instructions is often far more efficient
314 // than materializing the constant. Unfortunately, both the instcombiner
315 // and the dag combiner can often infer that bits are dead, and thus drop
316 // them from the mask in the dag. For example, it might turn 'AND X, 255'
317 // into 'AND X, 254' if it knows the low bit is set. Emit code that checks
318 // to handle this.
Florian Hahn6b1db822018-06-14 20:32:58 +0000319 if ((N->getOperator()->getName() == "and" ||
320 N->getOperator()->getName() == "or") &&
Nicolai Haehnle445b0b62018-11-30 14:15:13 +0000321 N->getChild(1)->isLeaf() && N->getChild(1)->getPredicateCalls().empty() &&
322 N->getPredicateCalls().empty()) {
Florian Hahn6b1db822018-06-14 20:32:58 +0000323 if (IntInit *II = dyn_cast<IntInit>(N->getChild(1)->getLeafValue())) {
Chris Lattnerb02cdaa2010-02-15 08:04:42 +0000324 if (!isPowerOf2_32(II->getValue())) { // Don't bother with single bits.
Chris Lattner90b1b9d2010-03-01 02:15:34 +0000325 // If this is at the root of the pattern, we emit a redundant
326 // CheckOpcode so that the following checks get factored properly under
327 // a single opcode check.
Florian Hahn6b1db822018-06-14 20:32:58 +0000328 if (N == Pattern.getSrcPattern())
Chris Lattner90b1b9d2010-03-01 02:15:34 +0000329 AddMatcher(new CheckOpcodeMatcher(CInfo));
330
331 // Emit the CheckAndImm/CheckOrImm node.
Florian Hahn6b1db822018-06-14 20:32:58 +0000332 if (N->getOperator()->getName() == "and")
Chris Lattner2c3f6492010-02-25 02:04:40 +0000333 AddMatcher(new CheckAndImmMatcher(II->getValue()));
Chris Lattnerb02cdaa2010-02-15 08:04:42 +0000334 else
Chris Lattner2c3f6492010-02-25 02:04:40 +0000335 AddMatcher(new CheckOrImmMatcher(II->getValue()));
Chris Lattnerb02cdaa2010-02-15 08:04:42 +0000336
337 // Match the LHS of the AND as appropriate.
Chris Lattner2c3f6492010-02-25 02:04:40 +0000338 AddMatcher(new MoveChildMatcher(0));
Florian Hahn6b1db822018-06-14 20:32:58 +0000339 EmitMatchCode(N->getChild(0), NodeNoTypes->getChild(0), ForceMode);
Chris Lattner2c3f6492010-02-25 02:04:40 +0000340 AddMatcher(new MoveParentMatcher());
Chris Lattnerb02cdaa2010-02-15 08:04:42 +0000341 return;
342 }
343 }
344 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000345
Chris Lattnerb02cdaa2010-02-15 08:04:42 +0000346 // Check that the current opcode lines up.
Chris Lattner278606b2010-02-27 21:48:43 +0000347 AddMatcher(new CheckOpcodeMatcher(CInfo));
Jim Grosbach65586fe2010-12-21 16:16:00 +0000348
Chris Lattner132df652010-02-21 03:22:59 +0000349 // If this node has memory references (i.e. is a load or store), tell the
350 // interpreter to capture them in the memref array.
Florian Hahn6b1db822018-06-14 20:32:58 +0000351 if (N->NodeHasProperty(SDNPMemOperand, CGP))
Chris Lattner2c3f6492010-02-25 02:04:40 +0000352 AddMatcher(new RecordMemRefMatcher());
Jim Grosbach65586fe2010-12-21 16:16:00 +0000353
Chris Lattnerb02cdaa2010-02-15 08:04:42 +0000354 // If this node has a chain, then the chain is operand #0 is the SDNode, and
355 // the child numbers of the node are all offset by one.
356 unsigned OpNo = 0;
Florian Hahn6b1db822018-06-14 20:32:58 +0000357 if (N->NodeHasProperty(SDNPHasChain, CGP)) {
Chris Lattner132df652010-02-21 03:22:59 +0000358 // Record the node and remember it in our chained nodes list.
Florian Hahn6b1db822018-06-14 20:32:58 +0000359 AddMatcher(new RecordMatcher("'" + N->getOperator()->getName().str() +
Chris Lattner4634d9b2010-03-01 02:24:17 +0000360 "' chained node",
361 NextRecordedOperandNo));
Chris Lattner469cfb92010-02-17 02:16:19 +0000362 // Remember all of the input chains our pattern will match.
Chris Lattner132df652010-02-21 03:22:59 +0000363 MatchedChainNodes.push_back(NextRecordedOperandNo++);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000364
Chris Lattner022e5112010-02-17 01:34:15 +0000365 // Don't look at the input chain when matching the tree pattern to the
366 // SDNode.
Chris Lattnerb02cdaa2010-02-15 08:04:42 +0000367 OpNo = 1;
368
Chris Lattner6c132332010-02-16 19:19:58 +0000369 // If this node is not the root and the subtree underneath it produces a
370 // chain, then the result of matching the node is also produce a chain.
371 // Beyond that, this means that we're also folding (at least) the root node
372 // into the node that produce the chain (for example, matching
373 // "(add reg, (load ptr))" as a add_with_memory on X86). This is
374 // problematic, if the 'reg' node also uses the load (say, its chain).
375 // Graphically:
376 //
377 // [LD]
378 // ^ ^
379 // | \ DAG's like cheese.
380 // / |
381 // / [YY]
382 // | ^
383 // [XX]--/
384 //
385 // It would be invalid to fold XX and LD. In this case, folding the two
386 // nodes together would induce a cycle in the DAG, making it a 'cyclic DAG'
387 // To prevent this, we emit a dynamic check for legality before allowing
388 // this to be folded.
389 //
390 const TreePatternNode *Root = Pattern.getSrcPattern();
Florian Hahn6b1db822018-06-14 20:32:58 +0000391 if (N != Root) { // Not the root of the pattern.
Chris Lattneraa7d3e02010-02-16 06:10:58 +0000392 // If there is a node between the root and this node, then we definitely
393 // need to emit the check.
Florian Hahn6b1db822018-06-14 20:32:58 +0000394 bool NeedCheck = !Root->hasChild(N);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000395
Chris Lattneraa7d3e02010-02-16 06:10:58 +0000396 // If it *is* an immediate child of the root, we can still need a check if
397 // the root SDNode has multiple inputs. For us, this means that it is an
398 // intrinsic, has multiple operands, or has other inputs like chain or
Chris Lattnerf7f9e8c2010-12-23 17:03:20 +0000399 // glue).
Chris Lattneraa7d3e02010-02-16 06:10:58 +0000400 if (!NeedCheck) {
401 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(Root->getOperator());
402 NeedCheck =
403 Root->getOperator() == CGP.get_intrinsic_void_sdnode() ||
404 Root->getOperator() == CGP.get_intrinsic_w_chain_sdnode() ||
405 Root->getOperator() == CGP.get_intrinsic_wo_chain_sdnode() ||
406 PInfo.getNumOperands() > 1 ||
407 PInfo.hasProperty(SDNPHasChain) ||
Chris Lattner2a0a3b42010-12-23 18:28:41 +0000408 PInfo.hasProperty(SDNPInGlue) ||
409 PInfo.hasProperty(SDNPOptInGlue);
Chris Lattneraa7d3e02010-02-16 06:10:58 +0000410 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000411
Chris Lattneraa7d3e02010-02-16 06:10:58 +0000412 if (NeedCheck)
Chris Lattner2c3f6492010-02-25 02:04:40 +0000413 AddMatcher(new CheckFoldableChainNodeMatcher());
Chris Lattneraa7d3e02010-02-16 06:10:58 +0000414 }
Chris Lattnerb02cdaa2010-02-15 08:04:42 +0000415 }
Chris Lattner29364372010-02-24 05:33:42 +0000416
Chris Lattnerf7f9e8c2010-12-23 17:03:20 +0000417 // If this node has an output glue and isn't the root, remember it.
Florian Hahn6b1db822018-06-14 20:32:58 +0000418 if (N->NodeHasProperty(SDNPOutGlue, CGP) &&
419 N != Pattern.getSrcPattern()) {
Chris Lattnerf7f9e8c2010-12-23 17:03:20 +0000420 // TODO: This redundantly records nodes with both glues and chains.
Jim Grosbach65586fe2010-12-21 16:16:00 +0000421
Chris Lattner29364372010-02-24 05:33:42 +0000422 // Record the node and remember it in our chained nodes list.
Florian Hahn6b1db822018-06-14 20:32:58 +0000423 AddMatcher(new RecordMatcher("'" + N->getOperator()->getName().str() +
Chris Lattnerf7f9e8c2010-12-23 17:03:20 +0000424 "' glue output node",
Chris Lattner4634d9b2010-03-01 02:24:17 +0000425 NextRecordedOperandNo));
Chris Lattner29364372010-02-24 05:33:42 +0000426 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000427
Chris Lattnerf7f9e8c2010-12-23 17:03:20 +0000428 // If this node is known to have an input glue or if it *might* have an input
429 // glue, capture it as the glue input of the pattern.
Florian Hahn6b1db822018-06-14 20:32:58 +0000430 if (N->NodeHasProperty(SDNPOptInGlue, CGP) ||
431 N->NodeHasProperty(SDNPInGlue, CGP))
Chris Lattnerf7f9e8c2010-12-23 17:03:20 +0000432 AddMatcher(new CaptureGlueInputMatcher());
Jim Grosbach65586fe2010-12-21 16:16:00 +0000433
Florian Hahn6b1db822018-06-14 20:32:58 +0000434 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
Chris Lattnerb02cdaa2010-02-15 08:04:42 +0000435 // Get the code suitable for matching this child. Move to the child, check
436 // it then move back to the parent.
Chris Lattner2c3f6492010-02-25 02:04:40 +0000437 AddMatcher(new MoveChildMatcher(OpNo));
Florian Hahn6b1db822018-06-14 20:32:58 +0000438 EmitMatchCode(N->getChild(i), NodeNoTypes->getChild(i), ForceMode);
Chris Lattner2c3f6492010-02-25 02:04:40 +0000439 AddMatcher(new MoveParentMatcher());
Chris Lattnerb02cdaa2010-02-15 08:04:42 +0000440 }
441}
442
Nicolai Haehnle445b0b62018-11-30 14:15:13 +0000443bool MatcherGen::recordUniqueNode(ArrayRef<std::string> Names) {
444 unsigned Entry = 0;
445 for (const std::string &Name : Names) {
446 unsigned &VarMapEntry = VariableMap[Name];
447 if (!Entry)
448 Entry = VarMapEntry;
449 assert(Entry == VarMapEntry);
Tim Northoverc807a172014-05-20 11:52:46 +0000450 }
451
Nicolai Haehnle445b0b62018-11-30 14:15:13 +0000452 bool NewRecord = false;
453 if (Entry == 0) {
454 // If it is a named node, we must emit a 'Record' opcode.
455 std::string WhatFor;
456 for (const std::string &Name : Names) {
457 if (!WhatFor.empty())
458 WhatFor += ',';
459 WhatFor += "$" + Name;
460 }
461 AddMatcher(new RecordMatcher(WhatFor, NextRecordedOperandNo));
462 Entry = ++NextRecordedOperandNo;
463 NewRecord = true;
464 } else {
465 // If we get here, this is a second reference to a specific name. Since
466 // we already have checked that the first reference is valid, we don't
467 // have to recursively match it, just check that it's the same as the
468 // previously named thing.
469 AddMatcher(new CheckSameMatcher(Entry-1));
470 }
471
472 for (const std::string &Name : Names)
473 VariableMap[Name] = Entry;
474
475 return NewRecord;
Tim Northoverc807a172014-05-20 11:52:46 +0000476}
Chris Lattnerb02cdaa2010-02-15 08:04:42 +0000477
Florian Hahn6b1db822018-06-14 20:32:58 +0000478void MatcherGen::EmitMatchCode(const TreePatternNode *N,
479 TreePatternNode *NodeNoTypes,
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000480 unsigned ForceMode) {
Chris Lattnerb02cdaa2010-02-15 08:04:42 +0000481 // If N and NodeNoTypes don't agree on a type, then this is a case where we
Craig Topper336e1f12014-01-25 17:34:23 +0000482 // need to do a type check. Emit the check, apply the type to NodeNoTypes and
Chris Lattnerb02cdaa2010-02-15 08:04:42 +0000483 // reinfer any correlated types.
Chris Lattner6c2d1782010-03-24 00:41:19 +0000484 SmallVector<unsigned, 2> ResultsToTypeCheck;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000485
Florian Hahn6b1db822018-06-14 20:32:58 +0000486 for (unsigned i = 0, e = NodeNoTypes->getNumTypes(); i != e; ++i) {
487 if (NodeNoTypes->getExtType(i) == N->getExtType(i)) continue;
488 NodeNoTypes->setType(i, N->getExtType(i));
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000489 InferPossibleTypes(ForceMode);
Chris Lattner6c2d1782010-03-24 00:41:19 +0000490 ResultsToTypeCheck.push_back(i);
Chris Lattnerb02cdaa2010-02-15 08:04:42 +0000491 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000492
Chris Lattnerb02cdaa2010-02-15 08:04:42 +0000493 // If this node has a name associated with it, capture it in VariableMap. If
494 // we already saw this in the pattern, emit code to verify dagness.
Nicolai Haehnle445b0b62018-11-30 14:15:13 +0000495 SmallVector<std::string, 4> Names;
Florian Hahn6b1db822018-06-14 20:32:58 +0000496 if (!N->getName().empty())
Nicolai Haehnle445b0b62018-11-30 14:15:13 +0000497 Names.push_back(N->getName());
498
499 for (const ScopedName &Name : N->getNamesAsPredicateArg()) {
500 Names.push_back(("pred:" + Twine(Name.getScope()) + ":" + Name.getIdentifier()).str());
501 }
502
503 if (!Names.empty()) {
504 if (!recordUniqueNode(Names))
Chris Lattnerb02cdaa2010-02-15 08:04:42 +0000505 return;
Nicolai Haehnle445b0b62018-11-30 14:15:13 +0000506 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000507
Florian Hahn6b1db822018-06-14 20:32:58 +0000508 if (N->isLeaf())
Chris Lattnerb02cdaa2010-02-15 08:04:42 +0000509 EmitLeafMatchCode(N);
510 else
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000511 EmitOperatorMatchCode(N, NodeNoTypes, ForceMode);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000512
Chris Lattnera1603892010-03-07 07:20:49 +0000513 // If there are node predicates for this node, generate their checks.
Nicolai Haehnle445b0b62018-11-30 14:15:13 +0000514 for (unsigned i = 0, e = N->getPredicateCalls().size(); i != e; ++i) {
515 const TreePredicateCall &Pred = N->getPredicateCalls()[i];
516 SmallVector<unsigned, 4> Operands;
517 if (Pred.Fn.usesOperands()) {
518 TreePattern *TP = Pred.Fn.getOrigPatFragRecord();
519 for (unsigned i = 0; i < TP->getNumArgs(); ++i) {
520 std::string Name =
521 ("pred:" + Twine(Pred.Scope) + ":" + TP->getArgName(i)).str();
522 Operands.push_back(getNamedArgumentSlot(Name));
523 }
524 }
525 AddMatcher(new CheckPredicateMatcher(Pred.Fn, Operands));
526 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000527
Chris Lattner6c2d1782010-03-24 00:41:19 +0000528 for (unsigned i = 0, e = ResultsToTypeCheck.size(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +0000529 AddMatcher(new CheckTypeMatcher(N->getSimpleType(ResultsToTypeCheck[i]),
Chris Lattner6c2d1782010-03-24 00:41:19 +0000530 ResultsToTypeCheck[i]));
Chris Lattnerb02cdaa2010-02-15 08:04:42 +0000531}
532
Chris Lattner053a28a2010-03-01 07:17:40 +0000533/// EmitMatcherCode - Generate the code that matches the predicate of this
534/// pattern for the specified Variant. If the variant is invalid this returns
535/// true and does not generate code, if it is valid, it returns false.
536bool MatcherGen::EmitMatcherCode(unsigned Variant) {
537 // If the root of the pattern is a ComplexPattern and if it is specified to
538 // match some number of root opcodes, these are considered to be our variants.
539 // Depending on which variant we're generating code for, emit the root opcode
540 // check.
541 if (const ComplexPattern *CP =
542 Pattern.getSrcPattern()->getComplexPatternInfo(CGP)) {
Chris Lattner053a28a2010-03-01 07:17:40 +0000543 const std::vector<Record*> &OpNodes = CP->getRootNodes();
Chris Lattner1e634e32010-03-01 22:29:19 +0000544 assert(!OpNodes.empty() &&"Complex Pattern must specify what it can match");
545 if (Variant >= OpNodes.size()) return true;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000546
Chris Lattner1e634e32010-03-01 22:29:19 +0000547 AddMatcher(new CheckOpcodeMatcher(CGP.getSDNodeInfo(OpNodes[Variant])));
Chris Lattner053a28a2010-03-01 07:17:40 +0000548 } else {
549 if (Variant != 0) return true;
550 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000551
Chris Lattner0e2cedb2010-03-04 01:25:36 +0000552 // Emit the matcher for the pattern structure and types.
Florian Hahn6b1db822018-06-14 20:32:58 +0000553 EmitMatchCode(Pattern.getSrcPattern(), PatWithNoTypes.get(),
Florian Hahn75e87c32018-05-30 21:00:18 +0000554 Pattern.ForceMode);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000555
Chris Lattnerb02cdaa2010-02-15 08:04:42 +0000556 // If the pattern has a predicate on it (e.g. only enabled when a subtarget
557 // feature is around, do the check).
558 if (!Pattern.getPredicateCheck().empty())
Chris Lattner053a28a2010-03-01 07:17:40 +0000559 AddMatcher(new CheckPatternPredicateMatcher(Pattern.getPredicateCheck()));
Jim Grosbach65586fe2010-12-21 16:16:00 +0000560
Chris Lattner0acbb712010-03-04 01:23:08 +0000561 // Now that we've completed the structural type match, emit any ComplexPattern
562 // checks (e.g. addrmode matches). We emit this after the structural match
563 // because they are generally more expensive to evaluate and more difficult to
564 // factor.
Chris Lattner0acbb712010-03-04 01:23:08 +0000565 for (unsigned i = 0, e = MatchedComplexPatterns.size(); i != e; ++i) {
Florian Hahn75e87c32018-05-30 21:00:18 +0000566 auto N = MatchedComplexPatterns[i].first;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000567
Chris Lattner0acbb712010-03-04 01:23:08 +0000568 // Remember where the results of this match get stuck.
Tim Northoverc807a172014-05-20 11:52:46 +0000569 if (N->isLeaf()) {
570 NamedComplexPatternOperands[N->getName()] = NextRecordedOperandNo + 1;
571 } else {
572 unsigned CurOp = NextRecordedOperandNo;
573 for (unsigned i = 0; i < N->getNumChildren(); ++i) {
Florian Hahn6b1db822018-06-14 20:32:58 +0000574 NamedComplexPatternOperands[N->getChild(i)->getName()] = CurOp + 1;
575 CurOp += N->getChild(i)->getNumMIResults(CGP);
Tim Northoverc807a172014-05-20 11:52:46 +0000576 }
577 }
Chris Lattner0acbb712010-03-04 01:23:08 +0000578
579 // Get the slot we recorded the value in from the name on the node.
Tim Northoverc807a172014-05-20 11:52:46 +0000580 unsigned RecNodeEntry = MatchedComplexPatterns[i].second;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000581
Tim Northoverc807a172014-05-20 11:52:46 +0000582 const ComplexPattern &CP = *N->getComplexPatternInfo(CGP);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000583
Chris Lattner0acbb712010-03-04 01:23:08 +0000584 // Emit a CheckComplexPat operation, which does the match (aborting if it
585 // fails) and pushes the matched operands onto the recorded nodes list.
586 AddMatcher(new CheckComplexPatMatcher(CP, RecNodeEntry,
587 N->getName(), NextRecordedOperandNo));
Jim Grosbach65586fe2010-12-21 16:16:00 +0000588
Chris Lattner0acbb712010-03-04 01:23:08 +0000589 // Record the right number of operands.
590 NextRecordedOperandNo += CP.getNumOperands();
591 if (CP.hasProperty(SDNPHasChain)) {
592 // If the complex pattern has a chain, then we need to keep track of the
593 // fact that we just recorded a chain input. The chain input will be
594 // matched as the last operand of the predicate if it was successful.
595 ++NextRecordedOperandNo; // Chained node operand.
Jim Grosbach65586fe2010-12-21 16:16:00 +0000596
Chris Lattner0acbb712010-03-04 01:23:08 +0000597 // It is the last operand recorded.
598 assert(NextRecordedOperandNo > 1 &&
599 "Should have recorded input/result chains at least!");
600 MatchedChainNodes.push_back(NextRecordedOperandNo-1);
601 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000602
Chris Lattnerf7f9e8c2010-12-23 17:03:20 +0000603 // TODO: Complex patterns can't have output glues, if they did, we'd want
Chris Lattner0acbb712010-03-04 01:23:08 +0000604 // to record them.
605 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000606
Chris Lattner053a28a2010-03-01 07:17:40 +0000607 return false;
Chris Lattnerb02cdaa2010-02-15 08:04:42 +0000608}
609
610
Chris Lattner7ed81692010-02-18 06:47:49 +0000611//===----------------------------------------------------------------------===//
612// Node Result Generation
613//===----------------------------------------------------------------------===//
614
Florian Hahn6b1db822018-06-14 20:32:58 +0000615void MatcherGen::EmitResultOfNamedOperand(const TreePatternNode *N,
Chris Lattner132df652010-02-21 03:22:59 +0000616 SmallVectorImpl<unsigned> &ResultOps){
Florian Hahn6b1db822018-06-14 20:32:58 +0000617 assert(!N->getName().empty() && "Operand not named!");
Jim Grosbach65586fe2010-12-21 16:16:00 +0000618
Florian Hahn6b1db822018-06-14 20:32:58 +0000619 if (unsigned SlotNo = NamedComplexPatternOperands[N->getName()]) {
Tim Northoverc807a172014-05-20 11:52:46 +0000620 // Complex operands have already been completely selected, just find the
621 // right slot ant add the arguments directly.
Florian Hahn6b1db822018-06-14 20:32:58 +0000622 for (unsigned i = 0; i < N->getNumMIResults(CGP); ++i)
Tim Northoverc807a172014-05-20 11:52:46 +0000623 ResultOps.push_back(SlotNo - 1 + i);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000624
Chris Lattner132df652010-02-21 03:22:59 +0000625 return;
626 }
627
Florian Hahn6b1db822018-06-14 20:32:58 +0000628 unsigned SlotNo = getNamedArgumentSlot(N->getName());
Chris Lattner0acbb712010-03-04 01:23:08 +0000629
Chris Lattner132df652010-02-21 03:22:59 +0000630 // If this is an 'imm' or 'fpimm' node, make sure to convert it to the target
631 // version of the immediate so that it doesn't get selected due to some other
632 // node use.
Florian Hahn6b1db822018-06-14 20:32:58 +0000633 if (!N->isLeaf()) {
634 StringRef OperatorName = N->getOperator()->getName();
Chris Lattner132df652010-02-21 03:22:59 +0000635 if (OperatorName == "imm" || OperatorName == "fpimm") {
Chris Lattner2c3f6492010-02-25 02:04:40 +0000636 AddMatcher(new EmitConvertToTargetMatcher(SlotNo));
Chris Lattner132df652010-02-21 03:22:59 +0000637 ResultOps.push_back(NextRecordedOperandNo++);
638 return;
639 }
640 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000641
Florian Hahn6b1db822018-06-14 20:32:58 +0000642 for (unsigned i = 0; i < N->getNumMIResults(CGP); ++i)
Tim Northoverc807a172014-05-20 11:52:46 +0000643 ResultOps.push_back(SlotNo + i);
Chris Lattner132df652010-02-21 03:22:59 +0000644}
645
Florian Hahn6b1db822018-06-14 20:32:58 +0000646void MatcherGen::EmitResultLeafAsOperand(const TreePatternNode *N,
Chris Lattner132df652010-02-21 03:22:59 +0000647 SmallVectorImpl<unsigned> &ResultOps) {
Florian Hahn6b1db822018-06-14 20:32:58 +0000648 assert(N->isLeaf() && "Must be a leaf");
Jim Grosbach65586fe2010-12-21 16:16:00 +0000649
Florian Hahn6b1db822018-06-14 20:32:58 +0000650 if (IntInit *II = dyn_cast<IntInit>(N->getLeafValue())) {
651 AddMatcher(new EmitIntegerMatcher(II->getValue(), N->getSimpleType(0)));
Chris Lattner132df652010-02-21 03:22:59 +0000652 ResultOps.push_back(NextRecordedOperandNo++);
Chris Lattner42a7ba72010-02-18 22:03:03 +0000653 return;
654 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000655
Chris Lattner42a7ba72010-02-18 22:03:03 +0000656 // If this is an explicit register reference, handle it.
Florian Hahn6b1db822018-06-14 20:32:58 +0000657 if (DefInit *DI = dyn_cast<DefInit>(N->getLeafValue())) {
Owen Andersona84be6c2011-06-27 21:06:21 +0000658 Record *Def = DI->getDef();
659 if (Def->isSubClassOf("Register")) {
Jakob Stoklund Olesen8e188be2011-06-18 04:26:06 +0000660 const CodeGenRegister *Reg =
Owen Andersona84be6c2011-06-27 21:06:21 +0000661 CGP.getTargetInfo().getRegBank().getReg(Def);
Florian Hahn6b1db822018-06-14 20:32:58 +0000662 AddMatcher(new EmitRegisterMatcher(Reg, N->getSimpleType(0)));
Chris Lattner132df652010-02-21 03:22:59 +0000663 ResultOps.push_back(NextRecordedOperandNo++);
Chris Lattner42a7ba72010-02-18 22:03:03 +0000664 return;
665 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000666
Owen Andersona84be6c2011-06-27 21:06:21 +0000667 if (Def->getName() == "zero_reg") {
Florian Hahn6b1db822018-06-14 20:32:58 +0000668 AddMatcher(new EmitRegisterMatcher(nullptr, N->getSimpleType(0)));
Chris Lattner132df652010-02-21 03:22:59 +0000669 ResultOps.push_back(NextRecordedOperandNo++);
Chris Lattner42a7ba72010-02-18 22:03:03 +0000670 return;
671 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000672
Chris Lattner132df652010-02-21 03:22:59 +0000673 // Handle a reference to a register class. This is used
674 // in COPY_TO_SUBREG instructions.
Owen Andersona84be6c2011-06-27 21:06:21 +0000675 if (Def->isSubClassOf("RegisterOperand"))
676 Def = Def->getValueAsDef("RegClass");
677 if (Def->isSubClassOf("RegisterClass")) {
678 std::string Value = getQualifiedName(Def) + "RegClassID";
Chris Lattner2c3f6492010-02-25 02:04:40 +0000679 AddMatcher(new EmitStringIntegerMatcher(Value, MVT::i32));
Chris Lattner132df652010-02-21 03:22:59 +0000680 ResultOps.push_back(NextRecordedOperandNo++);
681 return;
Chris Lattner42a7ba72010-02-18 22:03:03 +0000682 }
Jakob Stoklund Olesen1c696462010-05-24 14:48:12 +0000683
684 // Handle a subregister index. This is used for INSERT_SUBREG etc.
Owen Andersona84be6c2011-06-27 21:06:21 +0000685 if (Def->isSubClassOf("SubRegIndex")) {
686 std::string Value = getQualifiedName(Def);
Jakob Stoklund Olesen1c696462010-05-24 14:48:12 +0000687 AddMatcher(new EmitStringIntegerMatcher(Value, MVT::i32));
688 ResultOps.push_back(NextRecordedOperandNo++);
689 return;
690 }
Chris Lattner42a7ba72010-02-18 22:03:03 +0000691 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000692
Chris Lattner7ed81692010-02-18 06:47:49 +0000693 errs() << "unhandled leaf node: \n";
Florian Hahn6b1db822018-06-14 20:32:58 +0000694 N->dump();
Chris Lattner7ed81692010-02-18 06:47:49 +0000695}
696
Cameron Zwarich8b76e012011-05-19 21:13:30 +0000697static bool
Florian Hahn6b1db822018-06-14 20:32:58 +0000698mayInstNodeLoadOrStore(const TreePatternNode *N,
Cameron Zwarich8b76e012011-05-19 21:13:30 +0000699 const CodeGenDAGPatterns &CGP) {
Florian Hahn6b1db822018-06-14 20:32:58 +0000700 Record *Op = N->getOperator();
Cameron Zwarich8b76e012011-05-19 21:13:30 +0000701 const CodeGenTarget &CGT = CGP.getTargetInfo();
702 CodeGenInstruction &II = CGT.getInstruction(Op);
703 return II.mayLoad || II.mayStore;
704}
705
706static unsigned
Florian Hahn6b1db822018-06-14 20:32:58 +0000707numNodesThatMayLoadOrStore(const TreePatternNode *N,
Cameron Zwarich8b76e012011-05-19 21:13:30 +0000708 const CodeGenDAGPatterns &CGP) {
Florian Hahn6b1db822018-06-14 20:32:58 +0000709 if (N->isLeaf())
Cameron Zwarich8b76e012011-05-19 21:13:30 +0000710 return 0;
711
Florian Hahn6b1db822018-06-14 20:32:58 +0000712 Record *OpRec = N->getOperator();
Cameron Zwarich8b76e012011-05-19 21:13:30 +0000713 if (!OpRec->isSubClassOf("Instruction"))
714 return 0;
715
716 unsigned Count = 0;
717 if (mayInstNodeLoadOrStore(N, CGP))
718 ++Count;
719
Florian Hahn6b1db822018-06-14 20:32:58 +0000720 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
721 Count += numNodesThatMayLoadOrStore(N->getChild(i), CGP);
Cameron Zwarich8b76e012011-05-19 21:13:30 +0000722
723 return Count;
724}
725
Chris Lattner132df652010-02-21 03:22:59 +0000726void MatcherGen::
Florian Hahn6b1db822018-06-14 20:32:58 +0000727EmitResultInstructionAsOperand(const TreePatternNode *N,
Chris Lattner132df652010-02-21 03:22:59 +0000728 SmallVectorImpl<unsigned> &OutputOps) {
Florian Hahn6b1db822018-06-14 20:32:58 +0000729 Record *Op = N->getOperator();
Chris Lattner7ed81692010-02-18 06:47:49 +0000730 const CodeGenTarget &CGT = CGP.getTargetInfo();
Chris Lattner9aec14b2010-03-19 00:07:20 +0000731 CodeGenInstruction &II = CGT.getInstruction(Op);
Chris Lattner7ed81692010-02-18 06:47:49 +0000732 const DAGInstruction &Inst = CGP.getInstruction(Op);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000733
Florian Hahn6b1db822018-06-14 20:32:58 +0000734 bool isRoot = N == Pattern.getDstPattern();
Chris Lattner132df652010-02-21 03:22:59 +0000735
Chris Lattnerf7f9e8c2010-12-23 17:03:20 +0000736 // TreeHasOutGlue - True if this tree has glue.
737 bool TreeHasInGlue = false, TreeHasOutGlue = false;
Chris Lattner132df652010-02-21 03:22:59 +0000738 if (isRoot) {
739 const TreePatternNode *SrcPat = Pattern.getSrcPattern();
Chris Lattner2a0a3b42010-12-23 18:28:41 +0000740 TreeHasInGlue = SrcPat->TreeHasProperty(SDNPOptInGlue, CGP) ||
741 SrcPat->TreeHasProperty(SDNPInGlue, CGP);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000742
Chris Lattner132df652010-02-21 03:22:59 +0000743 // FIXME2: this is checking the entire pattern, not just the node in
744 // question, doing this just for the root seems like a total hack.
Chris Lattner2a0a3b42010-12-23 18:28:41 +0000745 TreeHasOutGlue = SrcPat->TreeHasProperty(SDNPOutGlue, CGP);
Chris Lattner132df652010-02-21 03:22:59 +0000746 }
747
748 // NumResults - This is the number of results produced by the instruction in
749 // the "outs" list.
Jim Grosbach65586fe2010-12-21 16:16:00 +0000750 unsigned NumResults = Inst.getNumResults();
Chris Lattner7ed81692010-02-18 06:47:49 +0000751
Matt Arsenaulteb492162014-11-02 23:46:51 +0000752 // Number of operands we know the output instruction must have. If it is
753 // variadic, we could have more operands.
754 unsigned NumFixedOperands = II.Operands.size();
Jim Grosbach65586fe2010-12-21 16:16:00 +0000755
Matt Arsenaulteb492162014-11-02 23:46:51 +0000756 SmallVector<unsigned, 8> InstOps;
757
758 // Loop over all of the fixed operands of the instruction pattern, emitting
759 // code to fill them all in. The node 'N' usually has number children equal to
760 // the number of input operands of the instruction. However, in cases where
761 // there are predicate operands for an instruction, we need to fill in the
762 // 'execute always' values. Match up the node operands to the instruction
763 // operands to do this.
764 unsigned ChildNo = 0;
765 for (unsigned InstOpNo = NumResults, e = NumFixedOperands;
766 InstOpNo != e; ++InstOpNo) {
Chris Lattner7ed81692010-02-18 06:47:49 +0000767 // Determine what to emit for this operand.
Chris Lattnerd8adec72010-11-01 04:03:32 +0000768 Record *OperandNode = II.Operands[InstOpNo].Rec;
Tom Stellardb7246a72012-09-06 14:15:52 +0000769 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
Chris Lattner7ed81692010-02-18 06:47:49 +0000770 !CGP.getDefaultOperand(OperandNode).DefaultOps.empty()) {
771 // This is a predicate or optional def operand; emit the
772 // 'default ops' operands.
Eric Christophere264e092010-08-10 23:46:20 +0000773 const DAGDefaultOperand &DefaultOp
Jim Grosbach65586fe2010-12-21 16:16:00 +0000774 = CGP.getDefaultOperand(OperandNode);
Chris Lattner7ed81692010-02-18 06:47:49 +0000775 for (unsigned i = 0, e = DefaultOp.DefaultOps.size(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +0000776 EmitResultOperand(DefaultOp.DefaultOps[i].get(), InstOps);
Chris Lattner7ed81692010-02-18 06:47:49 +0000777 continue;
778 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000779
Chris Lattner7ed81692010-02-18 06:47:49 +0000780 // Otherwise this is a normal operand or a predicate operand without
781 // 'execute always'; emit it.
Jim Grosbach65586fe2010-12-21 16:16:00 +0000782
Ulrich Weigande618abd2013-03-19 19:51:09 +0000783 // For operands with multiple sub-operands we may need to emit
784 // multiple child patterns to cover them all. However, ComplexPattern
785 // children may themselves emit multiple MI operands.
786 unsigned NumSubOps = 1;
787 if (OperandNode->isSubClassOf("Operand")) {
788 DagInit *MIOpInfo = OperandNode->getValueAsDag("MIOperandInfo");
789 if (unsigned NumArgs = MIOpInfo->getNumArgs())
790 NumSubOps = NumArgs;
791 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000792
Ulrich Weigande618abd2013-03-19 19:51:09 +0000793 unsigned FinalNumOps = InstOps.size() + NumSubOps;
794 while (InstOps.size() < FinalNumOps) {
Florian Hahn6b1db822018-06-14 20:32:58 +0000795 const TreePatternNode *Child = N->getChild(ChildNo);
Ulrich Weigande618abd2013-03-19 19:51:09 +0000796 unsigned BeforeAddingNumOps = InstOps.size();
797 EmitResultOperand(Child, InstOps);
798 assert(InstOps.size() > BeforeAddingNumOps && "Didn't add any operands");
799
800 // If the operand is an instruction and it produced multiple results, just
801 // take the first one.
Florian Hahn6b1db822018-06-14 20:32:58 +0000802 if (!Child->isLeaf() && Child->getOperator()->isSubClassOf("Instruction"))
Ulrich Weigande618abd2013-03-19 19:51:09 +0000803 InstOps.resize(BeforeAddingNumOps+1);
804
805 ++ChildNo;
806 }
Chris Lattner7ed81692010-02-18 06:47:49 +0000807 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000808
Matt Arsenaulteb492162014-11-02 23:46:51 +0000809 // If this is a variadic output instruction (i.e. REG_SEQUENCE), we can't
810 // expand suboperands, use default operands, or other features determined from
811 // the CodeGenInstruction after the fixed operands, which were handled
812 // above. Emit the remaining instructions implicitly added by the use for
813 // variable_ops.
814 if (II.Operands.isVariadic) {
Florian Hahn6b1db822018-06-14 20:32:58 +0000815 for (unsigned I = ChildNo, E = N->getNumChildren(); I < E; ++I)
816 EmitResultOperand(N->getChild(I), InstOps);
Matt Arsenaulteb492162014-11-02 23:46:51 +0000817 }
818
Chris Lattnerf7f9e8c2010-12-23 17:03:20 +0000819 // If this node has input glue or explicitly specified input physregs, we
820 // need to add chained and glued copyfromreg nodes and materialize the glue
Chris Lattner132df652010-02-21 03:22:59 +0000821 // input.
822 if (isRoot && !PhysRegInputs.empty()) {
823 // Emit all of the CopyToReg nodes for the input physical registers. These
824 // occur in patterns like (mul:i8 AL:i8, GR8:i8:$src).
825 for (unsigned i = 0, e = PhysRegInputs.size(); i != e; ++i)
Chris Lattner2c3f6492010-02-25 02:04:40 +0000826 AddMatcher(new EmitCopyToRegMatcher(PhysRegInputs[i].second,
Chris Lattner63a627c2010-03-18 23:57:40 +0000827 PhysRegInputs[i].first));
Chris Lattnerf7f9e8c2010-12-23 17:03:20 +0000828 // Even if the node has no other glue inputs, the resultant node must be
829 // glued to the CopyFromReg nodes we just generated.
830 TreeHasInGlue = true;
Chris Lattner132df652010-02-21 03:22:59 +0000831 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000832
Chris Lattnerf7f9e8c2010-12-23 17:03:20 +0000833 // Result order: node results, chain, glue
Jim Grosbach65586fe2010-12-21 16:16:00 +0000834
Chris Lattner132df652010-02-21 03:22:59 +0000835 // Determine the result types.
836 SmallVector<MVT::SimpleValueType, 4> ResultVTs;
Florian Hahn6b1db822018-06-14 20:32:58 +0000837 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i)
838 ResultVTs.push_back(N->getSimpleType(i));
Jim Grosbach65586fe2010-12-21 16:16:00 +0000839
Chris Lattner132df652010-02-21 03:22:59 +0000840 // If this is the root instruction of a pattern that has physical registers in
841 // its result pattern, add output VTs for them. For example, X86 has:
842 // (set AL, (mul ...))
843 // This also handles implicit results like:
844 // (implicit EFLAGS)
Chris Lattner725d3f62010-03-27 20:45:15 +0000845 if (isRoot && !Pattern.getDstRegs().empty()) {
Chris Lattner63a627c2010-03-18 23:57:40 +0000846 // If the root came from an implicit def in the instruction handling stuff,
847 // don't re-add it.
Craig Topper24064772014-04-15 07:20:03 +0000848 Record *HandledReg = nullptr;
Chris Lattner7bc5d9b2010-03-27 20:09:24 +0000849 if (II.HasOneImplicitDefWithKnownVT(CGT) != MVT::Other)
Chris Lattner63a627c2010-03-18 23:57:40 +0000850 HandledReg = II.ImplicitDefs[0];
Jim Grosbach65586fe2010-12-21 16:16:00 +0000851
Simon Pilgrim48bed532017-06-19 13:24:12 +0000852 for (Record *Reg : Pattern.getDstRegs()) {
Chris Lattner63a627c2010-03-18 23:57:40 +0000853 if (!Reg->isSubClassOf("Register") || Reg == HandledReg) continue;
854 ResultVTs.push_back(getRegisterValueType(Reg, CGT));
855 }
Chris Lattner132df652010-02-21 03:22:59 +0000856 }
Chris Lattner132df652010-02-21 03:22:59 +0000857
Chris Lattnerbb34b4e2010-03-19 05:34:15 +0000858 // If this is the root of the pattern and the pattern we're matching includes
859 // a node that is variadic, mark the generated node as variadic so that it
860 // gets the excess operands from the input DAG.
Chris Lattner132df652010-02-21 03:22:59 +0000861 int NumFixedArityOperands = -1;
Chris Lattnerbb34b4e2010-03-19 05:34:15 +0000862 if (isRoot &&
Matt Arsenaulteb492162014-11-02 23:46:51 +0000863 Pattern.getSrcPattern()->NodeHasProperty(SDNPVariadic, CGP))
Chris Lattner132df652010-02-21 03:22:59 +0000864 NumFixedArityOperands = Pattern.getSrcPattern()->getNumChildren();
Jim Grosbach65586fe2010-12-21 16:16:00 +0000865
Cameron Zwarich8b76e012011-05-19 21:13:30 +0000866 // If this is the root node and multiple matched nodes in the input pattern
867 // have MemRefs in them, have the interpreter collect them and plop them onto
868 // this node. If there is just one node with MemRefs, leave them on that node
869 // even if it is not the root.
Chris Lattner132df652010-02-21 03:22:59 +0000870 //
Cameron Zwarich8b76e012011-05-19 21:13:30 +0000871 // FIXME3: This is actively incorrect for result patterns with multiple
872 // memory-referencing instructions.
873 bool PatternHasMemOperands =
874 Pattern.getSrcPattern()->TreeHasProperty(SDNPMemOperand, CGP);
875
876 bool NodeHasMemRefs = false;
877 if (PatternHasMemOperands) {
878 unsigned NumNodesThatLoadOrStore =
Florian Hahn6b1db822018-06-14 20:32:58 +0000879 numNodesThatMayLoadOrStore(Pattern.getDstPattern(), CGP);
Cameron Zwarich8b76e012011-05-19 21:13:30 +0000880 bool NodeIsUniqueLoadOrStore = mayInstNodeLoadOrStore(N, CGP) &&
881 NumNodesThatLoadOrStore == 1;
882 NodeHasMemRefs =
883 NodeIsUniqueLoadOrStore || (isRoot && (mayInstNodeLoadOrStore(N, CGP) ||
884 NumNodesThatLoadOrStore != 1));
885 }
Chris Lattner132df652010-02-21 03:22:59 +0000886
Ulrich Weigandc48aefb2018-07-13 13:18:00 +0000887 // Determine whether we need to attach a chain to this node.
888 bool NodeHasChain = false;
889 if (Pattern.getSrcPattern()->TreeHasProperty(SDNPHasChain, CGP)) {
890 // For some instructions, we were able to infer from the pattern whether
891 // they should have a chain. Otherwise, attach the chain to the root.
892 //
893 // FIXME2: This is extremely dubious for several reasons, not the least of
894 // which it gives special status to instructions with patterns that Pat<>
895 // nodes can't duplicate.
896 if (II.hasChain_Inferred)
897 NodeHasChain = II.hasChain;
898 else
899 NodeHasChain = isRoot;
900 // Instructions which load and store from memory should have a chain,
901 // regardless of whether they happen to have a pattern saying so.
902 if (II.hasCtrlDep || II.mayLoad || II.mayStore || II.canFoldAsLoad ||
903 II.hasSideEffects)
904 NodeHasChain = true;
905 }
906
Chris Lattnerf7f9e8c2010-12-23 17:03:20 +0000907 assert((!ResultVTs.empty() || TreeHasOutGlue || NodeHasChain) &&
Chris Lattnerd44966f2010-03-27 19:15:02 +0000908 "Node has no result");
Jim Grosbach65586fe2010-12-21 16:16:00 +0000909
Craig Topper86a9aee2017-07-07 06:22:35 +0000910 AddMatcher(new EmitNodeMatcher(II.Namespace.str()+"::"+II.TheDef->getName().str(),
Craig Toppera2c60192014-01-21 07:20:05 +0000911 ResultVTs, InstOps,
Chris Lattnerf7f9e8c2010-12-23 17:03:20 +0000912 NodeHasChain, TreeHasInGlue, TreeHasOutGlue,
Chris Lattnerabb1c792010-02-28 02:41:25 +0000913 NodeHasMemRefs, NumFixedArityOperands,
914 NextRecordedOperandNo));
Jim Grosbach65586fe2010-12-21 16:16:00 +0000915
Chris Lattnerf7f9e8c2010-12-23 17:03:20 +0000916 // The non-chain and non-glue results of the newly emitted node get recorded.
Chris Lattner9fd97c32010-02-21 23:54:05 +0000917 for (unsigned i = 0, e = ResultVTs.size(); i != e; ++i) {
Chris Lattner3e5fbd72010-12-21 02:38:05 +0000918 if (ResultVTs[i] == MVT::Other || ResultVTs[i] == MVT::Glue) break;
Chris Lattner79eaeb42010-02-21 06:03:07 +0000919 OutputOps.push_back(NextRecordedOperandNo++);
Chris Lattner9fd97c32010-02-21 23:54:05 +0000920 }
Chris Lattner132df652010-02-21 03:22:59 +0000921}
922
923void MatcherGen::
Florian Hahn6b1db822018-06-14 20:32:58 +0000924EmitResultSDNodeXFormAsOperand(const TreePatternNode *N,
Chris Lattner132df652010-02-21 03:22:59 +0000925 SmallVectorImpl<unsigned> &ResultOps) {
Florian Hahn6b1db822018-06-14 20:32:58 +0000926 assert(N->getOperator()->isSubClassOf("SDNodeXForm") && "Not SDNodeXForm?");
Chris Lattner132df652010-02-21 03:22:59 +0000927
928 // Emit the operand.
929 SmallVector<unsigned, 8> InputOps;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000930
Chris Lattner132df652010-02-21 03:22:59 +0000931 // FIXME2: Could easily generalize this to support multiple inputs and outputs
932 // to the SDNodeXForm. For now we just support one input and one output like
933 // the old instruction selector.
Florian Hahn6b1db822018-06-14 20:32:58 +0000934 assert(N->getNumChildren() == 1);
935 EmitResultOperand(N->getChild(0), InputOps);
Chris Lattner132df652010-02-21 03:22:59 +0000936
937 // The input currently must have produced exactly one result.
938 assert(InputOps.size() == 1 && "Unexpected input to SDNodeXForm");
939
Florian Hahn6b1db822018-06-14 20:32:58 +0000940 AddMatcher(new EmitNodeXFormMatcher(InputOps[0], N->getOperator()));
Chris Lattner132df652010-02-21 03:22:59 +0000941 ResultOps.push_back(NextRecordedOperandNo++);
Chris Lattner7ed81692010-02-18 06:47:49 +0000942}
943
Florian Hahn6b1db822018-06-14 20:32:58 +0000944void MatcherGen::EmitResultOperand(const TreePatternNode *N,
Chris Lattner132df652010-02-21 03:22:59 +0000945 SmallVectorImpl<unsigned> &ResultOps) {
Chris Lattner7ed81692010-02-18 06:47:49 +0000946 // This is something selected from the pattern we matched.
Florian Hahn6b1db822018-06-14 20:32:58 +0000947 if (!N->getName().empty())
Chris Lattner132df652010-02-21 03:22:59 +0000948 return EmitResultOfNamedOperand(N, ResultOps);
Chris Lattner7ed81692010-02-18 06:47:49 +0000949
Florian Hahn6b1db822018-06-14 20:32:58 +0000950 if (N->isLeaf())
Chris Lattner7ed81692010-02-18 06:47:49 +0000951 return EmitResultLeafAsOperand(N, ResultOps);
952
Florian Hahn6b1db822018-06-14 20:32:58 +0000953 Record *OpRec = N->getOperator();
Chris Lattner7ed81692010-02-18 06:47:49 +0000954 if (OpRec->isSubClassOf("Instruction"))
955 return EmitResultInstructionAsOperand(N, ResultOps);
956 if (OpRec->isSubClassOf("SDNodeXForm"))
Chris Lattner132df652010-02-21 03:22:59 +0000957 return EmitResultSDNodeXFormAsOperand(N, ResultOps);
Florian Hahn6b1db822018-06-14 20:32:58 +0000958 errs() << "Unknown result node to emit code for: " << *N << '\n';
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000959 PrintFatalError("Unknown node in result pattern!");
Chris Lattner7ed81692010-02-18 06:47:49 +0000960}
961
962void MatcherGen::EmitResultCode() {
Chris Lattner28182722010-03-01 22:46:42 +0000963 // Patterns that match nodes with (potentially multiple) chain inputs have to
964 // merge them together into a token factor. This informs the generated code
965 // what all the chained nodes are.
966 if (!MatchedChainNodes.empty())
Craig Toppera2c60192014-01-21 07:20:05 +0000967 AddMatcher(new EmitMergeInputChainsMatcher(MatchedChainNodes));
Jim Grosbach65586fe2010-12-21 16:16:00 +0000968
Chris Lattner9fd97c32010-02-21 23:54:05 +0000969 // Codegen the root of the result pattern, capturing the resulting values.
Chris Lattner132df652010-02-21 03:22:59 +0000970 SmallVector<unsigned, 8> Ops;
Florian Hahn6b1db822018-06-14 20:32:58 +0000971 EmitResultOperand(Pattern.getDstPattern(), Ops);
Chris Lattner132df652010-02-21 03:22:59 +0000972
Chris Lattner9fd97c32010-02-21 23:54:05 +0000973 // At this point, we have however many values the result pattern produces.
974 // However, the input pattern might not need all of these. If there are
Chris Lattner725d3f62010-03-27 20:45:15 +0000975 // excess values at the end (such as implicit defs of condition codes etc)
Chris Lattnerf7f9e8c2010-12-23 17:03:20 +0000976 // just lop them off. This doesn't need to worry about glue or chains, just
Chris Lattner725d3f62010-03-27 20:45:15 +0000977 // explicit results.
Chris Lattner9fd97c32010-02-21 23:54:05 +0000978 //
Chris Lattner725d3f62010-03-27 20:45:15 +0000979 unsigned NumSrcResults = Pattern.getSrcPattern()->getNumTypes();
Jim Grosbach65586fe2010-12-21 16:16:00 +0000980
Chris Lattner725d3f62010-03-27 20:45:15 +0000981 // If the pattern also has (implicit) results, count them as well.
982 if (!Pattern.getDstRegs().empty()) {
983 // If the root came from an implicit def in the instruction handling stuff,
984 // don't re-add it.
Craig Topper24064772014-04-15 07:20:03 +0000985 Record *HandledReg = nullptr;
Chris Lattner725d3f62010-03-27 20:45:15 +0000986 const TreePatternNode *DstPat = Pattern.getDstPattern();
987 if (!DstPat->isLeaf() &&DstPat->getOperator()->isSubClassOf("Instruction")){
988 const CodeGenTarget &CGT = CGP.getTargetInfo();
989 CodeGenInstruction &II = CGT.getInstruction(DstPat->getOperator());
990
991 if (II.HasOneImplicitDefWithKnownVT(CGT) != MVT::Other)
992 HandledReg = II.ImplicitDefs[0];
993 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000994
Simon Pilgrim48bed532017-06-19 13:24:12 +0000995 for (Record *Reg : Pattern.getDstRegs()) {
Chris Lattner725d3f62010-03-27 20:45:15 +0000996 if (!Reg->isSubClassOf("Register") || Reg == HandledReg) continue;
997 ++NumSrcResults;
998 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000999 }
1000
Chris Lattner9fd97c32010-02-21 23:54:05 +00001001 assert(Ops.size() >= NumSrcResults && "Didn't provide enough results");
Craig Topperbd199f82018-12-05 00:47:59 +00001002 SmallVector<unsigned, 8> Results(Ops);
Chris Lattner29364372010-02-24 05:33:42 +00001003
Craig Topperbd199f82018-12-05 00:47:59 +00001004 // Apply result permutation.
1005 for (unsigned ResNo = 0; ResNo < Pattern.getDstPattern()->getNumResults();
1006 ++ResNo) {
1007 Results[ResNo] = Ops[Pattern.getDstPattern()->getResultIndex(ResNo)];
1008 }
1009
1010 Results.resize(NumSrcResults);
1011 AddMatcher(new CompleteMatchMatcher(Results, Pattern));
Chris Lattner7ed81692010-02-18 06:47:49 +00001012}
1013
1014
Chris Lattner053a28a2010-03-01 07:17:40 +00001015/// ConvertPatternToMatcher - Create the matcher for the specified pattern with
1016/// the specified variant. If the variant number is invalid, this returns null.
Chris Lattner2c3f6492010-02-25 02:04:40 +00001017Matcher *llvm::ConvertPatternToMatcher(const PatternToMatch &Pattern,
Chris Lattner053a28a2010-03-01 07:17:40 +00001018 unsigned Variant,
Chris Lattner102a8a02010-02-28 20:49:53 +00001019 const CodeGenDAGPatterns &CGP) {
Chris Lattnerb02cdaa2010-02-15 08:04:42 +00001020 MatcherGen Gen(Pattern, CGP);
1021
1022 // Generate the code for the matcher.
Chris Lattner053a28a2010-03-01 07:17:40 +00001023 if (Gen.EmitMatcherCode(Variant))
Craig Topper24064772014-04-15 07:20:03 +00001024 return nullptr;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001025
Chris Lattner132df652010-02-21 03:22:59 +00001026 // FIXME2: Kill extra MoveParent commands at the end of the matcher sequence.
1027 // FIXME2: Split result code out to another table, and make the matcher end
1028 // with an "Emit <index>" command. This allows result generation stuff to be
1029 // shared and factored?
Jim Grosbach65586fe2010-12-21 16:16:00 +00001030
Chris Lattnerb02cdaa2010-02-15 08:04:42 +00001031 // If the match succeeds, then we generate Pattern.
Chris Lattner7ed81692010-02-18 06:47:49 +00001032 Gen.EmitResultCode();
Chris Lattnerb02cdaa2010-02-15 08:04:42 +00001033
1034 // Unconditional match.
Chris Lattner7ed81692010-02-18 06:47:49 +00001035 return Gen.GetMatcher();
Chris Lattnerb02cdaa2010-02-15 08:04:42 +00001036}