DAGISelMatcherOpt.cpp revision 205218
1204642Srdivacky//===- DAGISelMatcherOpt.cpp - Optimize a DAG Matcher ---------------------===//
2204642Srdivacky//
3204642Srdivacky//                     The LLVM Compiler Infrastructure
4204642Srdivacky//
5204642Srdivacky// This file is distributed under the University of Illinois Open Source
6204642Srdivacky// License. See LICENSE.TXT for details.
7204642Srdivacky//
8204642Srdivacky//===----------------------------------------------------------------------===//
9204642Srdivacky//
10204642Srdivacky// This file implements the DAG Matcher optimizer.
11204642Srdivacky//
12204642Srdivacky//===----------------------------------------------------------------------===//
13204642Srdivacky
14204642Srdivacky#define DEBUG_TYPE "isel-opt"
15204642Srdivacky#include "DAGISelMatcher.h"
16204642Srdivacky#include "CodeGenDAGPatterns.h"
17204642Srdivacky#include "llvm/ADT/DenseSet.h"
18204642Srdivacky#include "llvm/ADT/StringSet.h"
19204642Srdivacky#include "llvm/Support/Debug.h"
20204642Srdivacky#include "llvm/Support/raw_ostream.h"
21204642Srdivacky#include <vector>
22204642Srdivackyusing namespace llvm;
23204642Srdivacky
24204642Srdivacky/// ContractNodes - Turn multiple matcher node patterns like 'MoveChild+Record'
25204642Srdivacky/// into single compound nodes like RecordChild.
26204642Srdivackystatic void ContractNodes(OwningPtr<Matcher> &MatcherPtr,
27204642Srdivacky                          const CodeGenDAGPatterns &CGP) {
28204642Srdivacky  // If we reached the end of the chain, we're done.
29204642Srdivacky  Matcher *N = MatcherPtr.get();
30204642Srdivacky  if (N == 0) return;
31204642Srdivacky
32204642Srdivacky  // If we have a scope node, walk down all of the children.
33204642Srdivacky  if (ScopeMatcher *Scope = dyn_cast<ScopeMatcher>(N)) {
34204642Srdivacky    for (unsigned i = 0, e = Scope->getNumChildren(); i != e; ++i) {
35204642Srdivacky      OwningPtr<Matcher> Child(Scope->takeChild(i));
36204642Srdivacky      ContractNodes(Child, CGP);
37204642Srdivacky      Scope->resetChild(i, Child.take());
38204642Srdivacky    }
39204642Srdivacky    return;
40204642Srdivacky  }
41204642Srdivacky
42204642Srdivacky  // If we found a movechild node with a node that comes in a 'foochild' form,
43204642Srdivacky  // transform it.
44204642Srdivacky  if (MoveChildMatcher *MC = dyn_cast<MoveChildMatcher>(N)) {
45204642Srdivacky    Matcher *New = 0;
46204642Srdivacky    if (RecordMatcher *RM = dyn_cast<RecordMatcher>(MC->getNext()))
47205218Srdivacky      if (MC->getChildNo() < 8)  // Only have RecordChild0...7
48205218Srdivacky        New = new RecordChildMatcher(MC->getChildNo(), RM->getWhatFor(),
49205218Srdivacky                                     RM->getResultNo());
50204642Srdivacky
51204642Srdivacky    if (CheckTypeMatcher *CT= dyn_cast<CheckTypeMatcher>(MC->getNext()))
52205218Srdivacky      if (MC->getChildNo() < 8)  // Only have CheckChildType0...7
53205218Srdivacky        New = new CheckChildTypeMatcher(MC->getChildNo(), CT->getType());
54204642Srdivacky
55204642Srdivacky    if (New) {
56204642Srdivacky      // Insert the new node.
57204642Srdivacky      New->setNext(MatcherPtr.take());
58204642Srdivacky      MatcherPtr.reset(New);
59204642Srdivacky      // Remove the old one.
60204642Srdivacky      MC->setNext(MC->getNext()->takeNext());
61204642Srdivacky      return ContractNodes(MatcherPtr, CGP);
62204642Srdivacky    }
63204642Srdivacky  }
64204642Srdivacky
65204642Srdivacky  // Zap movechild -> moveparent.
66204642Srdivacky  if (MoveChildMatcher *MC = dyn_cast<MoveChildMatcher>(N))
67204642Srdivacky    if (MoveParentMatcher *MP =
68204642Srdivacky          dyn_cast<MoveParentMatcher>(MC->getNext())) {
69204642Srdivacky      MatcherPtr.reset(MP->takeNext());
70204642Srdivacky      return ContractNodes(MatcherPtr, CGP);
71204642Srdivacky    }
72204642Srdivacky
73204642Srdivacky  // Turn EmitNode->MarkFlagResults->CompleteMatch into
74204642Srdivacky  // MarkFlagResults->EmitNode->CompleteMatch when we can to encourage
75204642Srdivacky  // MorphNodeTo formation.  This is safe because MarkFlagResults never refers
76204642Srdivacky  // to the root of the pattern.
77204642Srdivacky  if (isa<EmitNodeMatcher>(N) && isa<MarkFlagResultsMatcher>(N->getNext()) &&
78204642Srdivacky      isa<CompleteMatchMatcher>(N->getNext()->getNext())) {
79204642Srdivacky    // Unlink the two nodes from the list.
80204642Srdivacky    Matcher *EmitNode = MatcherPtr.take();
81204642Srdivacky    Matcher *MFR = EmitNode->takeNext();
82204642Srdivacky    Matcher *Tail = MFR->takeNext();
83204642Srdivacky
84204642Srdivacky    // Relink them.
85204642Srdivacky    MatcherPtr.reset(MFR);
86204642Srdivacky    MFR->setNext(EmitNode);
87204642Srdivacky    EmitNode->setNext(Tail);
88204642Srdivacky    return ContractNodes(MatcherPtr, CGP);
89204642Srdivacky  }
90204642Srdivacky
91204642Srdivacky  // Turn EmitNode->CompleteMatch into MorphNodeTo if we can.
92204642Srdivacky  if (EmitNodeMatcher *EN = dyn_cast<EmitNodeMatcher>(N))
93204642Srdivacky    if (CompleteMatchMatcher *CM =
94204642Srdivacky          dyn_cast<CompleteMatchMatcher>(EN->getNext())) {
95204642Srdivacky      // We can only use MorphNodeTo if the result values match up.
96204642Srdivacky      unsigned RootResultFirst = EN->getFirstResultSlot();
97204642Srdivacky      bool ResultsMatch = true;
98204642Srdivacky      for (unsigned i = 0, e = CM->getNumResults(); i != e; ++i)
99204642Srdivacky        if (CM->getResult(i) != RootResultFirst+i)
100204642Srdivacky          ResultsMatch = false;
101204642Srdivacky
102204642Srdivacky      // If the selected node defines a subset of the flag/chain results, we
103204642Srdivacky      // can't use MorphNodeTo.  For example, we can't use MorphNodeTo if the
104204642Srdivacky      // matched pattern has a chain but the root node doesn't.
105204642Srdivacky      const PatternToMatch &Pattern = CM->getPattern();
106204642Srdivacky
107204642Srdivacky      if (!EN->hasChain() &&
108204642Srdivacky          Pattern.getSrcPattern()->NodeHasProperty(SDNPHasChain, CGP))
109204642Srdivacky        ResultsMatch = false;
110204642Srdivacky
111204642Srdivacky      // If the matched node has a flag and the output root doesn't, we can't
112204642Srdivacky      // use MorphNodeTo.
113204642Srdivacky      //
114204642Srdivacky      // NOTE: Strictly speaking, we don't have to check for the flag here
115204642Srdivacky      // because the code in the pattern generator doesn't handle it right.  We
116204642Srdivacky      // do it anyway for thoroughness.
117204642Srdivacky      if (!EN->hasOutFlag() &&
118204642Srdivacky          Pattern.getSrcPattern()->NodeHasProperty(SDNPOutFlag, CGP))
119204642Srdivacky        ResultsMatch = false;
120204642Srdivacky
121204642Srdivacky
122204642Srdivacky      // If the root result node defines more results than the source root node
123204642Srdivacky      // *and* has a chain or flag input, then we can't match it because it
124204642Srdivacky      // would end up replacing the extra result with the chain/flag.
125204642Srdivacky#if 0
126204642Srdivacky      if ((EN->hasFlag() || EN->hasChain()) &&
127204642Srdivacky          EN->getNumNonChainFlagVTs() > ... need to get no results reliably ...)
128204642Srdivacky        ResultMatch = false;
129204642Srdivacky#endif
130204642Srdivacky
131204642Srdivacky      if (ResultsMatch) {
132204642Srdivacky        const SmallVectorImpl<MVT::SimpleValueType> &VTs = EN->getVTList();
133204642Srdivacky        const SmallVectorImpl<unsigned> &Operands = EN->getOperandList();
134204642Srdivacky        MatcherPtr.reset(new MorphNodeToMatcher(EN->getOpcodeName(),
135204642Srdivacky                                                VTs.data(), VTs.size(),
136204642Srdivacky                                                Operands.data(),Operands.size(),
137204642Srdivacky                                                EN->hasChain(), EN->hasInFlag(),
138204642Srdivacky                                                EN->hasOutFlag(),
139204642Srdivacky                                                EN->hasMemRefs(),
140204642Srdivacky                                                EN->getNumFixedArityOperands(),
141204642Srdivacky                                                Pattern));
142204642Srdivacky        return;
143204642Srdivacky      }
144204642Srdivacky
145204642Srdivacky      // FIXME2: Kill off all the SelectionDAG::SelectNodeTo and getMachineNode
146204642Srdivacky      // variants.
147204642Srdivacky    }
148204642Srdivacky
149204642Srdivacky  ContractNodes(N->getNextPtr(), CGP);
150204642Srdivacky
151204642Srdivacky
152204642Srdivacky  // If we have a CheckType/CheckChildType/Record node followed by a
153204642Srdivacky  // CheckOpcode, invert the two nodes.  We prefer to do structural checks
154204642Srdivacky  // before type checks, as this opens opportunities for factoring on targets
155204642Srdivacky  // like X86 where many operations are valid on multiple types.
156204642Srdivacky  if ((isa<CheckTypeMatcher>(N) || isa<CheckChildTypeMatcher>(N) ||
157204642Srdivacky       isa<RecordMatcher>(N)) &&
158204642Srdivacky      isa<CheckOpcodeMatcher>(N->getNext())) {
159204642Srdivacky    // Unlink the two nodes from the list.
160204642Srdivacky    Matcher *CheckType = MatcherPtr.take();
161204642Srdivacky    Matcher *CheckOpcode = CheckType->takeNext();
162204642Srdivacky    Matcher *Tail = CheckOpcode->takeNext();
163204642Srdivacky
164204642Srdivacky    // Relink them.
165204642Srdivacky    MatcherPtr.reset(CheckOpcode);
166204642Srdivacky    CheckOpcode->setNext(CheckType);
167204642Srdivacky    CheckType->setNext(Tail);
168204642Srdivacky    return ContractNodes(MatcherPtr, CGP);
169204642Srdivacky  }
170204642Srdivacky}
171204642Srdivacky
172204642Srdivacky/// SinkPatternPredicates - Pattern predicates can be checked at any level of
173204642Srdivacky/// the matching tree.  The generator dumps them at the top level of the pattern
174204642Srdivacky/// though, which prevents factoring from being able to see past them.  This
175204642Srdivacky/// optimization sinks them as far down into the pattern as possible.
176204642Srdivacky///
177204642Srdivacky/// Conceptually, we'd like to sink these predicates all the way to the last
178204642Srdivacky/// matcher predicate in the series.  However, it turns out that some
179204642Srdivacky/// ComplexPatterns have side effects on the graph, so we really don't want to
180204642Srdivacky/// run a the complex pattern if the pattern predicate will fail.  For this
181204642Srdivacky/// reason, we refuse to sink the pattern predicate past a ComplexPattern.
182204642Srdivacky///
183204642Srdivackystatic void SinkPatternPredicates(OwningPtr<Matcher> &MatcherPtr) {
184204642Srdivacky  // Recursively scan for a PatternPredicate.
185204642Srdivacky  // If we reached the end of the chain, we're done.
186204642Srdivacky  Matcher *N = MatcherPtr.get();
187204642Srdivacky  if (N == 0) return;
188204642Srdivacky
189204642Srdivacky  // Walk down all members of a scope node.
190204642Srdivacky  if (ScopeMatcher *Scope = dyn_cast<ScopeMatcher>(N)) {
191204642Srdivacky    for (unsigned i = 0, e = Scope->getNumChildren(); i != e; ++i) {
192204642Srdivacky      OwningPtr<Matcher> Child(Scope->takeChild(i));
193204642Srdivacky      SinkPatternPredicates(Child);
194204642Srdivacky      Scope->resetChild(i, Child.take());
195204642Srdivacky    }
196204642Srdivacky    return;
197204642Srdivacky  }
198204642Srdivacky
199204642Srdivacky  // If this node isn't a CheckPatternPredicateMatcher we keep scanning until
200204642Srdivacky  // we find one.
201204642Srdivacky  CheckPatternPredicateMatcher *CPPM =dyn_cast<CheckPatternPredicateMatcher>(N);
202204642Srdivacky  if (CPPM == 0)
203204642Srdivacky    return SinkPatternPredicates(N->getNextPtr());
204204642Srdivacky
205204642Srdivacky  // Ok, we found one, lets try to sink it. Check if we can sink it past the
206204642Srdivacky  // next node in the chain.  If not, we won't be able to change anything and
207204642Srdivacky  // might as well bail.
208204642Srdivacky  if (!CPPM->getNext()->isSafeToReorderWithPatternPredicate())
209204642Srdivacky    return;
210204642Srdivacky
211204642Srdivacky  // Okay, we know we can sink it past at least one node.  Unlink it from the
212204642Srdivacky  // chain and scan for the new insertion point.
213204642Srdivacky  MatcherPtr.take();  // Don't delete CPPM.
214204642Srdivacky  MatcherPtr.reset(CPPM->takeNext());
215204642Srdivacky
216204642Srdivacky  N = MatcherPtr.get();
217204642Srdivacky  while (N->getNext()->isSafeToReorderWithPatternPredicate())
218204642Srdivacky    N = N->getNext();
219204642Srdivacky
220204642Srdivacky  // At this point, we want to insert CPPM after N.
221204642Srdivacky  CPPM->setNext(N->takeNext());
222204642Srdivacky  N->setNext(CPPM);
223204642Srdivacky}
224204642Srdivacky
225204961Srdivacky/// FindNodeWithKind - Scan a series of matchers looking for a matcher with a
226204961Srdivacky/// specified kind.  Return null if we didn't find one otherwise return the
227204961Srdivacky/// matcher.
228204961Srdivackystatic Matcher *FindNodeWithKind(Matcher *M, Matcher::KindTy Kind) {
229204961Srdivacky  for (; M; M = M->getNext())
230204961Srdivacky    if (M->getKind() == Kind)
231204961Srdivacky      return M;
232204961Srdivacky  return 0;
233204961Srdivacky}
234204961Srdivacky
235204961Srdivacky
236204642Srdivacky/// FactorNodes - Turn matches like this:
237204642Srdivacky///   Scope
238204642Srdivacky///     OPC_CheckType i32
239204642Srdivacky///       ABC
240204642Srdivacky///     OPC_CheckType i32
241204642Srdivacky///       XYZ
242204642Srdivacky/// into:
243204642Srdivacky///   OPC_CheckType i32
244204642Srdivacky///     Scope
245204642Srdivacky///       ABC
246204642Srdivacky///       XYZ
247204642Srdivacky///
248204642Srdivackystatic void FactorNodes(OwningPtr<Matcher> &MatcherPtr) {
249204642Srdivacky  // If we reached the end of the chain, we're done.
250204642Srdivacky  Matcher *N = MatcherPtr.get();
251204642Srdivacky  if (N == 0) return;
252204642Srdivacky
253204642Srdivacky  // If this is not a push node, just scan for one.
254204642Srdivacky  ScopeMatcher *Scope = dyn_cast<ScopeMatcher>(N);
255204642Srdivacky  if (Scope == 0)
256204642Srdivacky    return FactorNodes(N->getNextPtr());
257204642Srdivacky
258204642Srdivacky  // Okay, pull together the children of the scope node into a vector so we can
259204642Srdivacky  // inspect it more easily.  While we're at it, bucket them up by the hash
260204642Srdivacky  // code of their first predicate.
261204642Srdivacky  SmallVector<Matcher*, 32> OptionsToMatch;
262204642Srdivacky
263204642Srdivacky  for (unsigned i = 0, e = Scope->getNumChildren(); i != e; ++i) {
264204642Srdivacky    // Factor the subexpression.
265204642Srdivacky    OwningPtr<Matcher> Child(Scope->takeChild(i));
266204642Srdivacky    FactorNodes(Child);
267204642Srdivacky
268204642Srdivacky    if (Matcher *N = Child.take())
269204642Srdivacky      OptionsToMatch.push_back(N);
270204642Srdivacky  }
271204642Srdivacky
272204642Srdivacky  SmallVector<Matcher*, 32> NewOptionsToMatch;
273204642Srdivacky
274204642Srdivacky  // Loop over options to match, merging neighboring patterns with identical
275204642Srdivacky  // starting nodes into a shared matcher.
276204642Srdivacky  for (unsigned OptionIdx = 0, e = OptionsToMatch.size(); OptionIdx != e;) {
277204642Srdivacky    // Find the set of matchers that start with this node.
278204642Srdivacky    Matcher *Optn = OptionsToMatch[OptionIdx++];
279204642Srdivacky
280204642Srdivacky    if (OptionIdx == e) {
281204642Srdivacky      NewOptionsToMatch.push_back(Optn);
282204642Srdivacky      continue;
283204642Srdivacky    }
284204642Srdivacky
285204642Srdivacky    // See if the next option starts with the same matcher.  If the two
286204642Srdivacky    // neighbors *do* start with the same matcher, we can factor the matcher out
287204642Srdivacky    // of at least these two patterns.  See what the maximal set we can merge
288204642Srdivacky    // together is.
289204642Srdivacky    SmallVector<Matcher*, 8> EqualMatchers;
290204642Srdivacky    EqualMatchers.push_back(Optn);
291204642Srdivacky
292204642Srdivacky    // Factor all of the known-equal matchers after this one into the same
293204642Srdivacky    // group.
294204642Srdivacky    while (OptionIdx != e && OptionsToMatch[OptionIdx]->isEqual(Optn))
295204642Srdivacky      EqualMatchers.push_back(OptionsToMatch[OptionIdx++]);
296204642Srdivacky
297204642Srdivacky    // If we found a non-equal matcher, see if it is contradictory with the
298204642Srdivacky    // current node.  If so, we know that the ordering relation between the
299204642Srdivacky    // current sets of nodes and this node don't matter.  Look past it to see if
300204642Srdivacky    // we can merge anything else into this matching group.
301204642Srdivacky    unsigned Scan = OptionIdx;
302204642Srdivacky    while (1) {
303204961Srdivacky      // If we ran out of stuff to scan, we're done.
304204961Srdivacky      if (Scan == e) break;
305204961Srdivacky
306204961Srdivacky      Matcher *ScanMatcher = OptionsToMatch[Scan];
307204961Srdivacky
308204961Srdivacky      // If we found an entry that matches out matcher, merge it into the set to
309204961Srdivacky      // handle.
310204961Srdivacky      if (Optn->isEqual(ScanMatcher)) {
311204961Srdivacky        // If is equal after all, add the option to EqualMatchers and remove it
312204961Srdivacky        // from OptionsToMatch.
313204961Srdivacky        EqualMatchers.push_back(ScanMatcher);
314204961Srdivacky        OptionsToMatch.erase(OptionsToMatch.begin()+Scan);
315204961Srdivacky        --e;
316204961Srdivacky        continue;
317204961Srdivacky      }
318204961Srdivacky
319204961Srdivacky      // If the option we're checking for contradicts the start of the list,
320204961Srdivacky      // skip over it.
321204961Srdivacky      if (Optn->isContradictory(ScanMatcher)) {
322204642Srdivacky        ++Scan;
323204961Srdivacky        continue;
324204961Srdivacky      }
325204961Srdivacky
326204961Srdivacky      // If we're scanning for a simple node, see if it occurs later in the
327204961Srdivacky      // sequence.  If so, and if we can move it up, it might be contradictory
328204961Srdivacky      // or the same as what we're looking for.  If so, reorder it.
329204961Srdivacky      if (Optn->isSimplePredicateOrRecordNode()) {
330204961Srdivacky        Matcher *M2 = FindNodeWithKind(ScanMatcher, Optn->getKind());
331204961Srdivacky        if (M2 != 0 && M2 != ScanMatcher &&
332204961Srdivacky            M2->canMoveBefore(ScanMatcher) &&
333204961Srdivacky            (M2->isEqual(Optn) || M2->isContradictory(Optn))) {
334204961Srdivacky          Matcher *MatcherWithoutM2 = ScanMatcher->unlinkNode(M2);
335204961Srdivacky          M2->setNext(MatcherWithoutM2);
336204961Srdivacky          OptionsToMatch[Scan] = M2;
337204961Srdivacky          continue;
338204961Srdivacky        }
339204961Srdivacky      }
340204642Srdivacky
341204961Srdivacky      // Otherwise, we don't know how to handle this entry, we have to bail.
342204961Srdivacky      break;
343204642Srdivacky    }
344204642Srdivacky
345204642Srdivacky    if (Scan != e &&
346204642Srdivacky        // Don't print it's obvious nothing extra could be merged anyway.
347204642Srdivacky        Scan+1 != e) {
348204642Srdivacky      DEBUG(errs() << "Couldn't merge this:\n";
349204642Srdivacky            Optn->print(errs(), 4);
350204642Srdivacky            errs() << "into this:\n";
351204642Srdivacky            OptionsToMatch[Scan]->print(errs(), 4);
352204642Srdivacky            if (Scan+1 != e)
353204642Srdivacky              OptionsToMatch[Scan+1]->printOne(errs());
354204642Srdivacky            if (Scan+2 < e)
355204642Srdivacky              OptionsToMatch[Scan+2]->printOne(errs());
356204642Srdivacky            errs() << "\n");
357204642Srdivacky    }
358204642Srdivacky
359204642Srdivacky    // If we only found one option starting with this matcher, no factoring is
360204642Srdivacky    // possible.
361204642Srdivacky    if (EqualMatchers.size() == 1) {
362204642Srdivacky      NewOptionsToMatch.push_back(EqualMatchers[0]);
363204642Srdivacky      continue;
364204642Srdivacky    }
365204642Srdivacky
366204642Srdivacky    // Factor these checks by pulling the first node off each entry and
367204642Srdivacky    // discarding it.  Take the first one off the first entry to reuse.
368204642Srdivacky    Matcher *Shared = Optn;
369204642Srdivacky    Optn = Optn->takeNext();
370204642Srdivacky    EqualMatchers[0] = Optn;
371204642Srdivacky
372204642Srdivacky    // Remove and delete the first node from the other matchers we're factoring.
373204642Srdivacky    for (unsigned i = 1, e = EqualMatchers.size(); i != e; ++i) {
374204642Srdivacky      Matcher *Tmp = EqualMatchers[i]->takeNext();
375204642Srdivacky      delete EqualMatchers[i];
376204642Srdivacky      EqualMatchers[i] = Tmp;
377204642Srdivacky    }
378204642Srdivacky
379204642Srdivacky    Shared->setNext(new ScopeMatcher(&EqualMatchers[0], EqualMatchers.size()));
380204642Srdivacky
381204642Srdivacky    // Recursively factor the newly created node.
382204642Srdivacky    FactorNodes(Shared->getNextPtr());
383204642Srdivacky
384204642Srdivacky    NewOptionsToMatch.push_back(Shared);
385204642Srdivacky  }
386204642Srdivacky
387204642Srdivacky  // If we're down to a single pattern to match, then we don't need this scope
388204642Srdivacky  // anymore.
389204642Srdivacky  if (NewOptionsToMatch.size() == 1) {
390204642Srdivacky    MatcherPtr.reset(NewOptionsToMatch[0]);
391204642Srdivacky    return;
392204642Srdivacky  }
393204642Srdivacky
394204642Srdivacky  if (NewOptionsToMatch.empty()) {
395204642Srdivacky    MatcherPtr.reset(0);
396204642Srdivacky    return;
397204642Srdivacky  }
398204642Srdivacky
399204642Srdivacky  // If our factoring failed (didn't achieve anything) see if we can simplify in
400204642Srdivacky  // other ways.
401204642Srdivacky
402204642Srdivacky  // Check to see if all of the leading entries are now opcode checks.  If so,
403204642Srdivacky  // we can convert this Scope to be a OpcodeSwitch instead.
404204642Srdivacky  bool AllOpcodeChecks = true, AllTypeChecks = true;
405204642Srdivacky  for (unsigned i = 0, e = NewOptionsToMatch.size(); i != e; ++i) {
406204961Srdivacky    // Check to see if this breaks a series of CheckOpcodeMatchers.
407204961Srdivacky    if (AllOpcodeChecks &&
408204961Srdivacky        !isa<CheckOpcodeMatcher>(NewOptionsToMatch[i])) {
409204642Srdivacky#if 0
410204961Srdivacky      if (i > 3) {
411204642Srdivacky        errs() << "FAILING OPC #" << i << "\n";
412204642Srdivacky        NewOptionsToMatch[i]->dump();
413204642Srdivacky      }
414204642Srdivacky#endif
415204642Srdivacky      AllOpcodeChecks = false;
416204642Srdivacky    }
417204642Srdivacky
418204961Srdivacky    // Check to see if this breaks a series of CheckTypeMatcher's.
419204961Srdivacky    if (AllTypeChecks) {
420204961Srdivacky      CheckTypeMatcher *CTM =
421204961Srdivacky        cast_or_null<CheckTypeMatcher>(FindNodeWithKind(NewOptionsToMatch[i],
422204961Srdivacky                                                        Matcher::CheckType));
423204961Srdivacky      if (CTM == 0 ||
424204961Srdivacky          // iPTR checks could alias any other case without us knowing, don't
425204961Srdivacky          // bother with them.
426204961Srdivacky          CTM->getType() == MVT::iPTR ||
427204961Srdivacky          // If the CheckType isn't at the start of the list, see if we can move
428204961Srdivacky          // it there.
429204961Srdivacky          !CTM->canMoveBefore(NewOptionsToMatch[i])) {
430204642Srdivacky#if 0
431204961Srdivacky        if (i > 3 && AllTypeChecks) {
432204961Srdivacky          errs() << "FAILING TYPE #" << i << "\n";
433204961Srdivacky          NewOptionsToMatch[i]->dump();
434204961Srdivacky        }
435204961Srdivacky#endif
436204961Srdivacky        AllTypeChecks = false;
437204642Srdivacky      }
438204642Srdivacky    }
439204642Srdivacky  }
440204642Srdivacky
441204642Srdivacky  // If all the options are CheckOpcode's, we can form the SwitchOpcode, woot.
442204642Srdivacky  if (AllOpcodeChecks) {
443204642Srdivacky    StringSet<> Opcodes;
444204642Srdivacky    SmallVector<std::pair<const SDNodeInfo*, Matcher*>, 8> Cases;
445204642Srdivacky    for (unsigned i = 0, e = NewOptionsToMatch.size(); i != e; ++i) {
446204642Srdivacky      CheckOpcodeMatcher *COM = cast<CheckOpcodeMatcher>(NewOptionsToMatch[i]);
447204642Srdivacky      assert(Opcodes.insert(COM->getOpcode().getEnumName()) &&
448204642Srdivacky             "Duplicate opcodes not factored?");
449204642Srdivacky      Cases.push_back(std::make_pair(&COM->getOpcode(), COM->getNext()));
450204642Srdivacky    }
451204642Srdivacky
452204642Srdivacky    MatcherPtr.reset(new SwitchOpcodeMatcher(&Cases[0], Cases.size()));
453204642Srdivacky    return;
454204642Srdivacky  }
455204642Srdivacky
456204642Srdivacky  // If all the options are CheckType's, we can form the SwitchType, woot.
457204642Srdivacky  if (AllTypeChecks) {
458204961Srdivacky    DenseMap<unsigned, unsigned> TypeEntry;
459204642Srdivacky    SmallVector<std::pair<MVT::SimpleValueType, Matcher*>, 8> Cases;
460204642Srdivacky    for (unsigned i = 0, e = NewOptionsToMatch.size(); i != e; ++i) {
461204961Srdivacky      CheckTypeMatcher *CTM =
462204961Srdivacky        cast_or_null<CheckTypeMatcher>(FindNodeWithKind(NewOptionsToMatch[i],
463204961Srdivacky                                                        Matcher::CheckType));
464204961Srdivacky      Matcher *MatcherWithoutCTM = NewOptionsToMatch[i]->unlinkNode(CTM);
465204961Srdivacky      MVT::SimpleValueType CTMTy = CTM->getType();
466204961Srdivacky      delete CTM;
467204961Srdivacky
468204961Srdivacky      unsigned &Entry = TypeEntry[CTMTy];
469204961Srdivacky      if (Entry != 0) {
470204961Srdivacky        // If we have unfactored duplicate types, then we should factor them.
471204961Srdivacky        Matcher *PrevMatcher = Cases[Entry-1].second;
472204961Srdivacky        if (ScopeMatcher *SM = dyn_cast<ScopeMatcher>(PrevMatcher)) {
473204961Srdivacky          SM->setNumChildren(SM->getNumChildren()+1);
474204961Srdivacky          SM->resetChild(SM->getNumChildren()-1, MatcherWithoutCTM);
475204961Srdivacky          continue;
476204961Srdivacky        }
477204961Srdivacky
478204961Srdivacky        Matcher *Entries[2] = { PrevMatcher, MatcherWithoutCTM };
479204961Srdivacky        Cases[Entry-1].second = new ScopeMatcher(Entries, 2);
480204961Srdivacky        continue;
481204961Srdivacky      }
482204961Srdivacky
483204961Srdivacky      Entry = Cases.size()+1;
484204961Srdivacky      Cases.push_back(std::make_pair(CTMTy, MatcherWithoutCTM));
485204642Srdivacky    }
486204642Srdivacky
487204961Srdivacky    if (Cases.size() != 1) {
488204961Srdivacky      MatcherPtr.reset(new SwitchTypeMatcher(&Cases[0], Cases.size()));
489204961Srdivacky    } else {
490204961Srdivacky      // If we factored and ended up with one case, create it now.
491204961Srdivacky      MatcherPtr.reset(new CheckTypeMatcher(Cases[0].first));
492204961Srdivacky      MatcherPtr->setNext(Cases[0].second);
493204961Srdivacky    }
494204642Srdivacky    return;
495204642Srdivacky  }
496204642Srdivacky
497204642Srdivacky
498204642Srdivacky  // Reassemble the Scope node with the adjusted children.
499204642Srdivacky  Scope->setNumChildren(NewOptionsToMatch.size());
500204642Srdivacky  for (unsigned i = 0, e = NewOptionsToMatch.size(); i != e; ++i)
501204642Srdivacky    Scope->resetChild(i, NewOptionsToMatch[i]);
502204642Srdivacky}
503204642Srdivacky
504204642SrdivackyMatcher *llvm::OptimizeMatcher(Matcher *TheMatcher,
505204642Srdivacky                               const CodeGenDAGPatterns &CGP) {
506204642Srdivacky  OwningPtr<Matcher> MatcherPtr(TheMatcher);
507204642Srdivacky  ContractNodes(MatcherPtr, CGP);
508204642Srdivacky  SinkPatternPredicates(MatcherPtr);
509204642Srdivacky  FactorNodes(MatcherPtr);
510204642Srdivacky  return MatcherPtr.take();
511204642Srdivacky}
512