add a new SDNPVariadic SDNP node flag, and use it in
[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 public:
1961   InstAnalyzer(const CodeGenDAGPatterns &cdp,
1962                bool &maystore, bool &mayload, bool &hse)
1963     : CDP(cdp), mayStore(maystore), mayLoad(mayload), HasSideEffects(hse){
1964   }
1965
1966   /// Analyze - Analyze the specified instruction, returning true if the
1967   /// instruction had a pattern.
1968   bool Analyze(Record *InstRecord) {
1969     const TreePattern *Pattern = CDP.getInstruction(InstRecord).getPattern();
1970     if (Pattern == 0) {
1971       HasSideEffects = 1;
1972       return false;  // No pattern.
1973     }
1974
1975     // FIXME: Assume only the first tree is the pattern. The others are clobber
1976     // nodes.
1977     AnalyzeNode(Pattern->getTree(0));
1978     return true;
1979   }
1980
1981 private:
1982   void AnalyzeNode(const TreePatternNode *N) {
1983     if (N->isLeaf()) {
1984       if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
1985         Record *LeafRec = DI->getDef();
1986         // Handle ComplexPattern leaves.
1987         if (LeafRec->isSubClassOf("ComplexPattern")) {
1988           const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
1989           if (CP.hasProperty(SDNPMayStore)) mayStore = true;
1990           if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
1991           if (CP.hasProperty(SDNPSideEffect)) HasSideEffects = true;
1992         }
1993       }
1994       return;
1995     }
1996
1997     // Analyze children.
1998     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1999       AnalyzeNode(N->getChild(i));
2000
2001     // Ignore set nodes, which are not SDNodes.
2002     if (N->getOperator()->getName() == "set")
2003       return;
2004
2005     // Get information about the SDNode for the operator.
2006     const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N->getOperator());
2007
2008     // Notice properties of the node.
2009     if (OpInfo.hasProperty(SDNPMayStore)) mayStore = true;
2010     if (OpInfo.hasProperty(SDNPMayLoad)) mayLoad = true;
2011     if (OpInfo.hasProperty(SDNPSideEffect)) HasSideEffects = true;
2012
2013     if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
2014       // If this is an intrinsic, analyze it.
2015       if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
2016         mayLoad = true;// These may load memory.
2017
2018       if (IntInfo->ModRef >= CodeGenIntrinsic::WriteArgMem)
2019         mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
2020
2021       if (IntInfo->ModRef >= CodeGenIntrinsic::WriteMem)
2022         // WriteMem intrinsics can have other strange effects.
2023         HasSideEffects = true;
2024     }
2025   }
2026
2027 };
2028
2029 static void InferFromPattern(const CodeGenInstruction &Inst,
2030                              bool &MayStore, bool &MayLoad,
2031                              bool &HasSideEffects,
2032                              const CodeGenDAGPatterns &CDP) {
2033   MayStore = MayLoad = HasSideEffects = false;
2034
2035   bool HadPattern =
2036     InstAnalyzer(CDP, MayStore, MayLoad, HasSideEffects).Analyze(Inst.TheDef);
2037
2038   // InstAnalyzer only correctly analyzes mayStore/mayLoad so far.
2039   if (Inst.mayStore) {  // If the .td file explicitly sets mayStore, use it.
2040     // If we decided that this is a store from the pattern, then the .td file
2041     // entry is redundant.
2042     if (MayStore)
2043       fprintf(stderr,
2044               "Warning: mayStore flag explicitly set on instruction '%s'"
2045               " but flag already inferred from pattern.\n",
2046               Inst.TheDef->getName().c_str());
2047     MayStore = true;
2048   }
2049
2050   if (Inst.mayLoad) {  // If the .td file explicitly sets mayLoad, use it.
2051     // If we decided that this is a load from the pattern, then the .td file
2052     // entry is redundant.
2053     if (MayLoad)
2054       fprintf(stderr,
2055               "Warning: mayLoad flag explicitly set on instruction '%s'"
2056               " but flag already inferred from pattern.\n",
2057               Inst.TheDef->getName().c_str());
2058     MayLoad = true;
2059   }
2060
2061   if (Inst.neverHasSideEffects) {
2062     if (HadPattern)
2063       fprintf(stderr, "Warning: neverHasSideEffects set on instruction '%s' "
2064               "which already has a pattern\n", Inst.TheDef->getName().c_str());
2065     HasSideEffects = false;
2066   }
2067
2068   if (Inst.hasSideEffects) {
2069     if (HasSideEffects)
2070       fprintf(stderr, "Warning: hasSideEffects set on instruction '%s' "
2071               "which already inferred this.\n", Inst.TheDef->getName().c_str());
2072     HasSideEffects = true;
2073   }
2074 }
2075
2076 /// ParseInstructions - Parse all of the instructions, inlining and resolving
2077 /// any fragments involved.  This populates the Instructions list with fully
2078 /// resolved instructions.
2079 void CodeGenDAGPatterns::ParseInstructions() {
2080   std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
2081   
2082   for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
2083     ListInit *LI = 0;
2084     
2085     if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
2086       LI = Instrs[i]->getValueAsListInit("Pattern");
2087     
2088     // If there is no pattern, only collect minimal information about the
2089     // instruction for its operand list.  We have to assume that there is one
2090     // result, as we have no detailed info.
2091     if (!LI || LI->getSize() == 0) {
2092       std::vector<Record*> Results;
2093       std::vector<Record*> Operands;
2094       
2095       CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
2096
2097       if (InstInfo.OperandList.size() != 0) {
2098         if (InstInfo.NumDefs == 0) {
2099           // These produce no results
2100           for (unsigned j = 0, e = InstInfo.OperandList.size(); j < e; ++j)
2101             Operands.push_back(InstInfo.OperandList[j].Rec);
2102         } else {
2103           // Assume the first operand is the result.
2104           Results.push_back(InstInfo.OperandList[0].Rec);
2105       
2106           // The rest are inputs.
2107           for (unsigned j = 1, e = InstInfo.OperandList.size(); j < e; ++j)
2108             Operands.push_back(InstInfo.OperandList[j].Rec);
2109         }
2110       }
2111       
2112       // Create and insert the instruction.
2113       std::vector<Record*> ImpResults;
2114       std::vector<Record*> ImpOperands;
2115       Instructions.insert(std::make_pair(Instrs[i], 
2116                           DAGInstruction(0, Results, Operands, ImpResults,
2117                                          ImpOperands)));
2118       continue;  // no pattern.
2119     }
2120     
2121     // Parse the instruction.
2122     TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
2123     // Inline pattern fragments into it.
2124     I->InlinePatternFragments();
2125     
2126     // Infer as many types as possible.  If we cannot infer all of them, we can
2127     // never do anything with this instruction pattern: report it to the user.
2128     if (!I->InferAllTypes())
2129       I->error("Could not infer all types in pattern!");
2130     
2131     // InstInputs - Keep track of all of the inputs of the instruction, along 
2132     // with the record they are declared as.
2133     std::map<std::string, TreePatternNode*> InstInputs;
2134     
2135     // InstResults - Keep track of all the virtual registers that are 'set'
2136     // in the instruction, including what reg class they are.
2137     std::map<std::string, TreePatternNode*> InstResults;
2138
2139     std::vector<Record*> InstImpInputs;
2140     std::vector<Record*> InstImpResults;
2141     
2142     // Verify that the top-level forms in the instruction are of void type, and
2143     // fill in the InstResults map.
2144     for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
2145       TreePatternNode *Pat = I->getTree(j);
2146       if (!Pat->hasTypeSet() || Pat->getType() != MVT::isVoid)
2147         I->error("Top-level forms in instruction pattern should have"
2148                  " void types");
2149
2150       // Find inputs and outputs, and verify the structure of the uses/defs.
2151       FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
2152                                   InstImpInputs, InstImpResults);
2153     }
2154
2155     // Now that we have inputs and outputs of the pattern, inspect the operands
2156     // list for the instruction.  This determines the order that operands are
2157     // added to the machine instruction the node corresponds to.
2158     unsigned NumResults = InstResults.size();
2159
2160     // Parse the operands list from the (ops) list, validating it.
2161     assert(I->getArgList().empty() && "Args list should still be empty here!");
2162     CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]);
2163
2164     // Check that all of the results occur first in the list.
2165     std::vector<Record*> Results;
2166     TreePatternNode *Res0Node = NULL;
2167     for (unsigned i = 0; i != NumResults; ++i) {
2168       if (i == CGI.OperandList.size())
2169         I->error("'" + InstResults.begin()->first +
2170                  "' set but does not appear in operand list!");
2171       const std::string &OpName = CGI.OperandList[i].Name;
2172       
2173       // Check that it exists in InstResults.
2174       TreePatternNode *RNode = InstResults[OpName];
2175       if (RNode == 0)
2176         I->error("Operand $" + OpName + " does not exist in operand list!");
2177         
2178       if (i == 0)
2179         Res0Node = RNode;
2180       Record *R = dynamic_cast<DefInit*>(RNode->getLeafValue())->getDef();
2181       if (R == 0)
2182         I->error("Operand $" + OpName + " should be a set destination: all "
2183                  "outputs must occur before inputs in operand list!");
2184       
2185       if (CGI.OperandList[i].Rec != R)
2186         I->error("Operand $" + OpName + " class mismatch!");
2187       
2188       // Remember the return type.
2189       Results.push_back(CGI.OperandList[i].Rec);
2190       
2191       // Okay, this one checks out.
2192       InstResults.erase(OpName);
2193     }
2194
2195     // Loop over the inputs next.  Make a copy of InstInputs so we can destroy
2196     // the copy while we're checking the inputs.
2197     std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
2198
2199     std::vector<TreePatternNode*> ResultNodeOperands;
2200     std::vector<Record*> Operands;
2201     for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
2202       CodeGenInstruction::OperandInfo &Op = CGI.OperandList[i];
2203       const std::string &OpName = Op.Name;
2204       if (OpName.empty())
2205         I->error("Operand #" + utostr(i) + " in operands list has no name!");
2206
2207       if (!InstInputsCheck.count(OpName)) {
2208         // If this is an predicate operand or optional def operand with an
2209         // DefaultOps set filled in, we can ignore this.  When we codegen it,
2210         // we will do so as always executed.
2211         if (Op.Rec->isSubClassOf("PredicateOperand") ||
2212             Op.Rec->isSubClassOf("OptionalDefOperand")) {
2213           // Does it have a non-empty DefaultOps field?  If so, ignore this
2214           // operand.
2215           if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
2216             continue;
2217         }
2218         I->error("Operand $" + OpName +
2219                  " does not appear in the instruction pattern");
2220       }
2221       TreePatternNode *InVal = InstInputsCheck[OpName];
2222       InstInputsCheck.erase(OpName);   // It occurred, remove from map.
2223       
2224       if (InVal->isLeaf() &&
2225           dynamic_cast<DefInit*>(InVal->getLeafValue())) {
2226         Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
2227         if (Op.Rec != InRec && !InRec->isSubClassOf("ComplexPattern"))
2228           I->error("Operand $" + OpName + "'s register class disagrees"
2229                    " between the operand and pattern");
2230       }
2231       Operands.push_back(Op.Rec);
2232       
2233       // Construct the result for the dest-pattern operand list.
2234       TreePatternNode *OpNode = InVal->clone();
2235       
2236       // No predicate is useful on the result.
2237       OpNode->clearPredicateFns();
2238       
2239       // Promote the xform function to be an explicit node if set.
2240       if (Record *Xform = OpNode->getTransformFn()) {
2241         OpNode->setTransformFn(0);
2242         std::vector<TreePatternNode*> Children;
2243         Children.push_back(OpNode);
2244         OpNode = new TreePatternNode(Xform, Children);
2245       }
2246       
2247       ResultNodeOperands.push_back(OpNode);
2248     }
2249     
2250     if (!InstInputsCheck.empty())
2251       I->error("Input operand $" + InstInputsCheck.begin()->first +
2252                " occurs in pattern but not in operands list!");
2253
2254     TreePatternNode *ResultPattern =
2255       new TreePatternNode(I->getRecord(), ResultNodeOperands);
2256     // Copy fully inferred output node type to instruction result pattern.
2257     if (NumResults > 0)
2258       ResultPattern->setType(Res0Node->getExtType());
2259
2260     // Create and insert the instruction.
2261     // FIXME: InstImpResults and InstImpInputs should not be part of
2262     // DAGInstruction.
2263     DAGInstruction TheInst(I, Results, Operands, InstImpResults, InstImpInputs);
2264     Instructions.insert(std::make_pair(I->getRecord(), TheInst));
2265
2266     // Use a temporary tree pattern to infer all types and make sure that the
2267     // constructed result is correct.  This depends on the instruction already
2268     // being inserted into the Instructions map.
2269     TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
2270     Temp.InferAllTypes(&I->getNamedNodesMap());
2271
2272     DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
2273     TheInsertedInst.setResultPattern(Temp.getOnlyTree());
2274     
2275     DEBUG(I->dump());
2276   }
2277    
2278   // If we can, convert the instructions to be patterns that are matched!
2279   for (std::map<Record*, DAGInstruction, RecordPtrCmp>::iterator II =
2280         Instructions.begin(),
2281        E = Instructions.end(); II != E; ++II) {
2282     DAGInstruction &TheInst = II->second;
2283     const TreePattern *I = TheInst.getPattern();
2284     if (I == 0) continue;  // No pattern.
2285
2286     // FIXME: Assume only the first tree is the pattern. The others are clobber
2287     // nodes.
2288     TreePatternNode *Pattern = I->getTree(0);
2289     TreePatternNode *SrcPattern;
2290     if (Pattern->getOperator()->getName() == "set") {
2291       SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
2292     } else{
2293       // Not a set (store or something?)
2294       SrcPattern = Pattern;
2295     }
2296     
2297     Record *Instr = II->first;
2298     AddPatternToMatch(I,
2299                       PatternToMatch(Instr->getValueAsListInit("Predicates"),
2300                                      SrcPattern,
2301                                      TheInst.getResultPattern(),
2302                                      TheInst.getImpResults(),
2303                                      Instr->getValueAsInt("AddedComplexity"),
2304                                      Instr->getID()));
2305   }
2306 }
2307
2308
2309 typedef std::pair<const TreePatternNode*, unsigned> NameRecord;
2310
2311 static void FindNames(const TreePatternNode *P, 
2312                       std::map<std::string, NameRecord> &Names,
2313                       const TreePattern *PatternTop) {
2314   if (!P->getName().empty()) {
2315     NameRecord &Rec = Names[P->getName()];
2316     // If this is the first instance of the name, remember the node.
2317     if (Rec.second++ == 0)
2318       Rec.first = P;
2319     else if (Rec.first->getType() != P->getType())
2320       PatternTop->error("repetition of value: $" + P->getName() +
2321                         " where different uses have different types!");
2322   }
2323   
2324   if (!P->isLeaf()) {
2325     for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
2326       FindNames(P->getChild(i), Names, PatternTop);
2327   }
2328 }
2329
2330 void CodeGenDAGPatterns::AddPatternToMatch(const TreePattern *Pattern,
2331                                            const PatternToMatch &PTM) {
2332   // Do some sanity checking on the pattern we're about to match.
2333   std::string Reason;
2334   if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this))
2335     Pattern->error("Pattern can never match: " + Reason);
2336   
2337   // If the source pattern's root is a complex pattern, that complex pattern
2338   // must specify the nodes it can potentially match.
2339   if (const ComplexPattern *CP =
2340         PTM.getSrcPattern()->getComplexPatternInfo(*this))
2341     if (CP->getRootNodes().empty())
2342       Pattern->error("ComplexPattern at root must specify list of opcodes it"
2343                      " could match");
2344   
2345   
2346   // Find all of the named values in the input and output, ensure they have the
2347   // same type.
2348   std::map<std::string, NameRecord> SrcNames, DstNames;
2349   FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
2350   FindNames(PTM.getDstPattern(), DstNames, Pattern);
2351
2352   // Scan all of the named values in the destination pattern, rejecting them if
2353   // they don't exist in the input pattern.
2354   for (std::map<std::string, NameRecord>::iterator
2355        I = DstNames.begin(), E = DstNames.end(); I != E; ++I) {
2356     if (SrcNames[I->first].first == 0)
2357       Pattern->error("Pattern has input without matching name in output: $" +
2358                      I->first);
2359   }
2360   
2361   // Scan all of the named values in the source pattern, rejecting them if the
2362   // name isn't used in the dest, and isn't used to tie two values together.
2363   for (std::map<std::string, NameRecord>::iterator
2364        I = SrcNames.begin(), E = SrcNames.end(); I != E; ++I)
2365     if (DstNames[I->first].first == 0 && SrcNames[I->first].second == 1)
2366       Pattern->error("Pattern has dead named input: $" + I->first);
2367   
2368   PatternsToMatch.push_back(PTM);
2369 }
2370
2371
2372
2373 void CodeGenDAGPatterns::InferInstructionFlags() {
2374   const std::vector<const CodeGenInstruction*> &Instructions =
2375     Target.getInstructionsByEnumValue();
2376   for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
2377     CodeGenInstruction &InstInfo =
2378       const_cast<CodeGenInstruction &>(*Instructions[i]);
2379     // Determine properties of the instruction from its pattern.
2380     bool MayStore, MayLoad, HasSideEffects;
2381     InferFromPattern(InstInfo, MayStore, MayLoad, HasSideEffects, *this);
2382     InstInfo.mayStore = MayStore;
2383     InstInfo.mayLoad = MayLoad;
2384     InstInfo.hasSideEffects = HasSideEffects;
2385   }
2386 }
2387
2388 /// Given a pattern result with an unresolved type, see if we can find one
2389 /// instruction with an unresolved result type.  Force this result type to an
2390 /// arbitrary element if it's possible types to converge results.
2391 static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
2392   if (N->isLeaf())
2393     return false;
2394   
2395   // Analyze children.
2396   for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2397     if (ForceArbitraryInstResultType(N->getChild(i), TP))
2398       return true;
2399
2400   if (!N->getOperator()->isSubClassOf("Instruction"))
2401     return false;
2402
2403   // If this type is already concrete or completely unknown we can't do
2404   // anything.
2405   if (N->getExtType().isCompletelyUnknown() || N->getExtType().isConcrete())
2406     return false;
2407   
2408   // Otherwise, force its type to the first possibility (an arbitrary choice).
2409   return N->getExtType().MergeInTypeInfo(N->getExtType().getTypeList()[0], TP);
2410 }
2411
2412 void CodeGenDAGPatterns::ParsePatterns() {
2413   std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
2414
2415   for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
2416     DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
2417     DefInit *OpDef = dynamic_cast<DefInit*>(Tree->getOperator());
2418     Record *Operator = OpDef->getDef();
2419     TreePattern *Pattern;
2420     if (Operator->getName() != "parallel")
2421       Pattern = new TreePattern(Patterns[i], Tree, true, *this);
2422     else {
2423       std::vector<Init*> Values;
2424       RecTy *ListTy = 0;
2425       for (unsigned j = 0, ee = Tree->getNumArgs(); j != ee; ++j) {
2426         Values.push_back(Tree->getArg(j));
2427         TypedInit *TArg = dynamic_cast<TypedInit*>(Tree->getArg(j));
2428         if (TArg == 0) {
2429           errs() << "In dag: " << Tree->getAsString();
2430           errs() << " --  Untyped argument in pattern\n";
2431           assert(0 && "Untyped argument in pattern");
2432         }
2433         if (ListTy != 0) {
2434           ListTy = resolveTypes(ListTy, TArg->getType());
2435           if (ListTy == 0) {
2436             errs() << "In dag: " << Tree->getAsString();
2437             errs() << " --  Incompatible types in pattern arguments\n";
2438             assert(0 && "Incompatible types in pattern arguments");
2439           }
2440         }
2441         else {
2442           ListTy = TArg->getType();
2443         }
2444       }
2445       ListInit *LI = new ListInit(Values, new ListRecTy(ListTy));
2446       Pattern = new TreePattern(Patterns[i], LI, true, *this);
2447     }
2448
2449     // Inline pattern fragments into it.
2450     Pattern->InlinePatternFragments();
2451     
2452     ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
2453     if (LI->getSize() == 0) continue;  // no pattern.
2454     
2455     // Parse the instruction.
2456     TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
2457     
2458     // Inline pattern fragments into it.
2459     Result->InlinePatternFragments();
2460
2461     if (Result->getNumTrees() != 1)
2462       Result->error("Cannot handle instructions producing instructions "
2463                     "with temporaries yet!");
2464     
2465     bool IterateInference;
2466     bool InferredAllPatternTypes, InferredAllResultTypes;
2467     do {
2468       // Infer as many types as possible.  If we cannot infer all of them, we
2469       // can never do anything with this pattern: report it to the user.
2470       InferredAllPatternTypes =
2471         Pattern->InferAllTypes(&Pattern->getNamedNodesMap());
2472       
2473       // Infer as many types as possible.  If we cannot infer all of them, we
2474       // can never do anything with this pattern: report it to the user.
2475       InferredAllResultTypes =
2476         Result->InferAllTypes(&Pattern->getNamedNodesMap());
2477
2478       IterateInference = false;
2479       
2480       // Apply the type of the result to the source pattern.  This helps us
2481       // resolve cases where the input type is known to be a pointer type (which
2482       // is considered resolved), but the result knows it needs to be 32- or
2483       // 64-bits.  Infer the other way for good measure.
2484       if (!Result->getTree(0)->getExtType().isVoid() &&
2485           !Pattern->getTree(0)->getExtType().isVoid()) {
2486         IterateInference = Pattern->getTree(0)->
2487           UpdateNodeType(Result->getTree(0)->getExtType(), *Result);
2488         IterateInference |= Result->getTree(0)->
2489           UpdateNodeType(Pattern->getTree(0)->getExtType(), *Result);
2490       }
2491       
2492       // If our iteration has converged and the input pattern's types are fully
2493       // resolved but the result pattern is not fully resolved, we may have a
2494       // situation where we have two instructions in the result pattern and
2495       // the instructions require a common register class, but don't care about
2496       // what actual MVT is used.  This is actually a bug in our modelling:
2497       // output patterns should have register classes, not MVTs.
2498       //
2499       // In any case, to handle this, we just go through and disambiguate some
2500       // arbitrary types to the result pattern's nodes.
2501       if (!IterateInference && InferredAllPatternTypes &&
2502           !InferredAllResultTypes)
2503         IterateInference = ForceArbitraryInstResultType(Result->getTree(0),
2504                                                         *Result);
2505     } while (IterateInference);
2506     
2507     // Verify that we inferred enough types that we can do something with the
2508     // pattern and result.  If these fire the user has to add type casts.
2509     if (!InferredAllPatternTypes)
2510       Pattern->error("Could not infer all types in pattern!");
2511     if (!InferredAllResultTypes) {
2512       Pattern->dump();
2513       Result->error("Could not infer all types in pattern result!");
2514     }
2515     
2516     // Validate that the input pattern is correct.
2517     std::map<std::string, TreePatternNode*> InstInputs;
2518     std::map<std::string, TreePatternNode*> InstResults;
2519     std::vector<Record*> InstImpInputs;
2520     std::vector<Record*> InstImpResults;
2521     for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
2522       FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
2523                                   InstInputs, InstResults,
2524                                   InstImpInputs, InstImpResults);
2525
2526     // Promote the xform function to be an explicit node if set.
2527     TreePatternNode *DstPattern = Result->getOnlyTree();
2528     std::vector<TreePatternNode*> ResultNodeOperands;
2529     for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
2530       TreePatternNode *OpNode = DstPattern->getChild(ii);
2531       if (Record *Xform = OpNode->getTransformFn()) {
2532         OpNode->setTransformFn(0);
2533         std::vector<TreePatternNode*> Children;
2534         Children.push_back(OpNode);
2535         OpNode = new TreePatternNode(Xform, Children);
2536       }
2537       ResultNodeOperands.push_back(OpNode);
2538     }
2539     DstPattern = Result->getOnlyTree();
2540     if (!DstPattern->isLeaf())
2541       DstPattern = new TreePatternNode(DstPattern->getOperator(),
2542                                        ResultNodeOperands);
2543     DstPattern->setType(Result->getOnlyTree()->getExtType());
2544     TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
2545     Temp.InferAllTypes();
2546
2547     
2548     AddPatternToMatch(Pattern,
2549                  PatternToMatch(Patterns[i]->getValueAsListInit("Predicates"),
2550                                 Pattern->getTree(0),
2551                                 Temp.getOnlyTree(), InstImpResults,
2552                                 Patterns[i]->getValueAsInt("AddedComplexity"),
2553                                 Patterns[i]->getID()));
2554   }
2555 }
2556
2557 /// CombineChildVariants - Given a bunch of permutations of each child of the
2558 /// 'operator' node, put them together in all possible ways.
2559 static void CombineChildVariants(TreePatternNode *Orig, 
2560                const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
2561                                  std::vector<TreePatternNode*> &OutVariants,
2562                                  CodeGenDAGPatterns &CDP,
2563                                  const MultipleUseVarSet &DepVars) {
2564   // Make sure that each operand has at least one variant to choose from.
2565   for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2566     if (ChildVariants[i].empty())
2567       return;
2568         
2569   // The end result is an all-pairs construction of the resultant pattern.
2570   std::vector<unsigned> Idxs;
2571   Idxs.resize(ChildVariants.size());
2572   bool NotDone;
2573   do {
2574 #ifndef NDEBUG
2575     DEBUG(if (!Idxs.empty()) {
2576             errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
2577               for (unsigned i = 0; i < Idxs.size(); ++i) {
2578                 errs() << Idxs[i] << " ";
2579             }
2580             errs() << "]\n";
2581           });
2582 #endif
2583     // Create the variant and add it to the output list.
2584     std::vector<TreePatternNode*> NewChildren;
2585     for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2586       NewChildren.push_back(ChildVariants[i][Idxs[i]]);
2587     TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
2588     
2589     // Copy over properties.
2590     R->setName(Orig->getName());
2591     R->setPredicateFns(Orig->getPredicateFns());
2592     R->setTransformFn(Orig->getTransformFn());
2593     R->setType(Orig->getExtType());
2594     
2595     // If this pattern cannot match, do not include it as a variant.
2596     std::string ErrString;
2597     if (!R->canPatternMatch(ErrString, CDP)) {
2598       delete R;
2599     } else {
2600       bool AlreadyExists = false;
2601       
2602       // Scan to see if this pattern has already been emitted.  We can get
2603       // duplication due to things like commuting:
2604       //   (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
2605       // which are the same pattern.  Ignore the dups.
2606       for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
2607         if (R->isIsomorphicTo(OutVariants[i], DepVars)) {
2608           AlreadyExists = true;
2609           break;
2610         }
2611       
2612       if (AlreadyExists)
2613         delete R;
2614       else
2615         OutVariants.push_back(R);
2616     }
2617     
2618     // Increment indices to the next permutation by incrementing the
2619     // indicies from last index backward, e.g., generate the sequence
2620     // [0, 0], [0, 1], [1, 0], [1, 1].
2621     int IdxsIdx;
2622     for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
2623       if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
2624         Idxs[IdxsIdx] = 0;
2625       else
2626         break;
2627     }
2628     NotDone = (IdxsIdx >= 0);
2629   } while (NotDone);
2630 }
2631
2632 /// CombineChildVariants - A helper function for binary operators.
2633 ///
2634 static void CombineChildVariants(TreePatternNode *Orig, 
2635                                  const std::vector<TreePatternNode*> &LHS,
2636                                  const std::vector<TreePatternNode*> &RHS,
2637                                  std::vector<TreePatternNode*> &OutVariants,
2638                                  CodeGenDAGPatterns &CDP,
2639                                  const MultipleUseVarSet &DepVars) {
2640   std::vector<std::vector<TreePatternNode*> > ChildVariants;
2641   ChildVariants.push_back(LHS);
2642   ChildVariants.push_back(RHS);
2643   CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
2644 }  
2645
2646
2647 static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
2648                                      std::vector<TreePatternNode *> &Children) {
2649   assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
2650   Record *Operator = N->getOperator();
2651   
2652   // Only permit raw nodes.
2653   if (!N->getName().empty() || !N->getPredicateFns().empty() ||
2654       N->getTransformFn()) {
2655     Children.push_back(N);
2656     return;
2657   }
2658
2659   if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
2660     Children.push_back(N->getChild(0));
2661   else
2662     GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
2663
2664   if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
2665     Children.push_back(N->getChild(1));
2666   else
2667     GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
2668 }
2669
2670 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
2671 /// the (potentially recursive) pattern by using algebraic laws.
2672 ///
2673 static void GenerateVariantsOf(TreePatternNode *N,
2674                                std::vector<TreePatternNode*> &OutVariants,
2675                                CodeGenDAGPatterns &CDP,
2676                                const MultipleUseVarSet &DepVars) {
2677   // We cannot permute leaves.
2678   if (N->isLeaf()) {
2679     OutVariants.push_back(N);
2680     return;
2681   }
2682
2683   // Look up interesting info about the node.
2684   const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
2685
2686   // If this node is associative, re-associate.
2687   if (NodeInfo.hasProperty(SDNPAssociative)) {
2688     // Re-associate by pulling together all of the linked operators 
2689     std::vector<TreePatternNode*> MaximalChildren;
2690     GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
2691
2692     // Only handle child sizes of 3.  Otherwise we'll end up trying too many
2693     // permutations.
2694     if (MaximalChildren.size() == 3) {
2695       // Find the variants of all of our maximal children.
2696       std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
2697       GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
2698       GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
2699       GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
2700       
2701       // There are only two ways we can permute the tree:
2702       //   (A op B) op C    and    A op (B op C)
2703       // Within these forms, we can also permute A/B/C.
2704       
2705       // Generate legal pair permutations of A/B/C.
2706       std::vector<TreePatternNode*> ABVariants;
2707       std::vector<TreePatternNode*> BAVariants;
2708       std::vector<TreePatternNode*> ACVariants;
2709       std::vector<TreePatternNode*> CAVariants;
2710       std::vector<TreePatternNode*> BCVariants;
2711       std::vector<TreePatternNode*> CBVariants;
2712       CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
2713       CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
2714       CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
2715       CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
2716       CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
2717       CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
2718
2719       // Combine those into the result: (x op x) op x
2720       CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
2721       CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
2722       CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
2723       CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
2724       CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
2725       CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
2726
2727       // Combine those into the result: x op (x op x)
2728       CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
2729       CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
2730       CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
2731       CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
2732       CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
2733       CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
2734       return;
2735     }
2736   }
2737   
2738   // Compute permutations of all children.
2739   std::vector<std::vector<TreePatternNode*> > ChildVariants;
2740   ChildVariants.resize(N->getNumChildren());
2741   for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2742     GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
2743
2744   // Build all permutations based on how the children were formed.
2745   CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
2746
2747   // If this node is commutative, consider the commuted order.
2748   bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
2749   if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
2750     assert((N->getNumChildren()==2 || isCommIntrinsic) &&
2751            "Commutative but doesn't have 2 children!");
2752     // Don't count children which are actually register references.
2753     unsigned NC = 0;
2754     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2755       TreePatternNode *Child = N->getChild(i);
2756       if (Child->isLeaf())
2757         if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2758           Record *RR = DI->getDef();
2759           if (RR->isSubClassOf("Register"))
2760             continue;
2761         }
2762       NC++;
2763     }
2764     // Consider the commuted order.
2765     if (isCommIntrinsic) {
2766       // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
2767       // operands are the commutative operands, and there might be more operands
2768       // after those.
2769       assert(NC >= 3 &&
2770              "Commutative intrinsic should have at least 3 childrean!");
2771       std::vector<std::vector<TreePatternNode*> > Variants;
2772       Variants.push_back(ChildVariants[0]); // Intrinsic id.
2773       Variants.push_back(ChildVariants[2]);
2774       Variants.push_back(ChildVariants[1]);
2775       for (unsigned i = 3; i != NC; ++i)
2776         Variants.push_back(ChildVariants[i]);
2777       CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
2778     } else if (NC == 2)
2779       CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
2780                            OutVariants, CDP, DepVars);
2781   }
2782 }
2783
2784
2785 // GenerateVariants - Generate variants.  For example, commutative patterns can
2786 // match multiple ways.  Add them to PatternsToMatch as well.
2787 void CodeGenDAGPatterns::GenerateVariants() {
2788   DEBUG(errs() << "Generating instruction variants.\n");
2789   
2790   // Loop over all of the patterns we've collected, checking to see if we can
2791   // generate variants of the instruction, through the exploitation of
2792   // identities.  This permits the target to provide aggressive matching without
2793   // the .td file having to contain tons of variants of instructions.
2794   //
2795   // Note that this loop adds new patterns to the PatternsToMatch list, but we
2796   // intentionally do not reconsider these.  Any variants of added patterns have
2797   // already been added.
2798   //
2799   for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
2800     MultipleUseVarSet             DepVars;
2801     std::vector<TreePatternNode*> Variants;
2802     FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
2803     DEBUG(errs() << "Dependent/multiply used variables: ");
2804     DEBUG(DumpDepVars(DepVars));
2805     DEBUG(errs() << "\n");
2806     GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this, DepVars);
2807
2808     assert(!Variants.empty() && "Must create at least original variant!");
2809     Variants.erase(Variants.begin());  // Remove the original pattern.
2810
2811     if (Variants.empty())  // No variants for this pattern.
2812       continue;
2813
2814     DEBUG(errs() << "FOUND VARIANTS OF: ";
2815           PatternsToMatch[i].getSrcPattern()->dump();
2816           errs() << "\n");
2817
2818     for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
2819       TreePatternNode *Variant = Variants[v];
2820
2821       DEBUG(errs() << "  VAR#" << v <<  ": ";
2822             Variant->dump();
2823             errs() << "\n");
2824       
2825       // Scan to see if an instruction or explicit pattern already matches this.
2826       bool AlreadyExists = false;
2827       for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
2828         // Skip if the top level predicates do not match.
2829         if (PatternsToMatch[i].getPredicates() !=
2830             PatternsToMatch[p].getPredicates())
2831           continue;
2832         // Check to see if this variant already exists.
2833         if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(), DepVars)) {
2834           DEBUG(errs() << "  *** ALREADY EXISTS, ignoring variant.\n");
2835           AlreadyExists = true;
2836           break;
2837         }
2838       }
2839       // If we already have it, ignore the variant.
2840       if (AlreadyExists) continue;
2841
2842       // Otherwise, add it to the list of patterns we have.
2843       PatternsToMatch.
2844         push_back(PatternToMatch(PatternsToMatch[i].getPredicates(),
2845                                  Variant, PatternsToMatch[i].getDstPattern(),
2846                                  PatternsToMatch[i].getDstRegs(),
2847                                  PatternsToMatch[i].getAddedComplexity(),
2848                                  Record::getNewUID()));
2849     }
2850
2851     DEBUG(errs() << "\n");
2852   }
2853 }
2854