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