Fix -Asserts warning.
[oota-llvm.git] / utils / TableGen / CodeGenDAGPatterns.cpp
1 //===- CodeGenDAGPatterns.cpp - Read DAG patterns from .td file -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the CodeGenDAGPatterns class, which is used to read and
11 // represent the patterns present in a .td file for instructions.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "CodeGenDAGPatterns.h"
16 #include "Record.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/Support/Debug.h"
20 #include <set>
21 #include <algorithm>
22 using namespace llvm;
23
24 //===----------------------------------------------------------------------===//
25 //  EEVT::TypeSet Implementation
26 //===----------------------------------------------------------------------===//
27
28 static inline bool isInteger(MVT::SimpleValueType VT) {
29   return EVT(VT).isInteger();
30 }
31
32 static inline bool isFloatingPoint(MVT::SimpleValueType VT) {
33   return EVT(VT).isFloatingPoint();
34 }
35
36 static inline bool isVector(MVT::SimpleValueType VT) {
37   return EVT(VT).isVector();
38 }
39
40 EEVT::TypeSet::TypeSet(MVT::SimpleValueType VT, TreePattern &TP) {
41   if (VT == MVT::iAny)
42     EnforceInteger(TP);
43   else if (VT == MVT::fAny)
44     EnforceFloatingPoint(TP);
45   else if (VT == MVT::vAny)
46     EnforceVector(TP);
47   else {
48     assert((VT < MVT::LAST_VALUETYPE || VT == MVT::iPTR ||
49             VT == MVT::iPTRAny) && "Not a concrete type!");
50     TypeVec.push_back(VT);
51   }
52 }
53
54
55 EEVT::TypeSet::TypeSet(const std::vector<MVT::SimpleValueType> &VTList) {
56   assert(!VTList.empty() && "empty list?");
57   TypeVec.append(VTList.begin(), VTList.end());
58   
59   if (!VTList.empty())
60     assert(VTList[0] != MVT::iAny && VTList[0] != MVT::vAny &&
61            VTList[0] != MVT::fAny);
62   
63   // Remove duplicates.
64   array_pod_sort(TypeVec.begin(), TypeVec.end());
65   TypeVec.erase(std::unique(TypeVec.begin(), TypeVec.end()), TypeVec.end());
66 }
67
68
69 /// hasIntegerTypes - Return true if this TypeSet contains iAny or an
70 /// integer value type.
71 bool EEVT::TypeSet::hasIntegerTypes() const {
72   for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
73     if (isInteger(TypeVec[i]))
74       return true;
75   return false;
76 }  
77
78 /// hasFloatingPointTypes - Return true if this TypeSet contains an fAny or
79 /// a floating point value type.
80 bool EEVT::TypeSet::hasFloatingPointTypes() const {
81   for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
82     if (isFloatingPoint(TypeVec[i]))
83       return true;
84   return false;
85 }  
86
87 /// hasVectorTypes - Return true if this TypeSet contains a vAny or a vector
88 /// value type.
89 bool EEVT::TypeSet::hasVectorTypes() const {
90   for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
91     if (isVector(TypeVec[i]))
92       return true;
93   return false;
94 }
95
96
97 std::string EEVT::TypeSet::getName() const {
98   if (TypeVec.empty()) return "<empty>";
99   
100   std::string Result;
101     
102   for (unsigned i = 0, e = TypeVec.size(); i != e; ++i) {
103     std::string VTName = llvm::getEnumName(TypeVec[i]);
104     // Strip off MVT:: prefix if present.
105     if (VTName.substr(0,5) == "MVT::")
106       VTName = VTName.substr(5);
107     if (i) Result += ':';
108     Result += VTName;
109   }
110   
111   if (TypeVec.size() == 1)
112     return Result;
113   return "{" + Result + "}";
114 }
115
116 /// MergeInTypeInfo - This merges in type information from the specified
117 /// argument.  If 'this' changes, it returns true.  If the two types are
118 /// contradictory (e.g. merge f32 into i32) then this throws an exception.
119 bool EEVT::TypeSet::MergeInTypeInfo(const EEVT::TypeSet &InVT, TreePattern &TP){
120   if (InVT.isCompletelyUnknown() || *this == InVT)
121     return false;
122   
123   if (isCompletelyUnknown()) {
124     *this = InVT;
125     return true;
126   }
127   
128   assert(TypeVec.size() >= 1 && InVT.TypeVec.size() >= 1 && "No unknowns");
129   
130   // Handle the abstract cases, seeing if we can resolve them better.
131   switch (TypeVec[0]) {
132   default: break;
133   case MVT::iPTR:
134   case MVT::iPTRAny:
135     if (InVT.hasIntegerTypes()) {
136       EEVT::TypeSet InCopy(InVT);
137       InCopy.EnforceInteger(TP);
138       InCopy.EnforceScalar(TP);
139       
140       if (InCopy.isConcrete()) {
141         // If the RHS has one integer type, upgrade iPTR to i32.
142         TypeVec[0] = InVT.TypeVec[0];
143         return true;
144       }
145       
146       // If the input has multiple scalar integers, this doesn't add any info.
147       if (!InCopy.isCompletelyUnknown())
148         return false;
149     }
150     break;
151   }
152   
153   // If the input constraint is iAny/iPTR and this is an integer type list,
154   // remove non-integer types from the list.
155   if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
156       hasIntegerTypes()) {
157     bool MadeChange = EnforceInteger(TP);
158     
159     // If we're merging in iPTR/iPTRAny and the node currently has a list of
160     // multiple different integer types, replace them with a single iPTR.
161     if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
162         TypeVec.size() != 1) {
163       TypeVec.resize(1);
164       TypeVec[0] = InVT.TypeVec[0];
165       MadeChange = true;
166     }
167     
168     return MadeChange;
169   }
170   
171   // If this is a type list and the RHS is a typelist as well, eliminate entries
172   // from this list that aren't in the other one.
173   bool MadeChange = false;
174   TypeSet InputSet(*this);
175
176   for (unsigned i = 0; i != TypeVec.size(); ++i) {
177     bool InInVT = false;
178     for (unsigned j = 0, e = InVT.TypeVec.size(); j != e; ++j)
179       if (TypeVec[i] == InVT.TypeVec[j]) {
180         InInVT = true;
181         break;
182       }
183     
184     if (InInVT) continue;
185     TypeVec.erase(TypeVec.begin()+i--);
186     MadeChange = true;
187   }
188   
189   // If we removed all of our types, we have a type contradiction.
190   if (!TypeVec.empty())
191     return MadeChange;
192   
193   // FIXME: Really want an SMLoc here!
194   TP.error("Type inference contradiction found, merging '" +
195            InVT.getName() + "' into '" + InputSet.getName() + "'");
196   return true; // unreachable
197 }
198
199 /// EnforceInteger - Remove all non-integer types from this set.
200 bool EEVT::TypeSet::EnforceInteger(TreePattern &TP) {
201   TypeSet InputSet(*this);
202   bool MadeChange = false;
203   
204   // If we know nothing, then get the full set.
205   if (TypeVec.empty()) {
206     *this = TP.getDAGPatterns().getTargetInfo().getLegalValueTypes();
207     MadeChange = true;
208   }
209   
210   if (!hasFloatingPointTypes())
211     return MadeChange;
212   
213   // Filter out all the fp types.
214   for (unsigned i = 0; i != TypeVec.size(); ++i)
215     if (isFloatingPoint(TypeVec[i]))
216       TypeVec.erase(TypeVec.begin()+i--);
217   
218   if (TypeVec.empty())
219     TP.error("Type inference contradiction found, '" +
220              InputSet.getName() + "' needs to be integer");
221   return MadeChange;
222 }
223
224 /// EnforceFloatingPoint - Remove all integer types from this set.
225 bool EEVT::TypeSet::EnforceFloatingPoint(TreePattern &TP) {
226   TypeSet InputSet(*this);
227   bool MadeChange = false;
228   
229   // If we know nothing, then get the full set.
230   if (TypeVec.empty()) {
231     *this = TP.getDAGPatterns().getTargetInfo().getLegalValueTypes();
232     MadeChange = true;
233   }
234   
235   if (!hasIntegerTypes())
236     return MadeChange;
237   
238   // Filter out all the fp types.
239   for (unsigned i = 0; i != TypeVec.size(); ++i)
240     if (isInteger(TypeVec[i]))
241       TypeVec.erase(TypeVec.begin()+i--);
242   
243   if (TypeVec.empty())
244     TP.error("Type inference contradiction found, '" +
245              InputSet.getName() + "' needs to be floating point");
246   return MadeChange;
247 }
248
249 /// EnforceScalar - Remove all vector types from this.
250 bool EEVT::TypeSet::EnforceScalar(TreePattern &TP) {
251   TypeSet InputSet(*this);
252   bool MadeChange = false;
253   
254   // If we know nothing, then get the full set.
255   if (TypeVec.empty()) {
256     *this = TP.getDAGPatterns().getTargetInfo().getLegalValueTypes();
257     MadeChange = true;
258   }
259   
260   if (!hasVectorTypes())
261     return MadeChange;
262   
263   // Filter out all the vector types.
264   for (unsigned i = 0; i != TypeVec.size(); ++i)
265     if (isVector(TypeVec[i]))
266       TypeVec.erase(TypeVec.begin()+i--);
267   
268   if (TypeVec.empty())
269     TP.error("Type inference contradiction found, '" +
270              InputSet.getName() + "' needs to be scalar");
271   return MadeChange;
272 }
273
274 /// EnforceVector - Remove all vector types from this.
275 bool EEVT::TypeSet::EnforceVector(TreePattern &TP) {
276   TypeSet InputSet(*this);
277   bool MadeChange = false;
278   
279   // If we know nothing, then get the full set.
280   if (TypeVec.empty()) {
281     *this = TP.getDAGPatterns().getTargetInfo().getLegalValueTypes();
282     MadeChange = true;
283   }
284   
285   // Filter out all the scalar types.
286   for (unsigned i = 0; i != TypeVec.size(); ++i)
287     if (!isVector(TypeVec[i]))
288       TypeVec.erase(TypeVec.begin()+i--);
289   
290   if (TypeVec.empty())
291     TP.error("Type inference contradiction found, '" +
292              InputSet.getName() + "' needs to be a vector");
293   return MadeChange;
294 }
295
296
297 /// EnforceSmallerThan - 'this' must be a smaller VT than Other.  Update
298 /// this an other based on this information.
299 bool EEVT::TypeSet::EnforceSmallerThan(EEVT::TypeSet &Other, TreePattern &TP) {
300   // Both operands must be integer or FP, but we don't care which.
301   bool MadeChange = false;
302   
303   // This code does not currently handle nodes which have multiple types,
304   // where some types are integer, and some are fp.  Assert that this is not
305   // the case.
306   assert(!(hasIntegerTypes() && hasFloatingPointTypes()) &&
307          !(Other.hasIntegerTypes() && Other.hasFloatingPointTypes()) &&
308          "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
309   // If one side is known to be integer or known to be FP but the other side has
310   // no information, get at least the type integrality info in there.
311   if (hasIntegerTypes())
312     MadeChange |= Other.EnforceInteger(TP);
313   else if (hasFloatingPointTypes())
314     MadeChange |= Other.EnforceFloatingPoint(TP);
315   if (Other.hasIntegerTypes())
316     MadeChange |= EnforceInteger(TP);
317   else if (Other.hasFloatingPointTypes())
318     MadeChange |= EnforceFloatingPoint(TP);
319   
320   assert(!isCompletelyUnknown() && !Other.isCompletelyUnknown() &&
321          "Should have a type list now");
322   
323   // If one contains vectors but the other doesn't pull vectors out.
324   if (!hasVectorTypes() && Other.hasVectorTypes())
325     MadeChange |= Other.EnforceScalar(TP);
326   if (hasVectorTypes() && !Other.hasVectorTypes())
327     MadeChange |= EnforceScalar(TP);
328   
329   // FIXME: This is a bone-headed way to do this.
330   
331   // Get the set of legal VTs and filter it based on the known integrality.
332   const CodeGenTarget &CGT = TP.getDAGPatterns().getTargetInfo();
333   TypeSet LegalVTs = CGT.getLegalValueTypes();
334
335   // TODO: If one or the other side is known to be a specific VT, we could prune
336   // LegalVTs.
337   if (hasIntegerTypes())
338     LegalVTs.EnforceInteger(TP);
339   else if (hasFloatingPointTypes())
340     LegalVTs.EnforceFloatingPoint(TP);
341   else
342     return MadeChange;
343   
344   switch (LegalVTs.TypeVec.size()) {
345   case 0: assert(0 && "No legal VTs?");
346   default:         // Too many VT's to pick from.
347     // TODO: If the biggest type in LegalVTs is in this set, we could remove it.
348     // If one or the other side is known to be a specific VT, we could prune
349     // LegalVTs.
350     return MadeChange;
351   case 1: 
352     // Only one VT of this flavor.  Cannot ever satisfy the constraints.
353     return MergeInTypeInfo(MVT::Other, TP);  // throw
354   case 2:
355     // If we have exactly two possible types, the little operand must be the
356     // small one, the big operand should be the big one.  This is common with 
357     // float/double for example.
358     assert(LegalVTs.TypeVec[0] < LegalVTs.TypeVec[1] && "Should be sorted!");
359     MadeChange |= MergeInTypeInfo(LegalVTs.TypeVec[0], TP);
360     MadeChange |= Other.MergeInTypeInfo(LegalVTs.TypeVec[1], TP);
361     return MadeChange;
362   }    
363 }
364
365 /// EnforceVectorEltTypeIs - 'this' is now constrainted to be a vector type
366 /// whose element is VT.
367 bool EEVT::TypeSet::EnforceVectorEltTypeIs(MVT::SimpleValueType VT,
368                                            TreePattern &TP) {
369   TypeSet InputSet(*this);
370   bool MadeChange = false;
371   
372   // If we know nothing, then get the full set.
373   if (TypeVec.empty()) {
374     *this = TP.getDAGPatterns().getTargetInfo().getLegalValueTypes();
375     MadeChange = true;
376   }
377   
378   // Filter out all the non-vector types and types which don't have the right
379   // element type.
380   for (unsigned i = 0; i != TypeVec.size(); ++i)
381     if (!isVector(TypeVec[i]) ||
382         EVT(TypeVec[i]).getVectorElementType().getSimpleVT().SimpleTy != VT) {
383       TypeVec.erase(TypeVec.begin()+i--);
384       MadeChange = true;
385     }
386   
387   if (TypeVec.empty())  // FIXME: Really want an SMLoc here!
388     TP.error("Type inference contradiction found, forcing '" +
389              InputSet.getName() + "' to have a vector element");
390   return MadeChange;
391 }
392
393 //===----------------------------------------------------------------------===//
394 // Helpers for working with extended types.
395
396 bool RecordPtrCmp::operator()(const Record *LHS, const Record *RHS) const {
397   return LHS->getID() < RHS->getID();
398 }
399
400 /// Dependent variable map for CodeGenDAGPattern variant generation
401 typedef std::map<std::string, int> DepVarMap;
402
403 /// Const iterator shorthand for DepVarMap
404 typedef DepVarMap::const_iterator DepVarMap_citer;
405
406 namespace {
407 void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
408   if (N->isLeaf()) {
409     if (dynamic_cast<DefInit*>(N->getLeafValue()) != NULL) {
410       DepMap[N->getName()]++;
411     }
412   } else {
413     for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
414       FindDepVarsOf(N->getChild(i), DepMap);
415   }
416 }
417
418 //! Find dependent variables within child patterns
419 /*!
420  */
421 void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
422   DepVarMap depcounts;
423   FindDepVarsOf(N, depcounts);
424   for (DepVarMap_citer i = depcounts.begin(); i != depcounts.end(); ++i) {
425     if (i->second > 1) {            // std::pair<std::string, int>
426       DepVars.insert(i->first);
427     }
428   }
429 }
430
431 //! Dump the dependent variable set:
432 void DumpDepVars(MultipleUseVarSet &DepVars) {
433   if (DepVars.empty()) {
434     DEBUG(errs() << "<empty set>");
435   } else {
436     DEBUG(errs() << "[ ");
437     for (MultipleUseVarSet::const_iterator i = DepVars.begin(), e = DepVars.end();
438          i != e; ++i) {
439       DEBUG(errs() << (*i) << " ");
440     }
441     DEBUG(errs() << "]");
442   }
443 }
444 }
445
446 //===----------------------------------------------------------------------===//
447 // PatternToMatch implementation
448 //
449
450 /// getPredicateCheck - Return a single string containing all of this
451 /// pattern's predicates concatenated with "&&" operators.
452 ///
453 std::string PatternToMatch::getPredicateCheck() const {
454   std::string PredicateCheck;
455   for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
456     if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
457       Record *Def = Pred->getDef();
458       if (!Def->isSubClassOf("Predicate")) {
459 #ifndef NDEBUG
460         Def->dump();
461 #endif
462         assert(0 && "Unknown predicate type!");
463       }
464       if (!PredicateCheck.empty())
465         PredicateCheck += " && ";
466       PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
467     }
468   }
469
470   return PredicateCheck;
471 }
472
473 //===----------------------------------------------------------------------===//
474 // SDTypeConstraint implementation
475 //
476
477 SDTypeConstraint::SDTypeConstraint(Record *R) {
478   OperandNo = R->getValueAsInt("OperandNum");
479   
480   if (R->isSubClassOf("SDTCisVT")) {
481     ConstraintType = SDTCisVT;
482     x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
483   } else if (R->isSubClassOf("SDTCisPtrTy")) {
484     ConstraintType = SDTCisPtrTy;
485   } else if (R->isSubClassOf("SDTCisInt")) {
486     ConstraintType = SDTCisInt;
487   } else if (R->isSubClassOf("SDTCisFP")) {
488     ConstraintType = SDTCisFP;
489   } else if (R->isSubClassOf("SDTCisVec")) {
490     ConstraintType = SDTCisVec;
491   } else if (R->isSubClassOf("SDTCisSameAs")) {
492     ConstraintType = SDTCisSameAs;
493     x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
494   } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
495     ConstraintType = SDTCisVTSmallerThanOp;
496     x.SDTCisVTSmallerThanOp_Info.OtherOperandNum = 
497       R->getValueAsInt("OtherOperandNum");
498   } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
499     ConstraintType = SDTCisOpSmallerThanOp;
500     x.SDTCisOpSmallerThanOp_Info.BigOperandNum = 
501       R->getValueAsInt("BigOperandNum");
502   } else if (R->isSubClassOf("SDTCisEltOfVec")) {
503     ConstraintType = SDTCisEltOfVec;
504     x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
505   } else {
506     errs() << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
507     exit(1);
508   }
509 }
510
511 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
512 /// N, which has NumResults results.
513 TreePatternNode *SDTypeConstraint::getOperandNum(unsigned OpNo,
514                                                  TreePatternNode *N,
515                                                  unsigned NumResults) const {
516   assert(NumResults <= 1 &&
517          "We only work with nodes with zero or one result so far!");
518   
519   if (OpNo >= (NumResults + N->getNumChildren())) {
520     errs() << "Invalid operand number " << OpNo << " ";
521     N->dump();
522     errs() << '\n';
523     exit(1);
524   }
525
526   if (OpNo < NumResults)
527     return N;  // FIXME: need value #
528   else
529     return N->getChild(OpNo-NumResults);
530 }
531
532 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
533 /// constraint to the nodes operands.  This returns true if it makes a
534 /// change, false otherwise.  If a type contradiction is found, throw an
535 /// exception.
536 bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
537                                            const SDNodeInfo &NodeInfo,
538                                            TreePattern &TP) const {
539   unsigned NumResults = NodeInfo.getNumResults();
540   assert(NumResults <= 1 &&
541          "We only work with nodes with zero or one result so far!");
542   
543   // Check that the number of operands is sane.  Negative operands -> varargs.
544   if (NodeInfo.getNumOperands() >= 0) {
545     if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands())
546       TP.error(N->getOperator()->getName() + " node requires exactly " +
547                itostr(NodeInfo.getNumOperands()) + " operands!");
548   }
549
550   TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NumResults);
551   
552   switch (ConstraintType) {
553   default: assert(0 && "Unknown constraint type!");
554   case SDTCisVT:
555     // Operand must be a particular type.
556     return NodeToApply->UpdateNodeType(x.SDTCisVT_Info.VT, TP);
557   case SDTCisPtrTy:
558     // Operand must be same as target pointer type.
559     return NodeToApply->UpdateNodeType(MVT::iPTR, TP);
560   case SDTCisInt:
561     // Require it to be one of the legal integer VTs.
562     return NodeToApply->getExtType().EnforceInteger(TP);
563   case SDTCisFP:
564     // Require it to be one of the legal fp VTs.
565     return NodeToApply->getExtType().EnforceFloatingPoint(TP);
566   case SDTCisVec:
567     // Require it to be one of the legal vector VTs.
568     return NodeToApply->getExtType().EnforceVector(TP);
569   case SDTCisSameAs: {
570     TreePatternNode *OtherNode =
571       getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NumResults);
572     return NodeToApply->UpdateNodeType(OtherNode->getExtType(), TP) |
573            OtherNode->UpdateNodeType(NodeToApply->getExtType(), TP);
574   }
575   case SDTCisVTSmallerThanOp: {
576     // The NodeToApply must be a leaf node that is a VT.  OtherOperandNum must
577     // have an integer type that is smaller than the VT.
578     if (!NodeToApply->isLeaf() ||
579         !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
580         !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
581                ->isSubClassOf("ValueType"))
582       TP.error(N->getOperator()->getName() + " expects a VT operand!");
583     MVT::SimpleValueType VT =
584      getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
585     if (!isInteger(VT))
586       TP.error(N->getOperator()->getName() + " VT operand must be integer!");
587     
588     TreePatternNode *OtherNode =
589       getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N,NumResults);
590     
591     // It must be integer.
592     bool MadeChange = OtherNode->getExtType().EnforceInteger(TP);
593
594     // This doesn't try to enforce any information on the OtherNode, it just
595     // validates it when information is determined.
596     if (OtherNode->hasTypeSet() && OtherNode->getType() <= VT)
597       OtherNode->UpdateNodeType(MVT::Other, TP);  // Throw an error.
598     return MadeChange;
599   }
600   case SDTCisOpSmallerThanOp: {
601     TreePatternNode *BigOperand =
602       getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NumResults);
603     return NodeToApply->getExtType().
604                   EnforceSmallerThan(BigOperand->getExtType(), TP);
605   }
606   case SDTCisEltOfVec: {
607     TreePatternNode *VecOperand =
608       getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NumResults);
609     if (VecOperand->hasTypeSet()) {
610       if (!isVector(VecOperand->getType()))
611         TP.error(N->getOperator()->getName() + " VT operand must be a vector!");
612       EVT IVT = VecOperand->getType();
613       IVT = IVT.getVectorElementType();
614       return NodeToApply->UpdateNodeType(IVT.getSimpleVT().SimpleTy, TP);
615     }
616     
617     if (NodeToApply->hasTypeSet() && VecOperand->getExtType().hasVectorTypes()){
618       // Filter vector types out of VecOperand that don't have the right element
619       // type.
620       return VecOperand->getExtType().
621         EnforceVectorEltTypeIs(NodeToApply->getType(), TP);
622     }
623     return false;
624   }
625   }  
626   return false;
627 }
628
629 //===----------------------------------------------------------------------===//
630 // SDNodeInfo implementation
631 //
632 SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
633   EnumName    = R->getValueAsString("Opcode");
634   SDClassName = R->getValueAsString("SDClass");
635   Record *TypeProfile = R->getValueAsDef("TypeProfile");
636   NumResults = TypeProfile->getValueAsInt("NumResults");
637   NumOperands = TypeProfile->getValueAsInt("NumOperands");
638   
639   // Parse the properties.
640   Properties = 0;
641   std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
642   for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
643     if (PropList[i]->getName() == "SDNPCommutative") {
644       Properties |= 1 << SDNPCommutative;
645     } else if (PropList[i]->getName() == "SDNPAssociative") {
646       Properties |= 1 << SDNPAssociative;
647     } else if (PropList[i]->getName() == "SDNPHasChain") {
648       Properties |= 1 << SDNPHasChain;
649     } else if (PropList[i]->getName() == "SDNPOutFlag") {
650       Properties |= 1 << SDNPOutFlag;
651     } else if (PropList[i]->getName() == "SDNPInFlag") {
652       Properties |= 1 << SDNPInFlag;
653     } else if (PropList[i]->getName() == "SDNPOptInFlag") {
654       Properties |= 1 << SDNPOptInFlag;
655     } else if (PropList[i]->getName() == "SDNPMayStore") {
656       Properties |= 1 << SDNPMayStore;
657     } else if (PropList[i]->getName() == "SDNPMayLoad") {
658       Properties |= 1 << SDNPMayLoad;
659     } else if (PropList[i]->getName() == "SDNPSideEffect") {
660       Properties |= 1 << SDNPSideEffect;
661     } else if (PropList[i]->getName() == "SDNPMemOperand") {
662       Properties |= 1 << SDNPMemOperand;
663     } else {
664       errs() << "Unknown SD Node property '" << PropList[i]->getName()
665              << "' on node '" << R->getName() << "'!\n";
666       exit(1);
667     }
668   }
669   
670   
671   // Parse the type constraints.
672   std::vector<Record*> ConstraintList =
673     TypeProfile->getValueAsListOfDefs("Constraints");
674   TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
675 }
676
677 /// getKnownType - If the type constraints on this node imply a fixed type
678 /// (e.g. all stores return void, etc), then return it as an
679 /// MVT::SimpleValueType.  Otherwise, return EEVT::Other.
680 MVT::SimpleValueType SDNodeInfo::getKnownType() const {
681   unsigned NumResults = getNumResults();
682   assert(NumResults <= 1 &&
683          "We only work with nodes with zero or one result so far!");
684   
685   for (unsigned i = 0, e = TypeConstraints.size(); i != e; ++i) {
686     // Make sure that this applies to the correct node result.
687     if (TypeConstraints[i].OperandNo >= NumResults)  // FIXME: need value #
688       continue;
689     
690     switch (TypeConstraints[i].ConstraintType) {
691     default: break;
692     case SDTypeConstraint::SDTCisVT:
693       return TypeConstraints[i].x.SDTCisVT_Info.VT;
694     case SDTypeConstraint::SDTCisPtrTy:
695       return MVT::iPTR;
696     }
697   }
698   return MVT::Other;
699 }
700
701 //===----------------------------------------------------------------------===//
702 // TreePatternNode implementation
703 //
704
705 TreePatternNode::~TreePatternNode() {
706 #if 0 // FIXME: implement refcounted tree nodes!
707   for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
708     delete getChild(i);
709 #endif
710 }
711
712
713
714 void TreePatternNode::print(raw_ostream &OS) const {
715   if (isLeaf()) {
716     OS << *getLeafValue();
717   } else {
718     OS << '(' << getOperator()->getName();
719   }
720   
721   if (!isTypeCompletelyUnknown())
722     OS << ':' << getExtType().getName();
723
724   if (!isLeaf()) {
725     if (getNumChildren() != 0) {
726       OS << " ";
727       getChild(0)->print(OS);
728       for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
729         OS << ", ";
730         getChild(i)->print(OS);
731       }
732     }
733     OS << ")";
734   }
735   
736   for (unsigned i = 0, e = PredicateFns.size(); i != e; ++i)
737     OS << "<<P:" << PredicateFns[i] << ">>";
738   if (TransformFn)
739     OS << "<<X:" << TransformFn->getName() << ">>";
740   if (!getName().empty())
741     OS << ":$" << getName();
742
743 }
744 void TreePatternNode::dump() const {
745   print(errs());
746 }
747
748 /// isIsomorphicTo - Return true if this node is recursively
749 /// isomorphic to the specified node.  For this comparison, the node's
750 /// entire state is considered. The assigned name is ignored, since
751 /// nodes with differing names are considered isomorphic. However, if
752 /// the assigned name is present in the dependent variable set, then
753 /// the assigned name is considered significant and the node is
754 /// isomorphic if the names match.
755 bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
756                                      const MultipleUseVarSet &DepVars) const {
757   if (N == this) return true;
758   if (N->isLeaf() != isLeaf() || getExtType() != N->getExtType() ||
759       getPredicateFns() != N->getPredicateFns() ||
760       getTransformFn() != N->getTransformFn())
761     return false;
762
763   if (isLeaf()) {
764     if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
765       if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue())) {
766         return ((DI->getDef() == NDI->getDef())
767                 && (DepVars.find(getName()) == DepVars.end()
768                     || getName() == N->getName()));
769       }
770     }
771     return getLeafValue() == N->getLeafValue();
772   }
773   
774   if (N->getOperator() != getOperator() ||
775       N->getNumChildren() != getNumChildren()) return false;
776   for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
777     if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
778       return false;
779   return true;
780 }
781
782 /// clone - Make a copy of this tree and all of its children.
783 ///
784 TreePatternNode *TreePatternNode::clone() const {
785   TreePatternNode *New;
786   if (isLeaf()) {
787     New = new TreePatternNode(getLeafValue());
788   } else {
789     std::vector<TreePatternNode*> CChildren;
790     CChildren.reserve(Children.size());
791     for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
792       CChildren.push_back(getChild(i)->clone());
793     New = new TreePatternNode(getOperator(), CChildren);
794   }
795   New->setName(getName());
796   New->setType(getExtType());
797   New->setPredicateFns(getPredicateFns());
798   New->setTransformFn(getTransformFn());
799   return New;
800 }
801
802 /// RemoveAllTypes - Recursively strip all the types of this tree.
803 void TreePatternNode::RemoveAllTypes() {
804   setType(EEVT::TypeSet());  // Reset to unknown type.
805   if (isLeaf()) return;
806   for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
807     getChild(i)->RemoveAllTypes();
808 }
809
810
811 /// SubstituteFormalArguments - Replace the formal arguments in this tree
812 /// with actual values specified by ArgMap.
813 void TreePatternNode::
814 SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
815   if (isLeaf()) return;
816   
817   for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
818     TreePatternNode *Child = getChild(i);
819     if (Child->isLeaf()) {
820       Init *Val = Child->getLeafValue();
821       if (dynamic_cast<DefInit*>(Val) &&
822           static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
823         // We found a use of a formal argument, replace it with its value.
824         TreePatternNode *NewChild = ArgMap[Child->getName()];
825         assert(NewChild && "Couldn't find formal argument!");
826         assert((Child->getPredicateFns().empty() ||
827                 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
828                "Non-empty child predicate clobbered!");
829         setChild(i, NewChild);
830       }
831     } else {
832       getChild(i)->SubstituteFormalArguments(ArgMap);
833     }
834   }
835 }
836
837
838 /// InlinePatternFragments - If this pattern refers to any pattern
839 /// fragments, inline them into place, giving us a pattern without any
840 /// PatFrag references.
841 TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
842   if (isLeaf()) return this;  // nothing to do.
843   Record *Op = getOperator();
844   
845   if (!Op->isSubClassOf("PatFrag")) {
846     // Just recursively inline children nodes.
847     for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
848       TreePatternNode *Child = getChild(i);
849       TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
850
851       assert((Child->getPredicateFns().empty() ||
852               NewChild->getPredicateFns() == Child->getPredicateFns()) &&
853              "Non-empty child predicate clobbered!");
854
855       setChild(i, NewChild);
856     }
857     return this;
858   }
859
860   // Otherwise, we found a reference to a fragment.  First, look up its
861   // TreePattern record.
862   TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
863   
864   // Verify that we are passing the right number of operands.
865   if (Frag->getNumArgs() != Children.size())
866     TP.error("'" + Op->getName() + "' fragment requires " +
867              utostr(Frag->getNumArgs()) + " operands!");
868
869   TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
870
871   std::string Code = Op->getValueAsCode("Predicate");
872   if (!Code.empty())
873     FragTree->addPredicateFn("Predicate_"+Op->getName());
874
875   // Resolve formal arguments to their actual value.
876   if (Frag->getNumArgs()) {
877     // Compute the map of formal to actual arguments.
878     std::map<std::string, TreePatternNode*> ArgMap;
879     for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
880       ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
881   
882     FragTree->SubstituteFormalArguments(ArgMap);
883   }
884   
885   FragTree->setName(getName());
886   FragTree->UpdateNodeType(getExtType(), TP);
887
888   // Transfer in the old predicates.
889   for (unsigned i = 0, e = getPredicateFns().size(); i != e; ++i)
890     FragTree->addPredicateFn(getPredicateFns()[i]);
891
892   // Get a new copy of this fragment to stitch into here.
893   //delete this;    // FIXME: implement refcounting!
894   
895   // The fragment we inlined could have recursive inlining that is needed.  See
896   // if there are any pattern fragments in it and inline them as needed.
897   return FragTree->InlinePatternFragments(TP);
898 }
899
900 /// getImplicitType - Check to see if the specified record has an implicit
901 /// type which should be applied to it.  This will infer the type of register
902 /// references from the register file information, for example.
903 ///
904 static EEVT::TypeSet getImplicitType(Record *R, bool NotRegisters,
905                                      TreePattern &TP) {
906   // Check to see if this is a register or a register class.
907   if (R->isSubClassOf("RegisterClass")) {
908     if (NotRegisters) 
909       return EEVT::TypeSet(); // Unknown.
910     const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
911     return EEVT::TypeSet(T.getRegisterClass(R).getValueTypes());
912   } else if (R->isSubClassOf("PatFrag")) {
913     // Pattern fragment types will be resolved when they are inlined.
914     return EEVT::TypeSet(); // Unknown.
915   } else if (R->isSubClassOf("Register")) {
916     if (NotRegisters) 
917       return EEVT::TypeSet(); // Unknown.
918     const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
919     return EEVT::TypeSet(T.getRegisterVTs(R));
920   } else if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
921     // Using a VTSDNode or CondCodeSDNode.
922     return EEVT::TypeSet(MVT::Other, TP);
923   } else if (R->isSubClassOf("ComplexPattern")) {
924     if (NotRegisters) 
925       return EEVT::TypeSet(); // Unknown.
926    return EEVT::TypeSet(TP.getDAGPatterns().getComplexPattern(R).getValueType(),
927                          TP);
928   } else if (R->isSubClassOf("PointerLikeRegClass")) {
929     return EEVT::TypeSet(MVT::iPTR, TP);
930   } else if (R->getName() == "node" || R->getName() == "srcvalue" ||
931              R->getName() == "zero_reg") {
932     // Placeholder.
933     return EEVT::TypeSet(); // Unknown.
934   }
935   
936   TP.error("Unknown node flavor used in pattern: " + R->getName());
937   return EEVT::TypeSet(MVT::Other, TP);
938 }
939
940
941 /// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
942 /// CodeGenIntrinsic information for it, otherwise return a null pointer.
943 const CodeGenIntrinsic *TreePatternNode::
944 getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
945   if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
946       getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
947       getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
948     return 0;
949     
950   unsigned IID = 
951     dynamic_cast<IntInit*>(getChild(0)->getLeafValue())->getValue();
952   return &CDP.getIntrinsicInfo(IID);
953 }
954
955 /// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
956 /// return the ComplexPattern information, otherwise return null.
957 const ComplexPattern *
958 TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
959   if (!isLeaf()) return 0;
960   
961   DefInit *DI = dynamic_cast<DefInit*>(getLeafValue());
962   if (DI && DI->getDef()->isSubClassOf("ComplexPattern"))
963     return &CGP.getComplexPattern(DI->getDef());
964   return 0;
965 }
966
967 /// NodeHasProperty - Return true if this node has the specified property.
968 bool TreePatternNode::NodeHasProperty(SDNP Property,
969                                       const CodeGenDAGPatterns &CGP) const {
970   if (isLeaf()) {
971     if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
972       return CP->hasProperty(Property);
973     return false;
974   }
975   
976   Record *Operator = getOperator();
977   if (!Operator->isSubClassOf("SDNode")) return false;
978   
979   return CGP.getSDNodeInfo(Operator).hasProperty(Property);
980 }
981
982
983
984
985 /// TreeHasProperty - Return true if any node in this tree has the specified
986 /// property.
987 bool TreePatternNode::TreeHasProperty(SDNP Property,
988                                       const CodeGenDAGPatterns &CGP) const {
989   if (NodeHasProperty(Property, CGP))
990     return true;
991   for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
992     if (getChild(i)->TreeHasProperty(Property, CGP))
993       return true;
994   return false;
995 }  
996
997 /// isCommutativeIntrinsic - Return true if the node corresponds to a
998 /// commutative intrinsic.
999 bool
1000 TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
1001   if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
1002     return Int->isCommutative;
1003   return false;
1004 }
1005
1006
1007 /// ApplyTypeConstraints - Apply all of the type constraints relevant to
1008 /// this node and its children in the tree.  This returns true if it makes a
1009 /// change, false otherwise.  If a type contradiction is found, throw an
1010 /// exception.
1011 bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
1012   CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
1013   if (isLeaf()) {
1014     if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
1015       // If it's a regclass or something else known, include the type.
1016       return UpdateNodeType(getImplicitType(DI->getDef(), NotRegisters, TP),TP);
1017     }
1018     
1019     if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
1020       // Int inits are always integers. :)
1021       bool MadeChange = Type.EnforceInteger(TP);
1022       
1023       if (!hasTypeSet())
1024         return MadeChange;
1025       
1026       MVT::SimpleValueType VT = getType();
1027       if (VT == MVT::iPTR || VT == MVT::iPTRAny)
1028         return MadeChange;
1029       
1030       unsigned Size = EVT(VT).getSizeInBits();
1031       // Make sure that the value is representable for this type.
1032       if (Size >= 32) return MadeChange;
1033       
1034       int Val = (II->getValue() << (32-Size)) >> (32-Size);
1035       if (Val == II->getValue()) return MadeChange;
1036       
1037       // If sign-extended doesn't fit, does it fit as unsigned?
1038       unsigned ValueMask;
1039       unsigned UnsignedVal;
1040       ValueMask = unsigned(~uint32_t(0UL) >> (32-Size));
1041       UnsignedVal = unsigned(II->getValue());
1042
1043       if ((ValueMask & UnsignedVal) == UnsignedVal)
1044         return MadeChange;
1045       
1046       TP.error("Integer value '" + itostr(II->getValue())+
1047                "' is out of range for type '" + getEnumName(getType()) + "'!");
1048       return MadeChange;
1049     }
1050     return false;
1051   }
1052   
1053   // special handling for set, which isn't really an SDNode.
1054   if (getOperator()->getName() == "set") {
1055     assert (getNumChildren() >= 2 && "Missing RHS of a set?");
1056     unsigned NC = getNumChildren();
1057     bool MadeChange = false;
1058     for (unsigned i = 0; i < NC-1; ++i) {
1059       MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1060       MadeChange |= getChild(NC-1)->ApplyTypeConstraints(TP, NotRegisters);
1061     
1062       // Types of operands must match.
1063       MadeChange |=getChild(i)->UpdateNodeType(getChild(NC-1)->getExtType(),TP);
1064       MadeChange |=getChild(NC-1)->UpdateNodeType(getChild(i)->getExtType(),TP);
1065       MadeChange |=UpdateNodeType(MVT::isVoid, TP);
1066     }
1067     return MadeChange;
1068   }
1069   
1070   if (getOperator()->getName() == "implicit" ||
1071       getOperator()->getName() == "parallel") {
1072     bool MadeChange = false;
1073     for (unsigned i = 0; i < getNumChildren(); ++i)
1074       MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1075     MadeChange |= UpdateNodeType(MVT::isVoid, TP);
1076     return MadeChange;
1077   }
1078   
1079   if (getOperator()->getName() == "COPY_TO_REGCLASS") {
1080     bool MadeChange = false;
1081     MadeChange |= getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1082     MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
1083     
1084     // child #1 of COPY_TO_REGCLASS should be a register class.  We don't care
1085     // what type it gets, so if it didn't get a concrete type just give it the
1086     // first viable type from the reg class.
1087     if (!getChild(1)->hasTypeSet() &&
1088         !getChild(1)->getExtType().isCompletelyUnknown()) {
1089       MVT::SimpleValueType RCVT = getChild(1)->getExtType().getTypeList()[0];
1090       MadeChange |= getChild(1)->UpdateNodeType(RCVT, TP);
1091     }
1092     return MadeChange;
1093   }
1094   
1095   if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
1096     bool MadeChange = false;
1097
1098     // Apply the result type to the node.
1099     unsigned NumRetVTs = Int->IS.RetVTs.size();
1100     unsigned NumParamVTs = Int->IS.ParamVTs.size();
1101
1102     for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
1103       MadeChange |= UpdateNodeType(Int->IS.RetVTs[i], TP);
1104
1105     if (getNumChildren() != NumParamVTs + NumRetVTs)
1106       TP.error("Intrinsic '" + Int->Name + "' expects " +
1107                utostr(NumParamVTs + NumRetVTs - 1) + " operands, not " +
1108                utostr(getNumChildren() - 1) + " operands!");
1109
1110     // Apply type info to the intrinsic ID.
1111     MadeChange |= getChild(0)->UpdateNodeType(MVT::iPTR, TP);
1112     
1113     for (unsigned i = NumRetVTs, e = getNumChildren(); i != e; ++i) {
1114       MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i - NumRetVTs];
1115       MadeChange |= getChild(i)->UpdateNodeType(OpVT, TP);
1116       MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1117     }
1118     return MadeChange;
1119   }
1120   
1121   if (getOperator()->isSubClassOf("SDNode")) {
1122     const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
1123     
1124     bool MadeChange = NI.ApplyTypeConstraints(this, TP);
1125     for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1126       MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1127     // Branch, etc. do not produce results and top-level forms in instr pattern
1128     // must have void types.
1129     if (NI.getNumResults() == 0)
1130       MadeChange |= UpdateNodeType(MVT::isVoid, TP);
1131     
1132     return MadeChange;  
1133   }
1134   
1135   if (getOperator()->isSubClassOf("Instruction")) {
1136     const DAGInstruction &Inst = CDP.getInstruction(getOperator());
1137     assert(Inst.getNumResults() <= 1 &&
1138            "Only supports zero or one result instrs!");
1139
1140     CodeGenInstruction &InstInfo =
1141       CDP.getTargetInfo().getInstruction(getOperator());
1142     
1143     EEVT::TypeSet ResultType;
1144     
1145     // Apply the result type to the node
1146     if (InstInfo.NumDefs != 0) { // # of elements in (outs) list
1147       Record *ResultNode = Inst.getResult(0);
1148       
1149       if (ResultNode->isSubClassOf("PointerLikeRegClass")) {
1150         ResultType = EEVT::TypeSet(MVT::iPTR, TP);
1151       } else if (ResultNode->getName() == "unknown") {
1152         // Nothing to do.
1153       } else {
1154         assert(ResultNode->isSubClassOf("RegisterClass") &&
1155                "Operands should be register classes!");
1156         const CodeGenRegisterClass &RC = 
1157           CDP.getTargetInfo().getRegisterClass(ResultNode);
1158         ResultType = RC.getValueTypes();
1159       }
1160     } else if (!InstInfo.ImplicitDefs.empty()) {
1161       // If the instruction has implicit defs, the first one defines the result
1162       // type.
1163       Record *FirstImplicitDef = InstInfo.ImplicitDefs[0];
1164       assert(FirstImplicitDef->isSubClassOf("Register"));
1165       const std::vector<MVT::SimpleValueType> &RegVTs = 
1166         CDP.getTargetInfo().getRegisterVTs(FirstImplicitDef);
1167       if (RegVTs.size() == 1)
1168         ResultType = EEVT::TypeSet(RegVTs);
1169       else
1170         ResultType = EEVT::TypeSet(MVT::isVoid, TP);
1171     } else {
1172       // Otherwise, the instruction produces no value result.
1173       // FIXME: Model "no result" different than "one result that is void"
1174       ResultType = EEVT::TypeSet(MVT::isVoid, TP);
1175     }
1176     
1177     bool MadeChange = UpdateNodeType(ResultType, TP);
1178     
1179     // If this is an INSERT_SUBREG, constrain the source and destination VTs to
1180     // be the same.
1181     if (getOperator()->getName() == "INSERT_SUBREG") {
1182       MadeChange |= UpdateNodeType(getChild(0)->getExtType(), TP);
1183       MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
1184     }
1185
1186     unsigned ChildNo = 0;
1187     for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
1188       Record *OperandNode = Inst.getOperand(i);
1189       
1190       // If the instruction expects a predicate or optional def operand, we
1191       // codegen this by setting the operand to it's default value if it has a
1192       // non-empty DefaultOps field.
1193       if ((OperandNode->isSubClassOf("PredicateOperand") ||
1194            OperandNode->isSubClassOf("OptionalDefOperand")) &&
1195           !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1196         continue;
1197        
1198       // Verify that we didn't run out of provided operands.
1199       if (ChildNo >= getNumChildren())
1200         TP.error("Instruction '" + getOperator()->getName() +
1201                  "' expects more operands than were provided.");
1202       
1203       MVT::SimpleValueType VT;
1204       TreePatternNode *Child = getChild(ChildNo++);
1205       if (OperandNode->isSubClassOf("RegisterClass")) {
1206         const CodeGenRegisterClass &RC = 
1207           CDP.getTargetInfo().getRegisterClass(OperandNode);
1208         MadeChange |= Child->UpdateNodeType(RC.getValueTypes(), TP);
1209       } else if (OperandNode->isSubClassOf("Operand")) {
1210         VT = getValueType(OperandNode->getValueAsDef("Type"));
1211         MadeChange |= Child->UpdateNodeType(VT, TP);
1212       } else if (OperandNode->isSubClassOf("PointerLikeRegClass")) {
1213         MadeChange |= Child->UpdateNodeType(MVT::iPTR, TP);
1214       } else if (OperandNode->getName() == "unknown") {
1215         // Nothing to do.
1216       } else {
1217         assert(0 && "Unknown operand type!");
1218         abort();
1219       }
1220       MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
1221     }
1222
1223     if (ChildNo != getNumChildren())
1224       TP.error("Instruction '" + getOperator()->getName() +
1225                "' was provided too many operands!");
1226     
1227     return MadeChange;
1228   }
1229   
1230   assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
1231   
1232   // Node transforms always take one operand.
1233   if (getNumChildren() != 1)
1234     TP.error("Node transform '" + getOperator()->getName() +
1235              "' requires one operand!");
1236
1237   bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1238
1239   
1240   // If either the output or input of the xform does not have exact
1241   // type info. We assume they must be the same. Otherwise, it is perfectly
1242   // legal to transform from one type to a completely different type.
1243 #if 0
1244   if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
1245     bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
1246     MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
1247     return MadeChange;
1248   }
1249 #endif
1250   return MadeChange;
1251 }
1252
1253 /// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
1254 /// RHS of a commutative operation, not the on LHS.
1255 static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
1256   if (!N->isLeaf() && N->getOperator()->getName() == "imm")
1257     return true;
1258   if (N->isLeaf() && dynamic_cast<IntInit*>(N->getLeafValue()))
1259     return true;
1260   return false;
1261 }
1262
1263
1264 /// canPatternMatch - If it is impossible for this pattern to match on this
1265 /// target, fill in Reason and return false.  Otherwise, return true.  This is
1266 /// used as a sanity check for .td files (to prevent people from writing stuff
1267 /// that can never possibly work), and to prevent the pattern permuter from
1268 /// generating stuff that is useless.
1269 bool TreePatternNode::canPatternMatch(std::string &Reason, 
1270                                       const CodeGenDAGPatterns &CDP) {
1271   if (isLeaf()) return true;
1272
1273   for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1274     if (!getChild(i)->canPatternMatch(Reason, CDP))
1275       return false;
1276
1277   // If this is an intrinsic, handle cases that would make it not match.  For
1278   // example, if an operand is required to be an immediate.
1279   if (getOperator()->isSubClassOf("Intrinsic")) {
1280     // TODO:
1281     return true;
1282   }
1283   
1284   // If this node is a commutative operator, check that the LHS isn't an
1285   // immediate.
1286   const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
1287   bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
1288   if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
1289     // Scan all of the operands of the node and make sure that only the last one
1290     // is a constant node, unless the RHS also is.
1291     if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
1292       bool Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
1293       for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
1294         if (OnlyOnRHSOfCommutative(getChild(i))) {
1295           Reason="Immediate value must be on the RHS of commutative operators!";
1296           return false;
1297         }
1298     }
1299   }
1300   
1301   return true;
1302 }
1303
1304 //===----------------------------------------------------------------------===//
1305 // TreePattern implementation
1306 //
1307
1308 TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
1309                          CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
1310   isInputPattern = isInput;
1311   for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
1312     Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
1313 }
1314
1315 TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
1316                          CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
1317   isInputPattern = isInput;
1318   Trees.push_back(ParseTreePattern(Pat));
1319 }
1320
1321 TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
1322                          CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
1323   isInputPattern = isInput;
1324   Trees.push_back(Pat);
1325 }
1326
1327 void TreePattern::error(const std::string &Msg) const {
1328   dump();
1329   throw TGError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
1330 }
1331
1332 void TreePattern::ComputeNamedNodes() {
1333   for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1334     ComputeNamedNodes(Trees[i]);
1335 }
1336
1337 void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
1338   if (!N->getName().empty())
1339     NamedNodes[N->getName()].push_back(N);
1340   
1341   for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1342     ComputeNamedNodes(N->getChild(i));
1343 }
1344
1345 TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
1346   DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
1347   if (!OpDef) error("Pattern has unexpected operator type!");
1348   Record *Operator = OpDef->getDef();
1349   
1350   if (Operator->isSubClassOf("ValueType")) {
1351     // If the operator is a ValueType, then this must be "type cast" of a leaf
1352     // node.
1353     if (Dag->getNumArgs() != 1)
1354       error("Type cast only takes one operand!");
1355     
1356     Init *Arg = Dag->getArg(0);
1357     TreePatternNode *New;
1358     if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
1359       Record *R = DI->getDef();
1360       if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
1361         Dag->setArg(0, new DagInit(DI, "",
1362                                 std::vector<std::pair<Init*, std::string> >()));
1363         return ParseTreePattern(Dag);
1364       }
1365       
1366       // Input argument?
1367       if (R->getName() == "node") {
1368         if (Dag->getArgName(0).empty())
1369           error("'node' argument requires a name to match with operand list");
1370         Args.push_back(Dag->getArgName(0));
1371       }
1372       
1373       New = new TreePatternNode(DI);
1374     } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
1375       New = ParseTreePattern(DI);
1376     } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
1377       New = new TreePatternNode(II);
1378       if (!Dag->getArgName(0).empty())
1379         error("Constant int argument should not have a name!");
1380     } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
1381       // Turn this into an IntInit.
1382       Init *II = BI->convertInitializerTo(new IntRecTy());
1383       if (II == 0 || !dynamic_cast<IntInit*>(II))
1384         error("Bits value must be constants!");
1385       
1386       New = new TreePatternNode(dynamic_cast<IntInit*>(II));
1387       if (!Dag->getArgName(0).empty())
1388         error("Constant int argument should not have a name!");
1389     } else {
1390       Arg->dump();
1391       error("Unknown leaf value for tree pattern!");
1392       return 0;
1393     }
1394     
1395     // Apply the type cast.
1396     New->UpdateNodeType(getValueType(Operator), *this);
1397     if (New->getNumChildren() == 0)
1398       New->setName(Dag->getArgName(0));
1399     return New;
1400   }
1401   
1402   // Verify that this is something that makes sense for an operator.
1403   if (!Operator->isSubClassOf("PatFrag") && 
1404       !Operator->isSubClassOf("SDNode") &&
1405       !Operator->isSubClassOf("Instruction") && 
1406       !Operator->isSubClassOf("SDNodeXForm") &&
1407       !Operator->isSubClassOf("Intrinsic") &&
1408       Operator->getName() != "set" &&
1409       Operator->getName() != "implicit" &&
1410       Operator->getName() != "parallel")
1411     error("Unrecognized node '" + Operator->getName() + "'!");
1412   
1413   //  Check to see if this is something that is illegal in an input pattern.
1414   if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
1415                          Operator->isSubClassOf("SDNodeXForm")))
1416     error("Cannot use '" + Operator->getName() + "' in an input pattern!");
1417   
1418   std::vector<TreePatternNode*> Children;
1419   
1420   for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
1421     Init *Arg = Dag->getArg(i);
1422     if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
1423       Children.push_back(ParseTreePattern(DI));
1424       if (Children.back()->getName().empty())
1425         Children.back()->setName(Dag->getArgName(i));
1426     } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
1427       Record *R = DefI->getDef();
1428       // Direct reference to a leaf DagNode or PatFrag?  Turn it into a
1429       // TreePatternNode if its own.
1430       if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
1431         Dag->setArg(i, new DagInit(DefI, "",
1432                               std::vector<std::pair<Init*, std::string> >()));
1433         --i;  // Revisit this node...
1434       } else {
1435         TreePatternNode *Node = new TreePatternNode(DefI);
1436         Node->setName(Dag->getArgName(i));
1437         Children.push_back(Node);
1438         
1439         // Input argument?
1440         if (R->getName() == "node") {
1441           if (Dag->getArgName(i).empty())
1442             error("'node' argument requires a name to match with operand list");
1443           Args.push_back(Dag->getArgName(i));
1444         }
1445       }
1446     } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
1447       TreePatternNode *Node = new TreePatternNode(II);
1448       if (!Dag->getArgName(i).empty())
1449         error("Constant int argument should not have a name!");
1450       Children.push_back(Node);
1451     } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
1452       // Turn this into an IntInit.
1453       Init *II = BI->convertInitializerTo(new IntRecTy());
1454       if (II == 0 || !dynamic_cast<IntInit*>(II))
1455         error("Bits value must be constants!");
1456       
1457       TreePatternNode *Node = new TreePatternNode(dynamic_cast<IntInit*>(II));
1458       if (!Dag->getArgName(i).empty())
1459         error("Constant int argument should not have a name!");
1460       Children.push_back(Node);
1461     } else {
1462       errs() << '"';
1463       Arg->dump();
1464       errs() << "\": ";
1465       error("Unknown leaf value for tree pattern!");
1466     }
1467   }
1468   
1469   // If the operator is an intrinsic, then this is just syntactic sugar for for
1470   // (intrinsic_* <number>, ..children..).  Pick the right intrinsic node, and 
1471   // convert the intrinsic name to a number.
1472   if (Operator->isSubClassOf("Intrinsic")) {
1473     const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
1474     unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
1475
1476     // If this intrinsic returns void, it must have side-effects and thus a
1477     // chain.
1478     if (Int.IS.RetVTs[0] == MVT::isVoid) {
1479       Operator = getDAGPatterns().get_intrinsic_void_sdnode();
1480     } else if (Int.ModRef != CodeGenIntrinsic::NoMem) {
1481       // Has side-effects, requires chain.
1482       Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
1483     } else {
1484       // Otherwise, no chain.
1485       Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
1486     }
1487     
1488     TreePatternNode *IIDNode = new TreePatternNode(new IntInit(IID));
1489     Children.insert(Children.begin(), IIDNode);
1490   }
1491   
1492   TreePatternNode *Result = new TreePatternNode(Operator, Children);
1493   Result->setName(Dag->getName());
1494   return Result;
1495 }
1496
1497 /// InferAllTypes - Infer/propagate as many types throughout the expression
1498 /// patterns as possible.  Return true if all types are inferred, false
1499 /// otherwise.  Throw an exception if a type contradiction is found.
1500 bool TreePattern::
1501 InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
1502   if (NamedNodes.empty())
1503     ComputeNamedNodes();
1504
1505   bool MadeChange = true;
1506   while (MadeChange) {
1507     MadeChange = false;
1508     for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1509       MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
1510
1511     // If there are constraints on our named nodes, apply them.
1512     for (StringMap<SmallVector<TreePatternNode*,1> >::iterator 
1513          I = NamedNodes.begin(), E = NamedNodes.end(); I != E; ++I) {
1514       SmallVectorImpl<TreePatternNode*> &Nodes = I->second;
1515       
1516       // If we have input named node types, propagate their types to the named
1517       // values here.
1518       if (InNamedTypes) {
1519         // FIXME: Should be error?
1520         assert(InNamedTypes->count(I->getKey()) &&
1521                "Named node in output pattern but not input pattern?");
1522
1523         const SmallVectorImpl<TreePatternNode*> &InNodes =
1524           InNamedTypes->find(I->getKey())->second;
1525
1526         // The input types should be fully resolved by now.
1527         for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
1528           // If this node is a register class, and it is the root of the pattern
1529           // then we're mapping something onto an input register.  We allow
1530           // changing the type of the input register in this case.  This allows
1531           // us to match things like:
1532           //  def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
1533           if (Nodes[i] == Trees[0] && Nodes[i]->isLeaf()) {
1534             DefInit *DI = dynamic_cast<DefInit*>(Nodes[i]->getLeafValue());
1535             if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1536               continue;
1537           }
1538           
1539           MadeChange |=Nodes[i]->UpdateNodeType(InNodes[0]->getExtType(),*this);
1540         }
1541       }
1542       
1543       // If there are multiple nodes with the same name, they must all have the
1544       // same type.
1545       if (I->second.size() > 1) {
1546         for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
1547           MadeChange |=Nodes[i]->UpdateNodeType(Nodes[i+1]->getExtType(),*this);
1548           MadeChange |=Nodes[i+1]->UpdateNodeType(Nodes[i]->getExtType(),*this);
1549         }
1550       }
1551     }
1552   }
1553   
1554   bool HasUnresolvedTypes = false;
1555   for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1556     HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
1557   return !HasUnresolvedTypes;
1558 }
1559
1560 void TreePattern::print(raw_ostream &OS) const {
1561   OS << getRecord()->getName();
1562   if (!Args.empty()) {
1563     OS << "(" << Args[0];
1564     for (unsigned i = 1, e = Args.size(); i != e; ++i)
1565       OS << ", " << Args[i];
1566     OS << ")";
1567   }
1568   OS << ": ";
1569   
1570   if (Trees.size() > 1)
1571     OS << "[\n";
1572   for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
1573     OS << "\t";
1574     Trees[i]->print(OS);
1575     OS << "\n";
1576   }
1577
1578   if (Trees.size() > 1)
1579     OS << "]\n";
1580 }
1581
1582 void TreePattern::dump() const { print(errs()); }
1583
1584 //===----------------------------------------------------------------------===//
1585 // CodeGenDAGPatterns implementation
1586 //
1587
1588 CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) : Records(R) {
1589   Intrinsics = LoadIntrinsics(Records, false);
1590   TgtIntrinsics = LoadIntrinsics(Records, true);
1591   ParseNodeInfo();
1592   ParseNodeTransforms();
1593   ParseComplexPatterns();
1594   ParsePatternFragments();
1595   ParseDefaultOperands();
1596   ParseInstructions();
1597   ParsePatterns();
1598   
1599   // Generate variants.  For example, commutative patterns can match
1600   // multiple ways.  Add them to PatternsToMatch as well.
1601   GenerateVariants();
1602
1603   // Infer instruction flags.  For example, we can detect loads,
1604   // stores, and side effects in many cases by examining an
1605   // instruction's pattern.
1606   InferInstructionFlags();
1607 }
1608
1609 CodeGenDAGPatterns::~CodeGenDAGPatterns() {
1610   for (pf_iterator I = PatternFragments.begin(),
1611        E = PatternFragments.end(); I != E; ++I)
1612     delete I->second;
1613 }
1614
1615
1616 Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
1617   Record *N = Records.getDef(Name);
1618   if (!N || !N->isSubClassOf("SDNode")) {
1619     errs() << "Error getting SDNode '" << Name << "'!\n";
1620     exit(1);
1621   }
1622   return N;
1623 }
1624
1625 // Parse all of the SDNode definitions for the target, populating SDNodes.
1626 void CodeGenDAGPatterns::ParseNodeInfo() {
1627   std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
1628   while (!Nodes.empty()) {
1629     SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
1630     Nodes.pop_back();
1631   }
1632
1633   // Get the builtin intrinsic nodes.
1634   intrinsic_void_sdnode     = getSDNodeNamed("intrinsic_void");
1635   intrinsic_w_chain_sdnode  = getSDNodeNamed("intrinsic_w_chain");
1636   intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
1637 }
1638
1639 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
1640 /// map, and emit them to the file as functions.
1641 void CodeGenDAGPatterns::ParseNodeTransforms() {
1642   std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
1643   while (!Xforms.empty()) {
1644     Record *XFormNode = Xforms.back();
1645     Record *SDNode = XFormNode->getValueAsDef("Opcode");
1646     std::string Code = XFormNode->getValueAsCode("XFormFunction");
1647     SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
1648
1649     Xforms.pop_back();
1650   }
1651 }
1652
1653 void CodeGenDAGPatterns::ParseComplexPatterns() {
1654   std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
1655   while (!AMs.empty()) {
1656     ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
1657     AMs.pop_back();
1658   }
1659 }
1660
1661
1662 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
1663 /// file, building up the PatternFragments map.  After we've collected them all,
1664 /// inline fragments together as necessary, so that there are no references left
1665 /// inside a pattern fragment to a pattern fragment.
1666 ///
1667 void CodeGenDAGPatterns::ParsePatternFragments() {
1668   std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
1669   
1670   // First step, parse all of the fragments.
1671   for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1672     DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
1673     TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
1674     PatternFragments[Fragments[i]] = P;
1675     
1676     // Validate the argument list, converting it to set, to discard duplicates.
1677     std::vector<std::string> &Args = P->getArgList();
1678     std::set<std::string> OperandsSet(Args.begin(), Args.end());
1679     
1680     if (OperandsSet.count(""))
1681       P->error("Cannot have unnamed 'node' values in pattern fragment!");
1682     
1683     // Parse the operands list.
1684     DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
1685     DefInit *OpsOp = dynamic_cast<DefInit*>(OpsList->getOperator());
1686     // Special cases: ops == outs == ins. Different names are used to
1687     // improve readability.
1688     if (!OpsOp ||
1689         (OpsOp->getDef()->getName() != "ops" &&
1690          OpsOp->getDef()->getName() != "outs" &&
1691          OpsOp->getDef()->getName() != "ins"))
1692       P->error("Operands list should start with '(ops ... '!");
1693     
1694     // Copy over the arguments.       
1695     Args.clear();
1696     for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
1697       if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
1698           static_cast<DefInit*>(OpsList->getArg(j))->
1699           getDef()->getName() != "node")
1700         P->error("Operands list should all be 'node' values.");
1701       if (OpsList->getArgName(j).empty())
1702         P->error("Operands list should have names for each operand!");
1703       if (!OperandsSet.count(OpsList->getArgName(j)))
1704         P->error("'" + OpsList->getArgName(j) +
1705                  "' does not occur in pattern or was multiply specified!");
1706       OperandsSet.erase(OpsList->getArgName(j));
1707       Args.push_back(OpsList->getArgName(j));
1708     }
1709     
1710     if (!OperandsSet.empty())
1711       P->error("Operands list does not contain an entry for operand '" +
1712                *OperandsSet.begin() + "'!");
1713
1714     // If there is a code init for this fragment, keep track of the fact that
1715     // this fragment uses it.
1716     std::string Code = Fragments[i]->getValueAsCode("Predicate");
1717     if (!Code.empty())
1718       P->getOnlyTree()->addPredicateFn("Predicate_"+Fragments[i]->getName());
1719     
1720     // If there is a node transformation corresponding to this, keep track of
1721     // it.
1722     Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
1723     if (!getSDNodeTransform(Transform).second.empty())    // not noop xform?
1724       P->getOnlyTree()->setTransformFn(Transform);
1725   }
1726   
1727   // Now that we've parsed all of the tree fragments, do a closure on them so
1728   // that there are not references to PatFrags left inside of them.
1729   for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1730     TreePattern *ThePat = PatternFragments[Fragments[i]];
1731     ThePat->InlinePatternFragments();
1732         
1733     // Infer as many types as possible.  Don't worry about it if we don't infer
1734     // all of them, some may depend on the inputs of the pattern.
1735     try {
1736       ThePat->InferAllTypes();
1737     } catch (...) {
1738       // If this pattern fragment is not supported by this target (no types can
1739       // satisfy its constraints), just ignore it.  If the bogus pattern is
1740       // actually used by instructions, the type consistency error will be
1741       // reported there.
1742     }
1743     
1744     // If debugging, print out the pattern fragment result.
1745     DEBUG(ThePat->dump());
1746   }
1747 }
1748
1749 void CodeGenDAGPatterns::ParseDefaultOperands() {
1750   std::vector<Record*> DefaultOps[2];
1751   DefaultOps[0] = Records.getAllDerivedDefinitions("PredicateOperand");
1752   DefaultOps[1] = Records.getAllDerivedDefinitions("OptionalDefOperand");
1753
1754   // Find some SDNode.
1755   assert(!SDNodes.empty() && "No SDNodes parsed?");
1756   Init *SomeSDNode = new DefInit(SDNodes.begin()->first);
1757   
1758   for (unsigned iter = 0; iter != 2; ++iter) {
1759     for (unsigned i = 0, e = DefaultOps[iter].size(); i != e; ++i) {
1760       DagInit *DefaultInfo = DefaultOps[iter][i]->getValueAsDag("DefaultOps");
1761     
1762       // Clone the DefaultInfo dag node, changing the operator from 'ops' to
1763       // SomeSDnode so that we can parse this.
1764       std::vector<std::pair<Init*, std::string> > Ops;
1765       for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
1766         Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
1767                                      DefaultInfo->getArgName(op)));
1768       DagInit *DI = new DagInit(SomeSDNode, "", Ops);
1769     
1770       // Create a TreePattern to parse this.
1771       TreePattern P(DefaultOps[iter][i], DI, false, *this);
1772       assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
1773
1774       // Copy the operands over into a DAGDefaultOperand.
1775       DAGDefaultOperand DefaultOpInfo;
1776     
1777       TreePatternNode *T = P.getTree(0);
1778       for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
1779         TreePatternNode *TPN = T->getChild(op);
1780         while (TPN->ApplyTypeConstraints(P, false))
1781           /* Resolve all types */;
1782       
1783         if (TPN->ContainsUnresolvedType()) {
1784           if (iter == 0)
1785             throw "Value #" + utostr(i) + " of PredicateOperand '" +
1786               DefaultOps[iter][i]->getName() +"' doesn't have a concrete type!";
1787           else
1788             throw "Value #" + utostr(i) + " of OptionalDefOperand '" +
1789               DefaultOps[iter][i]->getName() +"' doesn't have a concrete type!";
1790         }
1791         DefaultOpInfo.DefaultOps.push_back(TPN);
1792       }
1793
1794       // Insert it into the DefaultOperands map so we can find it later.
1795       DefaultOperands[DefaultOps[iter][i]] = DefaultOpInfo;
1796     }
1797   }
1798 }
1799
1800 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
1801 /// instruction input.  Return true if this is a real use.
1802 static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
1803                       std::map<std::string, TreePatternNode*> &InstInputs,
1804                       std::vector<Record*> &InstImpInputs) {
1805   // No name -> not interesting.
1806   if (Pat->getName().empty()) {
1807     if (Pat->isLeaf()) {
1808       DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1809       if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1810         I->error("Input " + DI->getDef()->getName() + " must be named!");
1811       else if (DI && DI->getDef()->isSubClassOf("Register")) 
1812         InstImpInputs.push_back(DI->getDef());
1813     }
1814     return false;
1815   }
1816
1817   Record *Rec;
1818   if (Pat->isLeaf()) {
1819     DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1820     if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
1821     Rec = DI->getDef();
1822   } else {
1823     Rec = Pat->getOperator();
1824   }
1825
1826   // SRCVALUE nodes are ignored.
1827   if (Rec->getName() == "srcvalue")
1828     return false;
1829
1830   TreePatternNode *&Slot = InstInputs[Pat->getName()];
1831   if (!Slot) {
1832     Slot = Pat;
1833     return true;
1834   }
1835   Record *SlotRec;
1836   if (Slot->isLeaf()) {
1837     SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
1838   } else {
1839     assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
1840     SlotRec = Slot->getOperator();
1841   }
1842   
1843   // Ensure that the inputs agree if we've already seen this input.
1844   if (Rec != SlotRec)
1845     I->error("All $" + Pat->getName() + " inputs must agree with each other");
1846   if (Slot->getExtType() != Pat->getExtType())
1847     I->error("All $" + Pat->getName() + " inputs must agree with each other");
1848   return true;
1849 }
1850
1851 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
1852 /// part of "I", the instruction), computing the set of inputs and outputs of
1853 /// the pattern.  Report errors if we see anything naughty.
1854 void CodeGenDAGPatterns::
1855 FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
1856                             std::map<std::string, TreePatternNode*> &InstInputs,
1857                             std::map<std::string, TreePatternNode*>&InstResults,
1858                             std::vector<Record*> &InstImpInputs,
1859                             std::vector<Record*> &InstImpResults) {
1860   if (Pat->isLeaf()) {
1861     bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1862     if (!isUse && Pat->getTransformFn())
1863       I->error("Cannot specify a transform function for a non-input value!");
1864     return;
1865   }
1866   
1867   if (Pat->getOperator()->getName() == "implicit") {
1868     for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1869       TreePatternNode *Dest = Pat->getChild(i);
1870       if (!Dest->isLeaf())
1871         I->error("implicitly defined value should be a register!");
1872     
1873       DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1874       if (!Val || !Val->getDef()->isSubClassOf("Register"))
1875         I->error("implicitly defined value should be a register!");
1876       InstImpResults.push_back(Val->getDef());
1877     }
1878     return;
1879   }
1880   
1881   if (Pat->getOperator()->getName() != "set") {
1882     // If this is not a set, verify that the children nodes are not void typed,
1883     // and recurse.
1884     for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1885       if (Pat->getChild(i)->getType() == MVT::isVoid)
1886         I->error("Cannot have void nodes inside of patterns!");
1887       FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
1888                                   InstImpInputs, InstImpResults);
1889     }
1890     
1891     // If this is a non-leaf node with no children, treat it basically as if
1892     // it were a leaf.  This handles nodes like (imm).
1893     bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1894     
1895     if (!isUse && Pat->getTransformFn())
1896       I->error("Cannot specify a transform function for a non-input value!");
1897     return;
1898   }
1899   
1900   // Otherwise, this is a set, validate and collect instruction results.
1901   if (Pat->getNumChildren() == 0)
1902     I->error("set requires operands!");
1903   
1904   if (Pat->getTransformFn())
1905     I->error("Cannot specify a transform function on a set node!");
1906   
1907   // Check the set destinations.
1908   unsigned NumDests = Pat->getNumChildren()-1;
1909   for (unsigned i = 0; i != NumDests; ++i) {
1910     TreePatternNode *Dest = Pat->getChild(i);
1911     if (!Dest->isLeaf())
1912       I->error("set destination should be a register!");
1913     
1914     DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1915     if (!Val)
1916       I->error("set destination should be a register!");
1917
1918     if (Val->getDef()->isSubClassOf("RegisterClass") ||
1919         Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
1920       if (Dest->getName().empty())
1921         I->error("set destination must have a name!");
1922       if (InstResults.count(Dest->getName()))
1923         I->error("cannot set '" + Dest->getName() +"' multiple times");
1924       InstResults[Dest->getName()] = Dest;
1925     } else if (Val->getDef()->isSubClassOf("Register")) {
1926       InstImpResults.push_back(Val->getDef());
1927     } else {
1928       I->error("set destination should be a register!");
1929     }
1930   }
1931     
1932   // Verify and collect info from the computation.
1933   FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
1934                               InstInputs, InstResults,
1935                               InstImpInputs, InstImpResults);
1936 }
1937
1938 //===----------------------------------------------------------------------===//
1939 // Instruction Analysis
1940 //===----------------------------------------------------------------------===//
1941
1942 class InstAnalyzer {
1943   const CodeGenDAGPatterns &CDP;
1944   bool &mayStore;
1945   bool &mayLoad;
1946   bool &HasSideEffects;
1947 public:
1948   InstAnalyzer(const CodeGenDAGPatterns &cdp,
1949                bool &maystore, bool &mayload, bool &hse)
1950     : CDP(cdp), mayStore(maystore), mayLoad(mayload), HasSideEffects(hse){
1951   }
1952
1953   /// Analyze - Analyze the specified instruction, returning true if the
1954   /// instruction had a pattern.
1955   bool Analyze(Record *InstRecord) {
1956     const TreePattern *Pattern = CDP.getInstruction(InstRecord).getPattern();
1957     if (Pattern == 0) {
1958       HasSideEffects = 1;
1959       return false;  // No pattern.
1960     }
1961
1962     // FIXME: Assume only the first tree is the pattern. The others are clobber
1963     // nodes.
1964     AnalyzeNode(Pattern->getTree(0));
1965     return true;
1966   }
1967
1968 private:
1969   void AnalyzeNode(const TreePatternNode *N) {
1970     if (N->isLeaf()) {
1971       if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
1972         Record *LeafRec = DI->getDef();
1973         // Handle ComplexPattern leaves.
1974         if (LeafRec->isSubClassOf("ComplexPattern")) {
1975           const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
1976           if (CP.hasProperty(SDNPMayStore)) mayStore = true;
1977           if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
1978           if (CP.hasProperty(SDNPSideEffect)) HasSideEffects = true;
1979         }
1980       }
1981       return;
1982     }
1983
1984     // Analyze children.
1985     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1986       AnalyzeNode(N->getChild(i));
1987
1988     // Ignore set nodes, which are not SDNodes.
1989     if (N->getOperator()->getName() == "set")
1990       return;
1991
1992     // Get information about the SDNode for the operator.
1993     const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N->getOperator());
1994
1995     // Notice properties of the node.
1996     if (OpInfo.hasProperty(SDNPMayStore)) mayStore = true;
1997     if (OpInfo.hasProperty(SDNPMayLoad)) mayLoad = true;
1998     if (OpInfo.hasProperty(SDNPSideEffect)) HasSideEffects = true;
1999
2000     if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
2001       // If this is an intrinsic, analyze it.
2002       if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
2003         mayLoad = true;// These may load memory.
2004
2005       if (IntInfo->ModRef >= CodeGenIntrinsic::WriteArgMem)
2006         mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
2007
2008       if (IntInfo->ModRef >= CodeGenIntrinsic::WriteMem)
2009         // WriteMem intrinsics can have other strange effects.
2010         HasSideEffects = true;
2011     }
2012   }
2013
2014 };
2015
2016 static void InferFromPattern(const CodeGenInstruction &Inst,
2017                              bool &MayStore, bool &MayLoad,
2018                              bool &HasSideEffects,
2019                              const CodeGenDAGPatterns &CDP) {
2020   MayStore = MayLoad = HasSideEffects = false;
2021
2022   bool HadPattern =
2023     InstAnalyzer(CDP, MayStore, MayLoad, HasSideEffects).Analyze(Inst.TheDef);
2024
2025   // InstAnalyzer only correctly analyzes mayStore/mayLoad so far.
2026   if (Inst.mayStore) {  // If the .td file explicitly sets mayStore, use it.
2027     // If we decided that this is a store from the pattern, then the .td file
2028     // entry is redundant.
2029     if (MayStore)
2030       fprintf(stderr,
2031               "Warning: mayStore flag explicitly set on instruction '%s'"
2032               " but flag already inferred from pattern.\n",
2033               Inst.TheDef->getName().c_str());
2034     MayStore = true;
2035   }
2036
2037   if (Inst.mayLoad) {  // If the .td file explicitly sets mayLoad, use it.
2038     // If we decided that this is a load from the pattern, then the .td file
2039     // entry is redundant.
2040     if (MayLoad)
2041       fprintf(stderr,
2042               "Warning: mayLoad flag explicitly set on instruction '%s'"
2043               " but flag already inferred from pattern.\n",
2044               Inst.TheDef->getName().c_str());
2045     MayLoad = true;
2046   }
2047
2048   if (Inst.neverHasSideEffects) {
2049     if (HadPattern)
2050       fprintf(stderr, "Warning: neverHasSideEffects set on instruction '%s' "
2051               "which already has a pattern\n", Inst.TheDef->getName().c_str());
2052     HasSideEffects = false;
2053   }
2054
2055   if (Inst.hasSideEffects) {
2056     if (HasSideEffects)
2057       fprintf(stderr, "Warning: hasSideEffects set on instruction '%s' "
2058               "which already inferred this.\n", Inst.TheDef->getName().c_str());
2059     HasSideEffects = true;
2060   }
2061 }
2062
2063 /// ParseInstructions - Parse all of the instructions, inlining and resolving
2064 /// any fragments involved.  This populates the Instructions list with fully
2065 /// resolved instructions.
2066 void CodeGenDAGPatterns::ParseInstructions() {
2067   std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
2068   
2069   for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
2070     ListInit *LI = 0;
2071     
2072     if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
2073       LI = Instrs[i]->getValueAsListInit("Pattern");
2074     
2075     // If there is no pattern, only collect minimal information about the
2076     // instruction for its operand list.  We have to assume that there is one
2077     // result, as we have no detailed info.
2078     if (!LI || LI->getSize() == 0) {
2079       std::vector<Record*> Results;
2080       std::vector<Record*> Operands;
2081       
2082       CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
2083
2084       if (InstInfo.OperandList.size() != 0) {
2085         if (InstInfo.NumDefs == 0) {
2086           // These produce no results
2087           for (unsigned j = 0, e = InstInfo.OperandList.size(); j < e; ++j)
2088             Operands.push_back(InstInfo.OperandList[j].Rec);
2089         } else {
2090           // Assume the first operand is the result.
2091           Results.push_back(InstInfo.OperandList[0].Rec);
2092       
2093           // The rest are inputs.
2094           for (unsigned j = 1, e = InstInfo.OperandList.size(); j < e; ++j)
2095             Operands.push_back(InstInfo.OperandList[j].Rec);
2096         }
2097       }
2098       
2099       // Create and insert the instruction.
2100       std::vector<Record*> ImpResults;
2101       std::vector<Record*> ImpOperands;
2102       Instructions.insert(std::make_pair(Instrs[i], 
2103                           DAGInstruction(0, Results, Operands, ImpResults,
2104                                          ImpOperands)));
2105       continue;  // no pattern.
2106     }
2107     
2108     // Parse the instruction.
2109     TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
2110     // Inline pattern fragments into it.
2111     I->InlinePatternFragments();
2112     
2113     // Infer as many types as possible.  If we cannot infer all of them, we can
2114     // never do anything with this instruction pattern: report it to the user.
2115     if (!I->InferAllTypes())
2116       I->error("Could not infer all types in pattern!");
2117     
2118     // InstInputs - Keep track of all of the inputs of the instruction, along 
2119     // with the record they are declared as.
2120     std::map<std::string, TreePatternNode*> InstInputs;
2121     
2122     // InstResults - Keep track of all the virtual registers that are 'set'
2123     // in the instruction, including what reg class they are.
2124     std::map<std::string, TreePatternNode*> InstResults;
2125
2126     std::vector<Record*> InstImpInputs;
2127     std::vector<Record*> InstImpResults;
2128     
2129     // Verify that the top-level forms in the instruction are of void type, and
2130     // fill in the InstResults map.
2131     for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
2132       TreePatternNode *Pat = I->getTree(j);
2133       if (!Pat->hasTypeSet() || Pat->getType() != MVT::isVoid)
2134         I->error("Top-level forms in instruction pattern should have"
2135                  " void types");
2136
2137       // Find inputs and outputs, and verify the structure of the uses/defs.
2138       FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
2139                                   InstImpInputs, InstImpResults);
2140     }
2141
2142     // Now that we have inputs and outputs of the pattern, inspect the operands
2143     // list for the instruction.  This determines the order that operands are
2144     // added to the machine instruction the node corresponds to.
2145     unsigned NumResults = InstResults.size();
2146
2147     // Parse the operands list from the (ops) list, validating it.
2148     assert(I->getArgList().empty() && "Args list should still be empty here!");
2149     CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]);
2150
2151     // Check that all of the results occur first in the list.
2152     std::vector<Record*> Results;
2153     TreePatternNode *Res0Node = NULL;
2154     for (unsigned i = 0; i != NumResults; ++i) {
2155       if (i == CGI.OperandList.size())
2156         I->error("'" + InstResults.begin()->first +
2157                  "' set but does not appear in operand list!");
2158       const std::string &OpName = CGI.OperandList[i].Name;
2159       
2160       // Check that it exists in InstResults.
2161       TreePatternNode *RNode = InstResults[OpName];
2162       if (RNode == 0)
2163         I->error("Operand $" + OpName + " does not exist in operand list!");
2164         
2165       if (i == 0)
2166         Res0Node = RNode;
2167       Record *R = dynamic_cast<DefInit*>(RNode->getLeafValue())->getDef();
2168       if (R == 0)
2169         I->error("Operand $" + OpName + " should be a set destination: all "
2170                  "outputs must occur before inputs in operand list!");
2171       
2172       if (CGI.OperandList[i].Rec != R)
2173         I->error("Operand $" + OpName + " class mismatch!");
2174       
2175       // Remember the return type.
2176       Results.push_back(CGI.OperandList[i].Rec);
2177       
2178       // Okay, this one checks out.
2179       InstResults.erase(OpName);
2180     }
2181
2182     // Loop over the inputs next.  Make a copy of InstInputs so we can destroy
2183     // the copy while we're checking the inputs.
2184     std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
2185
2186     std::vector<TreePatternNode*> ResultNodeOperands;
2187     std::vector<Record*> Operands;
2188     for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
2189       CodeGenInstruction::OperandInfo &Op = CGI.OperandList[i];
2190       const std::string &OpName = Op.Name;
2191       if (OpName.empty())
2192         I->error("Operand #" + utostr(i) + " in operands list has no name!");
2193
2194       if (!InstInputsCheck.count(OpName)) {
2195         // If this is an predicate operand or optional def operand with an
2196         // DefaultOps set filled in, we can ignore this.  When we codegen it,
2197         // we will do so as always executed.
2198         if (Op.Rec->isSubClassOf("PredicateOperand") ||
2199             Op.Rec->isSubClassOf("OptionalDefOperand")) {
2200           // Does it have a non-empty DefaultOps field?  If so, ignore this
2201           // operand.
2202           if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
2203             continue;
2204         }
2205         I->error("Operand $" + OpName +
2206                  " does not appear in the instruction pattern");
2207       }
2208       TreePatternNode *InVal = InstInputsCheck[OpName];
2209       InstInputsCheck.erase(OpName);   // It occurred, remove from map.
2210       
2211       if (InVal->isLeaf() &&
2212           dynamic_cast<DefInit*>(InVal->getLeafValue())) {
2213         Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
2214         if (Op.Rec != InRec && !InRec->isSubClassOf("ComplexPattern"))
2215           I->error("Operand $" + OpName + "'s register class disagrees"
2216                    " between the operand and pattern");
2217       }
2218       Operands.push_back(Op.Rec);
2219       
2220       // Construct the result for the dest-pattern operand list.
2221       TreePatternNode *OpNode = InVal->clone();
2222       
2223       // No predicate is useful on the result.
2224       OpNode->clearPredicateFns();
2225       
2226       // Promote the xform function to be an explicit node if set.
2227       if (Record *Xform = OpNode->getTransformFn()) {
2228         OpNode->setTransformFn(0);
2229         std::vector<TreePatternNode*> Children;
2230         Children.push_back(OpNode);
2231         OpNode = new TreePatternNode(Xform, Children);
2232       }
2233       
2234       ResultNodeOperands.push_back(OpNode);
2235     }
2236     
2237     if (!InstInputsCheck.empty())
2238       I->error("Input operand $" + InstInputsCheck.begin()->first +
2239                " occurs in pattern but not in operands list!");
2240
2241     TreePatternNode *ResultPattern =
2242       new TreePatternNode(I->getRecord(), ResultNodeOperands);
2243     // Copy fully inferred output node type to instruction result pattern.
2244     if (NumResults > 0)
2245       ResultPattern->setType(Res0Node->getExtType());
2246
2247     // Create and insert the instruction.
2248     // FIXME: InstImpResults and InstImpInputs should not be part of
2249     // DAGInstruction.
2250     DAGInstruction TheInst(I, Results, Operands, InstImpResults, InstImpInputs);
2251     Instructions.insert(std::make_pair(I->getRecord(), TheInst));
2252
2253     // Use a temporary tree pattern to infer all types and make sure that the
2254     // constructed result is correct.  This depends on the instruction already
2255     // being inserted into the Instructions map.
2256     TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
2257     Temp.InferAllTypes(&I->getNamedNodesMap());
2258
2259     DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
2260     TheInsertedInst.setResultPattern(Temp.getOnlyTree());
2261     
2262     DEBUG(I->dump());
2263   }
2264    
2265   // If we can, convert the instructions to be patterns that are matched!
2266   for (std::map<Record*, DAGInstruction, RecordPtrCmp>::iterator II =
2267         Instructions.begin(),
2268        E = Instructions.end(); II != E; ++II) {
2269     DAGInstruction &TheInst = II->second;
2270     const TreePattern *I = TheInst.getPattern();
2271     if (I == 0) continue;  // No pattern.
2272
2273     // FIXME: Assume only the first tree is the pattern. The others are clobber
2274     // nodes.
2275     TreePatternNode *Pattern = I->getTree(0);
2276     TreePatternNode *SrcPattern;
2277     if (Pattern->getOperator()->getName() == "set") {
2278       SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
2279     } else{
2280       // Not a set (store or something?)
2281       SrcPattern = Pattern;
2282     }
2283     
2284     Record *Instr = II->first;
2285     AddPatternToMatch(I,
2286                       PatternToMatch(Instr->getValueAsListInit("Predicates"),
2287                                      SrcPattern,
2288                                      TheInst.getResultPattern(),
2289                                      TheInst.getImpResults(),
2290                                      Instr->getValueAsInt("AddedComplexity"),
2291                                      Instr->getID()));
2292   }
2293 }
2294
2295
2296 typedef std::pair<const TreePatternNode*, unsigned> NameRecord;
2297
2298 static void FindNames(const TreePatternNode *P, 
2299                       std::map<std::string, NameRecord> &Names,
2300                       const TreePattern *PatternTop) {
2301   if (!P->getName().empty()) {
2302     NameRecord &Rec = Names[P->getName()];
2303     // If this is the first instance of the name, remember the node.
2304     if (Rec.second++ == 0)
2305       Rec.first = P;
2306     else if (Rec.first->getType() != P->getType())
2307       PatternTop->error("repetition of value: $" + P->getName() +
2308                         " where different uses have different types!");
2309   }
2310   
2311   if (!P->isLeaf()) {
2312     for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
2313       FindNames(P->getChild(i), Names, PatternTop);
2314   }
2315 }
2316
2317 void CodeGenDAGPatterns::AddPatternToMatch(const TreePattern *Pattern,
2318                                            const PatternToMatch &PTM) {
2319   // Do some sanity checking on the pattern we're about to match.
2320   std::string Reason;
2321   if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this))
2322     Pattern->error("Pattern can never match: " + Reason);
2323   
2324   // If the source pattern's root is a complex pattern, that complex pattern
2325   // must specify the nodes it can potentially match.
2326   if (const ComplexPattern *CP =
2327         PTM.getSrcPattern()->getComplexPatternInfo(*this))
2328     if (CP->getRootNodes().empty())
2329       Pattern->error("ComplexPattern at root must specify list of opcodes it"
2330                      " could match");
2331   
2332   
2333   // Find all of the named values in the input and output, ensure they have the
2334   // same type.
2335   std::map<std::string, NameRecord> SrcNames, DstNames;
2336   FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
2337   FindNames(PTM.getDstPattern(), DstNames, Pattern);
2338
2339   // Scan all of the named values in the destination pattern, rejecting them if
2340   // they don't exist in the input pattern.
2341   for (std::map<std::string, NameRecord>::iterator
2342        I = DstNames.begin(), E = DstNames.end(); I != E; ++I) {
2343     if (SrcNames[I->first].first == 0)
2344       Pattern->error("Pattern has input without matching name in output: $" +
2345                      I->first);
2346   }
2347   
2348   // Scan all of the named values in the source pattern, rejecting them if the
2349   // name isn't used in the dest, and isn't used to tie two values together.
2350   for (std::map<std::string, NameRecord>::iterator
2351        I = SrcNames.begin(), E = SrcNames.end(); I != E; ++I)
2352     if (DstNames[I->first].first == 0 && SrcNames[I->first].second == 1)
2353       Pattern->error("Pattern has dead named input: $" + I->first);
2354   
2355   PatternsToMatch.push_back(PTM);
2356 }
2357
2358
2359
2360 void CodeGenDAGPatterns::InferInstructionFlags() {
2361   const std::vector<const CodeGenInstruction*> &Instructions =
2362     Target.getInstructionsByEnumValue();
2363   for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
2364     CodeGenInstruction &InstInfo =
2365       const_cast<CodeGenInstruction &>(*Instructions[i]);
2366     // Determine properties of the instruction from its pattern.
2367     bool MayStore, MayLoad, HasSideEffects;
2368     InferFromPattern(InstInfo, MayStore, MayLoad, HasSideEffects, *this);
2369     InstInfo.mayStore = MayStore;
2370     InstInfo.mayLoad = MayLoad;
2371     InstInfo.hasSideEffects = HasSideEffects;
2372   }
2373 }
2374
2375 /// Given a pattern result with an unresolved type, see if we can find one
2376 /// instruction with an unresolved result type.  Force this result type to an
2377 /// arbitrary element if it's possible types to converge results.
2378 static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
2379   if (N->isLeaf())
2380     return false;
2381   
2382   // Analyze children.
2383   for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2384     if (ForceArbitraryInstResultType(N->getChild(i), TP))
2385       return true;
2386
2387   if (!N->getOperator()->isSubClassOf("Instruction"))
2388     return false;
2389
2390   // If this type is already concrete or completely unknown we can't do
2391   // anything.
2392   if (N->getExtType().isCompletelyUnknown() || N->getExtType().isConcrete())
2393     return false;
2394   
2395   // Otherwise, force its type to the first possibility (an arbitrary choice).
2396   return N->getExtType().MergeInTypeInfo(N->getExtType().getTypeList()[0], TP);
2397 }
2398
2399 void CodeGenDAGPatterns::ParsePatterns() {
2400   std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
2401
2402   for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
2403     DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
2404     DefInit *OpDef = dynamic_cast<DefInit*>(Tree->getOperator());
2405     Record *Operator = OpDef->getDef();
2406     TreePattern *Pattern;
2407     if (Operator->getName() != "parallel")
2408       Pattern = new TreePattern(Patterns[i], Tree, true, *this);
2409     else {
2410       std::vector<Init*> Values;
2411       RecTy *ListTy = 0;
2412       for (unsigned j = 0, ee = Tree->getNumArgs(); j != ee; ++j) {
2413         Values.push_back(Tree->getArg(j));
2414         TypedInit *TArg = dynamic_cast<TypedInit*>(Tree->getArg(j));
2415         if (TArg == 0) {
2416           errs() << "In dag: " << Tree->getAsString();
2417           errs() << " --  Untyped argument in pattern\n";
2418           assert(0 && "Untyped argument in pattern");
2419         }
2420         if (ListTy != 0) {
2421           ListTy = resolveTypes(ListTy, TArg->getType());
2422           if (ListTy == 0) {
2423             errs() << "In dag: " << Tree->getAsString();
2424             errs() << " --  Incompatible types in pattern arguments\n";
2425             assert(0 && "Incompatible types in pattern arguments");
2426           }
2427         }
2428         else {
2429           ListTy = TArg->getType();
2430         }
2431       }
2432       ListInit *LI = new ListInit(Values, new ListRecTy(ListTy));
2433       Pattern = new TreePattern(Patterns[i], LI, true, *this);
2434     }
2435
2436     // Inline pattern fragments into it.
2437     Pattern->InlinePatternFragments();
2438     
2439     ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
2440     if (LI->getSize() == 0) continue;  // no pattern.
2441     
2442     // Parse the instruction.
2443     TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
2444     
2445     // Inline pattern fragments into it.
2446     Result->InlinePatternFragments();
2447
2448     if (Result->getNumTrees() != 1)
2449       Result->error("Cannot handle instructions producing instructions "
2450                     "with temporaries yet!");
2451     
2452     bool IterateInference;
2453     bool InferredAllPatternTypes, InferredAllResultTypes;
2454     do {
2455       // Infer as many types as possible.  If we cannot infer all of them, we
2456       // can never do anything with this pattern: report it to the user.
2457       InferredAllPatternTypes =
2458         Pattern->InferAllTypes(&Pattern->getNamedNodesMap());
2459       
2460       // Infer as many types as possible.  If we cannot infer all of them, we
2461       // can never do anything with this pattern: report it to the user.
2462       InferredAllResultTypes =
2463         Result->InferAllTypes(&Pattern->getNamedNodesMap());
2464
2465       IterateInference = false;
2466       
2467       // Apply the type of the result to the source pattern.  This helps us
2468       // resolve cases where the input type is known to be a pointer type (which
2469       // is considered resolved), but the result knows it needs to be 32- or
2470       // 64-bits.  Infer the other way for good measure.
2471       if (!Result->getTree(0)->getExtType().isVoid() &&
2472           !Pattern->getTree(0)->getExtType().isVoid()) {
2473         IterateInference = Pattern->getTree(0)->
2474           UpdateNodeType(Result->getTree(0)->getExtType(), *Result);
2475         IterateInference |= Result->getTree(0)->
2476           UpdateNodeType(Pattern->getTree(0)->getExtType(), *Result);
2477       }
2478       
2479       // If our iteration has converged and the input pattern's types are fully
2480       // resolved but the result pattern is not fully resolved, we may have a
2481       // situation where we have two instructions in the result pattern and
2482       // the instructions require a common register class, but don't care about
2483       // what actual MVT is used.  This is actually a bug in our modelling:
2484       // output patterns should have register classes, not MVTs.
2485       //
2486       // In any case, to handle this, we just go through and disambiguate some
2487       // arbitrary types to the result pattern's nodes.
2488       if (!IterateInference && InferredAllPatternTypes &&
2489           !InferredAllResultTypes)
2490         IterateInference = ForceArbitraryInstResultType(Result->getTree(0),
2491                                                         *Result);
2492     } while (IterateInference);
2493     
2494     // Verify that we inferred enough types that we can do something with the
2495     // pattern and result.  If these fire the user has to add type casts.
2496     if (!InferredAllPatternTypes)
2497       Pattern->error("Could not infer all types in pattern!");
2498     if (!InferredAllResultTypes) {
2499       Pattern->dump();
2500       Result->error("Could not infer all types in pattern result!");
2501     }
2502     
2503     // Validate that the input pattern is correct.
2504     std::map<std::string, TreePatternNode*> InstInputs;
2505     std::map<std::string, TreePatternNode*> InstResults;
2506     std::vector<Record*> InstImpInputs;
2507     std::vector<Record*> InstImpResults;
2508     for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
2509       FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
2510                                   InstInputs, InstResults,
2511                                   InstImpInputs, InstImpResults);
2512
2513     // Promote the xform function to be an explicit node if set.
2514     TreePatternNode *DstPattern = Result->getOnlyTree();
2515     std::vector<TreePatternNode*> ResultNodeOperands;
2516     for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
2517       TreePatternNode *OpNode = DstPattern->getChild(ii);
2518       if (Record *Xform = OpNode->getTransformFn()) {
2519         OpNode->setTransformFn(0);
2520         std::vector<TreePatternNode*> Children;
2521         Children.push_back(OpNode);
2522         OpNode = new TreePatternNode(Xform, Children);
2523       }
2524       ResultNodeOperands.push_back(OpNode);
2525     }
2526     DstPattern = Result->getOnlyTree();
2527     if (!DstPattern->isLeaf())
2528       DstPattern = new TreePatternNode(DstPattern->getOperator(),
2529                                        ResultNodeOperands);
2530     DstPattern->setType(Result->getOnlyTree()->getExtType());
2531     TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
2532     Temp.InferAllTypes();
2533
2534     
2535     AddPatternToMatch(Pattern,
2536                  PatternToMatch(Patterns[i]->getValueAsListInit("Predicates"),
2537                                 Pattern->getTree(0),
2538                                 Temp.getOnlyTree(), InstImpResults,
2539                                 Patterns[i]->getValueAsInt("AddedComplexity"),
2540                                 Patterns[i]->getID()));
2541   }
2542 }
2543
2544 /// CombineChildVariants - Given a bunch of permutations of each child of the
2545 /// 'operator' node, put them together in all possible ways.
2546 static void CombineChildVariants(TreePatternNode *Orig, 
2547                const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
2548                                  std::vector<TreePatternNode*> &OutVariants,
2549                                  CodeGenDAGPatterns &CDP,
2550                                  const MultipleUseVarSet &DepVars) {
2551   // Make sure that each operand has at least one variant to choose from.
2552   for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2553     if (ChildVariants[i].empty())
2554       return;
2555         
2556   // The end result is an all-pairs construction of the resultant pattern.
2557   std::vector<unsigned> Idxs;
2558   Idxs.resize(ChildVariants.size());
2559   bool NotDone;
2560   do {
2561 #ifndef NDEBUG
2562     DEBUG(if (!Idxs.empty()) {
2563             errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
2564               for (unsigned i = 0; i < Idxs.size(); ++i) {
2565                 errs() << Idxs[i] << " ";
2566             }
2567             errs() << "]\n";
2568           });
2569 #endif
2570     // Create the variant and add it to the output list.
2571     std::vector<TreePatternNode*> NewChildren;
2572     for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2573       NewChildren.push_back(ChildVariants[i][Idxs[i]]);
2574     TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
2575     
2576     // Copy over properties.
2577     R->setName(Orig->getName());
2578     R->setPredicateFns(Orig->getPredicateFns());
2579     R->setTransformFn(Orig->getTransformFn());
2580     R->setType(Orig->getExtType());
2581     
2582     // If this pattern cannot match, do not include it as a variant.
2583     std::string ErrString;
2584     if (!R->canPatternMatch(ErrString, CDP)) {
2585       delete R;
2586     } else {
2587       bool AlreadyExists = false;
2588       
2589       // Scan to see if this pattern has already been emitted.  We can get
2590       // duplication due to things like commuting:
2591       //   (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
2592       // which are the same pattern.  Ignore the dups.
2593       for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
2594         if (R->isIsomorphicTo(OutVariants[i], DepVars)) {
2595           AlreadyExists = true;
2596           break;
2597         }
2598       
2599       if (AlreadyExists)
2600         delete R;
2601       else
2602         OutVariants.push_back(R);
2603     }
2604     
2605     // Increment indices to the next permutation by incrementing the
2606     // indicies from last index backward, e.g., generate the sequence
2607     // [0, 0], [0, 1], [1, 0], [1, 1].
2608     int IdxsIdx;
2609     for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
2610       if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
2611         Idxs[IdxsIdx] = 0;
2612       else
2613         break;
2614     }
2615     NotDone = (IdxsIdx >= 0);
2616   } while (NotDone);
2617 }
2618
2619 /// CombineChildVariants - A helper function for binary operators.
2620 ///
2621 static void CombineChildVariants(TreePatternNode *Orig, 
2622                                  const std::vector<TreePatternNode*> &LHS,
2623                                  const std::vector<TreePatternNode*> &RHS,
2624                                  std::vector<TreePatternNode*> &OutVariants,
2625                                  CodeGenDAGPatterns &CDP,
2626                                  const MultipleUseVarSet &DepVars) {
2627   std::vector<std::vector<TreePatternNode*> > ChildVariants;
2628   ChildVariants.push_back(LHS);
2629   ChildVariants.push_back(RHS);
2630   CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
2631 }  
2632
2633
2634 static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
2635                                      std::vector<TreePatternNode *> &Children) {
2636   assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
2637   Record *Operator = N->getOperator();
2638   
2639   // Only permit raw nodes.
2640   if (!N->getName().empty() || !N->getPredicateFns().empty() ||
2641       N->getTransformFn()) {
2642     Children.push_back(N);
2643     return;
2644   }
2645
2646   if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
2647     Children.push_back(N->getChild(0));
2648   else
2649     GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
2650
2651   if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
2652     Children.push_back(N->getChild(1));
2653   else
2654     GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
2655 }
2656
2657 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
2658 /// the (potentially recursive) pattern by using algebraic laws.
2659 ///
2660 static void GenerateVariantsOf(TreePatternNode *N,
2661                                std::vector<TreePatternNode*> &OutVariants,
2662                                CodeGenDAGPatterns &CDP,
2663                                const MultipleUseVarSet &DepVars) {
2664   // We cannot permute leaves.
2665   if (N->isLeaf()) {
2666     OutVariants.push_back(N);
2667     return;
2668   }
2669
2670   // Look up interesting info about the node.
2671   const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
2672
2673   // If this node is associative, re-associate.
2674   if (NodeInfo.hasProperty(SDNPAssociative)) {
2675     // Re-associate by pulling together all of the linked operators 
2676     std::vector<TreePatternNode*> MaximalChildren;
2677     GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
2678
2679     // Only handle child sizes of 3.  Otherwise we'll end up trying too many
2680     // permutations.
2681     if (MaximalChildren.size() == 3) {
2682       // Find the variants of all of our maximal children.
2683       std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
2684       GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
2685       GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
2686       GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
2687       
2688       // There are only two ways we can permute the tree:
2689       //   (A op B) op C    and    A op (B op C)
2690       // Within these forms, we can also permute A/B/C.
2691       
2692       // Generate legal pair permutations of A/B/C.
2693       std::vector<TreePatternNode*> ABVariants;
2694       std::vector<TreePatternNode*> BAVariants;
2695       std::vector<TreePatternNode*> ACVariants;
2696       std::vector<TreePatternNode*> CAVariants;
2697       std::vector<TreePatternNode*> BCVariants;
2698       std::vector<TreePatternNode*> CBVariants;
2699       CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
2700       CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
2701       CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
2702       CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
2703       CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
2704       CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
2705
2706       // Combine those into the result: (x op x) op x
2707       CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
2708       CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
2709       CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
2710       CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
2711       CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
2712       CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
2713
2714       // Combine those into the result: x op (x op x)
2715       CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
2716       CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
2717       CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
2718       CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
2719       CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
2720       CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
2721       return;
2722     }
2723   }
2724   
2725   // Compute permutations of all children.
2726   std::vector<std::vector<TreePatternNode*> > ChildVariants;
2727   ChildVariants.resize(N->getNumChildren());
2728   for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2729     GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
2730
2731   // Build all permutations based on how the children were formed.
2732   CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
2733
2734   // If this node is commutative, consider the commuted order.
2735   bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
2736   if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
2737     assert((N->getNumChildren()==2 || isCommIntrinsic) &&
2738            "Commutative but doesn't have 2 children!");
2739     // Don't count children which are actually register references.
2740     unsigned NC = 0;
2741     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2742       TreePatternNode *Child = N->getChild(i);
2743       if (Child->isLeaf())
2744         if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2745           Record *RR = DI->getDef();
2746           if (RR->isSubClassOf("Register"))
2747             continue;
2748         }
2749       NC++;
2750     }
2751     // Consider the commuted order.
2752     if (isCommIntrinsic) {
2753       // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
2754       // operands are the commutative operands, and there might be more operands
2755       // after those.
2756       assert(NC >= 3 &&
2757              "Commutative intrinsic should have at least 3 childrean!");
2758       std::vector<std::vector<TreePatternNode*> > Variants;
2759       Variants.push_back(ChildVariants[0]); // Intrinsic id.
2760       Variants.push_back(ChildVariants[2]);
2761       Variants.push_back(ChildVariants[1]);
2762       for (unsigned i = 3; i != NC; ++i)
2763         Variants.push_back(ChildVariants[i]);
2764       CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
2765     } else if (NC == 2)
2766       CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
2767                            OutVariants, CDP, DepVars);
2768   }
2769 }
2770
2771
2772 // GenerateVariants - Generate variants.  For example, commutative patterns can
2773 // match multiple ways.  Add them to PatternsToMatch as well.
2774 void CodeGenDAGPatterns::GenerateVariants() {
2775   DEBUG(errs() << "Generating instruction variants.\n");
2776   
2777   // Loop over all of the patterns we've collected, checking to see if we can
2778   // generate variants of the instruction, through the exploitation of
2779   // identities.  This permits the target to provide aggressive matching without
2780   // the .td file having to contain tons of variants of instructions.
2781   //
2782   // Note that this loop adds new patterns to the PatternsToMatch list, but we
2783   // intentionally do not reconsider these.  Any variants of added patterns have
2784   // already been added.
2785   //
2786   for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
2787     MultipleUseVarSet             DepVars;
2788     std::vector<TreePatternNode*> Variants;
2789     FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
2790     DEBUG(errs() << "Dependent/multiply used variables: ");
2791     DEBUG(DumpDepVars(DepVars));
2792     DEBUG(errs() << "\n");
2793     GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this, DepVars);
2794
2795     assert(!Variants.empty() && "Must create at least original variant!");
2796     Variants.erase(Variants.begin());  // Remove the original pattern.
2797
2798     if (Variants.empty())  // No variants for this pattern.
2799       continue;
2800
2801     DEBUG(errs() << "FOUND VARIANTS OF: ";
2802           PatternsToMatch[i].getSrcPattern()->dump();
2803           errs() << "\n");
2804
2805     for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
2806       TreePatternNode *Variant = Variants[v];
2807
2808       DEBUG(errs() << "  VAR#" << v <<  ": ";
2809             Variant->dump();
2810             errs() << "\n");
2811       
2812       // Scan to see if an instruction or explicit pattern already matches this.
2813       bool AlreadyExists = false;
2814       for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
2815         // Skip if the top level predicates do not match.
2816         if (PatternsToMatch[i].getPredicates() !=
2817             PatternsToMatch[p].getPredicates())
2818           continue;
2819         // Check to see if this variant already exists.
2820         if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(), DepVars)) {
2821           DEBUG(errs() << "  *** ALREADY EXISTS, ignoring variant.\n");
2822           AlreadyExists = true;
2823           break;
2824         }
2825       }
2826       // If we already have it, ignore the variant.
2827       if (AlreadyExists) continue;
2828
2829       // Otherwise, add it to the list of patterns we have.
2830       PatternsToMatch.
2831         push_back(PatternToMatch(PatternsToMatch[i].getPredicates(),
2832                                  Variant, PatternsToMatch[i].getDstPattern(),
2833                                  PatternsToMatch[i].getDstRegs(),
2834                                  PatternsToMatch[i].getAddedComplexity(),
2835                                  Record::getNewUID()));
2836     }
2837
2838     DEBUG(errs() << "\n");
2839   }
2840 }
2841