Prep work to handle input chains of matched patterns and checking for
[oota-llvm.git] / utils / TableGen / DAGISelMatcherGen.cpp
1 //===- 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"
13 #include "llvm/ADT/SmallVector.h"
14 #include "llvm/ADT/StringMap.h"
15 using namespace llvm;
16
17 namespace {
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     
33     /// 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.
38     MatcherNodeWithChild *Matcher;
39     
40     /// CurPredicate - As we emit matcher nodes, this points to the latest check
41     /// which should have future checks stuck into its child position.
42     MatcherNodeWithChild *CurPredicate;
43   public:
44     MatcherGen(const PatternToMatch &pattern, const CodeGenDAGPatterns &cgp);
45     
46     ~MatcherGen() {
47       delete PatWithNoTypes;
48     }
49     
50     void EmitMatcherCode();
51     
52     MatcherNodeWithChild *GetMatcher() const { return Matcher; }
53     MatcherNodeWithChild *GetCurPredicate() const { return CurPredicate; }
54   private:
55     void AddMatcherNode(MatcherNodeWithChild *NewNode);
56     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
65 MatcherGen::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.
92 void 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. 
110 void MatcherGen::AddMatcherNode(MatcherNodeWithChild *NewNode) {
111   if (CurPredicate != 0)
112     CurPredicate->setChild(NewNode);
113   else
114     Matcher = NewNode;
115   CurPredicate = NewNode;
116 }
117
118
119
120 /// EmitLeafMatchCode - Generate matching code for leaf nodes.
121 void 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")) {
149     // 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()) {
152       errs() << "We expect complex pattern uses to have names: " << *N << "\n";
153       exit(1);
154     }
155     
156     // Handle complex pattern.
157     const ComplexPattern &CP = CGP.getComplexPattern(LeafRec);
158     return AddMatcherNode(new CheckComplexPatMatcherNode(CP));
159   }
160   
161   errs() << "Unknown leaf kind: " << *N << "\n";
162   abort();
163 }
164
165 void MatcherGen::EmitOperatorMatchCode(const TreePatternNode *N,
166                                        TreePatternNode *NodeNoTypes) {
167   assert(!N->isLeaf() && "Not an operator?");
168   const SDNodeInfo &CInfo = CGP.getSDNodeInfo(N->getOperator());
169   
170   // If this is an 'and R, 1234' where the operation is AND/OR and the RHS is
171   // a constant without a predicate fn that has more that one bit set, handle
172   // this as a special case.  This is usually for targets that have special
173   // handling of certain large constants (e.g. alpha with it's 8/16/32-bit
174   // handling stuff).  Using these instructions is often far more efficient
175   // than materializing the constant.  Unfortunately, both the instcombiner
176   // and the dag combiner can often infer that bits are dead, and thus drop
177   // them from the mask in the dag.  For example, it might turn 'AND X, 255'
178   // into 'AND X, 254' if it knows the low bit is set.  Emit code that checks
179   // to handle this.
180   if ((N->getOperator()->getName() == "and" || 
181        N->getOperator()->getName() == "or") &&
182       N->getChild(1)->isLeaf() && N->getChild(1)->getPredicateFns().empty()) {
183     if (IntInit *II = dynamic_cast<IntInit*>(N->getChild(1)->getLeafValue())) {
184       if (!isPowerOf2_32(II->getValue())) {  // Don't bother with single bits.
185         if (N->getOperator()->getName() == "and")
186           AddMatcherNode(new CheckAndImmMatcherNode(II->getValue()));
187         else
188           AddMatcherNode(new CheckOrImmMatcherNode(II->getValue()));
189
190         // Match the LHS of the AND as appropriate.
191         AddMatcherNode(new MoveChildMatcherNode(0));
192         EmitMatchCode(N->getChild(0), NodeNoTypes->getChild(0));
193         AddMatcherNode(new MoveParentMatcherNode());
194         return;
195       }
196     }
197   }
198   
199   // Check that the current opcode lines up.
200   AddMatcherNode(new CheckOpcodeMatcherNode(CInfo.getEnumName()));
201   
202   // If this node has a chain, then the chain is operand #0 is the SDNode, and
203   // the child numbers of the node are all offset by one.
204   unsigned OpNo = 0;
205   if (N->NodeHasProperty(SDNPHasChain, CGP)) {
206     // FIXME: Not correct for complex patterns, they need to push their own
207     // *matched* input chain.
208     
209     // Record the input chain, which is always input #0 of the SDNode.
210     AddMatcherNode(new MoveChildMatcherNode(0));
211     AddMatcherNode(new RecordMatcherNode("'" + N->getOperator()->getName() +
212                                          "' input chain"));
213     
214     // Remember all of the input chains our pattern will match.
215     InputChains.push_back(NextRecordedOperandNo);
216     ++NextRecordedOperandNo;
217     AddMatcherNode(new MoveParentMatcherNode());
218     
219     // If this is the second (e.g. indbr(load) or store(add(load))) or third
220     // input chain (e.g. (store (add (load, load))) from msp430) we need to make
221     // sure that folding the chain won't induce cycles in the DAG.  This could
222     // happen if there were an intermediate node between the indbr and load, for
223     // example.
224     
225     // FIXME: Emit "lastchain.getNode() == CurrentNode ||
226     //               IsChainCompatible(lastchain.getNode(), CurrentNode)".
227     // Rename IsChainCompatible -> IsChainUnreachable, add comment about
228     // complexity.
229     
230     // Don't look at the input chain when matching the tree pattern to the
231     // SDNode.
232     OpNo = 1;
233
234     // If this node is not the root and the subtree underneath it produces a
235     // chain, then the result of matching the node is also produce a chain.
236     // Beyond that, this means that we're also folding (at least) the root node
237     // into the node that produce the chain (for example, matching
238     // "(add reg, (load ptr))" as a add_with_memory on X86).  This is
239     // problematic, if the 'reg' node also uses the load (say, its chain).
240     // Graphically:
241     //
242     //         [LD]
243     //         ^  ^
244     //         |  \                              DAG's like cheese.
245     //        /    |
246     //       /    [YY]
247     //       |     ^
248     //      [XX]--/
249     //
250     // It would be invalid to fold XX and LD.  In this case, folding the two
251     // nodes together would induce a cycle in the DAG, making it a 'cyclic DAG'
252     // To prevent this, we emit a dynamic check for legality before allowing
253     // this to be folded.
254     //
255     const TreePatternNode *Root = Pattern.getSrcPattern();
256     if (N != Root) {                             // Not the root of the pattern.
257       // If there is a node between the root and this node, then we definitely
258       // need to emit the check.
259       bool NeedCheck = !Root->hasChild(N);
260       
261       // If it *is* an immediate child of the root, we can still need a check if
262       // the root SDNode has multiple inputs.  For us, this means that it is an
263       // intrinsic, has multiple operands, or has other inputs like chain or
264       // flag).
265       if (!NeedCheck) {
266         const SDNodeInfo &PInfo = CGP.getSDNodeInfo(Root->getOperator());
267         NeedCheck =
268           Root->getOperator() == CGP.get_intrinsic_void_sdnode() ||
269           Root->getOperator() == CGP.get_intrinsic_w_chain_sdnode() ||
270           Root->getOperator() == CGP.get_intrinsic_wo_chain_sdnode() ||
271           PInfo.getNumOperands() > 1 ||
272           PInfo.hasProperty(SDNPHasChain) ||
273           PInfo.hasProperty(SDNPInFlag) ||
274           PInfo.hasProperty(SDNPOptInFlag);
275       }
276       
277       if (NeedCheck)
278         AddMatcherNode(new CheckFoldableChainNodeMatcherNode());
279     }
280   }
281       
282   for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
283     // Get the code suitable for matching this child.  Move to the child, check
284     // it then move back to the parent.
285     AddMatcherNode(new MoveChildMatcherNode(OpNo));
286     EmitMatchCode(N->getChild(i), NodeNoTypes->getChild(i));
287     AddMatcherNode(new MoveParentMatcherNode());
288   }
289 }
290
291
292 void MatcherGen::EmitMatchCode(const TreePatternNode *N,
293                                TreePatternNode *NodeNoTypes) {
294   // If N and NodeNoTypes don't agree on a type, then this is a case where we
295   // need to do a type check.  Emit the check, apply the tyep to NodeNoTypes and
296   // reinfer any correlated types.
297   if (NodeNoTypes->getExtTypes() != N->getExtTypes()) {
298     AddMatcherNode(new CheckTypeMatcherNode(N->getTypeNum(0)));
299     NodeNoTypes->setTypes(N->getExtTypes());
300     InferPossibleTypes();
301   }
302   
303   // If this node has a name associated with it, capture it in VariableMap. If
304   // we already saw this in the pattern, emit code to verify dagness.
305   if (!N->getName().empty()) {
306     unsigned &VarMapEntry = VariableMap[N->getName()];
307     if (VarMapEntry == 0) {
308       VarMapEntry = NextRecordedOperandNo+1;
309       
310       unsigned NumRecorded;
311       
312       // If this is a complex pattern, the match operation for it will
313       // implicitly record all of the outputs of it (which may be more than
314       // one).
315       if (const ComplexPattern *AM = N->getComplexPatternInfo(CGP)) {
316         // Record the right number of operands.
317         NumRecorded = AM->getNumOperands()-1;
318         
319         if (AM->hasProperty(SDNPHasChain))
320           NumRecorded += 2; // Input and output chains.
321       } else {
322         // If it is a normal named node, we must emit a 'Record' opcode.
323         AddMatcherNode(new RecordMatcherNode("$" + N->getName()));
324         NumRecorded = 1;
325       }
326       NextRecordedOperandNo += NumRecorded;
327       
328     } else {
329       // If we get here, this is a second reference to a specific name.  Since
330       // we already have checked that the first reference is valid, we don't
331       // have to recursively match it, just check that it's the same as the
332       // previously named thing.
333       AddMatcherNode(new CheckSameMatcherNode(VarMapEntry-1));
334       return;
335     }
336   }
337   
338   // If there are node predicates for this node, generate their checks.
339   for (unsigned i = 0, e = N->getPredicateFns().size(); i != e; ++i)
340     AddMatcherNode(new CheckPredicateMatcherNode(N->getPredicateFns()[i]));
341
342   if (N->isLeaf())
343     EmitLeafMatchCode(N);
344   else
345     EmitOperatorMatchCode(N, NodeNoTypes);
346 }
347
348 void MatcherGen::EmitMatcherCode() {
349   // If the pattern has a predicate on it (e.g. only enabled when a subtarget
350   // feature is around, do the check).
351   if (!Pattern.getPredicateCheck().empty())
352     AddMatcherNode(new 
353                  CheckPatternPredicateMatcherNode(Pattern.getPredicateCheck()));
354   
355   // Emit the matcher for the pattern structure and types.
356   EmitMatchCode(Pattern.getSrcPattern(), PatWithNoTypes);
357 }
358
359
360 MatcherNode *llvm::ConvertPatternToMatcher(const PatternToMatch &Pattern,
361                                            const CodeGenDAGPatterns &CGP) {
362   MatcherGen Gen(Pattern, CGP);
363
364   // Generate the code for the matcher.
365   Gen.EmitMatcherCode();
366   
367   // If the match succeeds, then we generate Pattern.
368   EmitNodeMatcherNode *Result = new EmitNodeMatcherNode(Pattern);
369   
370   // Link it into the pattern.
371   if (MatcherNodeWithChild *Pred = Gen.GetCurPredicate()) {
372     Pred->setChild(Result);
373     return Gen.GetMatcher();
374   }
375
376   // Unconditional match.
377   return Result;
378 }
379
380
381