CodeGenDAGPatterns.cpp revision 204642
1193323Sed//===- CodeGenDAGPatterns.cpp - Read DAG patterns from .td file -----------===//
2193323Sed//
3193323Sed//                     The LLVM Compiler Infrastructure
4193323Sed//
5193323Sed// This file is distributed under the University of Illinois Open Source
6193323Sed// License. See LICENSE.TXT for details.
7193323Sed//
8193323Sed//===----------------------------------------------------------------------===//
9193323Sed//
10193323Sed// This file implements the CodeGenDAGPatterns class, which is used to read and
11193323Sed// represent the patterns present in a .td file for instructions.
12193323Sed//
13193323Sed//===----------------------------------------------------------------------===//
14193323Sed
15193323Sed#include "CodeGenDAGPatterns.h"
16193323Sed#include "Record.h"
17193323Sed#include "llvm/ADT/StringExtras.h"
18193323Sed#include "llvm/Support/Debug.h"
19193323Sed#include <set>
20193323Sed#include <algorithm>
21195340Sed#include <iostream>
22193323Sedusing namespace llvm;
23193323Sed
24193323Sed//===----------------------------------------------------------------------===//
25193323Sed// Helpers for working with extended types.
26193323Sed
27193323Sed/// FilterVTs - Filter a list of VT's according to a predicate.
28193323Sed///
29193323Sedtemplate<typename T>
30193323Sedstatic std::vector<MVT::SimpleValueType>
31193323SedFilterVTs(const std::vector<MVT::SimpleValueType> &InVTs, T Filter) {
32193323Sed  std::vector<MVT::SimpleValueType> Result;
33193323Sed  for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
34193323Sed    if (Filter(InVTs[i]))
35193323Sed      Result.push_back(InVTs[i]);
36193323Sed  return Result;
37193323Sed}
38193323Sed
39193323Sedtemplate<typename T>
40193323Sedstatic std::vector<unsigned char>
41193323SedFilterEVTs(const std::vector<unsigned char> &InVTs, T Filter) {
42193323Sed  std::vector<unsigned char> Result;
43193323Sed  for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
44193323Sed    if (Filter((MVT::SimpleValueType)InVTs[i]))
45193323Sed      Result.push_back(InVTs[i]);
46193323Sed  return Result;
47193323Sed}
48193323Sed
49193323Sedstatic std::vector<unsigned char>
50193323SedConvertVTs(const std::vector<MVT::SimpleValueType> &InVTs) {
51193323Sed  std::vector<unsigned char> Result;
52193323Sed  for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
53193323Sed    Result.push_back(InVTs[i]);
54193323Sed  return Result;
55193323Sed}
56193323Sed
57193323Sedstatic inline bool isInteger(MVT::SimpleValueType VT) {
58198090Srdivacky  return EVT(VT).isInteger();
59193323Sed}
60193323Sed
61193323Sedstatic inline bool isFloatingPoint(MVT::SimpleValueType VT) {
62198090Srdivacky  return EVT(VT).isFloatingPoint();
63193323Sed}
64193323Sed
65193323Sedstatic inline bool isVector(MVT::SimpleValueType VT) {
66198090Srdivacky  return EVT(VT).isVector();
67193323Sed}
68193323Sed
69193323Sedstatic bool LHSIsSubsetOfRHS(const std::vector<unsigned char> &LHS,
70193323Sed                             const std::vector<unsigned char> &RHS) {
71193323Sed  if (LHS.size() > RHS.size()) return false;
72193323Sed  for (unsigned i = 0, e = LHS.size(); i != e; ++i)
73193323Sed    if (std::find(RHS.begin(), RHS.end(), LHS[i]) == RHS.end())
74193323Sed      return false;
75193323Sed  return true;
76193323Sed}
77193323Sed
78193323Sednamespace llvm {
79198090Srdivackynamespace EEVT {
80193323Sed/// isExtIntegerInVTs - Return true if the specified extended value type vector
81198090Srdivacky/// contains iAny or an integer value type.
82193323Sedbool isExtIntegerInVTs(const std::vector<unsigned char> &EVTs) {
83193323Sed  assert(!EVTs.empty() && "Cannot check for integer in empty ExtVT list!");
84198090Srdivacky  return EVTs[0] == MVT::iAny || !(FilterEVTs(EVTs, isInteger).empty());
85193323Sed}
86193323Sed
87193323Sed/// isExtFloatingPointInVTs - Return true if the specified extended value type
88198090Srdivacky/// vector contains fAny or a FP value type.
89193323Sedbool isExtFloatingPointInVTs(const std::vector<unsigned char> &EVTs) {
90198090Srdivacky  assert(!EVTs.empty() && "Cannot check for FP in empty ExtVT list!");
91198090Srdivacky  return EVTs[0] == MVT::fAny || !(FilterEVTs(EVTs, isFloatingPoint).empty());
92193323Sed}
93198090Srdivacky
94198090Srdivacky/// isExtVectorInVTs - Return true if the specified extended value type
95198090Srdivacky/// vector contains vAny or a vector value type.
96198090Srdivackybool isExtVectorInVTs(const std::vector<unsigned char> &EVTs) {
97198090Srdivacky  assert(!EVTs.empty() && "Cannot check for vector in empty ExtVT list!");
98198090Srdivacky  return EVTs[0] == MVT::vAny || !(FilterEVTs(EVTs, isVector).empty());
99198090Srdivacky}
100198090Srdivacky} // end namespace EEVT.
101193323Sed} // end namespace llvm.
102193323Sed
103198090Srdivackybool RecordPtrCmp::operator()(const Record *LHS, const Record *RHS) const {
104198090Srdivacky  return LHS->getID() < RHS->getID();
105198090Srdivacky}
106193323Sed
107193323Sed/// Dependent variable map for CodeGenDAGPattern variant generation
108193323Sedtypedef std::map<std::string, int> DepVarMap;
109193323Sed
110193323Sed/// Const iterator shorthand for DepVarMap
111193323Sedtypedef DepVarMap::const_iterator DepVarMap_citer;
112193323Sed
113193323Sednamespace {
114193323Sedvoid FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
115193323Sed  if (N->isLeaf()) {
116193323Sed    if (dynamic_cast<DefInit*>(N->getLeafValue()) != NULL) {
117193323Sed      DepMap[N->getName()]++;
118193323Sed    }
119193323Sed  } else {
120193323Sed    for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
121193323Sed      FindDepVarsOf(N->getChild(i), DepMap);
122193323Sed  }
123193323Sed}
124193323Sed
125193323Sed//! Find dependent variables within child patterns
126193323Sed/*!
127193323Sed */
128193323Sedvoid FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
129193323Sed  DepVarMap depcounts;
130193323Sed  FindDepVarsOf(N, depcounts);
131193323Sed  for (DepVarMap_citer i = depcounts.begin(); i != depcounts.end(); ++i) {
132193323Sed    if (i->second > 1) {            // std::pair<std::string, int>
133193323Sed      DepVars.insert(i->first);
134193323Sed    }
135193323Sed  }
136193323Sed}
137193323Sed
138193323Sed//! Dump the dependent variable set:
139193323Sedvoid DumpDepVars(MultipleUseVarSet &DepVars) {
140193323Sed  if (DepVars.empty()) {
141198090Srdivacky    DEBUG(errs() << "<empty set>");
142193323Sed  } else {
143198090Srdivacky    DEBUG(errs() << "[ ");
144193323Sed    for (MultipleUseVarSet::const_iterator i = DepVars.begin(), e = DepVars.end();
145193323Sed         i != e; ++i) {
146198090Srdivacky      DEBUG(errs() << (*i) << " ");
147193323Sed    }
148198090Srdivacky    DEBUG(errs() << "]");
149193323Sed  }
150193323Sed}
151193323Sed}
152193323Sed
153193323Sed//===----------------------------------------------------------------------===//
154193323Sed// PatternToMatch implementation
155193323Sed//
156193323Sed
157193323Sed/// getPredicateCheck - Return a single string containing all of this
158193323Sed/// pattern's predicates concatenated with "&&" operators.
159193323Sed///
160193323Sedstd::string PatternToMatch::getPredicateCheck() const {
161193323Sed  std::string PredicateCheck;
162193323Sed  for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
163193323Sed    if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
164193323Sed      Record *Def = Pred->getDef();
165193323Sed      if (!Def->isSubClassOf("Predicate")) {
166193323Sed#ifndef NDEBUG
167193323Sed        Def->dump();
168193323Sed#endif
169193323Sed        assert(0 && "Unknown predicate type!");
170193323Sed      }
171193323Sed      if (!PredicateCheck.empty())
172193323Sed        PredicateCheck += " && ";
173193323Sed      PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
174193323Sed    }
175193323Sed  }
176193323Sed
177193323Sed  return PredicateCheck;
178193323Sed}
179193323Sed
180193323Sed//===----------------------------------------------------------------------===//
181193323Sed// SDTypeConstraint implementation
182193323Sed//
183193323Sed
184193323SedSDTypeConstraint::SDTypeConstraint(Record *R) {
185193323Sed  OperandNo = R->getValueAsInt("OperandNum");
186193323Sed
187193323Sed  if (R->isSubClassOf("SDTCisVT")) {
188193323Sed    ConstraintType = SDTCisVT;
189193323Sed    x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
190193323Sed  } else if (R->isSubClassOf("SDTCisPtrTy")) {
191193323Sed    ConstraintType = SDTCisPtrTy;
192193323Sed  } else if (R->isSubClassOf("SDTCisInt")) {
193193323Sed    ConstraintType = SDTCisInt;
194193323Sed  } else if (R->isSubClassOf("SDTCisFP")) {
195193323Sed    ConstraintType = SDTCisFP;
196198090Srdivacky  } else if (R->isSubClassOf("SDTCisVec")) {
197198090Srdivacky    ConstraintType = SDTCisVec;
198193323Sed  } else if (R->isSubClassOf("SDTCisSameAs")) {
199193323Sed    ConstraintType = SDTCisSameAs;
200193323Sed    x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
201193323Sed  } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
202193323Sed    ConstraintType = SDTCisVTSmallerThanOp;
203193323Sed    x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
204193323Sed      R->getValueAsInt("OtherOperandNum");
205193323Sed  } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
206193323Sed    ConstraintType = SDTCisOpSmallerThanOp;
207193323Sed    x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
208193323Sed      R->getValueAsInt("BigOperandNum");
209193323Sed  } else if (R->isSubClassOf("SDTCisEltOfVec")) {
210193323Sed    ConstraintType = SDTCisEltOfVec;
211193323Sed    x.SDTCisEltOfVec_Info.OtherOperandNum =
212193323Sed      R->getValueAsInt("OtherOpNum");
213193323Sed  } else {
214195340Sed    errs() << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
215193323Sed    exit(1);
216193323Sed  }
217193323Sed}
218193323Sed
219193323Sed/// getOperandNum - Return the node corresponding to operand #OpNo in tree
220193323Sed/// N, which has NumResults results.
221193323SedTreePatternNode *SDTypeConstraint::getOperandNum(unsigned OpNo,
222193323Sed                                                 TreePatternNode *N,
223193323Sed                                                 unsigned NumResults) const {
224193323Sed  assert(NumResults <= 1 &&
225193323Sed         "We only work with nodes with zero or one result so far!");
226193323Sed
227193323Sed  if (OpNo >= (NumResults + N->getNumChildren())) {
228195340Sed    errs() << "Invalid operand number " << OpNo << " ";
229193323Sed    N->dump();
230195340Sed    errs() << '\n';
231193323Sed    exit(1);
232193323Sed  }
233193323Sed
234193323Sed  if (OpNo < NumResults)
235193323Sed    return N;  // FIXME: need value #
236193323Sed  else
237193323Sed    return N->getChild(OpNo-NumResults);
238193323Sed}
239193323Sed
240193323Sed/// ApplyTypeConstraint - Given a node in a pattern, apply this type
241193323Sed/// constraint to the nodes operands.  This returns true if it makes a
242193323Sed/// change, false otherwise.  If a type contradiction is found, throw an
243193323Sed/// exception.
244193323Sedbool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
245193323Sed                                           const SDNodeInfo &NodeInfo,
246193323Sed                                           TreePattern &TP) const {
247193323Sed  unsigned NumResults = NodeInfo.getNumResults();
248193323Sed  assert(NumResults <= 1 &&
249193323Sed         "We only work with nodes with zero or one result so far!");
250193323Sed
251193323Sed  // Check that the number of operands is sane.  Negative operands -> varargs.
252193323Sed  if (NodeInfo.getNumOperands() >= 0) {
253193323Sed    if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands())
254193323Sed      TP.error(N->getOperator()->getName() + " node requires exactly " +
255193323Sed               itostr(NodeInfo.getNumOperands()) + " operands!");
256193323Sed  }
257193323Sed
258193323Sed  const CodeGenTarget &CGT = TP.getDAGPatterns().getTargetInfo();
259193323Sed
260193323Sed  TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NumResults);
261193323Sed
262193323Sed  switch (ConstraintType) {
263193323Sed  default: assert(0 && "Unknown constraint type!");
264193323Sed  case SDTCisVT:
265193323Sed    // Operand must be a particular type.
266193323Sed    return NodeToApply->UpdateNodeType(x.SDTCisVT_Info.VT, TP);
267193323Sed  case SDTCisPtrTy: {
268193323Sed    // Operand must be same as target pointer type.
269193323Sed    return NodeToApply->UpdateNodeType(MVT::iPTR, TP);
270193323Sed  }
271193323Sed  case SDTCisInt: {
272193323Sed    // If there is only one integer type supported, this must be it.
273193323Sed    std::vector<MVT::SimpleValueType> IntVTs =
274193323Sed      FilterVTs(CGT.getLegalValueTypes(), isInteger);
275193323Sed
276193323Sed    // If we found exactly one supported integer type, apply it.
277193323Sed    if (IntVTs.size() == 1)
278193323Sed      return NodeToApply->UpdateNodeType(IntVTs[0], TP);
279198090Srdivacky    return NodeToApply->UpdateNodeType(MVT::iAny, TP);
280193323Sed  }
281193323Sed  case SDTCisFP: {
282193323Sed    // If there is only one FP type supported, this must be it.
283193323Sed    std::vector<MVT::SimpleValueType> FPVTs =
284193323Sed      FilterVTs(CGT.getLegalValueTypes(), isFloatingPoint);
285193323Sed
286193323Sed    // If we found exactly one supported FP type, apply it.
287193323Sed    if (FPVTs.size() == 1)
288193323Sed      return NodeToApply->UpdateNodeType(FPVTs[0], TP);
289198090Srdivacky    return NodeToApply->UpdateNodeType(MVT::fAny, TP);
290193323Sed  }
291198090Srdivacky  case SDTCisVec: {
292198090Srdivacky    // If there is only one vector type supported, this must be it.
293198090Srdivacky    std::vector<MVT::SimpleValueType> VecVTs =
294198090Srdivacky      FilterVTs(CGT.getLegalValueTypes(), isVector);
295198090Srdivacky
296198090Srdivacky    // If we found exactly one supported vector type, apply it.
297198090Srdivacky    if (VecVTs.size() == 1)
298198090Srdivacky      return NodeToApply->UpdateNodeType(VecVTs[0], TP);
299198090Srdivacky    return NodeToApply->UpdateNodeType(MVT::vAny, TP);
300198090Srdivacky  }
301193323Sed  case SDTCisSameAs: {
302193323Sed    TreePatternNode *OtherNode =
303193323Sed      getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NumResults);
304193323Sed    return NodeToApply->UpdateNodeType(OtherNode->getExtTypes(), TP) |
305193323Sed           OtherNode->UpdateNodeType(NodeToApply->getExtTypes(), TP);
306193323Sed  }
307193323Sed  case SDTCisVTSmallerThanOp: {
308193323Sed    // The NodeToApply must be a leaf node that is a VT.  OtherOperandNum must
309193323Sed    // have an integer type that is smaller than the VT.
310193323Sed    if (!NodeToApply->isLeaf() ||
311193323Sed        !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
312193323Sed        !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
313193323Sed               ->isSubClassOf("ValueType"))
314193323Sed      TP.error(N->getOperator()->getName() + " expects a VT operand!");
315193323Sed    MVT::SimpleValueType VT =
316193323Sed     getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
317193323Sed    if (!isInteger(VT))
318193323Sed      TP.error(N->getOperator()->getName() + " VT operand must be integer!");
319193323Sed
320193323Sed    TreePatternNode *OtherNode =
321193323Sed      getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N,NumResults);
322193323Sed
323193323Sed    // It must be integer.
324201360Srdivacky    bool MadeChange = OtherNode->UpdateNodeType(MVT::iAny, TP);
325193323Sed
326193323Sed    // This code only handles nodes that have one type set.  Assert here so
327193323Sed    // that we can change this if we ever need to deal with multiple value
328193323Sed    // types at this point.
329193323Sed    assert(OtherNode->getExtTypes().size() == 1 && "Node has too many types!");
330193323Sed    if (OtherNode->hasTypeSet() && OtherNode->getTypeNum(0) <= VT)
331193323Sed      OtherNode->UpdateNodeType(MVT::Other, TP);  // Throw an error.
332201360Srdivacky    return MadeChange;
333193323Sed  }
334193323Sed  case SDTCisOpSmallerThanOp: {
335193323Sed    TreePatternNode *BigOperand =
336193323Sed      getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NumResults);
337193323Sed
338193323Sed    // Both operands must be integer or FP, but we don't care which.
339193323Sed    bool MadeChange = false;
340193323Sed
341193323Sed    // This code does not currently handle nodes which have multiple types,
342193323Sed    // where some types are integer, and some are fp.  Assert that this is not
343193323Sed    // the case.
344198090Srdivacky    assert(!(EEVT::isExtIntegerInVTs(NodeToApply->getExtTypes()) &&
345198090Srdivacky             EEVT::isExtFloatingPointInVTs(NodeToApply->getExtTypes())) &&
346198090Srdivacky           !(EEVT::isExtIntegerInVTs(BigOperand->getExtTypes()) &&
347198090Srdivacky             EEVT::isExtFloatingPointInVTs(BigOperand->getExtTypes())) &&
348193323Sed           "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
349198090Srdivacky    if (EEVT::isExtIntegerInVTs(NodeToApply->getExtTypes()))
350198090Srdivacky      MadeChange |= BigOperand->UpdateNodeType(MVT::iAny, TP);
351198090Srdivacky    else if (EEVT::isExtFloatingPointInVTs(NodeToApply->getExtTypes()))
352198090Srdivacky      MadeChange |= BigOperand->UpdateNodeType(MVT::fAny, TP);
353198090Srdivacky    if (EEVT::isExtIntegerInVTs(BigOperand->getExtTypes()))
354198090Srdivacky      MadeChange |= NodeToApply->UpdateNodeType(MVT::iAny, TP);
355198090Srdivacky    else if (EEVT::isExtFloatingPointInVTs(BigOperand->getExtTypes()))
356198090Srdivacky      MadeChange |= NodeToApply->UpdateNodeType(MVT::fAny, TP);
357193323Sed
358193323Sed    std::vector<MVT::SimpleValueType> VTs = CGT.getLegalValueTypes();
359193323Sed
360198090Srdivacky    if (EEVT::isExtIntegerInVTs(NodeToApply->getExtTypes())) {
361193323Sed      VTs = FilterVTs(VTs, isInteger);
362198090Srdivacky    } else if (EEVT::isExtFloatingPointInVTs(NodeToApply->getExtTypes())) {
363193323Sed      VTs = FilterVTs(VTs, isFloatingPoint);
364193323Sed    } else {
365193323Sed      VTs.clear();
366193323Sed    }
367193323Sed
368193323Sed    switch (VTs.size()) {
369193323Sed    default:         // Too many VT's to pick from.
370193323Sed    case 0: break;   // No info yet.
371193323Sed    case 1:
372193323Sed      // Only one VT of this flavor.  Cannot ever satisfy the constraints.
373193323Sed      return NodeToApply->UpdateNodeType(MVT::Other, TP);  // throw
374193323Sed    case 2:
375193323Sed      // If we have exactly two possible types, the little operand must be the
376193323Sed      // small one, the big operand should be the big one.  Common with
377193323Sed      // float/double for example.
378193323Sed      assert(VTs[0] < VTs[1] && "Should be sorted!");
379193323Sed      MadeChange |= NodeToApply->UpdateNodeType(VTs[0], TP);
380193323Sed      MadeChange |= BigOperand->UpdateNodeType(VTs[1], TP);
381193323Sed      break;
382193323Sed    }
383193323Sed    return MadeChange;
384193323Sed  }
385193323Sed  case SDTCisEltOfVec: {
386193323Sed    TreePatternNode *OtherOperand =
387193323Sed      getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum,
388193323Sed                    N, NumResults);
389193323Sed    if (OtherOperand->hasTypeSet()) {
390193323Sed      if (!isVector(OtherOperand->getTypeNum(0)))
391193323Sed        TP.error(N->getOperator()->getName() + " VT operand must be a vector!");
392198090Srdivacky      EVT IVT = OtherOperand->getTypeNum(0);
393193323Sed      IVT = IVT.getVectorElementType();
394198090Srdivacky      return NodeToApply->UpdateNodeType(IVT.getSimpleVT().SimpleTy, TP);
395193323Sed    }
396193323Sed    return false;
397193323Sed  }
398193323Sed  }
399193323Sed  return false;
400193323Sed}
401193323Sed
402193323Sed//===----------------------------------------------------------------------===//
403193323Sed// SDNodeInfo implementation
404193323Sed//
405193323SedSDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
406193323Sed  EnumName    = R->getValueAsString("Opcode");
407193323Sed  SDClassName = R->getValueAsString("SDClass");
408193323Sed  Record *TypeProfile = R->getValueAsDef("TypeProfile");
409193323Sed  NumResults = TypeProfile->getValueAsInt("NumResults");
410193323Sed  NumOperands = TypeProfile->getValueAsInt("NumOperands");
411193323Sed
412193323Sed  // Parse the properties.
413193323Sed  Properties = 0;
414193323Sed  std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
415193323Sed  for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
416193323Sed    if (PropList[i]->getName() == "SDNPCommutative") {
417193323Sed      Properties |= 1 << SDNPCommutative;
418193323Sed    } else if (PropList[i]->getName() == "SDNPAssociative") {
419193323Sed      Properties |= 1 << SDNPAssociative;
420193323Sed    } else if (PropList[i]->getName() == "SDNPHasChain") {
421193323Sed      Properties |= 1 << SDNPHasChain;
422193323Sed    } else if (PropList[i]->getName() == "SDNPOutFlag") {
423193323Sed      Properties |= 1 << SDNPOutFlag;
424193323Sed    } else if (PropList[i]->getName() == "SDNPInFlag") {
425193323Sed      Properties |= 1 << SDNPInFlag;
426193323Sed    } else if (PropList[i]->getName() == "SDNPOptInFlag") {
427193323Sed      Properties |= 1 << SDNPOptInFlag;
428193323Sed    } else if (PropList[i]->getName() == "SDNPMayStore") {
429193323Sed      Properties |= 1 << SDNPMayStore;
430193323Sed    } else if (PropList[i]->getName() == "SDNPMayLoad") {
431193323Sed      Properties |= 1 << SDNPMayLoad;
432193323Sed    } else if (PropList[i]->getName() == "SDNPSideEffect") {
433193323Sed      Properties |= 1 << SDNPSideEffect;
434193323Sed    } else if (PropList[i]->getName() == "SDNPMemOperand") {
435193323Sed      Properties |= 1 << SDNPMemOperand;
436193323Sed    } else {
437195340Sed      errs() << "Unknown SD Node property '" << PropList[i]->getName()
438195340Sed             << "' on node '" << R->getName() << "'!\n";
439193323Sed      exit(1);
440193323Sed    }
441193323Sed  }
442193323Sed
443193323Sed
444193323Sed  // Parse the type constraints.
445193323Sed  std::vector<Record*> ConstraintList =
446193323Sed    TypeProfile->getValueAsListOfDefs("Constraints");
447193323Sed  TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
448193323Sed}
449193323Sed
450204642Srdivacky/// getKnownType - If the type constraints on this node imply a fixed type
451204642Srdivacky/// (e.g. all stores return void, etc), then return it as an
452204642Srdivacky/// MVT::SimpleValueType.  Otherwise, return EEVT::isUnknown.
453204642Srdivackyunsigned SDNodeInfo::getKnownType() const {
454204642Srdivacky  unsigned NumResults = getNumResults();
455204642Srdivacky  assert(NumResults <= 1 &&
456204642Srdivacky         "We only work with nodes with zero or one result so far!");
457204642Srdivacky
458204642Srdivacky  for (unsigned i = 0, e = TypeConstraints.size(); i != e; ++i) {
459204642Srdivacky    // Make sure that this applies to the correct node result.
460204642Srdivacky    if (TypeConstraints[i].OperandNo >= NumResults)  // FIXME: need value #
461204642Srdivacky      continue;
462204642Srdivacky
463204642Srdivacky    switch (TypeConstraints[i].ConstraintType) {
464204642Srdivacky    default: break;
465204642Srdivacky    case SDTypeConstraint::SDTCisVT:
466204642Srdivacky      return TypeConstraints[i].x.SDTCisVT_Info.VT;
467204642Srdivacky    case SDTypeConstraint::SDTCisPtrTy:
468204642Srdivacky      return MVT::iPTR;
469204642Srdivacky    }
470204642Srdivacky  }
471204642Srdivacky  return EEVT::isUnknown;
472204642Srdivacky}
473204642Srdivacky
474193323Sed//===----------------------------------------------------------------------===//
475193323Sed// TreePatternNode implementation
476193323Sed//
477193323Sed
478193323SedTreePatternNode::~TreePatternNode() {
479193323Sed#if 0 // FIXME: implement refcounted tree nodes!
480193323Sed  for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
481193323Sed    delete getChild(i);
482193323Sed#endif
483193323Sed}
484193323Sed
485193323Sed/// UpdateNodeType - Set the node type of N to VT if VT contains
486193323Sed/// information.  If N already contains a conflicting type, then throw an
487193323Sed/// exception.  This returns true if any information was updated.
488193323Sed///
489193323Sedbool TreePatternNode::UpdateNodeType(const std::vector<unsigned char> &ExtVTs,
490193323Sed                                     TreePattern &TP) {
491193323Sed  assert(!ExtVTs.empty() && "Cannot update node type with empty type vector!");
492193323Sed
493198090Srdivacky  if (ExtVTs[0] == EEVT::isUnknown || LHSIsSubsetOfRHS(getExtTypes(), ExtVTs))
494193323Sed    return false;
495193323Sed  if (isTypeCompletelyUnknown() || LHSIsSubsetOfRHS(ExtVTs, getExtTypes())) {
496193323Sed    setTypes(ExtVTs);
497193323Sed    return true;
498193323Sed  }
499193323Sed
500193323Sed  if (getExtTypeNum(0) == MVT::iPTR || getExtTypeNum(0) == MVT::iPTRAny) {
501193323Sed    if (ExtVTs[0] == MVT::iPTR || ExtVTs[0] == MVT::iPTRAny ||
502198090Srdivacky        ExtVTs[0] == MVT::iAny)
503193323Sed      return false;
504198090Srdivacky    if (EEVT::isExtIntegerInVTs(ExtVTs)) {
505193323Sed      std::vector<unsigned char> FVTs = FilterEVTs(ExtVTs, isInteger);
506193323Sed      if (FVTs.size()) {
507193323Sed        setTypes(ExtVTs);
508193323Sed        return true;
509193323Sed      }
510193323Sed    }
511193323Sed  }
512193323Sed
513198090Srdivacky  // Merge vAny with iAny/fAny.  The latter include vector types so keep them
514198090Srdivacky  // as the more specific information.
515198090Srdivacky  if (ExtVTs[0] == MVT::vAny &&
516198090Srdivacky      (getExtTypeNum(0) == MVT::iAny || getExtTypeNum(0) == MVT::fAny))
517198090Srdivacky    return false;
518198090Srdivacky  if (getExtTypeNum(0) == MVT::vAny &&
519198090Srdivacky      (ExtVTs[0] == MVT::iAny || ExtVTs[0] == MVT::fAny)) {
520198090Srdivacky    setTypes(ExtVTs);
521198090Srdivacky    return true;
522198090Srdivacky  }
523198090Srdivacky
524198090Srdivacky  if (ExtVTs[0] == MVT::iAny &&
525198090Srdivacky      EEVT::isExtIntegerInVTs(getExtTypes())) {
526193323Sed    assert(hasTypeSet() && "should be handled above!");
527193323Sed    std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), isInteger);
528193323Sed    if (getExtTypes() == FVTs)
529193323Sed      return false;
530193323Sed    setTypes(FVTs);
531193323Sed    return true;
532193323Sed  }
533193323Sed  if ((ExtVTs[0] == MVT::iPTR || ExtVTs[0] == MVT::iPTRAny) &&
534198090Srdivacky      EEVT::isExtIntegerInVTs(getExtTypes())) {
535193323Sed    //assert(hasTypeSet() && "should be handled above!");
536193323Sed    std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), isInteger);
537193323Sed    if (getExtTypes() == FVTs)
538193323Sed      return false;
539193323Sed    if (FVTs.size()) {
540193323Sed      setTypes(FVTs);
541193323Sed      return true;
542193323Sed    }
543193323Sed  }
544198090Srdivacky  if (ExtVTs[0] == MVT::fAny &&
545198090Srdivacky      EEVT::isExtFloatingPointInVTs(getExtTypes())) {
546193323Sed    assert(hasTypeSet() && "should be handled above!");
547193323Sed    std::vector<unsigned char> FVTs =
548193323Sed      FilterEVTs(getExtTypes(), isFloatingPoint);
549193323Sed    if (getExtTypes() == FVTs)
550193323Sed      return false;
551193323Sed    setTypes(FVTs);
552193323Sed    return true;
553193323Sed  }
554198090Srdivacky  if (ExtVTs[0] == MVT::vAny &&
555198090Srdivacky      EEVT::isExtVectorInVTs(getExtTypes())) {
556198090Srdivacky    assert(hasTypeSet() && "should be handled above!");
557198090Srdivacky    std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), isVector);
558198090Srdivacky    if (getExtTypes() == FVTs)
559198090Srdivacky      return false;
560198090Srdivacky    setTypes(FVTs);
561198090Srdivacky    return true;
562198090Srdivacky  }
563198090Srdivacky
564198090Srdivacky  // If we know this is an int, FP, or vector type, and we are told it is a
565198090Srdivacky  // specific one, take the advice.
566193323Sed  //
567193323Sed  // Similarly, we should probably set the type here to the intersection of
568198090Srdivacky  // {iAny|fAny|vAny} and ExtVTs
569198090Srdivacky  if ((getExtTypeNum(0) == MVT::iAny &&
570198090Srdivacky       EEVT::isExtIntegerInVTs(ExtVTs)) ||
571198090Srdivacky      (getExtTypeNum(0) == MVT::fAny &&
572198090Srdivacky       EEVT::isExtFloatingPointInVTs(ExtVTs)) ||
573198090Srdivacky      (getExtTypeNum(0) == MVT::vAny &&
574198090Srdivacky       EEVT::isExtVectorInVTs(ExtVTs))) {
575193323Sed    setTypes(ExtVTs);
576193323Sed    return true;
577193323Sed  }
578198090Srdivacky  if (getExtTypeNum(0) == MVT::iAny &&
579193323Sed      (ExtVTs[0] == MVT::iPTR || ExtVTs[0] == MVT::iPTRAny)) {
580193323Sed    setTypes(ExtVTs);
581193323Sed    return true;
582193323Sed  }
583193323Sed
584193323Sed  if (isLeaf()) {
585193323Sed    dump();
586195340Sed    errs() << " ";
587193323Sed    TP.error("Type inference contradiction found in node!");
588193323Sed  } else {
589193323Sed    TP.error("Type inference contradiction found in node " +
590193323Sed             getOperator()->getName() + "!");
591193323Sed  }
592193323Sed  return true; // unreachable
593193323Sed}
594193323Sed
595204642Srdivackystatic std::string GetTypeName(unsigned char TypeID) {
596204642Srdivacky  switch (TypeID) {
597204642Srdivacky  case MVT::Other:      return "Other";
598204642Srdivacky  case MVT::iAny:       return "iAny";
599204642Srdivacky  case MVT::fAny:       return "fAny";
600204642Srdivacky  case MVT::vAny:       return "vAny";
601204642Srdivacky  case EEVT::isUnknown: return "isUnknown";
602204642Srdivacky  case MVT::iPTR:       return "iPTR";
603204642Srdivacky  case MVT::iPTRAny:    return "iPTRAny";
604204642Srdivacky  default:
605204642Srdivacky    std::string VTName = llvm::getName((MVT::SimpleValueType)TypeID);
606204642Srdivacky    // Strip off EVT:: prefix if present.
607204642Srdivacky    if (VTName.substr(0,5) == "MVT::")
608204642Srdivacky      VTName = VTName.substr(5);
609204642Srdivacky    return VTName;
610204642Srdivacky  }
611204642Srdivacky}
612193323Sed
613204642Srdivacky
614195340Sedvoid TreePatternNode::print(raw_ostream &OS) const {
615193323Sed  if (isLeaf()) {
616193323Sed    OS << *getLeafValue();
617193323Sed  } else {
618204642Srdivacky    OS << '(' << getOperator()->getName();
619193323Sed  }
620193323Sed
621193323Sed  // FIXME: At some point we should handle printing all the value types for
622193323Sed  // nodes that are multiply typed.
623204642Srdivacky  if (getExtTypeNum(0) != EEVT::isUnknown)
624204642Srdivacky    OS << ':' << GetTypeName(getExtTypeNum(0));
625193323Sed
626193323Sed  if (!isLeaf()) {
627193323Sed    if (getNumChildren() != 0) {
628193323Sed      OS << " ";
629193323Sed      getChild(0)->print(OS);
630193323Sed      for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
631193323Sed        OS << ", ";
632193323Sed        getChild(i)->print(OS);
633193323Sed      }
634193323Sed    }
635193323Sed    OS << ")";
636193323Sed  }
637193323Sed
638193323Sed  for (unsigned i = 0, e = PredicateFns.size(); i != e; ++i)
639193323Sed    OS << "<<P:" << PredicateFns[i] << ">>";
640193323Sed  if (TransformFn)
641193323Sed    OS << "<<X:" << TransformFn->getName() << ">>";
642193323Sed  if (!getName().empty())
643193323Sed    OS << ":$" << getName();
644193323Sed
645193323Sed}
646193323Sedvoid TreePatternNode::dump() const {
647195340Sed  print(errs());
648193323Sed}
649193323Sed
650193323Sed/// isIsomorphicTo - Return true if this node is recursively
651193323Sed/// isomorphic to the specified node.  For this comparison, the node's
652193323Sed/// entire state is considered. The assigned name is ignored, since
653193323Sed/// nodes with differing names are considered isomorphic. However, if
654193323Sed/// the assigned name is present in the dependent variable set, then
655193323Sed/// the assigned name is considered significant and the node is
656193323Sed/// isomorphic if the names match.
657193323Sedbool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
658193323Sed                                     const MultipleUseVarSet &DepVars) const {
659193323Sed  if (N == this) return true;
660193323Sed  if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
661193323Sed      getPredicateFns() != N->getPredicateFns() ||
662193323Sed      getTransformFn() != N->getTransformFn())
663193323Sed    return false;
664193323Sed
665193323Sed  if (isLeaf()) {
666193323Sed    if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
667193323Sed      if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue())) {
668193323Sed        return ((DI->getDef() == NDI->getDef())
669193323Sed                && (DepVars.find(getName()) == DepVars.end()
670193323Sed                    || getName() == N->getName()));
671193323Sed      }
672193323Sed    }
673193323Sed    return getLeafValue() == N->getLeafValue();
674193323Sed  }
675193323Sed
676193323Sed  if (N->getOperator() != getOperator() ||
677193323Sed      N->getNumChildren() != getNumChildren()) return false;
678193323Sed  for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
679193323Sed    if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
680193323Sed      return false;
681193323Sed  return true;
682193323Sed}
683193323Sed
684193323Sed/// clone - Make a copy of this tree and all of its children.
685193323Sed///
686193323SedTreePatternNode *TreePatternNode::clone() const {
687193323Sed  TreePatternNode *New;
688193323Sed  if (isLeaf()) {
689193323Sed    New = new TreePatternNode(getLeafValue());
690193323Sed  } else {
691193323Sed    std::vector<TreePatternNode*> CChildren;
692193323Sed    CChildren.reserve(Children.size());
693193323Sed    for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
694193323Sed      CChildren.push_back(getChild(i)->clone());
695193323Sed    New = new TreePatternNode(getOperator(), CChildren);
696193323Sed  }
697193323Sed  New->setName(getName());
698193323Sed  New->setTypes(getExtTypes());
699193323Sed  New->setPredicateFns(getPredicateFns());
700193323Sed  New->setTransformFn(getTransformFn());
701193323Sed  return New;
702193323Sed}
703193323Sed
704203954Srdivacky/// RemoveAllTypes - Recursively strip all the types of this tree.
705203954Srdivackyvoid TreePatternNode::RemoveAllTypes() {
706203954Srdivacky  removeTypes();
707203954Srdivacky  if (isLeaf()) return;
708203954Srdivacky  for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
709203954Srdivacky    getChild(i)->RemoveAllTypes();
710203954Srdivacky}
711203954Srdivacky
712203954Srdivacky
713193323Sed/// SubstituteFormalArguments - Replace the formal arguments in this tree
714193323Sed/// with actual values specified by ArgMap.
715193323Sedvoid TreePatternNode::
716193323SedSubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
717193323Sed  if (isLeaf()) return;
718193323Sed
719193323Sed  for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
720193323Sed    TreePatternNode *Child = getChild(i);
721193323Sed    if (Child->isLeaf()) {
722193323Sed      Init *Val = Child->getLeafValue();
723193323Sed      if (dynamic_cast<DefInit*>(Val) &&
724193323Sed          static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
725193323Sed        // We found a use of a formal argument, replace it with its value.
726193323Sed        TreePatternNode *NewChild = ArgMap[Child->getName()];
727193323Sed        assert(NewChild && "Couldn't find formal argument!");
728193323Sed        assert((Child->getPredicateFns().empty() ||
729193323Sed                NewChild->getPredicateFns() == Child->getPredicateFns()) &&
730193323Sed               "Non-empty child predicate clobbered!");
731193323Sed        setChild(i, NewChild);
732193323Sed      }
733193323Sed    } else {
734193323Sed      getChild(i)->SubstituteFormalArguments(ArgMap);
735193323Sed    }
736193323Sed  }
737193323Sed}
738193323Sed
739193323Sed
740193323Sed/// InlinePatternFragments - If this pattern refers to any pattern
741193323Sed/// fragments, inline them into place, giving us a pattern without any
742193323Sed/// PatFrag references.
743193323SedTreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
744193323Sed  if (isLeaf()) return this;  // nothing to do.
745193323Sed  Record *Op = getOperator();
746193323Sed
747193323Sed  if (!Op->isSubClassOf("PatFrag")) {
748193323Sed    // Just recursively inline children nodes.
749193323Sed    for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
750193323Sed      TreePatternNode *Child = getChild(i);
751193323Sed      TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
752193323Sed
753193323Sed      assert((Child->getPredicateFns().empty() ||
754193323Sed              NewChild->getPredicateFns() == Child->getPredicateFns()) &&
755193323Sed             "Non-empty child predicate clobbered!");
756193323Sed
757193323Sed      setChild(i, NewChild);
758193323Sed    }
759193323Sed    return this;
760193323Sed  }
761193323Sed
762193323Sed  // Otherwise, we found a reference to a fragment.  First, look up its
763193323Sed  // TreePattern record.
764193323Sed  TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
765193323Sed
766193323Sed  // Verify that we are passing the right number of operands.
767193323Sed  if (Frag->getNumArgs() != Children.size())
768193323Sed    TP.error("'" + Op->getName() + "' fragment requires " +
769193323Sed             utostr(Frag->getNumArgs()) + " operands!");
770193323Sed
771193323Sed  TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
772193323Sed
773193323Sed  std::string Code = Op->getValueAsCode("Predicate");
774193323Sed  if (!Code.empty())
775193323Sed    FragTree->addPredicateFn("Predicate_"+Op->getName());
776193323Sed
777193323Sed  // Resolve formal arguments to their actual value.
778193323Sed  if (Frag->getNumArgs()) {
779193323Sed    // Compute the map of formal to actual arguments.
780193323Sed    std::map<std::string, TreePatternNode*> ArgMap;
781193323Sed    for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
782193323Sed      ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
783193323Sed
784193323Sed    FragTree->SubstituteFormalArguments(ArgMap);
785193323Sed  }
786193323Sed
787193323Sed  FragTree->setName(getName());
788193323Sed  FragTree->UpdateNodeType(getExtTypes(), TP);
789193323Sed
790193323Sed  // Transfer in the old predicates.
791193323Sed  for (unsigned i = 0, e = getPredicateFns().size(); i != e; ++i)
792193323Sed    FragTree->addPredicateFn(getPredicateFns()[i]);
793193323Sed
794193323Sed  // Get a new copy of this fragment to stitch into here.
795193323Sed  //delete this;    // FIXME: implement refcounting!
796193323Sed
797193323Sed  // The fragment we inlined could have recursive inlining that is needed.  See
798193323Sed  // if there are any pattern fragments in it and inline them as needed.
799193323Sed  return FragTree->InlinePatternFragments(TP);
800193323Sed}
801193323Sed
802193323Sed/// getImplicitType - Check to see if the specified record has an implicit
803194612Sed/// type which should be applied to it.  This will infer the type of register
804193323Sed/// references from the register file information, for example.
805193323Sed///
806193323Sedstatic std::vector<unsigned char> getImplicitType(Record *R, bool NotRegisters,
807203954Srdivacky                                                  TreePattern &TP) {
808193323Sed  // Some common return values
809198090Srdivacky  std::vector<unsigned char> Unknown(1, EEVT::isUnknown);
810193323Sed  std::vector<unsigned char> Other(1, MVT::Other);
811193323Sed
812193323Sed  // Check to see if this is a register or a register class...
813193323Sed  if (R->isSubClassOf("RegisterClass")) {
814193323Sed    if (NotRegisters)
815193323Sed      return Unknown;
816193323Sed    const CodeGenRegisterClass &RC =
817193323Sed      TP.getDAGPatterns().getTargetInfo().getRegisterClass(R);
818193323Sed    return ConvertVTs(RC.getValueTypes());
819193323Sed  } else if (R->isSubClassOf("PatFrag")) {
820193323Sed    // Pattern fragment types will be resolved when they are inlined.
821193323Sed    return Unknown;
822193323Sed  } else if (R->isSubClassOf("Register")) {
823193323Sed    if (NotRegisters)
824193323Sed      return Unknown;
825193323Sed    const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
826193323Sed    return T.getRegisterVTs(R);
827193323Sed  } else if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
828193323Sed    // Using a VTSDNode or CondCodeSDNode.
829193323Sed    return Other;
830193323Sed  } else if (R->isSubClassOf("ComplexPattern")) {
831193323Sed    if (NotRegisters)
832193323Sed      return Unknown;
833193323Sed    std::vector<unsigned char>
834193323Sed    ComplexPat(1, TP.getDAGPatterns().getComplexPattern(R).getValueType());
835193323Sed    return ComplexPat;
836198090Srdivacky  } else if (R->isSubClassOf("PointerLikeRegClass")) {
837193323Sed    Other[0] = MVT::iPTR;
838193323Sed    return Other;
839193323Sed  } else if (R->getName() == "node" || R->getName() == "srcvalue" ||
840193323Sed             R->getName() == "zero_reg") {
841193323Sed    // Placeholder.
842193323Sed    return Unknown;
843193323Sed  }
844193323Sed
845193323Sed  TP.error("Unknown node flavor used in pattern: " + R->getName());
846193323Sed  return Other;
847193323Sed}
848193323Sed
849193323Sed
850193323Sed/// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
851193323Sed/// CodeGenIntrinsic information for it, otherwise return a null pointer.
852193323Sedconst CodeGenIntrinsic *TreePatternNode::
853193323SedgetIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
854193323Sed  if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
855193323Sed      getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
856193323Sed      getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
857193323Sed    return 0;
858193323Sed
859193323Sed  unsigned IID =
860193323Sed    dynamic_cast<IntInit*>(getChild(0)->getLeafValue())->getValue();
861193323Sed  return &CDP.getIntrinsicInfo(IID);
862193323Sed}
863193323Sed
864203954Srdivacky/// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
865203954Srdivacky/// return the ComplexPattern information, otherwise return null.
866203954Srdivackyconst ComplexPattern *
867203954SrdivackyTreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
868203954Srdivacky  if (!isLeaf()) return 0;
869203954Srdivacky
870203954Srdivacky  DefInit *DI = dynamic_cast<DefInit*>(getLeafValue());
871203954Srdivacky  if (DI && DI->getDef()->isSubClassOf("ComplexPattern"))
872203954Srdivacky    return &CGP.getComplexPattern(DI->getDef());
873203954Srdivacky  return 0;
874203954Srdivacky}
875203954Srdivacky
876203954Srdivacky/// NodeHasProperty - Return true if this node has the specified property.
877203954Srdivackybool TreePatternNode::NodeHasProperty(SDNP Property,
878203954Srdivacky                                      const CodeGenDAGPatterns &CGP) const {
879203954Srdivacky  if (isLeaf()) {
880203954Srdivacky    if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
881203954Srdivacky      return CP->hasProperty(Property);
882203954Srdivacky    return false;
883203954Srdivacky  }
884203954Srdivacky
885203954Srdivacky  Record *Operator = getOperator();
886203954Srdivacky  if (!Operator->isSubClassOf("SDNode")) return false;
887203954Srdivacky
888203954Srdivacky  return CGP.getSDNodeInfo(Operator).hasProperty(Property);
889203954Srdivacky}
890203954Srdivacky
891203954Srdivacky
892203954Srdivacky
893203954Srdivacky
894203954Srdivacky/// TreeHasProperty - Return true if any node in this tree has the specified
895203954Srdivacky/// property.
896203954Srdivackybool TreePatternNode::TreeHasProperty(SDNP Property,
897203954Srdivacky                                      const CodeGenDAGPatterns &CGP) const {
898203954Srdivacky  if (NodeHasProperty(Property, CGP))
899203954Srdivacky    return true;
900203954Srdivacky  for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
901203954Srdivacky    if (getChild(i)->TreeHasProperty(Property, CGP))
902203954Srdivacky      return true;
903203954Srdivacky  return false;
904203954Srdivacky}
905203954Srdivacky
906193323Sed/// isCommutativeIntrinsic - Return true if the node corresponds to a
907193323Sed/// commutative intrinsic.
908193323Sedbool
909193323SedTreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
910193323Sed  if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
911193323Sed    return Int->isCommutative;
912193323Sed  return false;
913193323Sed}
914193323Sed
915193323Sed
916193323Sed/// ApplyTypeConstraints - Apply all of the type constraints relevant to
917193323Sed/// this node and its children in the tree.  This returns true if it makes a
918193323Sed/// change, false otherwise.  If a type contradiction is found, throw an
919193323Sed/// exception.
920193323Sedbool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
921193323Sed  CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
922193323Sed  if (isLeaf()) {
923193323Sed    if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
924193323Sed      // If it's a regclass or something else known, include the type.
925193323Sed      return UpdateNodeType(getImplicitType(DI->getDef(), NotRegisters, TP),TP);
926203954Srdivacky    }
927203954Srdivacky
928203954Srdivacky    if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
929193323Sed      // Int inits are always integers. :)
930198090Srdivacky      bool MadeChange = UpdateNodeType(MVT::iAny, TP);
931193323Sed
932193323Sed      if (hasTypeSet()) {
933193323Sed        // At some point, it may make sense for this tree pattern to have
934193323Sed        // multiple types.  Assert here that it does not, so we revisit this
935193323Sed        // code when appropriate.
936193323Sed        assert(getExtTypes().size() >= 1 && "TreePattern doesn't have a type!");
937193323Sed        MVT::SimpleValueType VT = getTypeNum(0);
938193323Sed        for (unsigned i = 1, e = getExtTypes().size(); i != e; ++i)
939193323Sed          assert(getTypeNum(i) == VT && "TreePattern has too many types!");
940193323Sed
941193323Sed        VT = getTypeNum(0);
942193323Sed        if (VT != MVT::iPTR && VT != MVT::iPTRAny) {
943198090Srdivacky          unsigned Size = EVT(VT).getSizeInBits();
944193323Sed          // Make sure that the value is representable for this type.
945193323Sed          if (Size < 32) {
946193323Sed            int Val = (II->getValue() << (32-Size)) >> (32-Size);
947193323Sed            if (Val != II->getValue()) {
948193323Sed              // If sign-extended doesn't fit, does it fit as unsigned?
949193323Sed              unsigned ValueMask;
950193323Sed              unsigned UnsignedVal;
951193323Sed              ValueMask = unsigned(~uint32_t(0UL) >> (32-Size));
952193323Sed              UnsignedVal = unsigned(II->getValue());
953193323Sed
954193323Sed              if ((ValueMask & UnsignedVal) != UnsignedVal) {
955193323Sed                TP.error("Integer value '" + itostr(II->getValue())+
956193323Sed                         "' is out of range for type '" +
957193323Sed                         getEnumName(getTypeNum(0)) + "'!");
958193323Sed              }
959193323Sed            }
960194612Sed          }
961194612Sed        }
962193323Sed      }
963193323Sed
964193323Sed      return MadeChange;
965193323Sed    }
966193323Sed    return false;
967193323Sed  }
968193323Sed
969193323Sed  // special handling for set, which isn't really an SDNode.
970193323Sed  if (getOperator()->getName() == "set") {
971193323Sed    assert (getNumChildren() >= 2 && "Missing RHS of a set?");
972193323Sed    unsigned NC = getNumChildren();
973193323Sed    bool MadeChange = false;
974193323Sed    for (unsigned i = 0; i < NC-1; ++i) {
975193323Sed      MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
976193323Sed      MadeChange |= getChild(NC-1)->ApplyTypeConstraints(TP, NotRegisters);
977193323Sed
978193323Sed      // Types of operands must match.
979193323Sed      MadeChange |= getChild(i)->UpdateNodeType(getChild(NC-1)->getExtTypes(),
980193323Sed                                                TP);
981193323Sed      MadeChange |= getChild(NC-1)->UpdateNodeType(getChild(i)->getExtTypes(),
982193323Sed                                                   TP);
983193323Sed      MadeChange |= UpdateNodeType(MVT::isVoid, TP);
984193323Sed    }
985193323Sed    return MadeChange;
986204642Srdivacky  }
987204642Srdivacky
988204642Srdivacky  if (getOperator()->getName() == "implicit" ||
989204642Srdivacky      getOperator()->getName() == "parallel") {
990193323Sed    bool MadeChange = false;
991193323Sed    for (unsigned i = 0; i < getNumChildren(); ++i)
992193323Sed      MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
993193323Sed    MadeChange |= UpdateNodeType(MVT::isVoid, TP);
994193323Sed    return MadeChange;
995204642Srdivacky  }
996204642Srdivacky
997204642Srdivacky  if (getOperator()->getName() == "COPY_TO_REGCLASS") {
998193323Sed    bool MadeChange = false;
999193323Sed    MadeChange |= getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1000193323Sed    MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
1001193323Sed    return MadeChange;
1002204642Srdivacky  }
1003204642Srdivacky
1004204642Srdivacky  if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
1005193323Sed    bool MadeChange = false;
1006193323Sed
1007193323Sed    // Apply the result type to the node.
1008193323Sed    unsigned NumRetVTs = Int->IS.RetVTs.size();
1009193323Sed    unsigned NumParamVTs = Int->IS.ParamVTs.size();
1010193323Sed
1011193323Sed    for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
1012193323Sed      MadeChange |= UpdateNodeType(Int->IS.RetVTs[i], TP);
1013193323Sed
1014193323Sed    if (getNumChildren() != NumParamVTs + NumRetVTs)
1015193323Sed      TP.error("Intrinsic '" + Int->Name + "' expects " +
1016193323Sed               utostr(NumParamVTs + NumRetVTs - 1) + " operands, not " +
1017193323Sed               utostr(getNumChildren() - 1) + " operands!");
1018193323Sed
1019193323Sed    // Apply type info to the intrinsic ID.
1020193323Sed    MadeChange |= getChild(0)->UpdateNodeType(MVT::iPTR, TP);
1021193323Sed
1022193323Sed    for (unsigned i = NumRetVTs, e = getNumChildren(); i != e; ++i) {
1023193323Sed      MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i - NumRetVTs];
1024193323Sed      MadeChange |= getChild(i)->UpdateNodeType(OpVT, TP);
1025193323Sed      MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1026193323Sed    }
1027193323Sed    return MadeChange;
1028204642Srdivacky  }
1029204642Srdivacky
1030204642Srdivacky  if (getOperator()->isSubClassOf("SDNode")) {
1031193323Sed    const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
1032193323Sed
1033193323Sed    bool MadeChange = NI.ApplyTypeConstraints(this, TP);
1034193323Sed    for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1035193323Sed      MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1036193323Sed    // Branch, etc. do not produce results and top-level forms in instr pattern
1037193323Sed    // must have void types.
1038193323Sed    if (NI.getNumResults() == 0)
1039193323Sed      MadeChange |= UpdateNodeType(MVT::isVoid, TP);
1040193323Sed
1041193323Sed    return MadeChange;
1042204642Srdivacky  }
1043204642Srdivacky
1044204642Srdivacky  if (getOperator()->isSubClassOf("Instruction")) {
1045193323Sed    const DAGInstruction &Inst = CDP.getInstruction(getOperator());
1046193323Sed    bool MadeChange = false;
1047193323Sed    unsigned NumResults = Inst.getNumResults();
1048193323Sed
1049193323Sed    assert(NumResults <= 1 &&
1050193323Sed           "Only supports zero or one result instrs!");
1051193323Sed
1052193323Sed    CodeGenInstruction &InstInfo =
1053193323Sed      CDP.getTargetInfo().getInstruction(getOperator()->getName());
1054193323Sed    // Apply the result type to the node
1055193323Sed    if (NumResults == 0 || InstInfo.NumDefs == 0) {
1056193323Sed      MadeChange = UpdateNodeType(MVT::isVoid, TP);
1057193323Sed    } else {
1058193323Sed      Record *ResultNode = Inst.getResult(0);
1059193323Sed
1060198090Srdivacky      if (ResultNode->isSubClassOf("PointerLikeRegClass")) {
1061193323Sed        std::vector<unsigned char> VT;
1062193323Sed        VT.push_back(MVT::iPTR);
1063193323Sed        MadeChange = UpdateNodeType(VT, TP);
1064193323Sed      } else if (ResultNode->getName() == "unknown") {
1065193323Sed        std::vector<unsigned char> VT;
1066198090Srdivacky        VT.push_back(EEVT::isUnknown);
1067193323Sed        MadeChange = UpdateNodeType(VT, TP);
1068193323Sed      } else {
1069193323Sed        assert(ResultNode->isSubClassOf("RegisterClass") &&
1070193323Sed               "Operands should be register classes!");
1071193323Sed
1072193323Sed        const CodeGenRegisterClass &RC =
1073193323Sed          CDP.getTargetInfo().getRegisterClass(ResultNode);
1074193323Sed        MadeChange = UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
1075193323Sed      }
1076193323Sed    }
1077193323Sed
1078193323Sed    unsigned ChildNo = 0;
1079193323Sed    for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
1080193323Sed      Record *OperandNode = Inst.getOperand(i);
1081193323Sed
1082193323Sed      // If the instruction expects a predicate or optional def operand, we
1083193323Sed      // codegen this by setting the operand to it's default value if it has a
1084193323Sed      // non-empty DefaultOps field.
1085193323Sed      if ((OperandNode->isSubClassOf("PredicateOperand") ||
1086193323Sed           OperandNode->isSubClassOf("OptionalDefOperand")) &&
1087193323Sed          !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1088193323Sed        continue;
1089193323Sed
1090193323Sed      // Verify that we didn't run out of provided operands.
1091193323Sed      if (ChildNo >= getNumChildren())
1092193323Sed        TP.error("Instruction '" + getOperator()->getName() +
1093193323Sed                 "' expects more operands than were provided.");
1094193323Sed
1095193323Sed      MVT::SimpleValueType VT;
1096193323Sed      TreePatternNode *Child = getChild(ChildNo++);
1097193323Sed      if (OperandNode->isSubClassOf("RegisterClass")) {
1098193323Sed        const CodeGenRegisterClass &RC =
1099193323Sed          CDP.getTargetInfo().getRegisterClass(OperandNode);
1100193323Sed        MadeChange |= Child->UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
1101193323Sed      } else if (OperandNode->isSubClassOf("Operand")) {
1102193323Sed        VT = getValueType(OperandNode->getValueAsDef("Type"));
1103193323Sed        MadeChange |= Child->UpdateNodeType(VT, TP);
1104198090Srdivacky      } else if (OperandNode->isSubClassOf("PointerLikeRegClass")) {
1105193323Sed        MadeChange |= Child->UpdateNodeType(MVT::iPTR, TP);
1106193323Sed      } else if (OperandNode->getName() == "unknown") {
1107198090Srdivacky        MadeChange |= Child->UpdateNodeType(EEVT::isUnknown, TP);
1108193323Sed      } else {
1109193323Sed        assert(0 && "Unknown operand type!");
1110193323Sed        abort();
1111193323Sed      }
1112193323Sed      MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
1113193323Sed    }
1114193323Sed
1115193323Sed    if (ChildNo != getNumChildren())
1116193323Sed      TP.error("Instruction '" + getOperator()->getName() +
1117193323Sed               "' was provided too many operands!");
1118193323Sed
1119193323Sed    return MadeChange;
1120204642Srdivacky  }
1121204642Srdivacky
1122204642Srdivacky  assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
1123204642Srdivacky
1124204642Srdivacky  // Node transforms always take one operand.
1125204642Srdivacky  if (getNumChildren() != 1)
1126204642Srdivacky    TP.error("Node transform '" + getOperator()->getName() +
1127204642Srdivacky             "' requires one operand!");
1128193323Sed
1129204642Srdivacky  // If either the output or input of the xform does not have exact
1130204642Srdivacky  // type info. We assume they must be the same. Otherwise, it is perfectly
1131204642Srdivacky  // legal to transform from one type to a completely different type.
1132204642Srdivacky  if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
1133204642Srdivacky    bool MadeChange = UpdateNodeType(getChild(0)->getExtTypes(), TP);
1134204642Srdivacky    MadeChange |= getChild(0)->UpdateNodeType(getExtTypes(), TP);
1135204642Srdivacky    return MadeChange;
1136193323Sed  }
1137204642Srdivacky  return false;
1138193323Sed}
1139193323Sed
1140193323Sed/// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
1141193323Sed/// RHS of a commutative operation, not the on LHS.
1142193323Sedstatic bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
1143193323Sed  if (!N->isLeaf() && N->getOperator()->getName() == "imm")
1144193323Sed    return true;
1145193323Sed  if (N->isLeaf() && dynamic_cast<IntInit*>(N->getLeafValue()))
1146193323Sed    return true;
1147193323Sed  return false;
1148193323Sed}
1149193323Sed
1150193323Sed
1151193323Sed/// canPatternMatch - If it is impossible for this pattern to match on this
1152193323Sed/// target, fill in Reason and return false.  Otherwise, return true.  This is
1153193323Sed/// used as a sanity check for .td files (to prevent people from writing stuff
1154193323Sed/// that can never possibly work), and to prevent the pattern permuter from
1155193323Sed/// generating stuff that is useless.
1156193323Sedbool TreePatternNode::canPatternMatch(std::string &Reason,
1157193323Sed                                      const CodeGenDAGPatterns &CDP) {
1158193323Sed  if (isLeaf()) return true;
1159193323Sed
1160193323Sed  for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1161193323Sed    if (!getChild(i)->canPatternMatch(Reason, CDP))
1162193323Sed      return false;
1163193323Sed
1164193323Sed  // If this is an intrinsic, handle cases that would make it not match.  For
1165193323Sed  // example, if an operand is required to be an immediate.
1166193323Sed  if (getOperator()->isSubClassOf("Intrinsic")) {
1167193323Sed    // TODO:
1168193323Sed    return true;
1169193323Sed  }
1170193323Sed
1171193323Sed  // If this node is a commutative operator, check that the LHS isn't an
1172193323Sed  // immediate.
1173193323Sed  const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
1174193323Sed  bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
1175193323Sed  if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
1176193323Sed    // Scan all of the operands of the node and make sure that only the last one
1177193323Sed    // is a constant node, unless the RHS also is.
1178193323Sed    if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
1179193323Sed      bool Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
1180193323Sed      for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
1181193323Sed        if (OnlyOnRHSOfCommutative(getChild(i))) {
1182193323Sed          Reason="Immediate value must be on the RHS of commutative operators!";
1183193323Sed          return false;
1184193323Sed        }
1185193323Sed    }
1186193323Sed  }
1187193323Sed
1188193323Sed  return true;
1189193323Sed}
1190193323Sed
1191193323Sed//===----------------------------------------------------------------------===//
1192193323Sed// TreePattern implementation
1193193323Sed//
1194193323Sed
1195193323SedTreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
1196193323Sed                         CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
1197193323Sed   isInputPattern = isInput;
1198193323Sed   for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
1199193323Sed     Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
1200193323Sed}
1201193323Sed
1202193323SedTreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
1203193323Sed                         CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
1204193323Sed  isInputPattern = isInput;
1205193323Sed  Trees.push_back(ParseTreePattern(Pat));
1206193323Sed}
1207193323Sed
1208193323SedTreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
1209193323Sed                         CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
1210193323Sed  isInputPattern = isInput;
1211193323Sed  Trees.push_back(Pat);
1212193323Sed}
1213193323Sed
1214193323Sed
1215193323Sed
1216193323Sedvoid TreePattern::error(const std::string &Msg) const {
1217193323Sed  dump();
1218193323Sed  throw TGError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
1219193323Sed}
1220193323Sed
1221193323SedTreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
1222193323Sed  DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
1223193323Sed  if (!OpDef) error("Pattern has unexpected operator type!");
1224193323Sed  Record *Operator = OpDef->getDef();
1225193323Sed
1226193323Sed  if (Operator->isSubClassOf("ValueType")) {
1227193323Sed    // If the operator is a ValueType, then this must be "type cast" of a leaf
1228193323Sed    // node.
1229193323Sed    if (Dag->getNumArgs() != 1)
1230193323Sed      error("Type cast only takes one operand!");
1231193323Sed
1232193323Sed    Init *Arg = Dag->getArg(0);
1233193323Sed    TreePatternNode *New;
1234193323Sed    if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
1235193323Sed      Record *R = DI->getDef();
1236193323Sed      if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
1237193323Sed        Dag->setArg(0, new DagInit(DI, "",
1238193323Sed                                std::vector<std::pair<Init*, std::string> >()));
1239193323Sed        return ParseTreePattern(Dag);
1240193323Sed      }
1241193323Sed      New = new TreePatternNode(DI);
1242193323Sed    } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
1243193323Sed      New = ParseTreePattern(DI);
1244193323Sed    } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
1245193323Sed      New = new TreePatternNode(II);
1246193323Sed      if (!Dag->getArgName(0).empty())
1247193323Sed        error("Constant int argument should not have a name!");
1248193323Sed    } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
1249193323Sed      // Turn this into an IntInit.
1250193323Sed      Init *II = BI->convertInitializerTo(new IntRecTy());
1251193323Sed      if (II == 0 || !dynamic_cast<IntInit*>(II))
1252193323Sed        error("Bits value must be constants!");
1253193323Sed
1254193323Sed      New = new TreePatternNode(dynamic_cast<IntInit*>(II));
1255193323Sed      if (!Dag->getArgName(0).empty())
1256193323Sed        error("Constant int argument should not have a name!");
1257193323Sed    } else {
1258193323Sed      Arg->dump();
1259193323Sed      error("Unknown leaf value for tree pattern!");
1260193323Sed      return 0;
1261193323Sed    }
1262193323Sed
1263193323Sed    // Apply the type cast.
1264193323Sed    New->UpdateNodeType(getValueType(Operator), *this);
1265193323Sed    if (New->getNumChildren() == 0)
1266193323Sed      New->setName(Dag->getArgName(0));
1267193323Sed    return New;
1268193323Sed  }
1269193323Sed
1270193323Sed  // Verify that this is something that makes sense for an operator.
1271193323Sed  if (!Operator->isSubClassOf("PatFrag") &&
1272193323Sed      !Operator->isSubClassOf("SDNode") &&
1273193323Sed      !Operator->isSubClassOf("Instruction") &&
1274193323Sed      !Operator->isSubClassOf("SDNodeXForm") &&
1275193323Sed      !Operator->isSubClassOf("Intrinsic") &&
1276193323Sed      Operator->getName() != "set" &&
1277193323Sed      Operator->getName() != "implicit" &&
1278193323Sed      Operator->getName() != "parallel")
1279193323Sed    error("Unrecognized node '" + Operator->getName() + "'!");
1280193323Sed
1281193323Sed  //  Check to see if this is something that is illegal in an input pattern.
1282193323Sed  if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
1283193323Sed                         Operator->isSubClassOf("SDNodeXForm")))
1284193323Sed    error("Cannot use '" + Operator->getName() + "' in an input pattern!");
1285193323Sed
1286193323Sed  std::vector<TreePatternNode*> Children;
1287193323Sed
1288193323Sed  for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
1289193323Sed    Init *Arg = Dag->getArg(i);
1290193323Sed    if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
1291193323Sed      Children.push_back(ParseTreePattern(DI));
1292193323Sed      if (Children.back()->getName().empty())
1293193323Sed        Children.back()->setName(Dag->getArgName(i));
1294193323Sed    } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
1295193323Sed      Record *R = DefI->getDef();
1296193323Sed      // Direct reference to a leaf DagNode or PatFrag?  Turn it into a
1297193323Sed      // TreePatternNode if its own.
1298193323Sed      if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
1299193323Sed        Dag->setArg(i, new DagInit(DefI, "",
1300193323Sed                              std::vector<std::pair<Init*, std::string> >()));
1301193323Sed        --i;  // Revisit this node...
1302193323Sed      } else {
1303193323Sed        TreePatternNode *Node = new TreePatternNode(DefI);
1304193323Sed        Node->setName(Dag->getArgName(i));
1305193323Sed        Children.push_back(Node);
1306193323Sed
1307193323Sed        // Input argument?
1308193323Sed        if (R->getName() == "node") {
1309193323Sed          if (Dag->getArgName(i).empty())
1310193323Sed            error("'node' argument requires a name to match with operand list");
1311193323Sed          Args.push_back(Dag->getArgName(i));
1312193323Sed        }
1313193323Sed      }
1314193323Sed    } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
1315193323Sed      TreePatternNode *Node = new TreePatternNode(II);
1316193323Sed      if (!Dag->getArgName(i).empty())
1317193323Sed        error("Constant int argument should not have a name!");
1318193323Sed      Children.push_back(Node);
1319193323Sed    } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
1320193323Sed      // Turn this into an IntInit.
1321193323Sed      Init *II = BI->convertInitializerTo(new IntRecTy());
1322193323Sed      if (II == 0 || !dynamic_cast<IntInit*>(II))
1323193323Sed        error("Bits value must be constants!");
1324193323Sed
1325193323Sed      TreePatternNode *Node = new TreePatternNode(dynamic_cast<IntInit*>(II));
1326193323Sed      if (!Dag->getArgName(i).empty())
1327193323Sed        error("Constant int argument should not have a name!");
1328193323Sed      Children.push_back(Node);
1329193323Sed    } else {
1330195340Sed      errs() << '"';
1331193323Sed      Arg->dump();
1332195340Sed      errs() << "\": ";
1333193323Sed      error("Unknown leaf value for tree pattern!");
1334193323Sed    }
1335193323Sed  }
1336193323Sed
1337193323Sed  // If the operator is an intrinsic, then this is just syntactic sugar for for
1338193323Sed  // (intrinsic_* <number>, ..children..).  Pick the right intrinsic node, and
1339193323Sed  // convert the intrinsic name to a number.
1340193323Sed  if (Operator->isSubClassOf("Intrinsic")) {
1341193323Sed    const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
1342193323Sed    unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
1343193323Sed
1344193323Sed    // If this intrinsic returns void, it must have side-effects and thus a
1345193323Sed    // chain.
1346193323Sed    if (Int.IS.RetVTs[0] == MVT::isVoid) {
1347193323Sed      Operator = getDAGPatterns().get_intrinsic_void_sdnode();
1348193323Sed    } else if (Int.ModRef != CodeGenIntrinsic::NoMem) {
1349193323Sed      // Has side-effects, requires chain.
1350193323Sed      Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
1351193323Sed    } else {
1352193323Sed      // Otherwise, no chain.
1353193323Sed      Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
1354193323Sed    }
1355193323Sed
1356193323Sed    TreePatternNode *IIDNode = new TreePatternNode(new IntInit(IID));
1357193323Sed    Children.insert(Children.begin(), IIDNode);
1358193323Sed  }
1359193323Sed
1360193323Sed  TreePatternNode *Result = new TreePatternNode(Operator, Children);
1361193323Sed  Result->setName(Dag->getName());
1362193323Sed  return Result;
1363193323Sed}
1364193323Sed
1365193323Sed/// InferAllTypes - Infer/propagate as many types throughout the expression
1366193323Sed/// patterns as possible.  Return true if all types are inferred, false
1367193323Sed/// otherwise.  Throw an exception if a type contradiction is found.
1368193323Sedbool TreePattern::InferAllTypes() {
1369193323Sed  bool MadeChange = true;
1370193323Sed  while (MadeChange) {
1371193323Sed    MadeChange = false;
1372193323Sed    for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1373193323Sed      MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
1374193323Sed  }
1375193323Sed
1376193323Sed  bool HasUnresolvedTypes = false;
1377193323Sed  for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1378193323Sed    HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
1379193323Sed  return !HasUnresolvedTypes;
1380193323Sed}
1381193323Sed
1382195340Sedvoid TreePattern::print(raw_ostream &OS) const {
1383193323Sed  OS << getRecord()->getName();
1384193323Sed  if (!Args.empty()) {
1385193323Sed    OS << "(" << Args[0];
1386193323Sed    for (unsigned i = 1, e = Args.size(); i != e; ++i)
1387193323Sed      OS << ", " << Args[i];
1388193323Sed    OS << ")";
1389193323Sed  }
1390193323Sed  OS << ": ";
1391193323Sed
1392193323Sed  if (Trees.size() > 1)
1393193323Sed    OS << "[\n";
1394193323Sed  for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
1395193323Sed    OS << "\t";
1396193323Sed    Trees[i]->print(OS);
1397193323Sed    OS << "\n";
1398193323Sed  }
1399193323Sed
1400193323Sed  if (Trees.size() > 1)
1401193323Sed    OS << "]\n";
1402193323Sed}
1403193323Sed
1404195340Sedvoid TreePattern::dump() const { print(errs()); }
1405193323Sed
1406193323Sed//===----------------------------------------------------------------------===//
1407193323Sed// CodeGenDAGPatterns implementation
1408193323Sed//
1409193323Sed
1410193323SedCodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) : Records(R) {
1411193323Sed  Intrinsics = LoadIntrinsics(Records, false);
1412193323Sed  TgtIntrinsics = LoadIntrinsics(Records, true);
1413193323Sed  ParseNodeInfo();
1414193323Sed  ParseNodeTransforms();
1415193323Sed  ParseComplexPatterns();
1416193323Sed  ParsePatternFragments();
1417193323Sed  ParseDefaultOperands();
1418193323Sed  ParseInstructions();
1419193323Sed  ParsePatterns();
1420193323Sed
1421193323Sed  // Generate variants.  For example, commutative patterns can match
1422193323Sed  // multiple ways.  Add them to PatternsToMatch as well.
1423193323Sed  GenerateVariants();
1424193323Sed
1425193323Sed  // Infer instruction flags.  For example, we can detect loads,
1426193323Sed  // stores, and side effects in many cases by examining an
1427193323Sed  // instruction's pattern.
1428193323Sed  InferInstructionFlags();
1429193323Sed}
1430193323Sed
1431193323SedCodeGenDAGPatterns::~CodeGenDAGPatterns() {
1432198090Srdivacky  for (pf_iterator I = PatternFragments.begin(),
1433193323Sed       E = PatternFragments.end(); I != E; ++I)
1434193323Sed    delete I->second;
1435193323Sed}
1436193323Sed
1437193323Sed
1438193323SedRecord *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
1439193323Sed  Record *N = Records.getDef(Name);
1440193323Sed  if (!N || !N->isSubClassOf("SDNode")) {
1441195340Sed    errs() << "Error getting SDNode '" << Name << "'!\n";
1442193323Sed    exit(1);
1443193323Sed  }
1444193323Sed  return N;
1445193323Sed}
1446193323Sed
1447193323Sed// Parse all of the SDNode definitions for the target, populating SDNodes.
1448193323Sedvoid CodeGenDAGPatterns::ParseNodeInfo() {
1449193323Sed  std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
1450193323Sed  while (!Nodes.empty()) {
1451193323Sed    SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
1452193323Sed    Nodes.pop_back();
1453193323Sed  }
1454193323Sed
1455193323Sed  // Get the builtin intrinsic nodes.
1456193323Sed  intrinsic_void_sdnode     = getSDNodeNamed("intrinsic_void");
1457193323Sed  intrinsic_w_chain_sdnode  = getSDNodeNamed("intrinsic_w_chain");
1458193323Sed  intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
1459193323Sed}
1460193323Sed
1461193323Sed/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
1462193323Sed/// map, and emit them to the file as functions.
1463193323Sedvoid CodeGenDAGPatterns::ParseNodeTransforms() {
1464193323Sed  std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
1465193323Sed  while (!Xforms.empty()) {
1466193323Sed    Record *XFormNode = Xforms.back();
1467193323Sed    Record *SDNode = XFormNode->getValueAsDef("Opcode");
1468193323Sed    std::string Code = XFormNode->getValueAsCode("XFormFunction");
1469193323Sed    SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
1470193323Sed
1471193323Sed    Xforms.pop_back();
1472193323Sed  }
1473193323Sed}
1474193323Sed
1475193323Sedvoid CodeGenDAGPatterns::ParseComplexPatterns() {
1476193323Sed  std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
1477193323Sed  while (!AMs.empty()) {
1478193323Sed    ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
1479193323Sed    AMs.pop_back();
1480193323Sed  }
1481193323Sed}
1482193323Sed
1483193323Sed
1484193323Sed/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
1485193323Sed/// file, building up the PatternFragments map.  After we've collected them all,
1486193323Sed/// inline fragments together as necessary, so that there are no references left
1487193323Sed/// inside a pattern fragment to a pattern fragment.
1488193323Sed///
1489193323Sedvoid CodeGenDAGPatterns::ParsePatternFragments() {
1490193323Sed  std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
1491193323Sed
1492193323Sed  // First step, parse all of the fragments.
1493193323Sed  for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1494193323Sed    DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
1495193323Sed    TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
1496193323Sed    PatternFragments[Fragments[i]] = P;
1497193323Sed
1498193323Sed    // Validate the argument list, converting it to set, to discard duplicates.
1499193323Sed    std::vector<std::string> &Args = P->getArgList();
1500193323Sed    std::set<std::string> OperandsSet(Args.begin(), Args.end());
1501193323Sed
1502193323Sed    if (OperandsSet.count(""))
1503193323Sed      P->error("Cannot have unnamed 'node' values in pattern fragment!");
1504193323Sed
1505193323Sed    // Parse the operands list.
1506193323Sed    DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
1507193323Sed    DefInit *OpsOp = dynamic_cast<DefInit*>(OpsList->getOperator());
1508193323Sed    // Special cases: ops == outs == ins. Different names are used to
1509193323Sed    // improve readability.
1510193323Sed    if (!OpsOp ||
1511193323Sed        (OpsOp->getDef()->getName() != "ops" &&
1512193323Sed         OpsOp->getDef()->getName() != "outs" &&
1513193323Sed         OpsOp->getDef()->getName() != "ins"))
1514193323Sed      P->error("Operands list should start with '(ops ... '!");
1515193323Sed
1516193323Sed    // Copy over the arguments.
1517193323Sed    Args.clear();
1518193323Sed    for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
1519193323Sed      if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
1520193323Sed          static_cast<DefInit*>(OpsList->getArg(j))->
1521193323Sed          getDef()->getName() != "node")
1522193323Sed        P->error("Operands list should all be 'node' values.");
1523193323Sed      if (OpsList->getArgName(j).empty())
1524193323Sed        P->error("Operands list should have names for each operand!");
1525193323Sed      if (!OperandsSet.count(OpsList->getArgName(j)))
1526193323Sed        P->error("'" + OpsList->getArgName(j) +
1527193323Sed                 "' does not occur in pattern or was multiply specified!");
1528193323Sed      OperandsSet.erase(OpsList->getArgName(j));
1529193323Sed      Args.push_back(OpsList->getArgName(j));
1530193323Sed    }
1531193323Sed
1532193323Sed    if (!OperandsSet.empty())
1533193323Sed      P->error("Operands list does not contain an entry for operand '" +
1534193323Sed               *OperandsSet.begin() + "'!");
1535193323Sed
1536193323Sed    // If there is a code init for this fragment, keep track of the fact that
1537193323Sed    // this fragment uses it.
1538193323Sed    std::string Code = Fragments[i]->getValueAsCode("Predicate");
1539193323Sed    if (!Code.empty())
1540193323Sed      P->getOnlyTree()->addPredicateFn("Predicate_"+Fragments[i]->getName());
1541193323Sed
1542193323Sed    // If there is a node transformation corresponding to this, keep track of
1543193323Sed    // it.
1544193323Sed    Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
1545193323Sed    if (!getSDNodeTransform(Transform).second.empty())    // not noop xform?
1546193323Sed      P->getOnlyTree()->setTransformFn(Transform);
1547193323Sed  }
1548193323Sed
1549193323Sed  // Now that we've parsed all of the tree fragments, do a closure on them so
1550193323Sed  // that there are not references to PatFrags left inside of them.
1551193323Sed  for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1552193323Sed    TreePattern *ThePat = PatternFragments[Fragments[i]];
1553193323Sed    ThePat->InlinePatternFragments();
1554193323Sed
1555193323Sed    // Infer as many types as possible.  Don't worry about it if we don't infer
1556193323Sed    // all of them, some may depend on the inputs of the pattern.
1557193323Sed    try {
1558193323Sed      ThePat->InferAllTypes();
1559193323Sed    } catch (...) {
1560193323Sed      // If this pattern fragment is not supported by this target (no types can
1561193323Sed      // satisfy its constraints), just ignore it.  If the bogus pattern is
1562193323Sed      // actually used by instructions, the type consistency error will be
1563193323Sed      // reported there.
1564193323Sed    }
1565193323Sed
1566193323Sed    // If debugging, print out the pattern fragment result.
1567193323Sed    DEBUG(ThePat->dump());
1568193323Sed  }
1569193323Sed}
1570193323Sed
1571193323Sedvoid CodeGenDAGPatterns::ParseDefaultOperands() {
1572193323Sed  std::vector<Record*> DefaultOps[2];
1573193323Sed  DefaultOps[0] = Records.getAllDerivedDefinitions("PredicateOperand");
1574193323Sed  DefaultOps[1] = Records.getAllDerivedDefinitions("OptionalDefOperand");
1575193323Sed
1576193323Sed  // Find some SDNode.
1577193323Sed  assert(!SDNodes.empty() && "No SDNodes parsed?");
1578193323Sed  Init *SomeSDNode = new DefInit(SDNodes.begin()->first);
1579193323Sed
1580193323Sed  for (unsigned iter = 0; iter != 2; ++iter) {
1581193323Sed    for (unsigned i = 0, e = DefaultOps[iter].size(); i != e; ++i) {
1582193323Sed      DagInit *DefaultInfo = DefaultOps[iter][i]->getValueAsDag("DefaultOps");
1583193323Sed
1584193323Sed      // Clone the DefaultInfo dag node, changing the operator from 'ops' to
1585193323Sed      // SomeSDnode so that we can parse this.
1586193323Sed      std::vector<std::pair<Init*, std::string> > Ops;
1587193323Sed      for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
1588193323Sed        Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
1589193323Sed                                     DefaultInfo->getArgName(op)));
1590193323Sed      DagInit *DI = new DagInit(SomeSDNode, "", Ops);
1591193323Sed
1592193323Sed      // Create a TreePattern to parse this.
1593193323Sed      TreePattern P(DefaultOps[iter][i], DI, false, *this);
1594193323Sed      assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
1595193323Sed
1596193323Sed      // Copy the operands over into a DAGDefaultOperand.
1597193323Sed      DAGDefaultOperand DefaultOpInfo;
1598193323Sed
1599193323Sed      TreePatternNode *T = P.getTree(0);
1600193323Sed      for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
1601193323Sed        TreePatternNode *TPN = T->getChild(op);
1602193323Sed        while (TPN->ApplyTypeConstraints(P, false))
1603193323Sed          /* Resolve all types */;
1604193323Sed
1605193323Sed        if (TPN->ContainsUnresolvedType()) {
1606193323Sed          if (iter == 0)
1607193323Sed            throw "Value #" + utostr(i) + " of PredicateOperand '" +
1608204642Srdivacky              DefaultOps[iter][i]->getName() +"' doesn't have a concrete type!";
1609193323Sed          else
1610193323Sed            throw "Value #" + utostr(i) + " of OptionalDefOperand '" +
1611204642Srdivacky              DefaultOps[iter][i]->getName() +"' doesn't have a concrete type!";
1612193323Sed        }
1613193323Sed        DefaultOpInfo.DefaultOps.push_back(TPN);
1614193323Sed      }
1615193323Sed
1616193323Sed      // Insert it into the DefaultOperands map so we can find it later.
1617193323Sed      DefaultOperands[DefaultOps[iter][i]] = DefaultOpInfo;
1618193323Sed    }
1619193323Sed  }
1620193323Sed}
1621193323Sed
1622193323Sed/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
1623193323Sed/// instruction input.  Return true if this is a real use.
1624193323Sedstatic bool HandleUse(TreePattern *I, TreePatternNode *Pat,
1625193323Sed                      std::map<std::string, TreePatternNode*> &InstInputs,
1626193323Sed                      std::vector<Record*> &InstImpInputs) {
1627193323Sed  // No name -> not interesting.
1628193323Sed  if (Pat->getName().empty()) {
1629193323Sed    if (Pat->isLeaf()) {
1630193323Sed      DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1631193323Sed      if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1632193323Sed        I->error("Input " + DI->getDef()->getName() + " must be named!");
1633193323Sed      else if (DI && DI->getDef()->isSubClassOf("Register"))
1634193323Sed        InstImpInputs.push_back(DI->getDef());
1635193323Sed    }
1636193323Sed    return false;
1637193323Sed  }
1638193323Sed
1639193323Sed  Record *Rec;
1640193323Sed  if (Pat->isLeaf()) {
1641193323Sed    DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1642193323Sed    if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
1643193323Sed    Rec = DI->getDef();
1644193323Sed  } else {
1645193323Sed    Rec = Pat->getOperator();
1646193323Sed  }
1647193323Sed
1648193323Sed  // SRCVALUE nodes are ignored.
1649193323Sed  if (Rec->getName() == "srcvalue")
1650193323Sed    return false;
1651193323Sed
1652193323Sed  TreePatternNode *&Slot = InstInputs[Pat->getName()];
1653193323Sed  if (!Slot) {
1654193323Sed    Slot = Pat;
1655204642Srdivacky    return true;
1656204642Srdivacky  }
1657204642Srdivacky  Record *SlotRec;
1658204642Srdivacky  if (Slot->isLeaf()) {
1659204642Srdivacky    SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
1660193323Sed  } else {
1661204642Srdivacky    assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
1662204642Srdivacky    SlotRec = Slot->getOperator();
1663193323Sed  }
1664204642Srdivacky
1665204642Srdivacky  // Ensure that the inputs agree if we've already seen this input.
1666204642Srdivacky  if (Rec != SlotRec)
1667204642Srdivacky    I->error("All $" + Pat->getName() + " inputs must agree with each other");
1668204642Srdivacky  if (Slot->getExtTypes() != Pat->getExtTypes())
1669204642Srdivacky    I->error("All $" + Pat->getName() + " inputs must agree with each other");
1670193323Sed  return true;
1671193323Sed}
1672193323Sed
1673193323Sed/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
1674193323Sed/// part of "I", the instruction), computing the set of inputs and outputs of
1675193323Sed/// the pattern.  Report errors if we see anything naughty.
1676193323Sedvoid CodeGenDAGPatterns::
1677193323SedFindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
1678193323Sed                            std::map<std::string, TreePatternNode*> &InstInputs,
1679193323Sed                            std::map<std::string, TreePatternNode*>&InstResults,
1680193323Sed                            std::vector<Record*> &InstImpInputs,
1681193323Sed                            std::vector<Record*> &InstImpResults) {
1682193323Sed  if (Pat->isLeaf()) {
1683193323Sed    bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1684193323Sed    if (!isUse && Pat->getTransformFn())
1685193323Sed      I->error("Cannot specify a transform function for a non-input value!");
1686193323Sed    return;
1687204642Srdivacky  }
1688204642Srdivacky
1689204642Srdivacky  if (Pat->getOperator()->getName() == "implicit") {
1690193323Sed    for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1691193323Sed      TreePatternNode *Dest = Pat->getChild(i);
1692193323Sed      if (!Dest->isLeaf())
1693193323Sed        I->error("implicitly defined value should be a register!");
1694193323Sed
1695193323Sed      DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1696193323Sed      if (!Val || !Val->getDef()->isSubClassOf("Register"))
1697193323Sed        I->error("implicitly defined value should be a register!");
1698193323Sed      InstImpResults.push_back(Val->getDef());
1699193323Sed    }
1700193323Sed    return;
1701204642Srdivacky  }
1702204642Srdivacky
1703204642Srdivacky  if (Pat->getOperator()->getName() != "set") {
1704193323Sed    // If this is not a set, verify that the children nodes are not void typed,
1705193323Sed    // and recurse.
1706193323Sed    for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1707193323Sed      if (Pat->getChild(i)->getExtTypeNum(0) == MVT::isVoid)
1708193323Sed        I->error("Cannot have void nodes inside of patterns!");
1709193323Sed      FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
1710193323Sed                                  InstImpInputs, InstImpResults);
1711193323Sed    }
1712193323Sed
1713193323Sed    // If this is a non-leaf node with no children, treat it basically as if
1714193323Sed    // it were a leaf.  This handles nodes like (imm).
1715193323Sed    bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1716193323Sed
1717193323Sed    if (!isUse && Pat->getTransformFn())
1718193323Sed      I->error("Cannot specify a transform function for a non-input value!");
1719193323Sed    return;
1720204642Srdivacky  }
1721193323Sed
1722193323Sed  // Otherwise, this is a set, validate and collect instruction results.
1723193323Sed  if (Pat->getNumChildren() == 0)
1724193323Sed    I->error("set requires operands!");
1725193323Sed
1726193323Sed  if (Pat->getTransformFn())
1727193323Sed    I->error("Cannot specify a transform function on a set node!");
1728193323Sed
1729193323Sed  // Check the set destinations.
1730193323Sed  unsigned NumDests = Pat->getNumChildren()-1;
1731193323Sed  for (unsigned i = 0; i != NumDests; ++i) {
1732193323Sed    TreePatternNode *Dest = Pat->getChild(i);
1733193323Sed    if (!Dest->isLeaf())
1734193323Sed      I->error("set destination should be a register!");
1735193323Sed
1736193323Sed    DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1737193323Sed    if (!Val)
1738193323Sed      I->error("set destination should be a register!");
1739193323Sed
1740193323Sed    if (Val->getDef()->isSubClassOf("RegisterClass") ||
1741198090Srdivacky        Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
1742193323Sed      if (Dest->getName().empty())
1743193323Sed        I->error("set destination must have a name!");
1744193323Sed      if (InstResults.count(Dest->getName()))
1745193323Sed        I->error("cannot set '" + Dest->getName() +"' multiple times");
1746193323Sed      InstResults[Dest->getName()] = Dest;
1747193323Sed    } else if (Val->getDef()->isSubClassOf("Register")) {
1748193323Sed      InstImpResults.push_back(Val->getDef());
1749193323Sed    } else {
1750193323Sed      I->error("set destination should be a register!");
1751193323Sed    }
1752193323Sed  }
1753193323Sed
1754193323Sed  // Verify and collect info from the computation.
1755193323Sed  FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
1756193323Sed                              InstInputs, InstResults,
1757193323Sed                              InstImpInputs, InstImpResults);
1758193323Sed}
1759193323Sed
1760193323Sed//===----------------------------------------------------------------------===//
1761193323Sed// Instruction Analysis
1762193323Sed//===----------------------------------------------------------------------===//
1763193323Sed
1764193323Sedclass InstAnalyzer {
1765193323Sed  const CodeGenDAGPatterns &CDP;
1766193323Sed  bool &mayStore;
1767193323Sed  bool &mayLoad;
1768193323Sed  bool &HasSideEffects;
1769193323Sedpublic:
1770193323Sed  InstAnalyzer(const CodeGenDAGPatterns &cdp,
1771193323Sed               bool &maystore, bool &mayload, bool &hse)
1772193323Sed    : CDP(cdp), mayStore(maystore), mayLoad(mayload), HasSideEffects(hse){
1773193323Sed  }
1774193323Sed
1775193323Sed  /// Analyze - Analyze the specified instruction, returning true if the
1776193323Sed  /// instruction had a pattern.
1777193323Sed  bool Analyze(Record *InstRecord) {
1778193323Sed    const TreePattern *Pattern = CDP.getInstruction(InstRecord).getPattern();
1779193323Sed    if (Pattern == 0) {
1780193323Sed      HasSideEffects = 1;
1781193323Sed      return false;  // No pattern.
1782193323Sed    }
1783193323Sed
1784193323Sed    // FIXME: Assume only the first tree is the pattern. The others are clobber
1785193323Sed    // nodes.
1786193323Sed    AnalyzeNode(Pattern->getTree(0));
1787193323Sed    return true;
1788193323Sed  }
1789193323Sed
1790193323Sedprivate:
1791193323Sed  void AnalyzeNode(const TreePatternNode *N) {
1792193323Sed    if (N->isLeaf()) {
1793193323Sed      if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
1794193323Sed        Record *LeafRec = DI->getDef();
1795193323Sed        // Handle ComplexPattern leaves.
1796193323Sed        if (LeafRec->isSubClassOf("ComplexPattern")) {
1797193323Sed          const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
1798193323Sed          if (CP.hasProperty(SDNPMayStore)) mayStore = true;
1799193323Sed          if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
1800193323Sed          if (CP.hasProperty(SDNPSideEffect)) HasSideEffects = true;
1801193323Sed        }
1802193323Sed      }
1803193323Sed      return;
1804193323Sed    }
1805193323Sed
1806193323Sed    // Analyze children.
1807193323Sed    for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1808193323Sed      AnalyzeNode(N->getChild(i));
1809193323Sed
1810193323Sed    // Ignore set nodes, which are not SDNodes.
1811193323Sed    if (N->getOperator()->getName() == "set")
1812193323Sed      return;
1813193323Sed
1814193323Sed    // Get information about the SDNode for the operator.
1815193323Sed    const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N->getOperator());
1816193323Sed
1817193323Sed    // Notice properties of the node.
1818193323Sed    if (OpInfo.hasProperty(SDNPMayStore)) mayStore = true;
1819193323Sed    if (OpInfo.hasProperty(SDNPMayLoad)) mayLoad = true;
1820193323Sed    if (OpInfo.hasProperty(SDNPSideEffect)) HasSideEffects = true;
1821193323Sed
1822193323Sed    if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
1823193323Sed      // If this is an intrinsic, analyze it.
1824193323Sed      if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
1825193323Sed        mayLoad = true;// These may load memory.
1826193323Sed
1827193323Sed      if (IntInfo->ModRef >= CodeGenIntrinsic::WriteArgMem)
1828193323Sed        mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
1829193323Sed
1830193323Sed      if (IntInfo->ModRef >= CodeGenIntrinsic::WriteMem)
1831193323Sed        // WriteMem intrinsics can have other strange effects.
1832193323Sed        HasSideEffects = true;
1833193323Sed    }
1834193323Sed  }
1835193323Sed
1836193323Sed};
1837193323Sed
1838193323Sedstatic void InferFromPattern(const CodeGenInstruction &Inst,
1839193323Sed                             bool &MayStore, bool &MayLoad,
1840193323Sed                             bool &HasSideEffects,
1841193323Sed                             const CodeGenDAGPatterns &CDP) {
1842193323Sed  MayStore = MayLoad = HasSideEffects = false;
1843193323Sed
1844193323Sed  bool HadPattern =
1845193323Sed    InstAnalyzer(CDP, MayStore, MayLoad, HasSideEffects).Analyze(Inst.TheDef);
1846193323Sed
1847193323Sed  // InstAnalyzer only correctly analyzes mayStore/mayLoad so far.
1848193323Sed  if (Inst.mayStore) {  // If the .td file explicitly sets mayStore, use it.
1849193323Sed    // If we decided that this is a store from the pattern, then the .td file
1850193323Sed    // entry is redundant.
1851193323Sed    if (MayStore)
1852193323Sed      fprintf(stderr,
1853193323Sed              "Warning: mayStore flag explicitly set on instruction '%s'"
1854193323Sed              " but flag already inferred from pattern.\n",
1855193323Sed              Inst.TheDef->getName().c_str());
1856193323Sed    MayStore = true;
1857193323Sed  }
1858193323Sed
1859193323Sed  if (Inst.mayLoad) {  // If the .td file explicitly sets mayLoad, use it.
1860193323Sed    // If we decided that this is a load from the pattern, then the .td file
1861193323Sed    // entry is redundant.
1862193323Sed    if (MayLoad)
1863193323Sed      fprintf(stderr,
1864193323Sed              "Warning: mayLoad flag explicitly set on instruction '%s'"
1865193323Sed              " but flag already inferred from pattern.\n",
1866193323Sed              Inst.TheDef->getName().c_str());
1867193323Sed    MayLoad = true;
1868193323Sed  }
1869193323Sed
1870193323Sed  if (Inst.neverHasSideEffects) {
1871193323Sed    if (HadPattern)
1872193323Sed      fprintf(stderr, "Warning: neverHasSideEffects set on instruction '%s' "
1873193323Sed              "which already has a pattern\n", Inst.TheDef->getName().c_str());
1874193323Sed    HasSideEffects = false;
1875193323Sed  }
1876193323Sed
1877193323Sed  if (Inst.hasSideEffects) {
1878193323Sed    if (HasSideEffects)
1879193323Sed      fprintf(stderr, "Warning: hasSideEffects set on instruction '%s' "
1880193323Sed              "which already inferred this.\n", Inst.TheDef->getName().c_str());
1881193323Sed    HasSideEffects = true;
1882193323Sed  }
1883193323Sed}
1884193323Sed
1885193323Sed/// ParseInstructions - Parse all of the instructions, inlining and resolving
1886193323Sed/// any fragments involved.  This populates the Instructions list with fully
1887193323Sed/// resolved instructions.
1888193323Sedvoid CodeGenDAGPatterns::ParseInstructions() {
1889193323Sed  std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
1890193323Sed
1891193323Sed  for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
1892193323Sed    ListInit *LI = 0;
1893193323Sed
1894193323Sed    if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
1895193323Sed      LI = Instrs[i]->getValueAsListInit("Pattern");
1896193323Sed
1897193323Sed    // If there is no pattern, only collect minimal information about the
1898193323Sed    // instruction for its operand list.  We have to assume that there is one
1899193323Sed    // result, as we have no detailed info.
1900193323Sed    if (!LI || LI->getSize() == 0) {
1901193323Sed      std::vector<Record*> Results;
1902193323Sed      std::vector<Record*> Operands;
1903193323Sed
1904193323Sed      CodeGenInstruction &InstInfo =Target.getInstruction(Instrs[i]->getName());
1905193323Sed
1906193323Sed      if (InstInfo.OperandList.size() != 0) {
1907193323Sed        if (InstInfo.NumDefs == 0) {
1908193323Sed          // These produce no results
1909193323Sed          for (unsigned j = 0, e = InstInfo.OperandList.size(); j < e; ++j)
1910193323Sed            Operands.push_back(InstInfo.OperandList[j].Rec);
1911193323Sed        } else {
1912193323Sed          // Assume the first operand is the result.
1913193323Sed          Results.push_back(InstInfo.OperandList[0].Rec);
1914193323Sed
1915193323Sed          // The rest are inputs.
1916193323Sed          for (unsigned j = 1, e = InstInfo.OperandList.size(); j < e; ++j)
1917193323Sed            Operands.push_back(InstInfo.OperandList[j].Rec);
1918193323Sed        }
1919193323Sed      }
1920193323Sed
1921193323Sed      // Create and insert the instruction.
1922193323Sed      std::vector<Record*> ImpResults;
1923193323Sed      std::vector<Record*> ImpOperands;
1924193323Sed      Instructions.insert(std::make_pair(Instrs[i],
1925193323Sed                          DAGInstruction(0, Results, Operands, ImpResults,
1926193323Sed                                         ImpOperands)));
1927193323Sed      continue;  // no pattern.
1928193323Sed    }
1929193323Sed
1930193323Sed    // Parse the instruction.
1931193323Sed    TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
1932193323Sed    // Inline pattern fragments into it.
1933193323Sed    I->InlinePatternFragments();
1934193323Sed
1935193323Sed    // Infer as many types as possible.  If we cannot infer all of them, we can
1936193323Sed    // never do anything with this instruction pattern: report it to the user.
1937193323Sed    if (!I->InferAllTypes())
1938193323Sed      I->error("Could not infer all types in pattern!");
1939193323Sed
1940193323Sed    // InstInputs - Keep track of all of the inputs of the instruction, along
1941193323Sed    // with the record they are declared as.
1942193323Sed    std::map<std::string, TreePatternNode*> InstInputs;
1943193323Sed
1944193323Sed    // InstResults - Keep track of all the virtual registers that are 'set'
1945193323Sed    // in the instruction, including what reg class they are.
1946193323Sed    std::map<std::string, TreePatternNode*> InstResults;
1947193323Sed
1948193323Sed    std::vector<Record*> InstImpInputs;
1949193323Sed    std::vector<Record*> InstImpResults;
1950193323Sed
1951193323Sed    // Verify that the top-level forms in the instruction are of void type, and
1952193323Sed    // fill in the InstResults map.
1953193323Sed    for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
1954193323Sed      TreePatternNode *Pat = I->getTree(j);
1955193323Sed      if (Pat->getExtTypeNum(0) != MVT::isVoid)
1956193323Sed        I->error("Top-level forms in instruction pattern should have"
1957193323Sed                 " void types");
1958193323Sed
1959193323Sed      // Find inputs and outputs, and verify the structure of the uses/defs.
1960193323Sed      FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
1961193323Sed                                  InstImpInputs, InstImpResults);
1962193323Sed    }
1963193323Sed
1964193323Sed    // Now that we have inputs and outputs of the pattern, inspect the operands
1965193323Sed    // list for the instruction.  This determines the order that operands are
1966193323Sed    // added to the machine instruction the node corresponds to.
1967193323Sed    unsigned NumResults = InstResults.size();
1968193323Sed
1969193323Sed    // Parse the operands list from the (ops) list, validating it.
1970193323Sed    assert(I->getArgList().empty() && "Args list should still be empty here!");
1971193323Sed    CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
1972193323Sed
1973193323Sed    // Check that all of the results occur first in the list.
1974193323Sed    std::vector<Record*> Results;
1975193323Sed    TreePatternNode *Res0Node = NULL;
1976193323Sed    for (unsigned i = 0; i != NumResults; ++i) {
1977193323Sed      if (i == CGI.OperandList.size())
1978193323Sed        I->error("'" + InstResults.begin()->first +
1979193323Sed                 "' set but does not appear in operand list!");
1980193323Sed      const std::string &OpName = CGI.OperandList[i].Name;
1981193323Sed
1982193323Sed      // Check that it exists in InstResults.
1983193323Sed      TreePatternNode *RNode = InstResults[OpName];
1984193323Sed      if (RNode == 0)
1985193323Sed        I->error("Operand $" + OpName + " does not exist in operand list!");
1986193323Sed
1987193323Sed      if (i == 0)
1988193323Sed        Res0Node = RNode;
1989193323Sed      Record *R = dynamic_cast<DefInit*>(RNode->getLeafValue())->getDef();
1990193323Sed      if (R == 0)
1991193323Sed        I->error("Operand $" + OpName + " should be a set destination: all "
1992193323Sed                 "outputs must occur before inputs in operand list!");
1993193323Sed
1994193323Sed      if (CGI.OperandList[i].Rec != R)
1995193323Sed        I->error("Operand $" + OpName + " class mismatch!");
1996193323Sed
1997193323Sed      // Remember the return type.
1998193323Sed      Results.push_back(CGI.OperandList[i].Rec);
1999193323Sed
2000193323Sed      // Okay, this one checks out.
2001193323Sed      InstResults.erase(OpName);
2002193323Sed    }
2003193323Sed
2004193323Sed    // Loop over the inputs next.  Make a copy of InstInputs so we can destroy
2005193323Sed    // the copy while we're checking the inputs.
2006193323Sed    std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
2007193323Sed
2008193323Sed    std::vector<TreePatternNode*> ResultNodeOperands;
2009193323Sed    std::vector<Record*> Operands;
2010193323Sed    for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
2011193323Sed      CodeGenInstruction::OperandInfo &Op = CGI.OperandList[i];
2012193323Sed      const std::string &OpName = Op.Name;
2013193323Sed      if (OpName.empty())
2014193323Sed        I->error("Operand #" + utostr(i) + " in operands list has no name!");
2015193323Sed
2016193323Sed      if (!InstInputsCheck.count(OpName)) {
2017193323Sed        // If this is an predicate operand or optional def operand with an
2018193323Sed        // DefaultOps set filled in, we can ignore this.  When we codegen it,
2019193323Sed        // we will do so as always executed.
2020193323Sed        if (Op.Rec->isSubClassOf("PredicateOperand") ||
2021193323Sed            Op.Rec->isSubClassOf("OptionalDefOperand")) {
2022193323Sed          // Does it have a non-empty DefaultOps field?  If so, ignore this
2023193323Sed          // operand.
2024193323Sed          if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
2025193323Sed            continue;
2026193323Sed        }
2027193323Sed        I->error("Operand $" + OpName +
2028193323Sed                 " does not appear in the instruction pattern");
2029193323Sed      }
2030193323Sed      TreePatternNode *InVal = InstInputsCheck[OpName];
2031193323Sed      InstInputsCheck.erase(OpName);   // It occurred, remove from map.
2032193323Sed
2033193323Sed      if (InVal->isLeaf() &&
2034193323Sed          dynamic_cast<DefInit*>(InVal->getLeafValue())) {
2035193323Sed        Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
2036193323Sed        if (Op.Rec != InRec && !InRec->isSubClassOf("ComplexPattern"))
2037193323Sed          I->error("Operand $" + OpName + "'s register class disagrees"
2038193323Sed                   " between the operand and pattern");
2039193323Sed      }
2040193323Sed      Operands.push_back(Op.Rec);
2041193323Sed
2042193323Sed      // Construct the result for the dest-pattern operand list.
2043193323Sed      TreePatternNode *OpNode = InVal->clone();
2044193323Sed
2045193323Sed      // No predicate is useful on the result.
2046193323Sed      OpNode->clearPredicateFns();
2047193323Sed
2048193323Sed      // Promote the xform function to be an explicit node if set.
2049193323Sed      if (Record *Xform = OpNode->getTransformFn()) {
2050193323Sed        OpNode->setTransformFn(0);
2051193323Sed        std::vector<TreePatternNode*> Children;
2052193323Sed        Children.push_back(OpNode);
2053193323Sed        OpNode = new TreePatternNode(Xform, Children);
2054193323Sed      }
2055193323Sed
2056193323Sed      ResultNodeOperands.push_back(OpNode);
2057193323Sed    }
2058193323Sed
2059193323Sed    if (!InstInputsCheck.empty())
2060193323Sed      I->error("Input operand $" + InstInputsCheck.begin()->first +
2061193323Sed               " occurs in pattern but not in operands list!");
2062193323Sed
2063193323Sed    TreePatternNode *ResultPattern =
2064193323Sed      new TreePatternNode(I->getRecord(), ResultNodeOperands);
2065193323Sed    // Copy fully inferred output node type to instruction result pattern.
2066193323Sed    if (NumResults > 0)
2067193323Sed      ResultPattern->setTypes(Res0Node->getExtTypes());
2068193323Sed
2069193323Sed    // Create and insert the instruction.
2070193323Sed    // FIXME: InstImpResults and InstImpInputs should not be part of
2071193323Sed    // DAGInstruction.
2072193323Sed    DAGInstruction TheInst(I, Results, Operands, InstImpResults, InstImpInputs);
2073193323Sed    Instructions.insert(std::make_pair(I->getRecord(), TheInst));
2074193323Sed
2075193323Sed    // Use a temporary tree pattern to infer all types and make sure that the
2076193323Sed    // constructed result is correct.  This depends on the instruction already
2077193323Sed    // being inserted into the Instructions map.
2078193323Sed    TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
2079193323Sed    Temp.InferAllTypes();
2080193323Sed
2081193323Sed    DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
2082193323Sed    TheInsertedInst.setResultPattern(Temp.getOnlyTree());
2083193323Sed
2084193323Sed    DEBUG(I->dump());
2085193323Sed  }
2086193323Sed
2087193323Sed  // If we can, convert the instructions to be patterns that are matched!
2088198090Srdivacky  for (std::map<Record*, DAGInstruction, RecordPtrCmp>::iterator II =
2089198090Srdivacky        Instructions.begin(),
2090193323Sed       E = Instructions.end(); II != E; ++II) {
2091193323Sed    DAGInstruction &TheInst = II->second;
2092193323Sed    const TreePattern *I = TheInst.getPattern();
2093193323Sed    if (I == 0) continue;  // No pattern.
2094193323Sed
2095193323Sed    // FIXME: Assume only the first tree is the pattern. The others are clobber
2096193323Sed    // nodes.
2097193323Sed    TreePatternNode *Pattern = I->getTree(0);
2098193323Sed    TreePatternNode *SrcPattern;
2099193323Sed    if (Pattern->getOperator()->getName() == "set") {
2100193323Sed      SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
2101193323Sed    } else{
2102193323Sed      // Not a set (store or something?)
2103193323Sed      SrcPattern = Pattern;
2104193323Sed    }
2105193323Sed
2106193323Sed    Record *Instr = II->first;
2107204642Srdivacky    AddPatternToMatch(I,
2108204642Srdivacky                      PatternToMatch(Instr->getValueAsListInit("Predicates"),
2109204642Srdivacky                                     SrcPattern,
2110204642Srdivacky                                     TheInst.getResultPattern(),
2111204642Srdivacky                                     TheInst.getImpResults(),
2112204642Srdivacky                                     Instr->getValueAsInt("AddedComplexity"),
2113204642Srdivacky                                     Instr->getID()));
2114193323Sed  }
2115193323Sed}
2116193323Sed
2117193323Sed
2118204642Srdivackytypedef std::pair<const TreePatternNode*, unsigned> NameRecord;
2119204642Srdivacky
2120204642Srdivackystatic void FindNames(const TreePatternNode *P,
2121204642Srdivacky                      std::map<std::string, NameRecord> &Names,
2122204642Srdivacky                      const TreePattern *PatternTop) {
2123204642Srdivacky  if (!P->getName().empty()) {
2124204642Srdivacky    NameRecord &Rec = Names[P->getName()];
2125204642Srdivacky    // If this is the first instance of the name, remember the node.
2126204642Srdivacky    if (Rec.second++ == 0)
2127204642Srdivacky      Rec.first = P;
2128204642Srdivacky    else if (Rec.first->getExtTypes() != P->getExtTypes())
2129204642Srdivacky      PatternTop->error("repetition of value: $" + P->getName() +
2130204642Srdivacky                        " where different uses have different types!");
2131204642Srdivacky  }
2132204642Srdivacky
2133204642Srdivacky  if (!P->isLeaf()) {
2134204642Srdivacky    for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
2135204642Srdivacky      FindNames(P->getChild(i), Names, PatternTop);
2136204642Srdivacky  }
2137204642Srdivacky}
2138204642Srdivacky
2139204642Srdivackyvoid CodeGenDAGPatterns::AddPatternToMatch(const TreePattern *Pattern,
2140204642Srdivacky                                           const PatternToMatch &PTM) {
2141204642Srdivacky  // Do some sanity checking on the pattern we're about to match.
2142204642Srdivacky  std::string Reason;
2143204642Srdivacky  if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this))
2144204642Srdivacky    Pattern->error("Pattern can never match: " + Reason);
2145204642Srdivacky
2146204642Srdivacky  // If the source pattern's root is a complex pattern, that complex pattern
2147204642Srdivacky  // must specify the nodes it can potentially match.
2148204642Srdivacky  if (const ComplexPattern *CP =
2149204642Srdivacky        PTM.getSrcPattern()->getComplexPatternInfo(*this))
2150204642Srdivacky    if (CP->getRootNodes().empty())
2151204642Srdivacky      Pattern->error("ComplexPattern at root must specify list of opcodes it"
2152204642Srdivacky                     " could match");
2153204642Srdivacky
2154204642Srdivacky
2155204642Srdivacky  // Find all of the named values in the input and output, ensure they have the
2156204642Srdivacky  // same type.
2157204642Srdivacky  std::map<std::string, NameRecord> SrcNames, DstNames;
2158204642Srdivacky  FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
2159204642Srdivacky  FindNames(PTM.getDstPattern(), DstNames, Pattern);
2160204642Srdivacky
2161204642Srdivacky  // Scan all of the named values in the destination pattern, rejecting them if
2162204642Srdivacky  // they don't exist in the input pattern.
2163204642Srdivacky  for (std::map<std::string, NameRecord>::iterator
2164204642Srdivacky       I = DstNames.begin(), E = DstNames.end(); I != E; ++I) {
2165204642Srdivacky    if (SrcNames[I->first].first == 0)
2166204642Srdivacky      Pattern->error("Pattern has input without matching name in output: $" +
2167204642Srdivacky                     I->first);
2168204642Srdivacky
2169204642Srdivacky#if 0
2170204642Srdivacky    const std::vector<unsigned char> &SrcTypeVec =
2171204642Srdivacky      SrcNames[I->first].first->getExtTypes();
2172204642Srdivacky    const std::vector<unsigned char> &DstTypeVec =
2173204642Srdivacky      I->second.first->getExtTypes();
2174204642Srdivacky    if (SrcTypeVec == DstTypeVec) continue;
2175204642Srdivacky
2176204642Srdivacky    std::string SrcType, DstType;
2177204642Srdivacky    for (unsigned i = 0, e = SrcTypeVec.size(); i != e; ++i)
2178204642Srdivacky      SrcType += ":" + GetTypeName(SrcTypeVec[i]);
2179204642Srdivacky    for (unsigned i = 0, e = DstTypeVec.size(); i != e; ++i)
2180204642Srdivacky      DstType += ":" + GetTypeName(DstTypeVec[i]);
2181204642Srdivacky
2182204642Srdivacky    Pattern->error("Variable $" + I->first +
2183204642Srdivacky                   " has different types in source (" + SrcType +
2184204642Srdivacky                   ") and dest (" + DstType + ") pattern!");
2185204642Srdivacky#endif
2186204642Srdivacky  }
2187204642Srdivacky
2188204642Srdivacky  // Scan all of the named values in the source pattern, rejecting them if the
2189204642Srdivacky  // name isn't used in the dest, and isn't used to tie two values together.
2190204642Srdivacky  for (std::map<std::string, NameRecord>::iterator
2191204642Srdivacky       I = SrcNames.begin(), E = SrcNames.end(); I != E; ++I)
2192204642Srdivacky    if (DstNames[I->first].first == 0 && SrcNames[I->first].second == 1)
2193204642Srdivacky      Pattern->error("Pattern has dead named input: $" + I->first);
2194204642Srdivacky
2195204642Srdivacky  PatternsToMatch.push_back(PTM);
2196204642Srdivacky}
2197204642Srdivacky
2198204642Srdivacky
2199204642Srdivacky
2200193323Sedvoid CodeGenDAGPatterns::InferInstructionFlags() {
2201193323Sed  std::map<std::string, CodeGenInstruction> &InstrDescs =
2202193323Sed    Target.getInstructions();
2203193323Sed  for (std::map<std::string, CodeGenInstruction>::iterator
2204193323Sed         II = InstrDescs.begin(), E = InstrDescs.end(); II != E; ++II) {
2205193323Sed    CodeGenInstruction &InstInfo = II->second;
2206193323Sed    // Determine properties of the instruction from its pattern.
2207193323Sed    bool MayStore, MayLoad, HasSideEffects;
2208193323Sed    InferFromPattern(InstInfo, MayStore, MayLoad, HasSideEffects, *this);
2209193323Sed    InstInfo.mayStore = MayStore;
2210193323Sed    InstInfo.mayLoad = MayLoad;
2211193323Sed    InstInfo.hasSideEffects = HasSideEffects;
2212193323Sed  }
2213193323Sed}
2214193323Sed
2215193323Sedvoid CodeGenDAGPatterns::ParsePatterns() {
2216193323Sed  std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
2217193323Sed
2218193323Sed  for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
2219193323Sed    DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
2220193323Sed    DefInit *OpDef = dynamic_cast<DefInit*>(Tree->getOperator());
2221193323Sed    Record *Operator = OpDef->getDef();
2222193323Sed    TreePattern *Pattern;
2223193323Sed    if (Operator->getName() != "parallel")
2224193323Sed      Pattern = new TreePattern(Patterns[i], Tree, true, *this);
2225193323Sed    else {
2226193323Sed      std::vector<Init*> Values;
2227194178Sed      RecTy *ListTy = 0;
2228194178Sed      for (unsigned j = 0, ee = Tree->getNumArgs(); j != ee; ++j) {
2229193323Sed        Values.push_back(Tree->getArg(j));
2230194178Sed        TypedInit *TArg = dynamic_cast<TypedInit*>(Tree->getArg(j));
2231194178Sed        if (TArg == 0) {
2232195340Sed          errs() << "In dag: " << Tree->getAsString();
2233195340Sed          errs() << " --  Untyped argument in pattern\n";
2234194178Sed          assert(0 && "Untyped argument in pattern");
2235194178Sed        }
2236194178Sed        if (ListTy != 0) {
2237194178Sed          ListTy = resolveTypes(ListTy, TArg->getType());
2238194178Sed          if (ListTy == 0) {
2239195340Sed            errs() << "In dag: " << Tree->getAsString();
2240195340Sed            errs() << " --  Incompatible types in pattern arguments\n";
2241194178Sed            assert(0 && "Incompatible types in pattern arguments");
2242194178Sed          }
2243194178Sed        }
2244194178Sed        else {
2245194178Sed          ListTy = TArg->getType();
2246194178Sed        }
2247194178Sed      }
2248194178Sed      ListInit *LI = new ListInit(Values, new ListRecTy(ListTy));
2249193323Sed      Pattern = new TreePattern(Patterns[i], LI, true, *this);
2250193323Sed    }
2251193323Sed
2252193323Sed    // Inline pattern fragments into it.
2253193323Sed    Pattern->InlinePatternFragments();
2254193323Sed
2255193323Sed    ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
2256193323Sed    if (LI->getSize() == 0) continue;  // no pattern.
2257193323Sed
2258193323Sed    // Parse the instruction.
2259193323Sed    TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
2260193323Sed
2261193323Sed    // Inline pattern fragments into it.
2262193323Sed    Result->InlinePatternFragments();
2263193323Sed
2264193323Sed    if (Result->getNumTrees() != 1)
2265193323Sed      Result->error("Cannot handle instructions producing instructions "
2266193323Sed                    "with temporaries yet!");
2267193323Sed
2268193323Sed    bool IterateInference;
2269193323Sed    bool InferredAllPatternTypes, InferredAllResultTypes;
2270193323Sed    do {
2271193323Sed      // Infer as many types as possible.  If we cannot infer all of them, we
2272193323Sed      // can never do anything with this pattern: report it to the user.
2273193323Sed      InferredAllPatternTypes = Pattern->InferAllTypes();
2274193323Sed
2275193323Sed      // Infer as many types as possible.  If we cannot infer all of them, we
2276193323Sed      // can never do anything with this pattern: report it to the user.
2277193323Sed      InferredAllResultTypes = Result->InferAllTypes();
2278193323Sed
2279193323Sed      // Apply the type of the result to the source pattern.  This helps us
2280193323Sed      // resolve cases where the input type is known to be a pointer type (which
2281193323Sed      // is considered resolved), but the result knows it needs to be 32- or
2282193323Sed      // 64-bits.  Infer the other way for good measure.
2283193323Sed      IterateInference = Pattern->getTree(0)->
2284193323Sed        UpdateNodeType(Result->getTree(0)->getExtTypes(), *Result);
2285193323Sed      IterateInference |= Result->getTree(0)->
2286193323Sed        UpdateNodeType(Pattern->getTree(0)->getExtTypes(), *Result);
2287193323Sed    } while (IterateInference);
2288193323Sed
2289193323Sed    // Verify that we inferred enough types that we can do something with the
2290193323Sed    // pattern and result.  If these fire the user has to add type casts.
2291193323Sed    if (!InferredAllPatternTypes)
2292193323Sed      Pattern->error("Could not infer all types in pattern!");
2293193323Sed    if (!InferredAllResultTypes)
2294193323Sed      Result->error("Could not infer all types in pattern result!");
2295193323Sed
2296193323Sed    // Validate that the input pattern is correct.
2297193323Sed    std::map<std::string, TreePatternNode*> InstInputs;
2298193323Sed    std::map<std::string, TreePatternNode*> InstResults;
2299193323Sed    std::vector<Record*> InstImpInputs;
2300193323Sed    std::vector<Record*> InstImpResults;
2301193323Sed    for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
2302193323Sed      FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
2303193323Sed                                  InstInputs, InstResults,
2304193323Sed                                  InstImpInputs, InstImpResults);
2305193323Sed
2306193323Sed    // Promote the xform function to be an explicit node if set.
2307193323Sed    TreePatternNode *DstPattern = Result->getOnlyTree();
2308193323Sed    std::vector<TreePatternNode*> ResultNodeOperands;
2309193323Sed    for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
2310193323Sed      TreePatternNode *OpNode = DstPattern->getChild(ii);
2311193323Sed      if (Record *Xform = OpNode->getTransformFn()) {
2312193323Sed        OpNode->setTransformFn(0);
2313193323Sed        std::vector<TreePatternNode*> Children;
2314193323Sed        Children.push_back(OpNode);
2315193323Sed        OpNode = new TreePatternNode(Xform, Children);
2316193323Sed      }
2317193323Sed      ResultNodeOperands.push_back(OpNode);
2318193323Sed    }
2319193323Sed    DstPattern = Result->getOnlyTree();
2320193323Sed    if (!DstPattern->isLeaf())
2321193323Sed      DstPattern = new TreePatternNode(DstPattern->getOperator(),
2322193323Sed                                       ResultNodeOperands);
2323193323Sed    DstPattern->setTypes(Result->getOnlyTree()->getExtTypes());
2324193323Sed    TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
2325193323Sed    Temp.InferAllTypes();
2326193323Sed
2327193323Sed
2328204642Srdivacky    AddPatternToMatch(Pattern,
2329204642Srdivacky                 PatternToMatch(Patterns[i]->getValueAsListInit("Predicates"),
2330204642Srdivacky                                Pattern->getTree(0),
2331204642Srdivacky                                Temp.getOnlyTree(), InstImpResults,
2332204642Srdivacky                                Patterns[i]->getValueAsInt("AddedComplexity"),
2333204642Srdivacky                                Patterns[i]->getID()));
2334193323Sed  }
2335193323Sed}
2336193323Sed
2337193323Sed/// CombineChildVariants - Given a bunch of permutations of each child of the
2338193323Sed/// 'operator' node, put them together in all possible ways.
2339193323Sedstatic void CombineChildVariants(TreePatternNode *Orig,
2340193323Sed               const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
2341193323Sed                                 std::vector<TreePatternNode*> &OutVariants,
2342193323Sed                                 CodeGenDAGPatterns &CDP,
2343193323Sed                                 const MultipleUseVarSet &DepVars) {
2344193323Sed  // Make sure that each operand has at least one variant to choose from.
2345193323Sed  for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2346193323Sed    if (ChildVariants[i].empty())
2347193323Sed      return;
2348193323Sed
2349193323Sed  // The end result is an all-pairs construction of the resultant pattern.
2350193323Sed  std::vector<unsigned> Idxs;
2351193323Sed  Idxs.resize(ChildVariants.size());
2352193323Sed  bool NotDone;
2353193323Sed  do {
2354193323Sed#ifndef NDEBUG
2355204642Srdivacky    DEBUG(if (!Idxs.empty()) {
2356204642Srdivacky            errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
2357204642Srdivacky              for (unsigned i = 0; i < Idxs.size(); ++i) {
2358204642Srdivacky                errs() << Idxs[i] << " ";
2359204642Srdivacky            }
2360204642Srdivacky            errs() << "]\n";
2361204642Srdivacky          });
2362193323Sed#endif
2363193323Sed    // Create the variant and add it to the output list.
2364193323Sed    std::vector<TreePatternNode*> NewChildren;
2365193323Sed    for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2366193323Sed      NewChildren.push_back(ChildVariants[i][Idxs[i]]);
2367193323Sed    TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
2368193323Sed
2369193323Sed    // Copy over properties.
2370193323Sed    R->setName(Orig->getName());
2371193323Sed    R->setPredicateFns(Orig->getPredicateFns());
2372193323Sed    R->setTransformFn(Orig->getTransformFn());
2373193323Sed    R->setTypes(Orig->getExtTypes());
2374193323Sed
2375193323Sed    // If this pattern cannot match, do not include it as a variant.
2376193323Sed    std::string ErrString;
2377193323Sed    if (!R->canPatternMatch(ErrString, CDP)) {
2378193323Sed      delete R;
2379193323Sed    } else {
2380193323Sed      bool AlreadyExists = false;
2381193323Sed
2382193323Sed      // Scan to see if this pattern has already been emitted.  We can get
2383193323Sed      // duplication due to things like commuting:
2384193323Sed      //   (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
2385193323Sed      // which are the same pattern.  Ignore the dups.
2386193323Sed      for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
2387193323Sed        if (R->isIsomorphicTo(OutVariants[i], DepVars)) {
2388193323Sed          AlreadyExists = true;
2389193323Sed          break;
2390193323Sed        }
2391193323Sed
2392193323Sed      if (AlreadyExists)
2393193323Sed        delete R;
2394193323Sed      else
2395193323Sed        OutVariants.push_back(R);
2396193323Sed    }
2397193323Sed
2398193323Sed    // Increment indices to the next permutation by incrementing the
2399193323Sed    // indicies from last index backward, e.g., generate the sequence
2400193323Sed    // [0, 0], [0, 1], [1, 0], [1, 1].
2401193323Sed    int IdxsIdx;
2402193323Sed    for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
2403193323Sed      if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
2404193323Sed        Idxs[IdxsIdx] = 0;
2405193323Sed      else
2406193323Sed        break;
2407193323Sed    }
2408193323Sed    NotDone = (IdxsIdx >= 0);
2409193323Sed  } while (NotDone);
2410193323Sed}
2411193323Sed
2412193323Sed/// CombineChildVariants - A helper function for binary operators.
2413193323Sed///
2414193323Sedstatic void CombineChildVariants(TreePatternNode *Orig,
2415193323Sed                                 const std::vector<TreePatternNode*> &LHS,
2416193323Sed                                 const std::vector<TreePatternNode*> &RHS,
2417193323Sed                                 std::vector<TreePatternNode*> &OutVariants,
2418193323Sed                                 CodeGenDAGPatterns &CDP,
2419193323Sed                                 const MultipleUseVarSet &DepVars) {
2420193323Sed  std::vector<std::vector<TreePatternNode*> > ChildVariants;
2421193323Sed  ChildVariants.push_back(LHS);
2422193323Sed  ChildVariants.push_back(RHS);
2423193323Sed  CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
2424193323Sed}
2425193323Sed
2426193323Sed
2427193323Sedstatic void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
2428193323Sed                                     std::vector<TreePatternNode *> &Children) {
2429193323Sed  assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
2430193323Sed  Record *Operator = N->getOperator();
2431193323Sed
2432193323Sed  // Only permit raw nodes.
2433193323Sed  if (!N->getName().empty() || !N->getPredicateFns().empty() ||
2434193323Sed      N->getTransformFn()) {
2435193323Sed    Children.push_back(N);
2436193323Sed    return;
2437193323Sed  }
2438193323Sed
2439193323Sed  if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
2440193323Sed    Children.push_back(N->getChild(0));
2441193323Sed  else
2442193323Sed    GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
2443193323Sed
2444193323Sed  if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
2445193323Sed    Children.push_back(N->getChild(1));
2446193323Sed  else
2447193323Sed    GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
2448193323Sed}
2449193323Sed
2450193323Sed/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
2451193323Sed/// the (potentially recursive) pattern by using algebraic laws.
2452193323Sed///
2453193323Sedstatic void GenerateVariantsOf(TreePatternNode *N,
2454193323Sed                               std::vector<TreePatternNode*> &OutVariants,
2455193323Sed                               CodeGenDAGPatterns &CDP,
2456193323Sed                               const MultipleUseVarSet &DepVars) {
2457193323Sed  // We cannot permute leaves.
2458193323Sed  if (N->isLeaf()) {
2459193323Sed    OutVariants.push_back(N);
2460193323Sed    return;
2461193323Sed  }
2462193323Sed
2463193323Sed  // Look up interesting info about the node.
2464193323Sed  const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
2465193323Sed
2466193323Sed  // If this node is associative, re-associate.
2467193323Sed  if (NodeInfo.hasProperty(SDNPAssociative)) {
2468193323Sed    // Re-associate by pulling together all of the linked operators
2469193323Sed    std::vector<TreePatternNode*> MaximalChildren;
2470193323Sed    GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
2471193323Sed
2472193323Sed    // Only handle child sizes of 3.  Otherwise we'll end up trying too many
2473193323Sed    // permutations.
2474193323Sed    if (MaximalChildren.size() == 3) {
2475193323Sed      // Find the variants of all of our maximal children.
2476193323Sed      std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
2477193323Sed      GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
2478193323Sed      GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
2479193323Sed      GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
2480193323Sed
2481193323Sed      // There are only two ways we can permute the tree:
2482193323Sed      //   (A op B) op C    and    A op (B op C)
2483193323Sed      // Within these forms, we can also permute A/B/C.
2484193323Sed
2485193323Sed      // Generate legal pair permutations of A/B/C.
2486193323Sed      std::vector<TreePatternNode*> ABVariants;
2487193323Sed      std::vector<TreePatternNode*> BAVariants;
2488193323Sed      std::vector<TreePatternNode*> ACVariants;
2489193323Sed      std::vector<TreePatternNode*> CAVariants;
2490193323Sed      std::vector<TreePatternNode*> BCVariants;
2491193323Sed      std::vector<TreePatternNode*> CBVariants;
2492193323Sed      CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
2493193323Sed      CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
2494193323Sed      CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
2495193323Sed      CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
2496193323Sed      CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
2497193323Sed      CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
2498193323Sed
2499193323Sed      // Combine those into the result: (x op x) op x
2500193323Sed      CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
2501193323Sed      CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
2502193323Sed      CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
2503193323Sed      CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
2504193323Sed      CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
2505193323Sed      CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
2506193323Sed
2507193323Sed      // Combine those into the result: x op (x op x)
2508193323Sed      CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
2509193323Sed      CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
2510193323Sed      CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
2511193323Sed      CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
2512193323Sed      CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
2513193323Sed      CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
2514193323Sed      return;
2515193323Sed    }
2516193323Sed  }
2517193323Sed
2518193323Sed  // Compute permutations of all children.
2519193323Sed  std::vector<std::vector<TreePatternNode*> > ChildVariants;
2520193323Sed  ChildVariants.resize(N->getNumChildren());
2521193323Sed  for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2522193323Sed    GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
2523193323Sed
2524193323Sed  // Build all permutations based on how the children were formed.
2525193323Sed  CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
2526193323Sed
2527193323Sed  // If this node is commutative, consider the commuted order.
2528193323Sed  bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
2529193323Sed  if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
2530193323Sed    assert((N->getNumChildren()==2 || isCommIntrinsic) &&
2531193323Sed           "Commutative but doesn't have 2 children!");
2532193323Sed    // Don't count children which are actually register references.
2533193323Sed    unsigned NC = 0;
2534193323Sed    for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2535193323Sed      TreePatternNode *Child = N->getChild(i);
2536193323Sed      if (Child->isLeaf())
2537193323Sed        if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2538193323Sed          Record *RR = DI->getDef();
2539193323Sed          if (RR->isSubClassOf("Register"))
2540193323Sed            continue;
2541193323Sed        }
2542193323Sed      NC++;
2543193323Sed    }
2544193323Sed    // Consider the commuted order.
2545193323Sed    if (isCommIntrinsic) {
2546193323Sed      // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
2547193323Sed      // operands are the commutative operands, and there might be more operands
2548193323Sed      // after those.
2549193323Sed      assert(NC >= 3 &&
2550193323Sed             "Commutative intrinsic should have at least 3 childrean!");
2551193323Sed      std::vector<std::vector<TreePatternNode*> > Variants;
2552193323Sed      Variants.push_back(ChildVariants[0]); // Intrinsic id.
2553193323Sed      Variants.push_back(ChildVariants[2]);
2554193323Sed      Variants.push_back(ChildVariants[1]);
2555193323Sed      for (unsigned i = 3; i != NC; ++i)
2556193323Sed        Variants.push_back(ChildVariants[i]);
2557193323Sed      CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
2558193323Sed    } else if (NC == 2)
2559193323Sed      CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
2560193323Sed                           OutVariants, CDP, DepVars);
2561193323Sed  }
2562193323Sed}
2563193323Sed
2564193323Sed
2565193323Sed// GenerateVariants - Generate variants.  For example, commutative patterns can
2566193323Sed// match multiple ways.  Add them to PatternsToMatch as well.
2567193323Sedvoid CodeGenDAGPatterns::GenerateVariants() {
2568198090Srdivacky  DEBUG(errs() << "Generating instruction variants.\n");
2569193323Sed
2570193323Sed  // Loop over all of the patterns we've collected, checking to see if we can
2571193323Sed  // generate variants of the instruction, through the exploitation of
2572193323Sed  // identities.  This permits the target to provide aggressive matching without
2573193323Sed  // the .td file having to contain tons of variants of instructions.
2574193323Sed  //
2575193323Sed  // Note that this loop adds new patterns to the PatternsToMatch list, but we
2576193323Sed  // intentionally do not reconsider these.  Any variants of added patterns have
2577193323Sed  // already been added.
2578193323Sed  //
2579193323Sed  for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
2580193323Sed    MultipleUseVarSet             DepVars;
2581193323Sed    std::vector<TreePatternNode*> Variants;
2582193323Sed    FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
2583198090Srdivacky    DEBUG(errs() << "Dependent/multiply used variables: ");
2584193323Sed    DEBUG(DumpDepVars(DepVars));
2585198090Srdivacky    DEBUG(errs() << "\n");
2586193323Sed    GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this, DepVars);
2587193323Sed
2588193323Sed    assert(!Variants.empty() && "Must create at least original variant!");
2589193323Sed    Variants.erase(Variants.begin());  // Remove the original pattern.
2590193323Sed
2591193323Sed    if (Variants.empty())  // No variants for this pattern.
2592193323Sed      continue;
2593193323Sed
2594198090Srdivacky    DEBUG(errs() << "FOUND VARIANTS OF: ";
2595198090Srdivacky          PatternsToMatch[i].getSrcPattern()->dump();
2596198090Srdivacky          errs() << "\n");
2597193323Sed
2598193323Sed    for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
2599193323Sed      TreePatternNode *Variant = Variants[v];
2600193323Sed
2601198090Srdivacky      DEBUG(errs() << "  VAR#" << v <<  ": ";
2602198090Srdivacky            Variant->dump();
2603198090Srdivacky            errs() << "\n");
2604193323Sed
2605193323Sed      // Scan to see if an instruction or explicit pattern already matches this.
2606193323Sed      bool AlreadyExists = false;
2607193323Sed      for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
2608195098Sed        // Skip if the top level predicates do not match.
2609195098Sed        if (PatternsToMatch[i].getPredicates() !=
2610195098Sed            PatternsToMatch[p].getPredicates())
2611195098Sed          continue;
2612193323Sed        // Check to see if this variant already exists.
2613193323Sed        if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(), DepVars)) {
2614198090Srdivacky          DEBUG(errs() << "  *** ALREADY EXISTS, ignoring variant.\n");
2615193323Sed          AlreadyExists = true;
2616193323Sed          break;
2617193323Sed        }
2618193323Sed      }
2619193323Sed      // If we already have it, ignore the variant.
2620193323Sed      if (AlreadyExists) continue;
2621193323Sed
2622193323Sed      // Otherwise, add it to the list of patterns we have.
2623193323Sed      PatternsToMatch.
2624193323Sed        push_back(PatternToMatch(PatternsToMatch[i].getPredicates(),
2625193323Sed                                 Variant, PatternsToMatch[i].getDstPattern(),
2626193323Sed                                 PatternsToMatch[i].getDstRegs(),
2627204642Srdivacky                                 PatternsToMatch[i].getAddedComplexity(),
2628204642Srdivacky                                 Record::getNewUID()));
2629193323Sed    }
2630193323Sed
2631198090Srdivacky    DEBUG(errs() << "\n");
2632193323Sed  }
2633193323Sed}
2634193323Sed
2635