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