blob: 39d51557e33103f24ef780195ed71286628a6016 [file] [log] [blame]
Chris Lattnerda272d12010-02-15 08:04:42 +00001//===- DAGISelMatcherGen.cpp - Matcher generator --------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "DAGISelMatcher.h"
11#include "CodeGenDAGPatterns.h"
12#include "Record.h"
Chris Lattner785d16f2010-02-17 02:16:19 +000013#include "llvm/ADT/SmallVector.h"
Chris Lattnerda272d12010-02-15 08:04:42 +000014#include "llvm/ADT/StringMap.h"
Chris Lattner8e946be2010-02-21 03:22:59 +000015#include <utility>
Chris Lattnerda272d12010-02-15 08:04:42 +000016using namespace llvm;
17
Chris Lattnerc94fa4c2010-02-19 00:27:40 +000018
Chris Lattner8e946be2010-02-21 03:22:59 +000019/// getRegisterValueType - Look up and return the ValueType of the specified
20/// register. If the register is a member of multiple register classes which
21/// have different associated types, return MVT::Other.
22static MVT::SimpleValueType getRegisterValueType(Record *R,
23 const CodeGenTarget &T) {
24 bool FoundRC = false;
25 MVT::SimpleValueType VT = MVT::Other;
26 const std::vector<CodeGenRegisterClass> &RCs = T.getRegisterClasses();
27 std::vector<Record*>::const_iterator Element;
28
29 for (unsigned rc = 0, e = RCs.size(); rc != e; ++rc) {
30 const CodeGenRegisterClass &RC = RCs[rc];
31 if (!std::count(RC.Elements.begin(), RC.Elements.end(), R))
32 continue;
33
34 if (!FoundRC) {
35 FoundRC = true;
36 VT = RC.getValueTypeNum(0);
37 continue;
Chris Lattnerc94fa4c2010-02-19 00:27:40 +000038 }
Chris Lattner8e946be2010-02-21 03:22:59 +000039
40 // In multiple RC's. If the Types of the RC's do not agree, return
41 // MVT::Other. The target is responsible for handling this.
42 if (VT != RC.getValueTypeNum(0))
43 // FIXME2: when does this happen? Abort?
44 return MVT::Other;
45 }
46 return VT;
47}
48
49
50namespace {
Chris Lattnerda272d12010-02-15 08:04:42 +000051 class MatcherGen {
52 const PatternToMatch &Pattern;
53 const CodeGenDAGPatterns &CGP;
54
55 /// PatWithNoTypes - This is a clone of Pattern.getSrcPattern() that starts
56 /// out with all of the types removed. This allows us to insert type checks
57 /// as we scan the tree.
58 TreePatternNode *PatWithNoTypes;
59
60 /// VariableMap - A map from variable names ('$dst') to the recorded operand
61 /// number that they were captured as. These are biased by 1 to make
62 /// insertion easier.
63 StringMap<unsigned> VariableMap;
Chris Lattnerc94fa4c2010-02-19 00:27:40 +000064
65 /// NextRecordedOperandNo - As we emit opcodes to record matched values in
66 /// the RecordedNodes array, this keeps track of which slot will be next to
67 /// record into.
Chris Lattnerda272d12010-02-15 08:04:42 +000068 unsigned NextRecordedOperandNo;
69
Chris Lattner8e946be2010-02-21 03:22:59 +000070 /// MatchedChainNodes - This maintains the position in the recorded nodes
71 /// array of all of the recorded input nodes that have chains.
72 SmallVector<unsigned, 2> MatchedChainNodes;
73
74 /// PhysRegInputs - List list has an entry for each explicitly specified
75 /// physreg input to the pattern. The first elt is the Register node, the
76 /// second is the recorded slot number the input pattern match saved it in.
77 SmallVector<std::pair<Record*, unsigned>, 2> PhysRegInputs;
78
79 /// EmittedMergeInputChains - For nodes that match patterns involving
80 /// chains, is set to true if we emitted the "MergeInputChains" operation.
81 bool EmittedMergeInputChains;
Chris Lattner785d16f2010-02-17 02:16:19 +000082
83 /// Matcher - This is the top level of the generated matcher, the result.
Chris Lattner8ef9c792010-02-18 02:49:24 +000084 MatcherNode *Matcher;
Chris Lattner785d16f2010-02-17 02:16:19 +000085
86 /// CurPredicate - As we emit matcher nodes, this points to the latest check
Chris Lattnerbd8227f2010-02-18 02:53:41 +000087 /// which should have future checks stuck into its Next position.
Chris Lattner8ef9c792010-02-18 02:49:24 +000088 MatcherNode *CurPredicate;
Chris Lattnerda272d12010-02-15 08:04:42 +000089 public:
90 MatcherGen(const PatternToMatch &pattern, const CodeGenDAGPatterns &cgp);
91
92 ~MatcherGen() {
93 delete PatWithNoTypes;
94 }
95
96 void EmitMatcherCode();
Chris Lattnerb49985a2010-02-18 06:47:49 +000097 void EmitResultCode();
Chris Lattnerda272d12010-02-15 08:04:42 +000098
Chris Lattner8ef9c792010-02-18 02:49:24 +000099 MatcherNode *GetMatcher() const { return Matcher; }
100 MatcherNode *GetCurPredicate() const { return CurPredicate; }
Chris Lattnerda272d12010-02-15 08:04:42 +0000101 private:
Chris Lattner8ef9c792010-02-18 02:49:24 +0000102 void AddMatcherNode(MatcherNode *NewNode);
Chris Lattnerda272d12010-02-15 08:04:42 +0000103 void InferPossibleTypes();
Chris Lattnerb49985a2010-02-18 06:47:49 +0000104
105 // Matcher Generation.
Chris Lattnerda272d12010-02-15 08:04:42 +0000106 void EmitMatchCode(const TreePatternNode *N, TreePatternNode *NodeNoTypes);
107 void EmitLeafMatchCode(const TreePatternNode *N);
108 void EmitOperatorMatchCode(const TreePatternNode *N,
109 TreePatternNode *NodeNoTypes);
Chris Lattnerb49985a2010-02-18 06:47:49 +0000110
111 // Result Code Generation.
Chris Lattner8e946be2010-02-21 03:22:59 +0000112 unsigned getNamedArgumentSlot(StringRef Name) {
113 unsigned VarMapEntry = VariableMap[Name];
114 assert(VarMapEntry != 0 &&
115 "Variable referenced but not defined and not caught earlier!");
116 return VarMapEntry-1;
117 }
118
119 /// GetInstPatternNode - Get the pattern for an instruction.
120 const TreePatternNode *GetInstPatternNode(const DAGInstruction &Ins,
121 const TreePatternNode *N);
122
Chris Lattnerb49985a2010-02-18 06:47:49 +0000123 void EmitResultOperand(const TreePatternNode *N,
Chris Lattner8e946be2010-02-21 03:22:59 +0000124 SmallVectorImpl<unsigned> &ResultOps);
125 void EmitResultOfNamedOperand(const TreePatternNode *N,
126 SmallVectorImpl<unsigned> &ResultOps);
Chris Lattnerb49985a2010-02-18 06:47:49 +0000127 void EmitResultLeafAsOperand(const TreePatternNode *N,
Chris Lattner8e946be2010-02-21 03:22:59 +0000128 SmallVectorImpl<unsigned> &ResultOps);
Chris Lattnerb49985a2010-02-18 06:47:49 +0000129 void EmitResultInstructionAsOperand(const TreePatternNode *N,
Chris Lattner8e946be2010-02-21 03:22:59 +0000130 SmallVectorImpl<unsigned> &ResultOps);
131 void EmitResultSDNodeXFormAsOperand(const TreePatternNode *N,
132 SmallVectorImpl<unsigned> &ResultOps);
133 };
Chris Lattnerda272d12010-02-15 08:04:42 +0000134
135} // end anon namespace.
136
137MatcherGen::MatcherGen(const PatternToMatch &pattern,
138 const CodeGenDAGPatterns &cgp)
Chris Lattner853b9192010-02-19 00:33:13 +0000139: Pattern(pattern), CGP(cgp), NextRecordedOperandNo(0),
Chris Lattner8e946be2010-02-21 03:22:59 +0000140 EmittedMergeInputChains(false), Matcher(0), CurPredicate(0) {
Chris Lattnerda272d12010-02-15 08:04:42 +0000141 // We need to produce the matcher tree for the patterns source pattern. To do
142 // this we need to match the structure as well as the types. To do the type
143 // matching, we want to figure out the fewest number of type checks we need to
144 // emit. For example, if there is only one integer type supported by a
145 // target, there should be no type comparisons at all for integer patterns!
146 //
147 // To figure out the fewest number of type checks needed, clone the pattern,
148 // remove the types, then perform type inference on the pattern as a whole.
149 // If there are unresolved types, emit an explicit check for those types,
150 // apply the type to the tree, then rerun type inference. Iterate until all
151 // types are resolved.
152 //
153 PatWithNoTypes = Pattern.getSrcPattern()->clone();
154 PatWithNoTypes->RemoveAllTypes();
155
156 // If there are types that are manifestly known, infer them.
157 InferPossibleTypes();
158}
159
160/// InferPossibleTypes - As we emit the pattern, we end up generating type
161/// checks and applying them to the 'PatWithNoTypes' tree. As we do this, we
162/// want to propagate implied types as far throughout the tree as possible so
163/// that we avoid doing redundant type checks. This does the type propagation.
164void MatcherGen::InferPossibleTypes() {
165 // TP - Get *SOME* tree pattern, we don't care which. It is only used for
166 // diagnostics, which we know are impossible at this point.
167 TreePattern &TP = *CGP.pf_begin()->second;
168
169 try {
170 bool MadeChange = true;
171 while (MadeChange)
172 MadeChange = PatWithNoTypes->ApplyTypeConstraints(TP,
173 true/*Ignore reg constraints*/);
174 } catch (...) {
175 errs() << "Type constraint application shouldn't fail!";
176 abort();
177 }
178}
179
180
181/// AddMatcherNode - Add a matcher node to the current graph we're building.
Chris Lattner8ef9c792010-02-18 02:49:24 +0000182void MatcherGen::AddMatcherNode(MatcherNode *NewNode) {
Chris Lattnerda272d12010-02-15 08:04:42 +0000183 if (CurPredicate != 0)
Chris Lattnerbd8227f2010-02-18 02:53:41 +0000184 CurPredicate->setNext(NewNode);
Chris Lattnerda272d12010-02-15 08:04:42 +0000185 else
186 Matcher = NewNode;
187 CurPredicate = NewNode;
188}
189
190
Chris Lattnerb49985a2010-02-18 06:47:49 +0000191//===----------------------------------------------------------------------===//
192// Pattern Match Generation
193//===----------------------------------------------------------------------===//
Chris Lattnerda272d12010-02-15 08:04:42 +0000194
195/// EmitLeafMatchCode - Generate matching code for leaf nodes.
196void MatcherGen::EmitLeafMatchCode(const TreePatternNode *N) {
197 assert(N->isLeaf() && "Not a leaf?");
Chris Lattner8e946be2010-02-21 03:22:59 +0000198
199 // If there are node predicates for this node, generate their checks.
200 for (unsigned i = 0, e = N->getPredicateFns().size(); i != e; ++i)
201 AddMatcherNode(new CheckPredicateMatcherNode(N->getPredicateFns()[i]));
202
Chris Lattnerda272d12010-02-15 08:04:42 +0000203 // Direct match against an integer constant.
204 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue()))
205 return AddMatcherNode(new CheckIntegerMatcherNode(II->getValue()));
206
207 DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue());
208 if (DI == 0) {
209 errs() << "Unknown leaf kind: " << *DI << "\n";
210 abort();
211 }
212
213 Record *LeafRec = DI->getDef();
214 if (// Handle register references. Nothing to do here, they always match.
215 LeafRec->isSubClassOf("RegisterClass") ||
216 LeafRec->isSubClassOf("PointerLikeRegClass") ||
Chris Lattnerda272d12010-02-15 08:04:42 +0000217 // Place holder for SRCVALUE nodes. Nothing to do here.
218 LeafRec->getName() == "srcvalue")
219 return;
Chris Lattner8e946be2010-02-21 03:22:59 +0000220
221 // If we have a physreg reference like (mul gpr:$src, EAX) then we need to
222 // record the register
223 if (LeafRec->isSubClassOf("Register")) {
224 AddMatcherNode(new RecordMatcherNode("physreg input "+LeafRec->getName()));
225 PhysRegInputs.push_back(std::make_pair(LeafRec, NextRecordedOperandNo++));
226 return;
227 }
Chris Lattnerda272d12010-02-15 08:04:42 +0000228
229 if (LeafRec->isSubClassOf("ValueType"))
230 return AddMatcherNode(new CheckValueTypeMatcherNode(LeafRec->getName()));
231
232 if (LeafRec->isSubClassOf("CondCode"))
233 return AddMatcherNode(new CheckCondCodeMatcherNode(LeafRec->getName()));
234
235 if (LeafRec->isSubClassOf("ComplexPattern")) {
Chris Lattnerc2676b22010-02-17 00:11:30 +0000236 // We can't model ComplexPattern uses that don't have their name taken yet.
237 // The OPC_CheckComplexPattern operation implicitly records the results.
238 if (N->getName().empty()) {
Chris Lattner53a2f602010-02-16 23:16:25 +0000239 errs() << "We expect complex pattern uses to have names: " << *N << "\n";
240 exit(1);
241 }
Chris Lattner1f2ed5f2010-02-22 22:18:05 +0000242
Chris Lattnerda272d12010-02-15 08:04:42 +0000243 // Handle complex pattern.
244 const ComplexPattern &CP = CGP.getComplexPattern(LeafRec);
Chris Lattner1f2ed5f2010-02-22 22:18:05 +0000245
246 // If we're at the root of the pattern, we have to check that the opcode
247 // is a one of the ones requested to be matched.
248 if (N == Pattern.getSrcPattern()) {
249 const std::vector<Record*> &OpNodes = CP.getRootNodes();
250 if (OpNodes.size() == 1) {
251 StringRef OpName = CGP.getSDNodeInfo(OpNodes[0]).getEnumName();
252 AddMatcherNode(new CheckOpcodeMatcherNode(OpName));
253 } else if (!OpNodes.empty()) {
Chris Lattner12a667c2010-02-22 22:30:37 +0000254 SmallVector<StringRef, 4> OpNames;
255 for (unsigned i = 0, e = OpNodes.size(); i != e; i++)
256 OpNames.push_back(CGP.getSDNodeInfo(OpNodes[i]).getEnumName());
257 AddMatcherNode(new CheckMultiOpcodeMatcherNode(OpNames.data(),
258 OpNames.size()));
Chris Lattner1f2ed5f2010-02-22 22:18:05 +0000259 }
260 }
261
Chris Lattner20df2422010-02-22 23:33:44 +0000262 // Emit a CheckComplexPat operation, which does the match (aborting if it
263 // fails) and pushes the matched operands onto the recorded nodes list.
Chris Lattner8dc4f2b2010-02-17 06:08:25 +0000264 AddMatcherNode(new CheckComplexPatMatcherNode(CP));
265
Chris Lattner20df2422010-02-22 23:33:44 +0000266 // Record the right number of operands.
267 NextRecordedOperandNo += CP.getNumOperands();
268 if (CP.hasProperty(SDNPHasChain))
269 ++NextRecordedOperandNo; // Chained node operand.
270
Chris Lattner8dc4f2b2010-02-17 06:08:25 +0000271 // If the complex pattern has a chain, then we need to keep track of the
272 // fact that we just recorded a chain input. The chain input will be
273 // matched as the last operand of the predicate if it was successful.
274 if (CP.hasProperty(SDNPHasChain)) {
275 // It is the last operand recorded.
276 assert(NextRecordedOperandNo > 1 &&
277 "Should have recorded input/result chains at least!");
Chris Lattner8e946be2010-02-21 03:22:59 +0000278 MatchedChainNodes.push_back(NextRecordedOperandNo-1);
Chris Lattner9a747f12010-02-17 06:23:39 +0000279
Chris Lattner8e946be2010-02-21 03:22:59 +0000280 // If we need to check chains, do so, see comment for
Chris Lattner9a747f12010-02-17 06:23:39 +0000281 // "NodeHasProperty(SDNPHasChain" below.
Chris Lattner8e946be2010-02-21 03:22:59 +0000282 if (MatchedChainNodes.size() > 1) {
283 // FIXME2: This is broken, we should eliminate this nonsense completely,
Chris Lattner9a747f12010-02-17 06:23:39 +0000284 // but we want to produce the same selections that the old matcher does
285 // for now.
Chris Lattner8e946be2010-02-21 03:22:59 +0000286 unsigned PrevOp = MatchedChainNodes[MatchedChainNodes.size()-2];
Chris Lattner9a747f12010-02-17 06:23:39 +0000287 AddMatcherNode(new CheckChainCompatibleMatcherNode(PrevOp));
288 }
Chris Lattner8dc4f2b2010-02-17 06:08:25 +0000289 }
290 return;
Chris Lattnerda272d12010-02-15 08:04:42 +0000291 }
292
293 errs() << "Unknown leaf kind: " << *N << "\n";
294 abort();
295}
296
297void MatcherGen::EmitOperatorMatchCode(const TreePatternNode *N,
298 TreePatternNode *NodeNoTypes) {
299 assert(!N->isLeaf() && "Not an operator?");
300 const SDNodeInfo &CInfo = CGP.getSDNodeInfo(N->getOperator());
301
302 // If this is an 'and R, 1234' where the operation is AND/OR and the RHS is
303 // a constant without a predicate fn that has more that one bit set, handle
304 // this as a special case. This is usually for targets that have special
305 // handling of certain large constants (e.g. alpha with it's 8/16/32-bit
306 // handling stuff). Using these instructions is often far more efficient
307 // than materializing the constant. Unfortunately, both the instcombiner
308 // and the dag combiner can often infer that bits are dead, and thus drop
309 // them from the mask in the dag. For example, it might turn 'AND X, 255'
310 // into 'AND X, 254' if it knows the low bit is set. Emit code that checks
311 // to handle this.
312 if ((N->getOperator()->getName() == "and" ||
313 N->getOperator()->getName() == "or") &&
Chris Lattner8e946be2010-02-21 03:22:59 +0000314 N->getChild(1)->isLeaf() && N->getChild(1)->getPredicateFns().empty() &&
315 N->getPredicateFns().empty()) {
Chris Lattnerda272d12010-02-15 08:04:42 +0000316 if (IntInit *II = dynamic_cast<IntInit*>(N->getChild(1)->getLeafValue())) {
317 if (!isPowerOf2_32(II->getValue())) { // Don't bother with single bits.
318 if (N->getOperator()->getName() == "and")
319 AddMatcherNode(new CheckAndImmMatcherNode(II->getValue()));
320 else
321 AddMatcherNode(new CheckOrImmMatcherNode(II->getValue()));
322
323 // Match the LHS of the AND as appropriate.
324 AddMatcherNode(new MoveChildMatcherNode(0));
325 EmitMatchCode(N->getChild(0), NodeNoTypes->getChild(0));
326 AddMatcherNode(new MoveParentMatcherNode());
327 return;
328 }
329 }
330 }
331
332 // Check that the current opcode lines up.
333 AddMatcherNode(new CheckOpcodeMatcherNode(CInfo.getEnumName()));
334
Chris Lattner8e946be2010-02-21 03:22:59 +0000335 // If there are node predicates for this node, generate their checks.
336 for (unsigned i = 0, e = N->getPredicateFns().size(); i != e; ++i)
337 AddMatcherNode(new CheckPredicateMatcherNode(N->getPredicateFns()[i]));
338
339
340 // If this node has memory references (i.e. is a load or store), tell the
341 // interpreter to capture them in the memref array.
342 if (N->NodeHasProperty(SDNPMemOperand, CGP))
343 AddMatcherNode(new RecordMemRefMatcherNode());
344
Chris Lattnerda272d12010-02-15 08:04:42 +0000345 // If this node has a chain, then the chain is operand #0 is the SDNode, and
346 // the child numbers of the node are all offset by one.
347 unsigned OpNo = 0;
Chris Lattner6bc1b512010-02-16 19:19:58 +0000348 if (N->NodeHasProperty(SDNPHasChain, CGP)) {
Chris Lattner8e946be2010-02-21 03:22:59 +0000349 // Record the node and remember it in our chained nodes list.
Chris Lattner2f7ecde2010-02-17 01:34:15 +0000350 AddMatcherNode(new RecordMatcherNode("'" + N->getOperator()->getName() +
Chris Lattner8e946be2010-02-21 03:22:59 +0000351 "' chained node"));
Chris Lattner785d16f2010-02-17 02:16:19 +0000352 // Remember all of the input chains our pattern will match.
Chris Lattner8e946be2010-02-21 03:22:59 +0000353 MatchedChainNodes.push_back(NextRecordedOperandNo++);
Chris Lattner785d16f2010-02-17 02:16:19 +0000354
355 // If this is the second (e.g. indbr(load) or store(add(load))) or third
356 // input chain (e.g. (store (add (load, load))) from msp430) we need to make
357 // sure that folding the chain won't induce cycles in the DAG. This could
358 // happen if there were an intermediate node between the indbr and load, for
359 // example.
Chris Lattner8e946be2010-02-21 03:22:59 +0000360 if (MatchedChainNodes.size() > 1) {
361 // FIXME2: This is broken, we should eliminate this nonsense completely,
Chris Lattner9a747f12010-02-17 06:23:39 +0000362 // but we want to produce the same selections that the old matcher does
363 // for now.
Chris Lattner8e946be2010-02-21 03:22:59 +0000364 unsigned PrevOp = MatchedChainNodes[MatchedChainNodes.size()-2];
Chris Lattner9a747f12010-02-17 06:23:39 +0000365 AddMatcherNode(new CheckChainCompatibleMatcherNode(PrevOp));
366 }
Chris Lattner785d16f2010-02-17 02:16:19 +0000367
Chris Lattner2f7ecde2010-02-17 01:34:15 +0000368 // Don't look at the input chain when matching the tree pattern to the
369 // SDNode.
Chris Lattnerda272d12010-02-15 08:04:42 +0000370 OpNo = 1;
371
Chris Lattner6bc1b512010-02-16 19:19:58 +0000372 // If this node is not the root and the subtree underneath it produces a
373 // chain, then the result of matching the node is also produce a chain.
374 // Beyond that, this means that we're also folding (at least) the root node
375 // into the node that produce the chain (for example, matching
376 // "(add reg, (load ptr))" as a add_with_memory on X86). This is
377 // problematic, if the 'reg' node also uses the load (say, its chain).
378 // Graphically:
379 //
380 // [LD]
381 // ^ ^
382 // | \ DAG's like cheese.
383 // / |
384 // / [YY]
385 // | ^
386 // [XX]--/
387 //
388 // It would be invalid to fold XX and LD. In this case, folding the two
389 // nodes together would induce a cycle in the DAG, making it a 'cyclic DAG'
390 // To prevent this, we emit a dynamic check for legality before allowing
391 // this to be folded.
392 //
393 const TreePatternNode *Root = Pattern.getSrcPattern();
394 if (N != Root) { // Not the root of the pattern.
Chris Lattnere39650a2010-02-16 06:10:58 +0000395 // If there is a node between the root and this node, then we definitely
396 // need to emit the check.
397 bool NeedCheck = !Root->hasChild(N);
398
399 // If it *is* an immediate child of the root, we can still need a check if
400 // the root SDNode has multiple inputs. For us, this means that it is an
401 // intrinsic, has multiple operands, or has other inputs like chain or
402 // flag).
403 if (!NeedCheck) {
404 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(Root->getOperator());
405 NeedCheck =
406 Root->getOperator() == CGP.get_intrinsic_void_sdnode() ||
407 Root->getOperator() == CGP.get_intrinsic_w_chain_sdnode() ||
408 Root->getOperator() == CGP.get_intrinsic_wo_chain_sdnode() ||
409 PInfo.getNumOperands() > 1 ||
410 PInfo.hasProperty(SDNPHasChain) ||
411 PInfo.hasProperty(SDNPInFlag) ||
412 PInfo.hasProperty(SDNPOptInFlag);
413 }
414
415 if (NeedCheck)
Chris Lattner21390d72010-02-16 19:15:55 +0000416 AddMatcherNode(new CheckFoldableChainNodeMatcherNode());
Chris Lattnere39650a2010-02-16 06:10:58 +0000417 }
Chris Lattnerda272d12010-02-15 08:04:42 +0000418 }
Chris Lattner8e946be2010-02-21 03:22:59 +0000419
420 // If this node is known to have an input flag or if it *might* have an input
421 // flag, capture it as the flag input of the pattern.
422 if (N->NodeHasProperty(SDNPOptInFlag, CGP) ||
423 N->NodeHasProperty(SDNPInFlag, CGP))
424 AddMatcherNode(new CaptureFlagInputMatcherNode());
Chris Lattnerda272d12010-02-15 08:04:42 +0000425
Chris Lattnerda272d12010-02-15 08:04:42 +0000426 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
427 // Get the code suitable for matching this child. Move to the child, check
428 // it then move back to the parent.
Chris Lattnerc642b842010-02-17 01:27:29 +0000429 AddMatcherNode(new MoveChildMatcherNode(OpNo));
Chris Lattnerda272d12010-02-15 08:04:42 +0000430 EmitMatchCode(N->getChild(i), NodeNoTypes->getChild(i));
431 AddMatcherNode(new MoveParentMatcherNode());
432 }
433}
434
435
436void MatcherGen::EmitMatchCode(const TreePatternNode *N,
437 TreePatternNode *NodeNoTypes) {
438 // If N and NodeNoTypes don't agree on a type, then this is a case where we
439 // need to do a type check. Emit the check, apply the tyep to NodeNoTypes and
440 // reinfer any correlated types.
441 if (NodeNoTypes->getExtTypes() != N->getExtTypes()) {
442 AddMatcherNode(new CheckTypeMatcherNode(N->getTypeNum(0)));
443 NodeNoTypes->setTypes(N->getExtTypes());
444 InferPossibleTypes();
445 }
446
Chris Lattnerda272d12010-02-15 08:04:42 +0000447 // If this node has a name associated with it, capture it in VariableMap. If
448 // we already saw this in the pattern, emit code to verify dagness.
449 if (!N->getName().empty()) {
450 unsigned &VarMapEntry = VariableMap[N->getName()];
451 if (VarMapEntry == 0) {
Chris Lattner20df2422010-02-22 23:33:44 +0000452 // If it is a named node, we must emit a 'Record' opcode.
453 VarMapEntry = ++NextRecordedOperandNo;
454 AddMatcherNode(new RecordMatcherNode("$" + N->getName()));
Chris Lattnerda272d12010-02-15 08:04:42 +0000455 } else {
456 // If we get here, this is a second reference to a specific name. Since
457 // we already have checked that the first reference is valid, we don't
458 // have to recursively match it, just check that it's the same as the
459 // previously named thing.
460 AddMatcherNode(new CheckSameMatcherNode(VarMapEntry-1));
461 return;
462 }
463 }
464
Chris Lattnerda272d12010-02-15 08:04:42 +0000465 if (N->isLeaf())
466 EmitLeafMatchCode(N);
467 else
468 EmitOperatorMatchCode(N, NodeNoTypes);
469}
470
471void MatcherGen::EmitMatcherCode() {
472 // If the pattern has a predicate on it (e.g. only enabled when a subtarget
473 // feature is around, do the check).
474 if (!Pattern.getPredicateCheck().empty())
475 AddMatcherNode(new
476 CheckPatternPredicateMatcherNode(Pattern.getPredicateCheck()));
477
478 // Emit the matcher for the pattern structure and types.
479 EmitMatchCode(Pattern.getSrcPattern(), PatWithNoTypes);
480}
481
482
Chris Lattnerb49985a2010-02-18 06:47:49 +0000483//===----------------------------------------------------------------------===//
484// Node Result Generation
485//===----------------------------------------------------------------------===//
486
Chris Lattner8e946be2010-02-21 03:22:59 +0000487void MatcherGen::EmitResultOfNamedOperand(const TreePatternNode *N,
488 SmallVectorImpl<unsigned> &ResultOps){
489 assert(!N->getName().empty() && "Operand not named!");
490
491 unsigned SlotNo = getNamedArgumentSlot(N->getName());
492
493 // A reference to a complex pattern gets all of the results of the complex
494 // pattern's match.
495 if (const ComplexPattern *CP = N->getComplexPatternInfo(CGP)) {
Chris Lattner20df2422010-02-22 23:33:44 +0000496 // The first slot entry is the node itself, the subsequent entries are the
497 // matched values.
Chris Lattner8e946be2010-02-21 03:22:59 +0000498 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
Chris Lattner20df2422010-02-22 23:33:44 +0000499 ResultOps.push_back(SlotNo+i+1);
Chris Lattner8e946be2010-02-21 03:22:59 +0000500 return;
501 }
502
503 // If this is an 'imm' or 'fpimm' node, make sure to convert it to the target
504 // version of the immediate so that it doesn't get selected due to some other
505 // node use.
506 if (!N->isLeaf()) {
507 StringRef OperatorName = N->getOperator()->getName();
508 if (OperatorName == "imm" || OperatorName == "fpimm") {
509 AddMatcherNode(new EmitConvertToTargetMatcherNode(SlotNo));
510 ResultOps.push_back(NextRecordedOperandNo++);
511 return;
512 }
513 }
514
515 ResultOps.push_back(SlotNo);
516}
517
Chris Lattnerb49985a2010-02-18 06:47:49 +0000518void MatcherGen::EmitResultLeafAsOperand(const TreePatternNode *N,
Chris Lattner8e946be2010-02-21 03:22:59 +0000519 SmallVectorImpl<unsigned> &ResultOps) {
Chris Lattner845c0422010-02-18 22:03:03 +0000520 assert(N->isLeaf() && "Must be a leaf");
521
522 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
523 AddMatcherNode(new EmitIntegerMatcherNode(II->getValue(),N->getTypeNum(0)));
Chris Lattner8e946be2010-02-21 03:22:59 +0000524 ResultOps.push_back(NextRecordedOperandNo++);
Chris Lattner845c0422010-02-18 22:03:03 +0000525 return;
526 }
527
528 // If this is an explicit register reference, handle it.
529 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
530 if (DI->getDef()->isSubClassOf("Register")) {
531 AddMatcherNode(new EmitRegisterMatcherNode(DI->getDef(),
532 N->getTypeNum(0)));
Chris Lattner8e946be2010-02-21 03:22:59 +0000533 ResultOps.push_back(NextRecordedOperandNo++);
Chris Lattner845c0422010-02-18 22:03:03 +0000534 return;
535 }
536
537 if (DI->getDef()->getName() == "zero_reg") {
538 AddMatcherNode(new EmitRegisterMatcherNode(0, N->getTypeNum(0)));
Chris Lattner8e946be2010-02-21 03:22:59 +0000539 ResultOps.push_back(NextRecordedOperandNo++);
Chris Lattner845c0422010-02-18 22:03:03 +0000540 return;
541 }
542
Chris Lattner8e946be2010-02-21 03:22:59 +0000543 // Handle a reference to a register class. This is used
544 // in COPY_TO_SUBREG instructions.
Chris Lattner845c0422010-02-18 22:03:03 +0000545 if (DI->getDef()->isSubClassOf("RegisterClass")) {
Chris Lattner8e946be2010-02-21 03:22:59 +0000546 std::string Value = getQualifiedName(DI->getDef()) + "RegClassID";
Chris Lattner664012b2010-02-21 20:53:45 +0000547 AddMatcherNode(new EmitStringIntegerMatcherNode(Value, MVT::i32));
Chris Lattner8e946be2010-02-21 03:22:59 +0000548 ResultOps.push_back(NextRecordedOperandNo++);
549 return;
Chris Lattner845c0422010-02-18 22:03:03 +0000550 }
Chris Lattner845c0422010-02-18 22:03:03 +0000551 }
552
Chris Lattnerb49985a2010-02-18 06:47:49 +0000553 errs() << "unhandled leaf node: \n";
554 N->dump();
555}
556
Chris Lattner8e946be2010-02-21 03:22:59 +0000557/// GetInstPatternNode - Get the pattern for an instruction.
558///
559const TreePatternNode *MatcherGen::
560GetInstPatternNode(const DAGInstruction &Inst, const TreePatternNode *N) {
561 const TreePattern *InstPat = Inst.getPattern();
562
563 // FIXME2?: Assume actual pattern comes before "implicit".
564 TreePatternNode *InstPatNode;
565 if (InstPat)
566 InstPatNode = InstPat->getTree(0);
567 else if (/*isRoot*/ N == Pattern.getDstPattern())
568 InstPatNode = Pattern.getSrcPattern();
569 else
570 return 0;
571
572 if (InstPatNode && !InstPatNode->isLeaf() &&
573 InstPatNode->getOperator()->getName() == "set")
574 InstPatNode = InstPatNode->getChild(InstPatNode->getNumChildren()-1);
575
576 return InstPatNode;
577}
578
579void MatcherGen::
580EmitResultInstructionAsOperand(const TreePatternNode *N,
581 SmallVectorImpl<unsigned> &OutputOps) {
Chris Lattnerb49985a2010-02-18 06:47:49 +0000582 Record *Op = N->getOperator();
583 const CodeGenTarget &CGT = CGP.getTargetInfo();
584 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
585 const DAGInstruction &Inst = CGP.getInstruction(Op);
586
Chris Lattner8e946be2010-02-21 03:22:59 +0000587 // If we can, get the pattern for the instruction we're generating. We derive
588 // a variety of information from this pattern, such as whether it has a chain.
589 //
590 // FIXME2: This is extremely dubious for several reasons, not the least of
591 // which it gives special status to instructions with patterns that Pat<>
592 // nodes can't duplicate.
593 const TreePatternNode *InstPatNode = GetInstPatternNode(Inst, N);
594
595 // NodeHasChain - Whether the instruction node we're creating takes chains.
596 bool NodeHasChain = InstPatNode &&
597 InstPatNode->TreeHasProperty(SDNPHasChain, CGP);
Chris Lattnerb49985a2010-02-18 06:47:49 +0000598
Chris Lattner8e946be2010-02-21 03:22:59 +0000599 bool isRoot = N == Pattern.getDstPattern();
600
601 // NodeHasOutFlag - True if this node has a flag.
602 bool NodeHasInFlag = false, NodeHasOutFlag = false;
603 if (isRoot) {
604 const TreePatternNode *SrcPat = Pattern.getSrcPattern();
605 NodeHasInFlag = SrcPat->TreeHasProperty(SDNPOptInFlag, CGP) ||
606 SrcPat->TreeHasProperty(SDNPInFlag, CGP);
607
608 // FIXME2: this is checking the entire pattern, not just the node in
609 // question, doing this just for the root seems like a total hack.
610 NodeHasOutFlag = SrcPat->TreeHasProperty(SDNPOutFlag, CGP);
611 }
612
613 // NumResults - This is the number of results produced by the instruction in
614 // the "outs" list.
Chris Lattnerb49985a2010-02-18 06:47:49 +0000615 unsigned NumResults = Inst.getNumResults();
616
Chris Lattnerb49985a2010-02-18 06:47:49 +0000617 // Loop over all of the operands of the instruction pattern, emitting code
618 // to fill them all in. The node 'N' usually has number children equal to
619 // the number of input operands of the instruction. However, in cases
620 // where there are predicate operands for an instruction, we need to fill
621 // in the 'execute always' values. Match up the node operands to the
622 // instruction operands to do this.
Chris Lattner8e946be2010-02-21 03:22:59 +0000623 SmallVector<unsigned, 8> InstOps;
Chris Lattnerb49985a2010-02-18 06:47:49 +0000624 for (unsigned ChildNo = 0, InstOpNo = NumResults, e = II.OperandList.size();
625 InstOpNo != e; ++InstOpNo) {
626
627 // Determine what to emit for this operand.
628 Record *OperandNode = II.OperandList[InstOpNo].Rec;
629 if ((OperandNode->isSubClassOf("PredicateOperand") ||
630 OperandNode->isSubClassOf("OptionalDefOperand")) &&
631 !CGP.getDefaultOperand(OperandNode).DefaultOps.empty()) {
632 // This is a predicate or optional def operand; emit the
633 // 'default ops' operands.
634 const DAGDefaultOperand &DefaultOp =
635 CGP.getDefaultOperand(II.OperandList[InstOpNo].Rec);
636 for (unsigned i = 0, e = DefaultOp.DefaultOps.size(); i != e; ++i)
Chris Lattner8e946be2010-02-21 03:22:59 +0000637 EmitResultOperand(DefaultOp.DefaultOps[i], InstOps);
Chris Lattnerb49985a2010-02-18 06:47:49 +0000638 continue;
639 }
640
641 // Otherwise this is a normal operand or a predicate operand without
642 // 'execute always'; emit it.
Chris Lattner8e946be2010-02-21 03:22:59 +0000643 EmitResultOperand(N->getChild(ChildNo), InstOps);
Chris Lattnerb49985a2010-02-18 06:47:49 +0000644 ++ChildNo;
645 }
646
Chris Lattner8e946be2010-02-21 03:22:59 +0000647 // Nodes that match patterns with (potentially multiple) chain inputs have to
648 // merge them together into a token factor.
649 if (NodeHasChain && !EmittedMergeInputChains) {
650 // FIXME2: Move this out of emitresult to a top level place.
651 assert(!MatchedChainNodes.empty() &&
652 "How can this node have chain if no inputs do?");
653 // Otherwise, we have to emit an operation to merge the input chains and
654 // set this as the current input chain.
655 AddMatcherNode(new EmitMergeInputChainsMatcherNode
656 (MatchedChainNodes.data(), MatchedChainNodes.size()));
657 EmittedMergeInputChains = true;
658 }
659
660 // If this node has an input flag or explicitly specified input physregs, we
661 // need to add chained and flagged copyfromreg nodes and materialize the flag
662 // input.
663 if (isRoot && !PhysRegInputs.empty()) {
664 // Emit all of the CopyToReg nodes for the input physical registers. These
665 // occur in patterns like (mul:i8 AL:i8, GR8:i8:$src).
666 for (unsigned i = 0, e = PhysRegInputs.size(); i != e; ++i)
667 AddMatcherNode(new EmitCopyToRegMatcherNode(PhysRegInputs[i].second,
668 PhysRegInputs[i].first));
669 // Even if the node has no other flag inputs, the resultant node must be
670 // flagged to the CopyFromReg nodes we just generated.
671 NodeHasInFlag = true;
672 }
673
674 // Result order: node results, chain, flags
675
676 // Determine the result types.
677 SmallVector<MVT::SimpleValueType, 4> ResultVTs;
Chris Lattner565a6f92010-02-21 23:54:05 +0000678 if (NumResults != 0 && N->getTypeNum(0) != MVT::isVoid) {
Chris Lattner8e946be2010-02-21 03:22:59 +0000679 // FIXME2: If the node has multiple results, we should add them. For now,
680 // preserve existing behavior?!
681 ResultVTs.push_back(N->getTypeNum(0));
682 }
683
684
685 // If this is the root instruction of a pattern that has physical registers in
686 // its result pattern, add output VTs for them. For example, X86 has:
687 // (set AL, (mul ...))
688 // This also handles implicit results like:
689 // (implicit EFLAGS)
690 if (isRoot && Pattern.getDstRegs().size() != 0) {
691 for (unsigned i = 0; i != Pattern.getDstRegs().size(); ++i)
692 if (Pattern.getDstRegs()[i]->isSubClassOf("Register"))
693 ResultVTs.push_back(getRegisterValueType(Pattern.getDstRegs()[i], CGT));
694 }
695 if (NodeHasChain)
696 ResultVTs.push_back(MVT::Other);
697 if (NodeHasOutFlag)
698 ResultVTs.push_back(MVT::Flag);
699
700 // FIXME2: Instead of using the isVariadic flag on the instruction, we should
701 // have an SDNP that indicates variadicism. The TargetInstrInfo isVariadic
702 // property should be inferred from this when an instruction has a pattern.
703 int NumFixedArityOperands = -1;
704 if (isRoot && II.isVariadic)
705 NumFixedArityOperands = Pattern.getSrcPattern()->getNumChildren();
706
707 // If this is the root node and any of the nodes matched nodes in the input
708 // pattern have MemRefs in them, have the interpreter collect them and plop
709 // them onto this node.
710 //
711 // FIXME3: This is actively incorrect for result patterns where the root of
712 // the pattern is not the memory reference and is also incorrect when the
713 // result pattern has multiple memory-referencing instructions. For example,
714 // in the X86 backend, this pattern causes the memrefs to get attached to the
715 // CVTSS2SDrr instead of the MOVSSrm:
716 //
717 // def : Pat<(extloadf32 addr:$src),
718 // (CVTSS2SDrr (MOVSSrm addr:$src))>;
719 //
720 bool NodeHasMemRefs =
721 isRoot && Pattern.getSrcPattern()->TreeHasProperty(SDNPMemOperand, CGP);
722
723 // FIXME: Eventually add a SelectNodeTo form. It works if the new node has a
724 // superset of the results of the old node, in the same places. E.g. turning
725 // (add (load)) -> add32rm is ok because result #0 is the result and result #1
726 // is new.
727 AddMatcherNode(new EmitNodeMatcherNode(II.Namespace+"::"+II.TheDef->getName(),
728 ResultVTs.data(), ResultVTs.size(),
729 InstOps.data(), InstOps.size(),
730 NodeHasChain, NodeHasInFlag,
731 NodeHasMemRefs,NumFixedArityOperands));
732
Chris Lattner565a6f92010-02-21 23:54:05 +0000733 // The non-chain and non-flag results of the newly emitted node get recorded.
734 for (unsigned i = 0, e = ResultVTs.size(); i != e; ++i) {
735 if (ResultVTs[i] == MVT::Other || ResultVTs[i] == MVT::Flag) break;
Chris Lattner77f2e272010-02-21 06:03:07 +0000736 OutputOps.push_back(NextRecordedOperandNo++);
Chris Lattner565a6f92010-02-21 23:54:05 +0000737 }
Chris Lattnerb49985a2010-02-18 06:47:49 +0000738
Chris Lattner8e946be2010-02-21 03:22:59 +0000739 // FIXME2: Kill off all the SelectionDAG::SelectNodeTo and getMachineNode
740 // variants. Call MorphNodeTo instead of SelectNodeTo.
741}
742
743void MatcherGen::
744EmitResultSDNodeXFormAsOperand(const TreePatternNode *N,
745 SmallVectorImpl<unsigned> &ResultOps) {
746 assert(N->getOperator()->isSubClassOf("SDNodeXForm") && "Not SDNodeXForm?");
747
748 // Emit the operand.
749 SmallVector<unsigned, 8> InputOps;
Chris Lattnerb49985a2010-02-18 06:47:49 +0000750
Chris Lattner8e946be2010-02-21 03:22:59 +0000751 // FIXME2: Could easily generalize this to support multiple inputs and outputs
752 // to the SDNodeXForm. For now we just support one input and one output like
753 // the old instruction selector.
754 assert(N->getNumChildren() == 1);
755 EmitResultOperand(N->getChild(0), InputOps);
756
757 // The input currently must have produced exactly one result.
758 assert(InputOps.size() == 1 && "Unexpected input to SDNodeXForm");
759
760 AddMatcherNode(new EmitNodeXFormMatcherNode(InputOps[0], N->getOperator()));
761 ResultOps.push_back(NextRecordedOperandNo++);
Chris Lattnerb49985a2010-02-18 06:47:49 +0000762}
763
764void MatcherGen::EmitResultOperand(const TreePatternNode *N,
Chris Lattner8e946be2010-02-21 03:22:59 +0000765 SmallVectorImpl<unsigned> &ResultOps) {
Chris Lattnerb49985a2010-02-18 06:47:49 +0000766 // This is something selected from the pattern we matched.
Chris Lattner8e946be2010-02-21 03:22:59 +0000767 if (!N->getName().empty())
768 return EmitResultOfNamedOperand(N, ResultOps);
Chris Lattnerb49985a2010-02-18 06:47:49 +0000769
770 if (N->isLeaf())
771 return EmitResultLeafAsOperand(N, ResultOps);
772
773 Record *OpRec = N->getOperator();
774 if (OpRec->isSubClassOf("Instruction"))
775 return EmitResultInstructionAsOperand(N, ResultOps);
776 if (OpRec->isSubClassOf("SDNodeXForm"))
Chris Lattner8e946be2010-02-21 03:22:59 +0000777 return EmitResultSDNodeXFormAsOperand(N, ResultOps);
Chris Lattnerb49985a2010-02-18 06:47:49 +0000778 errs() << "Unknown result node to emit code for: " << *N << '\n';
779 throw std::string("Unknown node in result pattern!");
780}
781
782void MatcherGen::EmitResultCode() {
Chris Lattner565a6f92010-02-21 23:54:05 +0000783 // Codegen the root of the result pattern, capturing the resulting values.
Chris Lattner8e946be2010-02-21 03:22:59 +0000784 SmallVector<unsigned, 8> Ops;
Chris Lattnerb49985a2010-02-18 06:47:49 +0000785 EmitResultOperand(Pattern.getDstPattern(), Ops);
Chris Lattner8e946be2010-02-21 03:22:59 +0000786
Chris Lattner565a6f92010-02-21 23:54:05 +0000787 // At this point, we have however many values the result pattern produces.
788 // However, the input pattern might not need all of these. If there are
789 // excess values at the end (such as condition codes etc) just lop them off.
790 // This doesn't need to worry about flags or chains, just explicit results.
791 //
792 // FIXME2: This doesn't work because there is currently no way to get an
793 // accurate count of the # results the source pattern sets. This is because
794 // of the "parallel" construct in X86 land, which looks like this:
795 //
796 //def : Pat<(parallel (X86and_flag GR8:$src1, GR8:$src2),
797 // (implicit EFLAGS)),
798 // (AND8rr GR8:$src1, GR8:$src2)>;
799 //
800 // This idiom means to match the two-result node X86and_flag (which is
801 // declared as returning a single result, because we can't match multi-result
802 // nodes yet). In this case, we would have to know that the input has two
803 // results. However, mul8r is modelled exactly the same way, but without
804 // implicit defs included. The fix is to support multiple results directly
805 // and eliminate 'parallel'.
806 //
807 // FIXME2: When this is fixed, we should revert the terrible hack in the
808 // OPC_EmitNode code in the interpreter.
809#if 0
810 const TreePatternNode *Src = Pattern.getSrcPattern();
811 unsigned NumSrcResults = Src->getTypeNum(0) != MVT::isVoid ? 1 : 0;
812 NumSrcResults += Pattern.getDstRegs().size();
813 assert(Ops.size() >= NumSrcResults && "Didn't provide enough results");
814 Ops.resize(NumSrcResults);
815#endif
816
Chris Lattner8e946be2010-02-21 03:22:59 +0000817 // We know that the resulting pattern has exactly one result/
818 // FIXME2: why? what about something like (set a,b,c, (complexpat))
819 // FIXME2: Implicit results should be pushed here I guess?
Chris Lattner77f2e272010-02-21 06:03:07 +0000820 AddMatcherNode(new CompleteMatchMatcherNode(Ops.data(), Ops.size(), Pattern));
Chris Lattnerb49985a2010-02-18 06:47:49 +0000821}
822
823
Chris Lattnerda272d12010-02-15 08:04:42 +0000824MatcherNode *llvm::ConvertPatternToMatcher(const PatternToMatch &Pattern,
825 const CodeGenDAGPatterns &CGP) {
826 MatcherGen Gen(Pattern, CGP);
827
828 // Generate the code for the matcher.
829 Gen.EmitMatcherCode();
830
Chris Lattner8e946be2010-02-21 03:22:59 +0000831
832 // FIXME2: Kill extra MoveParent commands at the end of the matcher sequence.
833 // FIXME2: Split result code out to another table, and make the matcher end
834 // with an "Emit <index>" command. This allows result generation stuff to be
835 // shared and factored?
836
Chris Lattnerda272d12010-02-15 08:04:42 +0000837 // If the match succeeds, then we generate Pattern.
Chris Lattnerb49985a2010-02-18 06:47:49 +0000838 Gen.EmitResultCode();
Chris Lattnerda272d12010-02-15 08:04:42 +0000839
840 // Unconditional match.
Chris Lattnerb49985a2010-02-18 06:47:49 +0000841 return Gen.GetMatcher();
Chris Lattnerda272d12010-02-15 08:04:42 +0000842}
843
844
845