blob: 01723d3ec84e2b9fa0829162e59fe895d1a5f0b2 [file] [log] [blame]
Chris Lattner36e646c2010-02-24 07:06:50 +00001//===- 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
Chris Lattnerddfd5ab2010-02-27 07:49:13 +000014#define DEBUG_TYPE "isel-opt"
Chris Lattner36e646c2010-02-24 07:06:50 +000015#include "DAGISelMatcher.h"
Chris Lattner5cc7a832010-02-28 20:49:53 +000016#include "CodeGenDAGPatterns.h"
Chris Lattnercd632fb2010-02-25 07:45:24 +000017#include "llvm/ADT/DenseMap.h"
Chris Lattnerddfd5ab2010-02-27 07:49:13 +000018#include "llvm/Support/Debug.h"
19#include "llvm/Support/raw_ostream.h"
Chris Lattnercd632fb2010-02-25 07:45:24 +000020#include <vector>
Chris Lattner36e646c2010-02-24 07:06:50 +000021using namespace llvm;
22
Chris Lattnerf4950d02010-02-27 06:22:57 +000023/// ContractNodes - Turn multiple matcher node patterns like 'MoveChild+Record'
24/// into single compound nodes like RecordChild.
Chris Lattner5cc7a832010-02-28 20:49:53 +000025static void ContractNodes(OwningPtr<Matcher> &MatcherPtr,
26 const CodeGenDAGPatterns &CGP) {
Chris Lattner3ee1bc42010-02-24 07:31:45 +000027 // If we reached the end of the chain, we're done.
Chris Lattner9a515172010-02-25 02:04:40 +000028 Matcher *N = MatcherPtr.get();
Chris Lattner3ee1bc42010-02-24 07:31:45 +000029 if (N == 0) return;
30
Chris Lattner42363662010-02-25 19:00:39 +000031 // 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));
Chris Lattner5cc7a832010-02-28 20:49:53 +000035 ContractNodes(Child, CGP);
Chris Lattner42363662010-02-25 19:00:39 +000036 Scope->resetChild(i, Child.take());
37 }
38 return;
39 }
Chris Lattner3ee1bc42010-02-24 07:31:45 +000040
Chris Lattner9feb1e32010-02-24 19:52:48 +000041 // If we found a movechild node with a node that comes in a 'foochild' form,
42 // transform it.
Chris Lattner9a515172010-02-25 02:04:40 +000043 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());
Chris Lattner3c664b32010-02-24 20:15:25 +000047
Chris Lattner9a515172010-02-25 02:04:40 +000048 if (CheckTypeMatcher *CT= dyn_cast<CheckTypeMatcher>(MC->getNext()))
49 New = new CheckChildTypeMatcher(MC->getChildNo(), CT->getType());
Chris Lattner3c664b32010-02-24 20:15:25 +000050
51 if (New) {
52 // Insert the new node.
Chris Lattnerac10e4f2010-02-25 01:56:48 +000053 New->setNext(MatcherPtr.take());
54 MatcherPtr.reset(New);
Chris Lattner3c664b32010-02-24 20:15:25 +000055 // Remove the old one.
56 MC->setNext(MC->getNext()->takeNext());
Chris Lattner5cc7a832010-02-28 20:49:53 +000057 return ContractNodes(MatcherPtr, CGP);
Chris Lattner9feb1e32010-02-24 19:52:48 +000058 }
Chris Lattner3ee1bc42010-02-24 07:31:45 +000059 }
Chris Lattner9feb1e32010-02-24 19:52:48 +000060
Chris Lattner7a1dab42010-02-28 02:31:26 +000061 // Zap movechild -> moveparent.
Chris Lattner9a515172010-02-25 02:04:40 +000062 if (MoveChildMatcher *MC = dyn_cast<MoveChildMatcher>(N))
63 if (MoveParentMatcher *MP =
64 dyn_cast<MoveParentMatcher>(MC->getNext())) {
Chris Lattnerac10e4f2010-02-25 01:56:48 +000065 MatcherPtr.reset(MP->takeNext());
Chris Lattner5cc7a832010-02-28 20:49:53 +000066 return ContractNodes(MatcherPtr, CGP);
Chris Lattner9feb1e32010-02-24 19:52:48 +000067 }
68
Chris Lattner7dae4af2010-02-28 20:55:18 +000069 // Turn EmitNode->CompleteMatch into MorphNodeTo if we can.
Chris Lattner7a1dab42010-02-28 02:31:26 +000070 if (EmitNodeMatcher *EN = dyn_cast<EmitNodeMatcher>(N))
Chris Lattner19a1fbe2010-02-28 02:41:25 +000071 if (CompleteMatchMatcher *CM =
72 dyn_cast<CompleteMatchMatcher>(EN->getNext())) {
Chris Lattner7dae4af2010-02-28 20:55:18 +000073 // We can only use MorphNodeTo if the result values match up.
Chris Lattner5cc7a832010-02-28 20:49:53 +000074 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
Chris Lattner7dae4af2010-02-28 20:55:18 +000081 // can't use MorphNodeTo. For example, we can't use MorphNodeTo if the
Chris Lattner5cc7a832010-02-28 20:49:53 +000082 // 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
Chris Lattner7dae4af2010-02-28 20:55:18 +000090 // use MorphNodeTo.
Chris Lattner5cc7a832010-02-28 20:49:53 +000091 //
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.
Chris Lattner414bac82010-02-28 21:53:42 +000095 if (!EN->hasOutFlag() &&
Chris Lattner5cc7a832010-02-28 20:49:53 +000096 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();
Chris Lattner7dae4af2010-02-28 20:55:18 +0000112 MatcherPtr.reset(new MorphNodeToMatcher(EN->getOpcodeName(),
Chris Lattner414bac82010-02-28 21:53:42 +0000113 VTs.data(), VTs.size(),
Chris Lattner7dae4af2010-02-28 20:55:18 +0000114 Operands.data(),Operands.size(),
Chris Lattner414bac82010-02-28 21:53:42 +0000115 EN->hasChain(), EN->hasInFlag(),
116 EN->hasOutFlag(),
Chris Lattner7dae4af2010-02-28 20:55:18 +0000117 EN->hasMemRefs(),
118 EN->getNumFixedArityOperands(),
119 Pattern));
Chris Lattner5cc7a832010-02-28 20:49:53 +0000120 return;
121 }
122
123 // FIXME: Handle OPC_MarkFlagResults.
124
Chris Lattner7dae4af2010-02-28 20:55:18 +0000125 // FIXME2: Kill off all the SelectionDAG::MorphNodeTo and getMachineNode
126 // variants.
Chris Lattner7a1dab42010-02-28 02:31:26 +0000127 }
128
Chris Lattner5cc7a832010-02-28 20:49:53 +0000129 ContractNodes(N->getNextPtr(), CGP);
Chris Lattner3ee1bc42010-02-24 07:31:45 +0000130}
131
Chris Lattnerf4950d02010-02-27 06:22:57 +0000132/// SinkPatternPredicates - Pattern predicates can be checked at any level of
133/// the matching tree. The generator dumps them at the top level of the pattern
134/// though, which prevents factoring from being able to see past them. This
135/// optimization sinks them as far down into the pattern as possible.
136///
137/// Conceptually, we'd like to sink these predicates all the way to the last
138/// matcher predicate in the series. However, it turns out that some
139/// ComplexPatterns have side effects on the graph, so we really don't want to
140/// run a the complex pattern if the pattern predicate will fail. For this
141/// reason, we refuse to sink the pattern predicate past a ComplexPattern.
142///
143static void SinkPatternPredicates(OwningPtr<Matcher> &MatcherPtr) {
144 // Recursively scan for a PatternPredicate.
145 // If we reached the end of the chain, we're done.
146 Matcher *N = MatcherPtr.get();
147 if (N == 0) return;
148
149 // Walk down all members of a scope node.
150 if (ScopeMatcher *Scope = dyn_cast<ScopeMatcher>(N)) {
151 for (unsigned i = 0, e = Scope->getNumChildren(); i != e; ++i) {
152 OwningPtr<Matcher> Child(Scope->takeChild(i));
153 SinkPatternPredicates(Child);
154 Scope->resetChild(i, Child.take());
155 }
156 return;
157 }
158
159 // If this node isn't a CheckPatternPredicateMatcher we keep scanning until
160 // we find one.
161 CheckPatternPredicateMatcher *CPPM =dyn_cast<CheckPatternPredicateMatcher>(N);
162 if (CPPM == 0)
163 return SinkPatternPredicates(N->getNextPtr());
164
165 // Ok, we found one, lets try to sink it. Check if we can sink it past the
166 // next node in the chain. If not, we won't be able to change anything and
167 // might as well bail.
168 if (!CPPM->getNext()->isSafeToReorderWithPatternPredicate())
169 return;
170
171 // Okay, we know we can sink it past at least one node. Unlink it from the
172 // chain and scan for the new insertion point.
173 MatcherPtr.take(); // Don't delete CPPM.
174 MatcherPtr.reset(CPPM->takeNext());
175
176 N = MatcherPtr.get();
177 while (N->getNext()->isSafeToReorderWithPatternPredicate())
178 N = N->getNext();
179
180 // At this point, we want to insert CPPM after N.
181 CPPM->setNext(N->takeNext());
182 N->setNext(CPPM);
183}
184
185/// FactorNodes - Turn matches like this:
186/// Scope
187/// OPC_CheckType i32
188/// ABC
189/// OPC_CheckType i32
190/// XYZ
191/// into:
192/// OPC_CheckType i32
193/// Scope
194/// ABC
195/// XYZ
196///
Chris Lattner9a515172010-02-25 02:04:40 +0000197static void FactorNodes(OwningPtr<Matcher> &MatcherPtr) {
Chris Lattner0acf2ba2010-02-25 01:57:41 +0000198 // If we reached the end of the chain, we're done.
Chris Lattner9a515172010-02-25 02:04:40 +0000199 Matcher *N = MatcherPtr.get();
Chris Lattner0acf2ba2010-02-25 01:57:41 +0000200 if (N == 0) return;
201
202 // If this is not a push node, just scan for one.
Chris Lattner42363662010-02-25 19:00:39 +0000203 ScopeMatcher *Scope = dyn_cast<ScopeMatcher>(N);
204 if (Scope == 0)
Chris Lattner0acf2ba2010-02-25 01:57:41 +0000205 return FactorNodes(N->getNextPtr());
206
Chris Lattner42363662010-02-25 19:00:39 +0000207 // Okay, pull together the children of the scope node into a vector so we can
Chris Lattnercd632fb2010-02-25 07:45:24 +0000208 // inspect it more easily. While we're at it, bucket them up by the hash
209 // code of their first predicate.
Chris Lattner9a515172010-02-25 02:04:40 +0000210 SmallVector<Matcher*, 32> OptionsToMatch;
Chris Lattner0acf2ba2010-02-25 01:57:41 +0000211
Chris Lattner42363662010-02-25 19:00:39 +0000212 for (unsigned i = 0, e = Scope->getNumChildren(); i != e; ++i) {
Chris Lattnercd632fb2010-02-25 07:45:24 +0000213 // Factor the subexpression.
Chris Lattner42363662010-02-25 19:00:39 +0000214 OwningPtr<Matcher> Child(Scope->takeChild(i));
215 FactorNodes(Child);
216
Chris Lattner92a22462010-02-26 08:08:41 +0000217 if (Matcher *N = Child.take())
Chris Lattner42363662010-02-25 19:00:39 +0000218 OptionsToMatch.push_back(N);
Chris Lattnercd632fb2010-02-25 07:45:24 +0000219 }
Chris Lattner0acf2ba2010-02-25 01:57:41 +0000220
Chris Lattnercd632fb2010-02-25 07:45:24 +0000221 SmallVector<Matcher*, 32> NewOptionsToMatch;
222
Chris Lattner92a22462010-02-26 08:08:41 +0000223 // Loop over options to match, merging neighboring patterns with identical
224 // starting nodes into a shared matcher.
Chris Lattnerddfd5ab2010-02-27 07:49:13 +0000225 for (unsigned OptionIdx = 0, e = OptionsToMatch.size(); OptionIdx != e;) {
Chris Lattnercd632fb2010-02-25 07:45:24 +0000226 // Find the set of matchers that start with this node.
Chris Lattnerddfd5ab2010-02-27 07:49:13 +0000227 Matcher *Optn = OptionsToMatch[OptionIdx++];
228
229 if (OptionIdx == e) {
Chris Lattnercd632fb2010-02-25 07:45:24 +0000230 NewOptionsToMatch.push_back(Optn);
231 continue;
232 }
233
Chris Lattnerddfd5ab2010-02-27 07:49:13 +0000234 // See if the next option starts with the same matcher. If the two
235 // neighbors *do* start with the same matcher, we can factor the matcher out
236 // of at least these two patterns. See what the maximal set we can merge
237 // together is.
Chris Lattner92a22462010-02-26 08:08:41 +0000238 SmallVector<Matcher*, 8> EqualMatchers;
239 EqualMatchers.push_back(Optn);
Chris Lattner92a22462010-02-26 08:08:41 +0000240
Chris Lattnerddfd5ab2010-02-27 07:49:13 +0000241 // Factor all of the known-equal matchers after this one into the same
242 // group.
243 while (OptionIdx != e && OptionsToMatch[OptionIdx]->isEqual(Optn))
244 EqualMatchers.push_back(OptionsToMatch[OptionIdx++]);
245
246 // If we found a non-equal matcher, see if it is contradictory with the
247 // current node. If so, we know that the ordering relation between the
248 // current sets of nodes and this node don't matter. Look past it to see if
249 // we can merge anything else into this matching group.
250 unsigned Scan = OptionIdx;
251 while (1) {
252 while (Scan != e && Optn->isContradictory(OptionsToMatch[Scan]))
253 ++Scan;
254
255 // Ok, we found something that isn't known to be contradictory. If it is
256 // equal, we can merge it into the set of nodes to factor, if not, we have
257 // to cease factoring.
258 if (Scan == e || !Optn->isEqual(OptionsToMatch[Scan])) break;
259
260 // If is equal after all, add the option to EqualMatchers and remove it
261 // from OptionsToMatch.
262 EqualMatchers.push_back(OptionsToMatch[Scan]);
263 OptionsToMatch.erase(OptionsToMatch.begin()+Scan);
264 --e;
265 }
266
Chris Lattnere9f720b2010-02-27 21:48:43 +0000267 if (Scan != e &&
268 // Don't print it's obvious nothing extra could be merged anyway.
269 Scan+1 != e) {
Chris Lattner086af322010-02-27 08:11:15 +0000270 DEBUG(errs() << "Couldn't merge this:\n";
271 Optn->print(errs(), 4);
272 errs() << "into this:\n";
273 OptionsToMatch[Scan]->print(errs(), 4);
Chris Lattner53d3ec92010-02-27 08:13:23 +0000274 if (Scan+1 != e)
Chris Lattner086af322010-02-27 08:11:15 +0000275 OptionsToMatch[Scan+1]->printOne(errs());
Chris Lattner53d3ec92010-02-27 08:13:23 +0000276 if (Scan+2 < e)
Chris Lattner086af322010-02-27 08:11:15 +0000277 OptionsToMatch[Scan+2]->printOne(errs());
Chris Lattnerddfd5ab2010-02-27 07:49:13 +0000278 errs() << "\n");
279 }
280
281 // If we only found one option starting with this matcher, no factoring is
282 // possible.
283 if (EqualMatchers.size() == 1) {
284 NewOptionsToMatch.push_back(EqualMatchers[0]);
285 continue;
286 }
Chris Lattner92a22462010-02-26 08:08:41 +0000287
Chris Lattnercd632fb2010-02-25 07:45:24 +0000288 // Factor these checks by pulling the first node off each entry and
Chris Lattnerb0e68102010-02-26 07:36:37 +0000289 // discarding it. Take the first one off the first entry to reuse.
290 Matcher *Shared = Optn;
291 Optn = Optn->takeNext();
292 EqualMatchers[0] = Optn;
293
Chris Lattner92a22462010-02-26 08:08:41 +0000294 // Remove and delete the first node from the other matchers we're factoring.
295 for (unsigned i = 1, e = EqualMatchers.size(); i != e; ++i) {
296 Matcher *Tmp = EqualMatchers[i]->takeNext();
297 delete EqualMatchers[i];
298 EqualMatchers[i] = Tmp;
299 }
Chris Lattnercd632fb2010-02-25 07:45:24 +0000300
Chris Lattnerb0e68102010-02-26 07:36:37 +0000301 Shared->setNext(new ScopeMatcher(&EqualMatchers[0], EqualMatchers.size()));
302
303 // Recursively factor the newly created node.
304 FactorNodes(Shared->getNextPtr());
305
306 NewOptionsToMatch.push_back(Shared);
Chris Lattnercd632fb2010-02-25 07:45:24 +0000307 }
308
309 // Reassemble a new Scope node.
Chris Lattnerb0e68102010-02-26 07:36:37 +0000310 assert(!NewOptionsToMatch.empty() && "where'd all our children go?");
Chris Lattner5cc7a832010-02-28 20:49:53 +0000311 if (NewOptionsToMatch.empty())
312 MatcherPtr.reset(0);
Chris Lattnerb0e68102010-02-26 07:36:37 +0000313 if (NewOptionsToMatch.size() == 1)
314 MatcherPtr.reset(NewOptionsToMatch[0]);
315 else {
316 Scope->setNumChildren(NewOptionsToMatch.size());
317 for (unsigned i = 0, e = NewOptionsToMatch.size(); i != e; ++i)
318 Scope->resetChild(i, NewOptionsToMatch[i]);
319 }
Chris Lattner0acf2ba2010-02-25 01:57:41 +0000320}
321
Chris Lattner5cc7a832010-02-28 20:49:53 +0000322Matcher *llvm::OptimizeMatcher(Matcher *TheMatcher,
323 const CodeGenDAGPatterns &CGP) {
Chris Lattner9a515172010-02-25 02:04:40 +0000324 OwningPtr<Matcher> MatcherPtr(TheMatcher);
Chris Lattner5cc7a832010-02-28 20:49:53 +0000325 ContractNodes(MatcherPtr, CGP);
Chris Lattnerf4950d02010-02-27 06:22:57 +0000326 SinkPatternPredicates(MatcherPtr);
Chris Lattner0acf2ba2010-02-25 01:57:41 +0000327 FactorNodes(MatcherPtr);
Chris Lattner3ee1bc42010-02-24 07:31:45 +0000328 return MatcherPtr.take();
Chris Lattner36e646c2010-02-24 07:06:50 +0000329}