blob: 5fe21f67389ef165d46952a4dc10e32adc9bc809 [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()))
Chris Lattner5377f912010-03-01 02:24:17 +000046 New = new RecordChildMatcher(MC->getChildNo(), RM->getWhatFor(),
47 RM->getResultNo());
Chris Lattner3c664b32010-02-24 20:15:25 +000048
Chris Lattner9a515172010-02-25 02:04:40 +000049 if (CheckTypeMatcher *CT= dyn_cast<CheckTypeMatcher>(MC->getNext()))
50 New = new CheckChildTypeMatcher(MC->getChildNo(), CT->getType());
Chris Lattner3c664b32010-02-24 20:15:25 +000051
52 if (New) {
53 // Insert the new node.
Chris Lattnerac10e4f2010-02-25 01:56:48 +000054 New->setNext(MatcherPtr.take());
55 MatcherPtr.reset(New);
Chris Lattner3c664b32010-02-24 20:15:25 +000056 // Remove the old one.
57 MC->setNext(MC->getNext()->takeNext());
Chris Lattner5cc7a832010-02-28 20:49:53 +000058 return ContractNodes(MatcherPtr, CGP);
Chris Lattner9feb1e32010-02-24 19:52:48 +000059 }
Chris Lattner3ee1bc42010-02-24 07:31:45 +000060 }
Chris Lattner9feb1e32010-02-24 19:52:48 +000061
Chris Lattner7a1dab42010-02-28 02:31:26 +000062 // Zap movechild -> moveparent.
Chris Lattner9a515172010-02-25 02:04:40 +000063 if (MoveChildMatcher *MC = dyn_cast<MoveChildMatcher>(N))
64 if (MoveParentMatcher *MP =
65 dyn_cast<MoveParentMatcher>(MC->getNext())) {
Chris Lattnerac10e4f2010-02-25 01:56:48 +000066 MatcherPtr.reset(MP->takeNext());
Chris Lattner5cc7a832010-02-28 20:49:53 +000067 return ContractNodes(MatcherPtr, CGP);
Chris Lattner9feb1e32010-02-24 19:52:48 +000068 }
Chris Lattner1f5ca1e2010-02-28 23:00:47 +000069
Chris Lattner304a3e12010-03-01 02:33:14 +000070 // Turn EmitNode->MarkFlagResults->CompleteMatch into
71 // MarkFlagResults->EmitNode->CompleteMatch when we can to encourage
72 // MorphNodeTo formation. This is safe because MarkFlagResults never refers
73 // to the root of the pattern.
74 if (isa<EmitNodeMatcher>(N) && isa<MarkFlagResultsMatcher>(N->getNext()) &&
75 isa<CompleteMatchMatcher>(N->getNext()->getNext())) {
76 // Unlink the two nodes from the list.
77 Matcher *EmitNode = MatcherPtr.take();
78 Matcher *MFR = EmitNode->takeNext();
79 Matcher *Tail = MFR->takeNext();
80
81 // Relink them.
82 MatcherPtr.reset(MFR);
83 MFR->setNext(EmitNode);
84 EmitNode->setNext(Tail);
85 return ContractNodes(MatcherPtr, CGP);
86 }
Chris Lattner1f5ca1e2010-02-28 23:00:47 +000087
Chris Lattner7dae4af2010-02-28 20:55:18 +000088 // Turn EmitNode->CompleteMatch into MorphNodeTo if we can.
Chris Lattner7a1dab42010-02-28 02:31:26 +000089 if (EmitNodeMatcher *EN = dyn_cast<EmitNodeMatcher>(N))
Chris Lattner19a1fbe2010-02-28 02:41:25 +000090 if (CompleteMatchMatcher *CM =
91 dyn_cast<CompleteMatchMatcher>(EN->getNext())) {
Chris Lattner7dae4af2010-02-28 20:55:18 +000092 // We can only use MorphNodeTo if the result values match up.
Chris Lattner5cc7a832010-02-28 20:49:53 +000093 unsigned RootResultFirst = EN->getFirstResultSlot();
94 bool ResultsMatch = true;
95 for (unsigned i = 0, e = CM->getNumResults(); i != e; ++i)
96 if (CM->getResult(i) != RootResultFirst+i)
97 ResultsMatch = false;
98
99 // If the selected node defines a subset of the flag/chain results, we
Chris Lattner7dae4af2010-02-28 20:55:18 +0000100 // can't use MorphNodeTo. For example, we can't use MorphNodeTo if the
Chris Lattner5cc7a832010-02-28 20:49:53 +0000101 // matched pattern has a chain but the root node doesn't.
102 const PatternToMatch &Pattern = CM->getPattern();
103
104 if (!EN->hasChain() &&
105 Pattern.getSrcPattern()->NodeHasProperty(SDNPHasChain, CGP))
106 ResultsMatch = false;
107
108 // If the matched node has a flag and the output root doesn't, we can't
Chris Lattner7dae4af2010-02-28 20:55:18 +0000109 // use MorphNodeTo.
Chris Lattner5cc7a832010-02-28 20:49:53 +0000110 //
111 // NOTE: Strictly speaking, we don't have to check for the flag here
112 // because the code in the pattern generator doesn't handle it right. We
113 // do it anyway for thoroughness.
Chris Lattner414bac82010-02-28 21:53:42 +0000114 if (!EN->hasOutFlag() &&
Chris Lattner5cc7a832010-02-28 20:49:53 +0000115 Pattern.getSrcPattern()->NodeHasProperty(SDNPOutFlag, CGP))
116 ResultsMatch = false;
117
118
119 // If the root result node defines more results than the source root node
120 // *and* has a chain or flag input, then we can't match it because it
121 // would end up replacing the extra result with the chain/flag.
122#if 0
123 if ((EN->hasFlag() || EN->hasChain()) &&
124 EN->getNumNonChainFlagVTs() > ... need to get no results reliably ...)
125 ResultMatch = false;
126#endif
127
128 if (ResultsMatch) {
129 const SmallVectorImpl<MVT::SimpleValueType> &VTs = EN->getVTList();
130 const SmallVectorImpl<unsigned> &Operands = EN->getOperandList();
Chris Lattner7dae4af2010-02-28 20:55:18 +0000131 MatcherPtr.reset(new MorphNodeToMatcher(EN->getOpcodeName(),
Chris Lattner414bac82010-02-28 21:53:42 +0000132 VTs.data(), VTs.size(),
Chris Lattner7dae4af2010-02-28 20:55:18 +0000133 Operands.data(),Operands.size(),
Chris Lattner414bac82010-02-28 21:53:42 +0000134 EN->hasChain(), EN->hasInFlag(),
135 EN->hasOutFlag(),
Chris Lattner7dae4af2010-02-28 20:55:18 +0000136 EN->hasMemRefs(),
137 EN->getNumFixedArityOperands(),
138 Pattern));
Chris Lattner5cc7a832010-02-28 20:49:53 +0000139 return;
140 }
141
Chris Lattner7dae4af2010-02-28 20:55:18 +0000142 // FIXME2: Kill off all the SelectionDAG::MorphNodeTo and getMachineNode
143 // variants.
Chris Lattner7a1dab42010-02-28 02:31:26 +0000144 }
145
Chris Lattner5cc7a832010-02-28 20:49:53 +0000146 ContractNodes(N->getNextPtr(), CGP);
Chris Lattnere0b45db2010-03-01 02:15:34 +0000147
148
149 // If we have a CheckType/CheckChildType/Record node followed by a
150 // CheckOpcode, invert the two nodes. We prefer to do structural checks
151 // before type checks, as this opens opportunities for factoring on targets
152 // like X86 where many operations are valid on multiple types.
153 if ((isa<CheckTypeMatcher>(N) || isa<CheckChildTypeMatcher>(N) ||
154 isa<RecordMatcher>(N)) &&
155 isa<CheckOpcodeMatcher>(N->getNext())) {
156 // Unlink the two nodes from the list.
157 Matcher *CheckType = MatcherPtr.take();
158 Matcher *CheckOpcode = CheckType->takeNext();
159 Matcher *Tail = CheckOpcode->takeNext();
160
161 // Relink them.
162 MatcherPtr.reset(CheckOpcode);
163 CheckOpcode->setNext(CheckType);
164 CheckType->setNext(Tail);
165 return ContractNodes(MatcherPtr, CGP);
166 }
Chris Lattner3ee1bc42010-02-24 07:31:45 +0000167}
168
Chris Lattnerf4950d02010-02-27 06:22:57 +0000169/// SinkPatternPredicates - Pattern predicates can be checked at any level of
170/// the matching tree. The generator dumps them at the top level of the pattern
171/// though, which prevents factoring from being able to see past them. This
172/// optimization sinks them as far down into the pattern as possible.
173///
174/// Conceptually, we'd like to sink these predicates all the way to the last
175/// matcher predicate in the series. However, it turns out that some
176/// ComplexPatterns have side effects on the graph, so we really don't want to
177/// run a the complex pattern if the pattern predicate will fail. For this
178/// reason, we refuse to sink the pattern predicate past a ComplexPattern.
179///
180static void SinkPatternPredicates(OwningPtr<Matcher> &MatcherPtr) {
181 // Recursively scan for a PatternPredicate.
182 // If we reached the end of the chain, we're done.
183 Matcher *N = MatcherPtr.get();
184 if (N == 0) return;
185
186 // Walk down all members of a scope node.
187 if (ScopeMatcher *Scope = dyn_cast<ScopeMatcher>(N)) {
188 for (unsigned i = 0, e = Scope->getNumChildren(); i != e; ++i) {
189 OwningPtr<Matcher> Child(Scope->takeChild(i));
190 SinkPatternPredicates(Child);
191 Scope->resetChild(i, Child.take());
192 }
193 return;
194 }
195
196 // If this node isn't a CheckPatternPredicateMatcher we keep scanning until
197 // we find one.
198 CheckPatternPredicateMatcher *CPPM =dyn_cast<CheckPatternPredicateMatcher>(N);
199 if (CPPM == 0)
200 return SinkPatternPredicates(N->getNextPtr());
201
202 // Ok, we found one, lets try to sink it. Check if we can sink it past the
203 // next node in the chain. If not, we won't be able to change anything and
204 // might as well bail.
205 if (!CPPM->getNext()->isSafeToReorderWithPatternPredicate())
206 return;
207
208 // Okay, we know we can sink it past at least one node. Unlink it from the
209 // chain and scan for the new insertion point.
210 MatcherPtr.take(); // Don't delete CPPM.
211 MatcherPtr.reset(CPPM->takeNext());
212
213 N = MatcherPtr.get();
214 while (N->getNext()->isSafeToReorderWithPatternPredicate())
215 N = N->getNext();
216
217 // At this point, we want to insert CPPM after N.
218 CPPM->setNext(N->takeNext());
219 N->setNext(CPPM);
220}
221
222/// FactorNodes - Turn matches like this:
223/// Scope
224/// OPC_CheckType i32
225/// ABC
226/// OPC_CheckType i32
227/// XYZ
228/// into:
229/// OPC_CheckType i32
230/// Scope
231/// ABC
232/// XYZ
233///
Chris Lattner9a515172010-02-25 02:04:40 +0000234static void FactorNodes(OwningPtr<Matcher> &MatcherPtr) {
Chris Lattner0acf2ba2010-02-25 01:57:41 +0000235 // If we reached the end of the chain, we're done.
Chris Lattner9a515172010-02-25 02:04:40 +0000236 Matcher *N = MatcherPtr.get();
Chris Lattner0acf2ba2010-02-25 01:57:41 +0000237 if (N == 0) return;
238
239 // If this is not a push node, just scan for one.
Chris Lattner42363662010-02-25 19:00:39 +0000240 ScopeMatcher *Scope = dyn_cast<ScopeMatcher>(N);
241 if (Scope == 0)
Chris Lattner0acf2ba2010-02-25 01:57:41 +0000242 return FactorNodes(N->getNextPtr());
243
Chris Lattner42363662010-02-25 19:00:39 +0000244 // Okay, pull together the children of the scope node into a vector so we can
Chris Lattnercd632fb2010-02-25 07:45:24 +0000245 // inspect it more easily. While we're at it, bucket them up by the hash
246 // code of their first predicate.
Chris Lattner9a515172010-02-25 02:04:40 +0000247 SmallVector<Matcher*, 32> OptionsToMatch;
Chris Lattner0acf2ba2010-02-25 01:57:41 +0000248
Chris Lattner42363662010-02-25 19:00:39 +0000249 for (unsigned i = 0, e = Scope->getNumChildren(); i != e; ++i) {
Chris Lattnercd632fb2010-02-25 07:45:24 +0000250 // Factor the subexpression.
Chris Lattner42363662010-02-25 19:00:39 +0000251 OwningPtr<Matcher> Child(Scope->takeChild(i));
252 FactorNodes(Child);
253
Chris Lattner92a22462010-02-26 08:08:41 +0000254 if (Matcher *N = Child.take())
Chris Lattner42363662010-02-25 19:00:39 +0000255 OptionsToMatch.push_back(N);
Chris Lattnercd632fb2010-02-25 07:45:24 +0000256 }
Chris Lattner0acf2ba2010-02-25 01:57:41 +0000257
Chris Lattnercd632fb2010-02-25 07:45:24 +0000258 SmallVector<Matcher*, 32> NewOptionsToMatch;
259
Chris Lattner92a22462010-02-26 08:08:41 +0000260 // Loop over options to match, merging neighboring patterns with identical
261 // starting nodes into a shared matcher.
Chris Lattnerddfd5ab2010-02-27 07:49:13 +0000262 for (unsigned OptionIdx = 0, e = OptionsToMatch.size(); OptionIdx != e;) {
Chris Lattnercd632fb2010-02-25 07:45:24 +0000263 // Find the set of matchers that start with this node.
Chris Lattnerddfd5ab2010-02-27 07:49:13 +0000264 Matcher *Optn = OptionsToMatch[OptionIdx++];
265
266 if (OptionIdx == e) {
Chris Lattnercd632fb2010-02-25 07:45:24 +0000267 NewOptionsToMatch.push_back(Optn);
268 continue;
269 }
270
Chris Lattnerddfd5ab2010-02-27 07:49:13 +0000271 // See if the next option starts with the same matcher. If the two
272 // neighbors *do* start with the same matcher, we can factor the matcher out
273 // of at least these two patterns. See what the maximal set we can merge
274 // together is.
Chris Lattner92a22462010-02-26 08:08:41 +0000275 SmallVector<Matcher*, 8> EqualMatchers;
276 EqualMatchers.push_back(Optn);
Chris Lattner92a22462010-02-26 08:08:41 +0000277
Chris Lattnerddfd5ab2010-02-27 07:49:13 +0000278 // Factor all of the known-equal matchers after this one into the same
279 // group.
280 while (OptionIdx != e && OptionsToMatch[OptionIdx]->isEqual(Optn))
281 EqualMatchers.push_back(OptionsToMatch[OptionIdx++]);
282
283 // If we found a non-equal matcher, see if it is contradictory with the
284 // current node. If so, we know that the ordering relation between the
285 // current sets of nodes and this node don't matter. Look past it to see if
286 // we can merge anything else into this matching group.
287 unsigned Scan = OptionIdx;
288 while (1) {
289 while (Scan != e && Optn->isContradictory(OptionsToMatch[Scan]))
290 ++Scan;
291
292 // Ok, we found something that isn't known to be contradictory. If it is
293 // equal, we can merge it into the set of nodes to factor, if not, we have
294 // to cease factoring.
295 if (Scan == e || !Optn->isEqual(OptionsToMatch[Scan])) break;
296
297 // If is equal after all, add the option to EqualMatchers and remove it
298 // from OptionsToMatch.
299 EqualMatchers.push_back(OptionsToMatch[Scan]);
300 OptionsToMatch.erase(OptionsToMatch.begin()+Scan);
301 --e;
302 }
303
Chris Lattnere9f720b2010-02-27 21:48:43 +0000304 if (Scan != e &&
305 // Don't print it's obvious nothing extra could be merged anyway.
306 Scan+1 != e) {
Chris Lattner086af322010-02-27 08:11:15 +0000307 DEBUG(errs() << "Couldn't merge this:\n";
308 Optn->print(errs(), 4);
309 errs() << "into this:\n";
310 OptionsToMatch[Scan]->print(errs(), 4);
Chris Lattner53d3ec92010-02-27 08:13:23 +0000311 if (Scan+1 != e)
Chris Lattner086af322010-02-27 08:11:15 +0000312 OptionsToMatch[Scan+1]->printOne(errs());
Chris Lattner53d3ec92010-02-27 08:13:23 +0000313 if (Scan+2 < e)
Chris Lattner086af322010-02-27 08:11:15 +0000314 OptionsToMatch[Scan+2]->printOne(errs());
Chris Lattnerddfd5ab2010-02-27 07:49:13 +0000315 errs() << "\n");
316 }
317
318 // If we only found one option starting with this matcher, no factoring is
319 // possible.
320 if (EqualMatchers.size() == 1) {
321 NewOptionsToMatch.push_back(EqualMatchers[0]);
322 continue;
323 }
Chris Lattner92a22462010-02-26 08:08:41 +0000324
Chris Lattnercd632fb2010-02-25 07:45:24 +0000325 // Factor these checks by pulling the first node off each entry and
Chris Lattnerb0e68102010-02-26 07:36:37 +0000326 // discarding it. Take the first one off the first entry to reuse.
327 Matcher *Shared = Optn;
328 Optn = Optn->takeNext();
329 EqualMatchers[0] = Optn;
330
Chris Lattner92a22462010-02-26 08:08:41 +0000331 // Remove and delete the first node from the other matchers we're factoring.
332 for (unsigned i = 1, e = EqualMatchers.size(); i != e; ++i) {
333 Matcher *Tmp = EqualMatchers[i]->takeNext();
334 delete EqualMatchers[i];
335 EqualMatchers[i] = Tmp;
336 }
Chris Lattnercd632fb2010-02-25 07:45:24 +0000337
Chris Lattnerb0e68102010-02-26 07:36:37 +0000338 Shared->setNext(new ScopeMatcher(&EqualMatchers[0], EqualMatchers.size()));
339
340 // Recursively factor the newly created node.
341 FactorNodes(Shared->getNextPtr());
342
343 NewOptionsToMatch.push_back(Shared);
Chris Lattnercd632fb2010-02-25 07:45:24 +0000344 }
345
346 // Reassemble a new Scope node.
Chris Lattnerb0e68102010-02-26 07:36:37 +0000347 assert(!NewOptionsToMatch.empty() && "where'd all our children go?");
Chris Lattner5cc7a832010-02-28 20:49:53 +0000348 if (NewOptionsToMatch.empty())
349 MatcherPtr.reset(0);
Chris Lattnerb0e68102010-02-26 07:36:37 +0000350 if (NewOptionsToMatch.size() == 1)
351 MatcherPtr.reset(NewOptionsToMatch[0]);
352 else {
353 Scope->setNumChildren(NewOptionsToMatch.size());
354 for (unsigned i = 0, e = NewOptionsToMatch.size(); i != e; ++i)
355 Scope->resetChild(i, NewOptionsToMatch[i]);
356 }
Chris Lattner0acf2ba2010-02-25 01:57:41 +0000357}
358
Chris Lattner5cc7a832010-02-28 20:49:53 +0000359Matcher *llvm::OptimizeMatcher(Matcher *TheMatcher,
360 const CodeGenDAGPatterns &CGP) {
Chris Lattner9a515172010-02-25 02:04:40 +0000361 OwningPtr<Matcher> MatcherPtr(TheMatcher);
Chris Lattner5cc7a832010-02-28 20:49:53 +0000362 ContractNodes(MatcherPtr, CGP);
Chris Lattnerf4950d02010-02-27 06:22:57 +0000363 SinkPatternPredicates(MatcherPtr);
Chris Lattner0acf2ba2010-02-25 01:57:41 +0000364 FactorNodes(MatcherPtr);
Chris Lattner3ee1bc42010-02-24 07:31:45 +0000365 return MatcherPtr.take();
Chris Lattner36e646c2010-02-24 07:06:50 +0000366}