use MorphNodeTo instead of SelectNodeTo. SelectNodeTo
[oota-llvm.git] / utils / TableGen / DAGISelMatcherOpt.cpp
1 //===- DAGISelMatcherOpt.cpp - Optimize a DAG Matcher ---------------------===//
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 // This file implements the DAG Matcher optimizer.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #define DEBUG_TYPE "isel-opt"
15 #include "DAGISelMatcher.h"
16 #include "CodeGenDAGPatterns.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/Support/Debug.h"
19 #include "llvm/Support/raw_ostream.h"
20 #include <vector>
21 using namespace llvm;
22
23 /// ContractNodes - Turn multiple matcher node patterns like 'MoveChild+Record'
24 /// into single compound nodes like RecordChild.
25 static void ContractNodes(OwningPtr<Matcher> &MatcherPtr,
26                           const CodeGenDAGPatterns &CGP) {
27   // If we reached the end of the chain, we're done.
28   Matcher *N = MatcherPtr.get();
29   if (N == 0) return;
30   
31   // If we have a scope node, walk down all of the children.
32   if (ScopeMatcher *Scope = dyn_cast<ScopeMatcher>(N)) {
33     for (unsigned i = 0, e = Scope->getNumChildren(); i != e; ++i) {
34       OwningPtr<Matcher> Child(Scope->takeChild(i));
35       ContractNodes(Child, CGP);
36       Scope->resetChild(i, Child.take());
37     }
38     return;
39   }
40   
41   // If we found a movechild node with a node that comes in a 'foochild' form,
42   // transform it.
43   if (MoveChildMatcher *MC = dyn_cast<MoveChildMatcher>(N)) {
44     Matcher *New = 0;
45     if (RecordMatcher *RM = dyn_cast<RecordMatcher>(MC->getNext()))
46       New = new RecordChildMatcher(MC->getChildNo(), RM->getWhatFor());
47     
48     if (CheckTypeMatcher *CT= dyn_cast<CheckTypeMatcher>(MC->getNext()))
49       New = new CheckChildTypeMatcher(MC->getChildNo(), CT->getType());
50     
51     if (New) {
52       // Insert the new node.
53       New->setNext(MatcherPtr.take());
54       MatcherPtr.reset(New);
55       // Remove the old one.
56       MC->setNext(MC->getNext()->takeNext());
57       return ContractNodes(MatcherPtr, CGP);
58     }
59   }
60   
61   // Zap movechild -> moveparent.
62   if (MoveChildMatcher *MC = dyn_cast<MoveChildMatcher>(N))
63     if (MoveParentMatcher *MP = 
64           dyn_cast<MoveParentMatcher>(MC->getNext())) {
65       MatcherPtr.reset(MP->takeNext());
66       return ContractNodes(MatcherPtr, CGP);
67     }
68   
69   // Turn EmitNode->CompleteMatch into MorphNodeTo if we can.
70   if (EmitNodeMatcher *EN = dyn_cast<EmitNodeMatcher>(N))
71     if (CompleteMatchMatcher *CM =
72           dyn_cast<CompleteMatchMatcher>(EN->getNext())) {
73       // We can only use MorphNodeTo if the result values match up.
74       unsigned RootResultFirst = EN->getFirstResultSlot();
75       bool ResultsMatch = true;
76       for (unsigned i = 0, e = CM->getNumResults(); i != e; ++i)
77         if (CM->getResult(i) != RootResultFirst+i)
78           ResultsMatch = false;
79       
80       // If the selected node defines a subset of the flag/chain results, we
81       // can't use MorphNodeTo.  For example, we can't use MorphNodeTo if the
82       // matched pattern has a chain but the root node doesn't.
83       const PatternToMatch &Pattern = CM->getPattern();
84       
85       if (!EN->hasChain() &&
86           Pattern.getSrcPattern()->NodeHasProperty(SDNPHasChain, CGP))
87         ResultsMatch = false;
88
89       // If the matched node has a flag and the output root doesn't, we can't
90       // use MorphNodeTo.
91       //
92       // NOTE: Strictly speaking, we don't have to check for the flag here
93       // because the code in the pattern generator doesn't handle it right.  We
94       // do it anyway for thoroughness.
95       if (!EN->hasFlag() &&
96           Pattern.getSrcPattern()->NodeHasProperty(SDNPOutFlag, CGP))
97         ResultsMatch = false;
98       
99       
100       // If the root result node defines more results than the source root node
101       // *and* has a chain or flag input, then we can't match it because it
102       // would end up replacing the extra result with the chain/flag.
103 #if 0
104       if ((EN->hasFlag() || EN->hasChain()) &&
105           EN->getNumNonChainFlagVTs() > ... need to get no results reliably ...)
106         ResultMatch = false;
107 #endif
108           
109       if (ResultsMatch) {
110         const SmallVectorImpl<MVT::SimpleValueType> &VTs = EN->getVTList();
111         const SmallVectorImpl<unsigned> &Operands = EN->getOperandList();
112         MatcherPtr.reset(new MorphNodeToMatcher(EN->getOpcodeName(),
113                                                 &VTs[0], VTs.size(),
114                                                 Operands.data(),Operands.size(),
115                                                 EN->hasChain(), EN->hasFlag(),
116                                                 EN->hasMemRefs(),
117                                                 EN->getNumFixedArityOperands(),
118                                                 Pattern));
119         return;
120       }
121
122       // FIXME: Handle OPC_MarkFlagResults.
123       
124       // FIXME2: Kill off all the SelectionDAG::MorphNodeTo and getMachineNode
125       // variants.
126     }
127   
128   ContractNodes(N->getNextPtr(), CGP);
129 }
130
131 /// SinkPatternPredicates - Pattern predicates can be checked at any level of
132 /// the matching tree.  The generator dumps them at the top level of the pattern
133 /// though, which prevents factoring from being able to see past them.  This
134 /// optimization sinks them as far down into the pattern as possible.
135 ///
136 /// Conceptually, we'd like to sink these predicates all the way to the last
137 /// matcher predicate in the series.  However, it turns out that some
138 /// ComplexPatterns have side effects on the graph, so we really don't want to
139 /// run a the complex pattern if the pattern predicate will fail.  For this
140 /// reason, we refuse to sink the pattern predicate past a ComplexPattern.
141 ///
142 static void SinkPatternPredicates(OwningPtr<Matcher> &MatcherPtr) {
143   // Recursively scan for a PatternPredicate.
144   // If we reached the end of the chain, we're done.
145   Matcher *N = MatcherPtr.get();
146   if (N == 0) return;
147   
148   // Walk down all members of a scope node.
149   if (ScopeMatcher *Scope = dyn_cast<ScopeMatcher>(N)) {
150     for (unsigned i = 0, e = Scope->getNumChildren(); i != e; ++i) {
151       OwningPtr<Matcher> Child(Scope->takeChild(i));
152       SinkPatternPredicates(Child);
153       Scope->resetChild(i, Child.take());
154     }
155     return;
156   }
157   
158   // If this node isn't a CheckPatternPredicateMatcher we keep scanning until
159   // we find one.
160   CheckPatternPredicateMatcher *CPPM =dyn_cast<CheckPatternPredicateMatcher>(N);
161   if (CPPM == 0)
162     return SinkPatternPredicates(N->getNextPtr());
163   
164   // Ok, we found one, lets try to sink it. Check if we can sink it past the
165   // next node in the chain.  If not, we won't be able to change anything and
166   // might as well bail.
167   if (!CPPM->getNext()->isSafeToReorderWithPatternPredicate())
168     return;
169   
170   // Okay, we know we can sink it past at least one node.  Unlink it from the
171   // chain and scan for the new insertion point.
172   MatcherPtr.take();  // Don't delete CPPM.
173   MatcherPtr.reset(CPPM->takeNext());
174   
175   N = MatcherPtr.get();
176   while (N->getNext()->isSafeToReorderWithPatternPredicate())
177     N = N->getNext();
178   
179   // At this point, we want to insert CPPM after N.
180   CPPM->setNext(N->takeNext());
181   N->setNext(CPPM);
182 }
183
184 /// FactorNodes - Turn matches like this:
185 ///   Scope
186 ///     OPC_CheckType i32
187 ///       ABC
188 ///     OPC_CheckType i32
189 ///       XYZ
190 /// into:
191 ///   OPC_CheckType i32
192 ///     Scope
193 ///       ABC
194 ///       XYZ
195 ///
196 static void FactorNodes(OwningPtr<Matcher> &MatcherPtr) {
197   // If we reached the end of the chain, we're done.
198   Matcher *N = MatcherPtr.get();
199   if (N == 0) return;
200   
201   // If this is not a push node, just scan for one.
202   ScopeMatcher *Scope = dyn_cast<ScopeMatcher>(N);
203   if (Scope == 0)
204     return FactorNodes(N->getNextPtr());
205   
206   // Okay, pull together the children of the scope node into a vector so we can
207   // inspect it more easily.  While we're at it, bucket them up by the hash
208   // code of their first predicate.
209   SmallVector<Matcher*, 32> OptionsToMatch;
210   
211   for (unsigned i = 0, e = Scope->getNumChildren(); i != e; ++i) {
212     // Factor the subexpression.
213     OwningPtr<Matcher> Child(Scope->takeChild(i));
214     FactorNodes(Child);
215     
216     if (Matcher *N = Child.take())
217       OptionsToMatch.push_back(N);
218   }
219   
220   SmallVector<Matcher*, 32> NewOptionsToMatch;
221
222   // Loop over options to match, merging neighboring patterns with identical
223   // starting nodes into a shared matcher.
224   for (unsigned OptionIdx = 0, e = OptionsToMatch.size(); OptionIdx != e;) {
225     // Find the set of matchers that start with this node.
226     Matcher *Optn = OptionsToMatch[OptionIdx++];
227
228     if (OptionIdx == e) {
229       NewOptionsToMatch.push_back(Optn);
230       continue;
231     }
232     
233     // See if the next option starts with the same matcher.  If the two
234     // neighbors *do* start with the same matcher, we can factor the matcher out
235     // of at least these two patterns.  See what the maximal set we can merge
236     // together is.
237     SmallVector<Matcher*, 8> EqualMatchers;
238     EqualMatchers.push_back(Optn);
239     
240     // Factor all of the known-equal matchers after this one into the same
241     // group.
242     while (OptionIdx != e && OptionsToMatch[OptionIdx]->isEqual(Optn))
243       EqualMatchers.push_back(OptionsToMatch[OptionIdx++]);
244
245     // If we found a non-equal matcher, see if it is contradictory with the
246     // current node.  If so, we know that the ordering relation between the
247     // current sets of nodes and this node don't matter.  Look past it to see if
248     // we can merge anything else into this matching group.
249     unsigned Scan = OptionIdx;
250     while (1) {
251       while (Scan != e && Optn->isContradictory(OptionsToMatch[Scan]))
252         ++Scan;
253       
254       // Ok, we found something that isn't known to be contradictory.  If it is
255       // equal, we can merge it into the set of nodes to factor, if not, we have
256       // to cease factoring.
257       if (Scan == e || !Optn->isEqual(OptionsToMatch[Scan])) break;
258
259       // If is equal after all, add the option to EqualMatchers and remove it
260       // from OptionsToMatch.
261       EqualMatchers.push_back(OptionsToMatch[Scan]);
262       OptionsToMatch.erase(OptionsToMatch.begin()+Scan);
263       --e;
264     }
265       
266     if (Scan != e &&
267         // Don't print it's obvious nothing extra could be merged anyway.
268         Scan+1 != e) {
269       DEBUG(errs() << "Couldn't merge this:\n";
270             Optn->print(errs(), 4);
271             errs() << "into this:\n";
272             OptionsToMatch[Scan]->print(errs(), 4);
273             if (Scan+1 != e)
274               OptionsToMatch[Scan+1]->printOne(errs());
275             if (Scan+2 < e)
276               OptionsToMatch[Scan+2]->printOne(errs());
277             errs() << "\n");
278     }
279     
280     // If we only found one option starting with this matcher, no factoring is
281     // possible.
282     if (EqualMatchers.size() == 1) {
283       NewOptionsToMatch.push_back(EqualMatchers[0]);
284       continue;
285     }
286     
287     // Factor these checks by pulling the first node off each entry and
288     // discarding it.  Take the first one off the first entry to reuse.
289     Matcher *Shared = Optn;
290     Optn = Optn->takeNext();
291     EqualMatchers[0] = Optn;
292
293     // Remove and delete the first node from the other matchers we're factoring.
294     for (unsigned i = 1, e = EqualMatchers.size(); i != e; ++i) {
295       Matcher *Tmp = EqualMatchers[i]->takeNext();
296       delete EqualMatchers[i];
297       EqualMatchers[i] = Tmp;
298     }
299     
300     Shared->setNext(new ScopeMatcher(&EqualMatchers[0], EqualMatchers.size()));
301
302     // Recursively factor the newly created node.
303     FactorNodes(Shared->getNextPtr());
304     
305     NewOptionsToMatch.push_back(Shared);
306   }
307
308   // Reassemble a new Scope node.
309   assert(!NewOptionsToMatch.empty() && "where'd all our children go?");
310   if (NewOptionsToMatch.empty())
311     MatcherPtr.reset(0);
312   if (NewOptionsToMatch.size() == 1)
313     MatcherPtr.reset(NewOptionsToMatch[0]);
314   else {
315     Scope->setNumChildren(NewOptionsToMatch.size());
316     for (unsigned i = 0, e = NewOptionsToMatch.size(); i != e; ++i)
317       Scope->resetChild(i, NewOptionsToMatch[i]);
318   }
319 }
320
321 Matcher *llvm::OptimizeMatcher(Matcher *TheMatcher,
322                                const CodeGenDAGPatterns &CGP) {
323   OwningPtr<Matcher> MatcherPtr(TheMatcher);
324   ContractNodes(MatcherPtr, CGP);
325   SinkPatternPredicates(MatcherPtr);
326   FactorNodes(MatcherPtr);
327   return MatcherPtr.take();
328 }