blob: 53f248e69233740da11802cb26d0ff3a5b8e20c8 [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"
15using namespace llvm;
16
17namespace {
18 class MatcherGen {
19 const PatternToMatch &Pattern;
20 const CodeGenDAGPatterns &CGP;
21
22 /// PatWithNoTypes - This is a clone of Pattern.getSrcPattern() that starts
23 /// out with all of the types removed. This allows us to insert type checks
24 /// as we scan the tree.
25 TreePatternNode *PatWithNoTypes;
26
27 /// VariableMap - A map from variable names ('$dst') to the recorded operand
28 /// number that they were captured as. These are biased by 1 to make
29 /// insertion easier.
30 StringMap<unsigned> VariableMap;
31 unsigned NextRecordedOperandNo;
32
Chris Lattner785d16f2010-02-17 02:16:19 +000033 /// InputChains - This maintains the position in the recorded nodes array of
34 /// all of the recorded input chains.
35 SmallVector<unsigned, 2> InputChains;
36
37 /// Matcher - This is the top level of the generated matcher, the result.
Chris Lattner8ef9c792010-02-18 02:49:24 +000038 MatcherNode *Matcher;
Chris Lattner785d16f2010-02-17 02:16:19 +000039
40 /// CurPredicate - As we emit matcher nodes, this points to the latest check
Chris Lattnerbd8227f2010-02-18 02:53:41 +000041 /// which should have future checks stuck into its Next position.
Chris Lattner8ef9c792010-02-18 02:49:24 +000042 MatcherNode *CurPredicate;
Chris Lattnerda272d12010-02-15 08:04:42 +000043 public:
44 MatcherGen(const PatternToMatch &pattern, const CodeGenDAGPatterns &cgp);
45
46 ~MatcherGen() {
47 delete PatWithNoTypes;
48 }
49
50 void EmitMatcherCode();
51
Chris Lattner8ef9c792010-02-18 02:49:24 +000052 MatcherNode *GetMatcher() const { return Matcher; }
53 MatcherNode *GetCurPredicate() const { return CurPredicate; }
Chris Lattnerda272d12010-02-15 08:04:42 +000054 private:
Chris Lattner8ef9c792010-02-18 02:49:24 +000055 void AddMatcherNode(MatcherNode *NewNode);
Chris Lattnerda272d12010-02-15 08:04:42 +000056 void InferPossibleTypes();
57 void EmitMatchCode(const TreePatternNode *N, TreePatternNode *NodeNoTypes);
58 void EmitLeafMatchCode(const TreePatternNode *N);
59 void EmitOperatorMatchCode(const TreePatternNode *N,
60 TreePatternNode *NodeNoTypes);
61 };
62
63} // end anon namespace.
64
65MatcherGen::MatcherGen(const PatternToMatch &pattern,
66 const CodeGenDAGPatterns &cgp)
67: Pattern(pattern), CGP(cgp), NextRecordedOperandNo(0),
68 Matcher(0), CurPredicate(0) {
69 // We need to produce the matcher tree for the patterns source pattern. To do
70 // this we need to match the structure as well as the types. To do the type
71 // matching, we want to figure out the fewest number of type checks we need to
72 // emit. For example, if there is only one integer type supported by a
73 // target, there should be no type comparisons at all for integer patterns!
74 //
75 // To figure out the fewest number of type checks needed, clone the pattern,
76 // remove the types, then perform type inference on the pattern as a whole.
77 // If there are unresolved types, emit an explicit check for those types,
78 // apply the type to the tree, then rerun type inference. Iterate until all
79 // types are resolved.
80 //
81 PatWithNoTypes = Pattern.getSrcPattern()->clone();
82 PatWithNoTypes->RemoveAllTypes();
83
84 // If there are types that are manifestly known, infer them.
85 InferPossibleTypes();
86}
87
88/// InferPossibleTypes - As we emit the pattern, we end up generating type
89/// checks and applying them to the 'PatWithNoTypes' tree. As we do this, we
90/// want to propagate implied types as far throughout the tree as possible so
91/// that we avoid doing redundant type checks. This does the type propagation.
92void MatcherGen::InferPossibleTypes() {
93 // TP - Get *SOME* tree pattern, we don't care which. It is only used for
94 // diagnostics, which we know are impossible at this point.
95 TreePattern &TP = *CGP.pf_begin()->second;
96
97 try {
98 bool MadeChange = true;
99 while (MadeChange)
100 MadeChange = PatWithNoTypes->ApplyTypeConstraints(TP,
101 true/*Ignore reg constraints*/);
102 } catch (...) {
103 errs() << "Type constraint application shouldn't fail!";
104 abort();
105 }
106}
107
108
109/// AddMatcherNode - Add a matcher node to the current graph we're building.
Chris Lattner8ef9c792010-02-18 02:49:24 +0000110void MatcherGen::AddMatcherNode(MatcherNode *NewNode) {
Chris Lattnerda272d12010-02-15 08:04:42 +0000111 if (CurPredicate != 0)
Chris Lattnerbd8227f2010-02-18 02:53:41 +0000112 CurPredicate->setNext(NewNode);
Chris Lattnerda272d12010-02-15 08:04:42 +0000113 else
114 Matcher = NewNode;
115 CurPredicate = NewNode;
116}
117
118
119
120/// EmitLeafMatchCode - Generate matching code for leaf nodes.
121void MatcherGen::EmitLeafMatchCode(const TreePatternNode *N) {
122 assert(N->isLeaf() && "Not a leaf?");
123 // Direct match against an integer constant.
124 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue()))
125 return AddMatcherNode(new CheckIntegerMatcherNode(II->getValue()));
126
127 DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue());
128 if (DI == 0) {
129 errs() << "Unknown leaf kind: " << *DI << "\n";
130 abort();
131 }
132
133 Record *LeafRec = DI->getDef();
134 if (// Handle register references. Nothing to do here, they always match.
135 LeafRec->isSubClassOf("RegisterClass") ||
136 LeafRec->isSubClassOf("PointerLikeRegClass") ||
137 LeafRec->isSubClassOf("Register") ||
138 // Place holder for SRCVALUE nodes. Nothing to do here.
139 LeafRec->getName() == "srcvalue")
140 return;
141
142 if (LeafRec->isSubClassOf("ValueType"))
143 return AddMatcherNode(new CheckValueTypeMatcherNode(LeafRec->getName()));
144
145 if (LeafRec->isSubClassOf("CondCode"))
146 return AddMatcherNode(new CheckCondCodeMatcherNode(LeafRec->getName()));
147
148 if (LeafRec->isSubClassOf("ComplexPattern")) {
Chris Lattnerc2676b22010-02-17 00:11:30 +0000149 // We can't model ComplexPattern uses that don't have their name taken yet.
150 // The OPC_CheckComplexPattern operation implicitly records the results.
151 if (N->getName().empty()) {
Chris Lattner53a2f602010-02-16 23:16:25 +0000152 errs() << "We expect complex pattern uses to have names: " << *N << "\n";
153 exit(1);
154 }
155
Chris Lattnerda272d12010-02-15 08:04:42 +0000156 // Handle complex pattern.
157 const ComplexPattern &CP = CGP.getComplexPattern(LeafRec);
Chris Lattner8dc4f2b2010-02-17 06:08:25 +0000158 AddMatcherNode(new CheckComplexPatMatcherNode(CP));
159
160 // If the complex pattern has a chain, then we need to keep track of the
161 // fact that we just recorded a chain input. The chain input will be
162 // matched as the last operand of the predicate if it was successful.
163 if (CP.hasProperty(SDNPHasChain)) {
164 // It is the last operand recorded.
165 assert(NextRecordedOperandNo > 1 &&
166 "Should have recorded input/result chains at least!");
167 InputChains.push_back(NextRecordedOperandNo-1);
Chris Lattner9a747f12010-02-17 06:23:39 +0000168
169 // IF we need to check chains, do so, see comment for
170 // "NodeHasProperty(SDNPHasChain" below.
171 if (InputChains.size() > 1) {
172 // FIXME: This is broken, we should eliminate this nonsense completely,
173 // but we want to produce the same selections that the old matcher does
174 // for now.
175 unsigned PrevOp = InputChains[InputChains.size()-2];
176 AddMatcherNode(new CheckChainCompatibleMatcherNode(PrevOp));
177 }
Chris Lattner8dc4f2b2010-02-17 06:08:25 +0000178 }
179 return;
Chris Lattnerda272d12010-02-15 08:04:42 +0000180 }
181
182 errs() << "Unknown leaf kind: " << *N << "\n";
183 abort();
184}
185
186void MatcherGen::EmitOperatorMatchCode(const TreePatternNode *N,
187 TreePatternNode *NodeNoTypes) {
188 assert(!N->isLeaf() && "Not an operator?");
189 const SDNodeInfo &CInfo = CGP.getSDNodeInfo(N->getOperator());
190
191 // If this is an 'and R, 1234' where the operation is AND/OR and the RHS is
192 // a constant without a predicate fn that has more that one bit set, handle
193 // this as a special case. This is usually for targets that have special
194 // handling of certain large constants (e.g. alpha with it's 8/16/32-bit
195 // handling stuff). Using these instructions is often far more efficient
196 // than materializing the constant. Unfortunately, both the instcombiner
197 // and the dag combiner can often infer that bits are dead, and thus drop
198 // them from the mask in the dag. For example, it might turn 'AND X, 255'
199 // into 'AND X, 254' if it knows the low bit is set. Emit code that checks
200 // to handle this.
201 if ((N->getOperator()->getName() == "and" ||
202 N->getOperator()->getName() == "or") &&
203 N->getChild(1)->isLeaf() && N->getChild(1)->getPredicateFns().empty()) {
204 if (IntInit *II = dynamic_cast<IntInit*>(N->getChild(1)->getLeafValue())) {
205 if (!isPowerOf2_32(II->getValue())) { // Don't bother with single bits.
206 if (N->getOperator()->getName() == "and")
207 AddMatcherNode(new CheckAndImmMatcherNode(II->getValue()));
208 else
209 AddMatcherNode(new CheckOrImmMatcherNode(II->getValue()));
210
211 // Match the LHS of the AND as appropriate.
212 AddMatcherNode(new MoveChildMatcherNode(0));
213 EmitMatchCode(N->getChild(0), NodeNoTypes->getChild(0));
214 AddMatcherNode(new MoveParentMatcherNode());
215 return;
216 }
217 }
218 }
219
220 // Check that the current opcode lines up.
221 AddMatcherNode(new CheckOpcodeMatcherNode(CInfo.getEnumName()));
222
223 // If this node has a chain, then the chain is operand #0 is the SDNode, and
224 // the child numbers of the node are all offset by one.
225 unsigned OpNo = 0;
Chris Lattner6bc1b512010-02-16 19:19:58 +0000226 if (N->NodeHasProperty(SDNPHasChain, CGP)) {
Chris Lattner2f7ecde2010-02-17 01:34:15 +0000227 // Record the input chain, which is always input #0 of the SDNode.
228 AddMatcherNode(new MoveChildMatcherNode(0));
Chris Lattner2f7ecde2010-02-17 01:34:15 +0000229 AddMatcherNode(new RecordMatcherNode("'" + N->getOperator()->getName() +
230 "' input chain"));
Chris Lattner785d16f2010-02-17 02:16:19 +0000231
232 // Remember all of the input chains our pattern will match.
233 InputChains.push_back(NextRecordedOperandNo);
234 ++NextRecordedOperandNo;
Chris Lattner2f7ecde2010-02-17 01:34:15 +0000235 AddMatcherNode(new MoveParentMatcherNode());
Chris Lattner785d16f2010-02-17 02:16:19 +0000236
237 // If this is the second (e.g. indbr(load) or store(add(load))) or third
238 // input chain (e.g. (store (add (load, load))) from msp430) we need to make
239 // sure that folding the chain won't induce cycles in the DAG. This could
240 // happen if there were an intermediate node between the indbr and load, for
241 // example.
Chris Lattner9a747f12010-02-17 06:23:39 +0000242 if (InputChains.size() > 1) {
243 // FIXME: This is broken, we should eliminate this nonsense completely,
244 // but we want to produce the same selections that the old matcher does
245 // for now.
246 unsigned PrevOp = InputChains[InputChains.size()-2];
247 AddMatcherNode(new CheckChainCompatibleMatcherNode(PrevOp));
248 }
Chris Lattner785d16f2010-02-17 02:16:19 +0000249
Chris Lattner2f7ecde2010-02-17 01:34:15 +0000250 // Don't look at the input chain when matching the tree pattern to the
251 // SDNode.
Chris Lattnerda272d12010-02-15 08:04:42 +0000252 OpNo = 1;
253
Chris Lattner6bc1b512010-02-16 19:19:58 +0000254 // If this node is not the root and the subtree underneath it produces a
255 // chain, then the result of matching the node is also produce a chain.
256 // Beyond that, this means that we're also folding (at least) the root node
257 // into the node that produce the chain (for example, matching
258 // "(add reg, (load ptr))" as a add_with_memory on X86). This is
259 // problematic, if the 'reg' node also uses the load (say, its chain).
260 // Graphically:
261 //
262 // [LD]
263 // ^ ^
264 // | \ DAG's like cheese.
265 // / |
266 // / [YY]
267 // | ^
268 // [XX]--/
269 //
270 // It would be invalid to fold XX and LD. In this case, folding the two
271 // nodes together would induce a cycle in the DAG, making it a 'cyclic DAG'
272 // To prevent this, we emit a dynamic check for legality before allowing
273 // this to be folded.
274 //
275 const TreePatternNode *Root = Pattern.getSrcPattern();
276 if (N != Root) { // Not the root of the pattern.
Chris Lattnere39650a2010-02-16 06:10:58 +0000277 // If there is a node between the root and this node, then we definitely
278 // need to emit the check.
279 bool NeedCheck = !Root->hasChild(N);
280
281 // If it *is* an immediate child of the root, we can still need a check if
282 // the root SDNode has multiple inputs. For us, this means that it is an
283 // intrinsic, has multiple operands, or has other inputs like chain or
284 // flag).
285 if (!NeedCheck) {
286 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(Root->getOperator());
287 NeedCheck =
288 Root->getOperator() == CGP.get_intrinsic_void_sdnode() ||
289 Root->getOperator() == CGP.get_intrinsic_w_chain_sdnode() ||
290 Root->getOperator() == CGP.get_intrinsic_wo_chain_sdnode() ||
291 PInfo.getNumOperands() > 1 ||
292 PInfo.hasProperty(SDNPHasChain) ||
293 PInfo.hasProperty(SDNPInFlag) ||
294 PInfo.hasProperty(SDNPOptInFlag);
295 }
296
297 if (NeedCheck)
Chris Lattner21390d72010-02-16 19:15:55 +0000298 AddMatcherNode(new CheckFoldableChainNodeMatcherNode());
Chris Lattnere39650a2010-02-16 06:10:58 +0000299 }
Chris Lattnerda272d12010-02-15 08:04:42 +0000300 }
301
Chris Lattnerda272d12010-02-15 08:04:42 +0000302 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
303 // Get the code suitable for matching this child. Move to the child, check
304 // it then move back to the parent.
Chris Lattnerc642b842010-02-17 01:27:29 +0000305 AddMatcherNode(new MoveChildMatcherNode(OpNo));
Chris Lattnerda272d12010-02-15 08:04:42 +0000306 EmitMatchCode(N->getChild(i), NodeNoTypes->getChild(i));
307 AddMatcherNode(new MoveParentMatcherNode());
308 }
309}
310
311
312void MatcherGen::EmitMatchCode(const TreePatternNode *N,
313 TreePatternNode *NodeNoTypes) {
314 // If N and NodeNoTypes don't agree on a type, then this is a case where we
315 // need to do a type check. Emit the check, apply the tyep to NodeNoTypes and
316 // reinfer any correlated types.
317 if (NodeNoTypes->getExtTypes() != N->getExtTypes()) {
318 AddMatcherNode(new CheckTypeMatcherNode(N->getTypeNum(0)));
319 NodeNoTypes->setTypes(N->getExtTypes());
320 InferPossibleTypes();
321 }
322
Chris Lattnerda272d12010-02-15 08:04:42 +0000323 // If this node has a name associated with it, capture it in VariableMap. If
324 // we already saw this in the pattern, emit code to verify dagness.
325 if (!N->getName().empty()) {
326 unsigned &VarMapEntry = VariableMap[N->getName()];
327 if (VarMapEntry == 0) {
Chris Lattnere609a512010-02-17 00:31:50 +0000328 VarMapEntry = NextRecordedOperandNo+1;
329
330 unsigned NumRecorded;
Chris Lattner53a2f602010-02-16 23:16:25 +0000331
332 // If this is a complex pattern, the match operation for it will
333 // implicitly record all of the outputs of it (which may be more than
334 // one).
335 if (const ComplexPattern *AM = N->getComplexPatternInfo(CGP)) {
336 // Record the right number of operands.
Chris Lattnere609a512010-02-17 00:31:50 +0000337 NumRecorded = AM->getNumOperands()-1;
338
339 if (AM->hasProperty(SDNPHasChain))
340 NumRecorded += 2; // Input and output chains.
Chris Lattner53a2f602010-02-16 23:16:25 +0000341 } else {
342 // If it is a normal named node, we must emit a 'Record' opcode.
Chris Lattnerc642b842010-02-17 01:27:29 +0000343 AddMatcherNode(new RecordMatcherNode("$" + N->getName()));
Chris Lattnere609a512010-02-17 00:31:50 +0000344 NumRecorded = 1;
Chris Lattner53a2f602010-02-16 23:16:25 +0000345 }
Chris Lattnere609a512010-02-17 00:31:50 +0000346 NextRecordedOperandNo += NumRecorded;
Chris Lattner53a2f602010-02-16 23:16:25 +0000347
Chris Lattnerda272d12010-02-15 08:04:42 +0000348 } else {
349 // If we get here, this is a second reference to a specific name. Since
350 // we already have checked that the first reference is valid, we don't
351 // have to recursively match it, just check that it's the same as the
352 // previously named thing.
353 AddMatcherNode(new CheckSameMatcherNode(VarMapEntry-1));
354 return;
355 }
356 }
357
358 // If there are node predicates for this node, generate their checks.
359 for (unsigned i = 0, e = N->getPredicateFns().size(); i != e; ++i)
360 AddMatcherNode(new CheckPredicateMatcherNode(N->getPredicateFns()[i]));
361
362 if (N->isLeaf())
363 EmitLeafMatchCode(N);
364 else
365 EmitOperatorMatchCode(N, NodeNoTypes);
366}
367
368void MatcherGen::EmitMatcherCode() {
369 // If the pattern has a predicate on it (e.g. only enabled when a subtarget
370 // feature is around, do the check).
371 if (!Pattern.getPredicateCheck().empty())
372 AddMatcherNode(new
373 CheckPatternPredicateMatcherNode(Pattern.getPredicateCheck()));
374
375 // Emit the matcher for the pattern structure and types.
376 EmitMatchCode(Pattern.getSrcPattern(), PatWithNoTypes);
377}
378
379
380MatcherNode *llvm::ConvertPatternToMatcher(const PatternToMatch &Pattern,
381 const CodeGenDAGPatterns &CGP) {
382 MatcherGen Gen(Pattern, CGP);
383
384 // Generate the code for the matcher.
385 Gen.EmitMatcherCode();
386
387 // If the match succeeds, then we generate Pattern.
388 EmitNodeMatcherNode *Result = new EmitNodeMatcherNode(Pattern);
389
390 // Link it into the pattern.
Chris Lattner8ef9c792010-02-18 02:49:24 +0000391 if (MatcherNode *Pred = Gen.GetCurPredicate()) {
Chris Lattnerbd8227f2010-02-18 02:53:41 +0000392 Pred->setNext(Result);
Chris Lattnerda272d12010-02-15 08:04:42 +0000393 return Gen.GetMatcher();
394 }
395
396 // Unconditional match.
397 return Result;
398}
399
400
401