fix 80 column violations
[oota-llvm.git] / utils / TableGen / DAGISelEmitter.cpp
1 //===- DAGISelEmitter.cpp - Generate an instruction selector --------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Chris Lattner and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This tablegen backend emits a DAG instruction selector.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "DAGISelEmitter.h"
15 #include "Record.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/Support/Debug.h"
18 #include <algorithm>
19 #include <set>
20 using namespace llvm;
21
22 //===----------------------------------------------------------------------===//
23 // Helpers for working with extended types.
24
25 /// FilterVTs - Filter a list of VT's according to a predicate.
26 ///
27 template<typename T>
28 static std::vector<MVT::ValueType> 
29 FilterVTs(const std::vector<MVT::ValueType> &InVTs, T Filter) {
30   std::vector<MVT::ValueType> Result;
31   for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
32     if (Filter(InVTs[i]))
33       Result.push_back(InVTs[i]);
34   return Result;
35 }
36
37 template<typename T>
38 static std::vector<unsigned char> 
39 FilterEVTs(const std::vector<unsigned char> &InVTs, T Filter) {
40   std::vector<unsigned char> Result;
41   for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
42     if (Filter((MVT::ValueType)InVTs[i]))
43       Result.push_back(InVTs[i]);
44   return Result;
45 }
46
47 static std::vector<unsigned char>
48 ConvertVTs(const std::vector<MVT::ValueType> &InVTs) {
49   std::vector<unsigned char> Result;
50   for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
51       Result.push_back(InVTs[i]);
52   return Result;
53 }
54
55 static bool LHSIsSubsetOfRHS(const std::vector<unsigned char> &LHS,
56                              const std::vector<unsigned char> &RHS) {
57   if (LHS.size() > RHS.size()) return false;
58   for (unsigned i = 0, e = LHS.size(); i != e; ++i)
59     if (std::find(RHS.begin(), RHS.end(), LHS[i]) == RHS.end())
60       return false;
61   return true;
62 }
63
64 /// isExtIntegerVT - Return true if the specified extended value type vector
65 /// contains isInt or an integer value type.
66 static bool isExtIntegerInVTs(const std::vector<unsigned char> &EVTs) {
67   assert(!EVTs.empty() && "Cannot check for integer in empty ExtVT list!");
68   return EVTs[0] == MVT::isInt || !(FilterEVTs(EVTs, MVT::isInteger).empty());
69 }
70
71 /// isExtFloatingPointVT - Return true if the specified extended value type 
72 /// vector contains isFP or a FP value type.
73 static bool isExtFloatingPointInVTs(const std::vector<unsigned char> &EVTs) {
74   assert(!EVTs.empty() && "Cannot check for integer in empty ExtVT list!");
75   return EVTs[0] == MVT::isFP ||
76          !(FilterEVTs(EVTs, MVT::isFloatingPoint).empty());
77 }
78
79 //===----------------------------------------------------------------------===//
80 // SDTypeConstraint implementation
81 //
82
83 SDTypeConstraint::SDTypeConstraint(Record *R) {
84   OperandNo = R->getValueAsInt("OperandNum");
85   
86   if (R->isSubClassOf("SDTCisVT")) {
87     ConstraintType = SDTCisVT;
88     x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
89   } else if (R->isSubClassOf("SDTCisPtrTy")) {
90     ConstraintType = SDTCisPtrTy;
91   } else if (R->isSubClassOf("SDTCisInt")) {
92     ConstraintType = SDTCisInt;
93   } else if (R->isSubClassOf("SDTCisFP")) {
94     ConstraintType = SDTCisFP;
95   } else if (R->isSubClassOf("SDTCisSameAs")) {
96     ConstraintType = SDTCisSameAs;
97     x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
98   } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
99     ConstraintType = SDTCisVTSmallerThanOp;
100     x.SDTCisVTSmallerThanOp_Info.OtherOperandNum = 
101       R->getValueAsInt("OtherOperandNum");
102   } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
103     ConstraintType = SDTCisOpSmallerThanOp;
104     x.SDTCisOpSmallerThanOp_Info.BigOperandNum = 
105       R->getValueAsInt("BigOperandNum");
106   } else if (R->isSubClassOf("SDTCisIntVectorOfSameSize")) {
107     ConstraintType = SDTCisIntVectorOfSameSize;
108     x.SDTCisIntVectorOfSameSize_Info.OtherOperandNum =
109       R->getValueAsInt("OtherOpNum");
110   } else {
111     std::cerr << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
112     exit(1);
113   }
114 }
115
116 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
117 /// N, which has NumResults results.
118 TreePatternNode *SDTypeConstraint::getOperandNum(unsigned OpNo,
119                                                  TreePatternNode *N,
120                                                  unsigned NumResults) const {
121   assert(NumResults <= 1 &&
122          "We only work with nodes with zero or one result so far!");
123   
124   if (OpNo < NumResults)
125     return N;  // FIXME: need value #
126   else
127     return N->getChild(OpNo-NumResults);
128 }
129
130 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
131 /// constraint to the nodes operands.  This returns true if it makes a
132 /// change, false otherwise.  If a type contradiction is found, throw an
133 /// exception.
134 bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
135                                            const SDNodeInfo &NodeInfo,
136                                            TreePattern &TP) const {
137   unsigned NumResults = NodeInfo.getNumResults();
138   assert(NumResults <= 1 &&
139          "We only work with nodes with zero or one result so far!");
140   
141   // Check that the number of operands is sane.
142   if (NodeInfo.getNumOperands() >= 0) {
143     if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands())
144       TP.error(N->getOperator()->getName() + " node requires exactly " +
145                itostr(NodeInfo.getNumOperands()) + " operands!");
146   }
147
148   const CodeGenTarget &CGT = TP.getDAGISelEmitter().getTargetInfo();
149   
150   TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NumResults);
151   
152   switch (ConstraintType) {
153   default: assert(0 && "Unknown constraint type!");
154   case SDTCisVT:
155     // Operand must be a particular type.
156     return NodeToApply->UpdateNodeType(x.SDTCisVT_Info.VT, TP);
157   case SDTCisPtrTy: {
158     // Operand must be same as target pointer type.
159     return NodeToApply->UpdateNodeType(CGT.getPointerType(), TP);
160   }
161   case SDTCisInt: {
162     // If there is only one integer type supported, this must be it.
163     std::vector<MVT::ValueType> IntVTs =
164       FilterVTs(CGT.getLegalValueTypes(), MVT::isInteger);
165
166     // If we found exactly one supported integer type, apply it.
167     if (IntVTs.size() == 1)
168       return NodeToApply->UpdateNodeType(IntVTs[0], TP);
169     return NodeToApply->UpdateNodeType(MVT::isInt, TP);
170   }
171   case SDTCisFP: {
172     // If there is only one FP type supported, this must be it.
173     std::vector<MVT::ValueType> FPVTs =
174       FilterVTs(CGT.getLegalValueTypes(), MVT::isFloatingPoint);
175         
176     // If we found exactly one supported FP type, apply it.
177     if (FPVTs.size() == 1)
178       return NodeToApply->UpdateNodeType(FPVTs[0], TP);
179     return NodeToApply->UpdateNodeType(MVT::isFP, TP);
180   }
181   case SDTCisSameAs: {
182     TreePatternNode *OtherNode =
183       getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NumResults);
184     return NodeToApply->UpdateNodeType(OtherNode->getExtTypes(), TP) |
185            OtherNode->UpdateNodeType(NodeToApply->getExtTypes(), TP);
186   }
187   case SDTCisVTSmallerThanOp: {
188     // The NodeToApply must be a leaf node that is a VT.  OtherOperandNum must
189     // have an integer type that is smaller than the VT.
190     if (!NodeToApply->isLeaf() ||
191         !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
192         !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
193                ->isSubClassOf("ValueType"))
194       TP.error(N->getOperator()->getName() + " expects a VT operand!");
195     MVT::ValueType VT =
196      getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
197     if (!MVT::isInteger(VT))
198       TP.error(N->getOperator()->getName() + " VT operand must be integer!");
199     
200     TreePatternNode *OtherNode =
201       getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N,NumResults);
202     
203     // It must be integer.
204     bool MadeChange = false;
205     MadeChange |= OtherNode->UpdateNodeType(MVT::isInt, TP);
206     
207     // This code only handles nodes that have one type set.  Assert here so
208     // that we can change this if we ever need to deal with multiple value
209     // types at this point.
210     assert(OtherNode->getExtTypes().size() == 1 && "Node has too many types!");
211     if (OtherNode->hasTypeSet() && OtherNode->getTypeNum(0) <= VT)
212       OtherNode->UpdateNodeType(MVT::Other, TP);  // Throw an error.
213     return false;
214   }
215   case SDTCisOpSmallerThanOp: {
216     TreePatternNode *BigOperand =
217       getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NumResults);
218
219     // Both operands must be integer or FP, but we don't care which.
220     bool MadeChange = false;
221     
222     // This code does not currently handle nodes which have multiple types,
223     // where some types are integer, and some are fp.  Assert that this is not
224     // the case.
225     assert(!(isExtIntegerInVTs(NodeToApply->getExtTypes()) &&
226              isExtFloatingPointInVTs(NodeToApply->getExtTypes())) &&
227            !(isExtIntegerInVTs(BigOperand->getExtTypes()) &&
228              isExtFloatingPointInVTs(BigOperand->getExtTypes())) &&
229            "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
230     if (isExtIntegerInVTs(NodeToApply->getExtTypes()))
231       MadeChange |= BigOperand->UpdateNodeType(MVT::isInt, TP);
232     else if (isExtFloatingPointInVTs(NodeToApply->getExtTypes()))
233       MadeChange |= BigOperand->UpdateNodeType(MVT::isFP, TP);
234     if (isExtIntegerInVTs(BigOperand->getExtTypes()))
235       MadeChange |= NodeToApply->UpdateNodeType(MVT::isInt, TP);
236     else if (isExtFloatingPointInVTs(BigOperand->getExtTypes()))
237       MadeChange |= NodeToApply->UpdateNodeType(MVT::isFP, TP);
238
239     std::vector<MVT::ValueType> VTs = CGT.getLegalValueTypes();
240     
241     if (isExtIntegerInVTs(NodeToApply->getExtTypes())) {
242       VTs = FilterVTs(VTs, MVT::isInteger);
243     } else if (isExtFloatingPointInVTs(NodeToApply->getExtTypes())) {
244       VTs = FilterVTs(VTs, MVT::isFloatingPoint);
245     } else {
246       VTs.clear();
247     }
248
249     switch (VTs.size()) {
250     default:         // Too many VT's to pick from.
251     case 0: break;   // No info yet.
252     case 1: 
253       // Only one VT of this flavor.  Cannot ever satisify the constraints.
254       return NodeToApply->UpdateNodeType(MVT::Other, TP);  // throw
255     case 2:
256       // If we have exactly two possible types, the little operand must be the
257       // small one, the big operand should be the big one.  Common with 
258       // float/double for example.
259       assert(VTs[0] < VTs[1] && "Should be sorted!");
260       MadeChange |= NodeToApply->UpdateNodeType(VTs[0], TP);
261       MadeChange |= BigOperand->UpdateNodeType(VTs[1], TP);
262       break;
263     }    
264     return MadeChange;
265   }
266   case SDTCisIntVectorOfSameSize: {
267     TreePatternNode *OtherOperand =
268       getOperandNum(x.SDTCisIntVectorOfSameSize_Info.OtherOperandNum,
269                     N, NumResults);
270     if (OtherOperand->hasTypeSet()) {
271       if (!MVT::isVector(OtherOperand->getTypeNum(0)))
272         TP.error(N->getOperator()->getName() + " VT operand must be a vector!");
273       MVT::ValueType IVT = OtherOperand->getTypeNum(0);
274       IVT = MVT::getIntVectorWithNumElements(MVT::getVectorNumElements(IVT));
275       return NodeToApply->UpdateNodeType(IVT, TP);
276     }
277     return false;
278   }
279   }  
280   return false;
281 }
282
283
284 //===----------------------------------------------------------------------===//
285 // SDNodeInfo implementation
286 //
287 SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
288   EnumName    = R->getValueAsString("Opcode");
289   SDClassName = R->getValueAsString("SDClass");
290   Record *TypeProfile = R->getValueAsDef("TypeProfile");
291   NumResults = TypeProfile->getValueAsInt("NumResults");
292   NumOperands = TypeProfile->getValueAsInt("NumOperands");
293   
294   // Parse the properties.
295   Properties = 0;
296   std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
297   for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
298     if (PropList[i]->getName() == "SDNPCommutative") {
299       Properties |= 1 << SDNPCommutative;
300     } else if (PropList[i]->getName() == "SDNPAssociative") {
301       Properties |= 1 << SDNPAssociative;
302     } else if (PropList[i]->getName() == "SDNPHasChain") {
303       Properties |= 1 << SDNPHasChain;
304     } else if (PropList[i]->getName() == "SDNPOutFlag") {
305       Properties |= 1 << SDNPOutFlag;
306     } else if (PropList[i]->getName() == "SDNPInFlag") {
307       Properties |= 1 << SDNPInFlag;
308     } else if (PropList[i]->getName() == "SDNPOptInFlag") {
309       Properties |= 1 << SDNPOptInFlag;
310     } else {
311       std::cerr << "Unknown SD Node property '" << PropList[i]->getName()
312                 << "' on node '" << R->getName() << "'!\n";
313       exit(1);
314     }
315   }
316   
317   
318   // Parse the type constraints.
319   std::vector<Record*> ConstraintList =
320     TypeProfile->getValueAsListOfDefs("Constraints");
321   TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
322 }
323
324 //===----------------------------------------------------------------------===//
325 // TreePatternNode implementation
326 //
327
328 TreePatternNode::~TreePatternNode() {
329 #if 0 // FIXME: implement refcounted tree nodes!
330   for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
331     delete getChild(i);
332 #endif
333 }
334
335 /// UpdateNodeType - Set the node type of N to VT if VT contains
336 /// information.  If N already contains a conflicting type, then throw an
337 /// exception.  This returns true if any information was updated.
338 ///
339 bool TreePatternNode::UpdateNodeType(const std::vector<unsigned char> &ExtVTs,
340                                      TreePattern &TP) {
341   assert(!ExtVTs.empty() && "Cannot update node type with empty type vector!");
342   
343   if (ExtVTs[0] == MVT::isUnknown || LHSIsSubsetOfRHS(getExtTypes(), ExtVTs)) 
344     return false;
345   if (isTypeCompletelyUnknown() || LHSIsSubsetOfRHS(ExtVTs, getExtTypes())) {
346     setTypes(ExtVTs);
347     return true;
348   }
349   
350   if (ExtVTs[0] == MVT::isInt && isExtIntegerInVTs(getExtTypes())) {
351     assert(hasTypeSet() && "should be handled above!");
352     std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), MVT::isInteger);
353     if (getExtTypes() == FVTs)
354       return false;
355     setTypes(FVTs);
356     return true;
357   }
358   if (ExtVTs[0] == MVT::isFP  && isExtFloatingPointInVTs(getExtTypes())) {
359     assert(hasTypeSet() && "should be handled above!");
360     std::vector<unsigned char> FVTs =
361       FilterEVTs(getExtTypes(), MVT::isFloatingPoint);
362     if (getExtTypes() == FVTs)
363       return false;
364     setTypes(FVTs);
365     return true;
366   }
367       
368   // If we know this is an int or fp type, and we are told it is a specific one,
369   // take the advice.
370   //
371   // Similarly, we should probably set the type here to the intersection of
372   // {isInt|isFP} and ExtVTs
373   if ((getExtTypeNum(0) == MVT::isInt && isExtIntegerInVTs(ExtVTs)) ||
374       (getExtTypeNum(0) == MVT::isFP  && isExtFloatingPointInVTs(ExtVTs))) {
375     setTypes(ExtVTs);
376     return true;
377   }      
378
379   if (isLeaf()) {
380     dump();
381     std::cerr << " ";
382     TP.error("Type inference contradiction found in node!");
383   } else {
384     TP.error("Type inference contradiction found in node " + 
385              getOperator()->getName() + "!");
386   }
387   return true; // unreachable
388 }
389
390
391 void TreePatternNode::print(std::ostream &OS) const {
392   if (isLeaf()) {
393     OS << *getLeafValue();
394   } else {
395     OS << "(" << getOperator()->getName();
396   }
397   
398   // FIXME: At some point we should handle printing all the value types for 
399   // nodes that are multiply typed.
400   switch (getExtTypeNum(0)) {
401   case MVT::Other: OS << ":Other"; break;
402   case MVT::isInt: OS << ":isInt"; break;
403   case MVT::isFP : OS << ":isFP"; break;
404   case MVT::isUnknown: ; /*OS << ":?";*/ break;
405   default:  OS << ":" << getTypeNum(0); break;
406   }
407
408   if (!isLeaf()) {
409     if (getNumChildren() != 0) {
410       OS << " ";
411       getChild(0)->print(OS);
412       for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
413         OS << ", ";
414         getChild(i)->print(OS);
415       }
416     }
417     OS << ")";
418   }
419   
420   if (!PredicateFn.empty())
421     OS << "<<P:" << PredicateFn << ">>";
422   if (TransformFn)
423     OS << "<<X:" << TransformFn->getName() << ">>";
424   if (!getName().empty())
425     OS << ":$" << getName();
426
427 }
428 void TreePatternNode::dump() const {
429   print(std::cerr);
430 }
431
432 /// isIsomorphicTo - Return true if this node is recursively isomorphic to
433 /// the specified node.  For this comparison, all of the state of the node
434 /// is considered, except for the assigned name.  Nodes with differing names
435 /// that are otherwise identical are considered isomorphic.
436 bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N) const {
437   if (N == this) return true;
438   if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
439       getPredicateFn() != N->getPredicateFn() ||
440       getTransformFn() != N->getTransformFn())
441     return false;
442
443   if (isLeaf()) {
444     if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue()))
445       if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue()))
446         return DI->getDef() == NDI->getDef();
447     return getLeafValue() == N->getLeafValue();
448   }
449   
450   if (N->getOperator() != getOperator() ||
451       N->getNumChildren() != getNumChildren()) return false;
452   for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
453     if (!getChild(i)->isIsomorphicTo(N->getChild(i)))
454       return false;
455   return true;
456 }
457
458 /// clone - Make a copy of this tree and all of its children.
459 ///
460 TreePatternNode *TreePatternNode::clone() const {
461   TreePatternNode *New;
462   if (isLeaf()) {
463     New = new TreePatternNode(getLeafValue());
464   } else {
465     std::vector<TreePatternNode*> CChildren;
466     CChildren.reserve(Children.size());
467     for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
468       CChildren.push_back(getChild(i)->clone());
469     New = new TreePatternNode(getOperator(), CChildren);
470   }
471   New->setName(getName());
472   New->setTypes(getExtTypes());
473   New->setPredicateFn(getPredicateFn());
474   New->setTransformFn(getTransformFn());
475   return New;
476 }
477
478 /// SubstituteFormalArguments - Replace the formal arguments in this tree
479 /// with actual values specified by ArgMap.
480 void TreePatternNode::
481 SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
482   if (isLeaf()) return;
483   
484   for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
485     TreePatternNode *Child = getChild(i);
486     if (Child->isLeaf()) {
487       Init *Val = Child->getLeafValue();
488       if (dynamic_cast<DefInit*>(Val) &&
489           static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
490         // We found a use of a formal argument, replace it with its value.
491         Child = ArgMap[Child->getName()];
492         assert(Child && "Couldn't find formal argument!");
493         setChild(i, Child);
494       }
495     } else {
496       getChild(i)->SubstituteFormalArguments(ArgMap);
497     }
498   }
499 }
500
501
502 /// InlinePatternFragments - If this pattern refers to any pattern
503 /// fragments, inline them into place, giving us a pattern without any
504 /// PatFrag references.
505 TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
506   if (isLeaf()) return this;  // nothing to do.
507   Record *Op = getOperator();
508   
509   if (!Op->isSubClassOf("PatFrag")) {
510     // Just recursively inline children nodes.
511     for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
512       setChild(i, getChild(i)->InlinePatternFragments(TP));
513     return this;
514   }
515
516   // Otherwise, we found a reference to a fragment.  First, look up its
517   // TreePattern record.
518   TreePattern *Frag = TP.getDAGISelEmitter().getPatternFragment(Op);
519   
520   // Verify that we are passing the right number of operands.
521   if (Frag->getNumArgs() != Children.size())
522     TP.error("'" + Op->getName() + "' fragment requires " +
523              utostr(Frag->getNumArgs()) + " operands!");
524
525   TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
526
527   // Resolve formal arguments to their actual value.
528   if (Frag->getNumArgs()) {
529     // Compute the map of formal to actual arguments.
530     std::map<std::string, TreePatternNode*> ArgMap;
531     for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
532       ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
533   
534     FragTree->SubstituteFormalArguments(ArgMap);
535   }
536   
537   FragTree->setName(getName());
538   FragTree->UpdateNodeType(getExtTypes(), TP);
539   
540   // Get a new copy of this fragment to stitch into here.
541   //delete this;    // FIXME: implement refcounting!
542   return FragTree;
543 }
544
545 /// getIntrinsicType - Check to see if the specified record has an intrinsic
546 /// type which should be applied to it.  This infer the type of register
547 /// references from the register file information, for example.
548 ///
549 static std::vector<unsigned char> getIntrinsicType(Record *R, bool NotRegisters,
550                                       TreePattern &TP) {
551   // Some common return values
552   std::vector<unsigned char> Unknown(1, MVT::isUnknown);
553   std::vector<unsigned char> Other(1, MVT::Other);
554
555   // Check to see if this is a register or a register class...
556   if (R->isSubClassOf("RegisterClass")) {
557     if (NotRegisters) 
558       return Unknown;
559     const CodeGenRegisterClass &RC = 
560       TP.getDAGISelEmitter().getTargetInfo().getRegisterClass(R);
561     return ConvertVTs(RC.getValueTypes());
562   } else if (R->isSubClassOf("PatFrag")) {
563     // Pattern fragment types will be resolved when they are inlined.
564     return Unknown;
565   } else if (R->isSubClassOf("Register")) {
566     if (NotRegisters) 
567       return Unknown;
568     // If the register appears in exactly one regclass, and the regclass has one
569     // value type, use it as the known type.
570     const CodeGenTarget &T = TP.getDAGISelEmitter().getTargetInfo();
571     if (const CodeGenRegisterClass *RC = T.getRegisterClassForRegister(R))
572       return ConvertVTs(RC->getValueTypes());
573     return Unknown;
574   } else if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
575     // Using a VTSDNode or CondCodeSDNode.
576     return Other;
577   } else if (R->isSubClassOf("ComplexPattern")) {
578     if (NotRegisters) 
579       return Unknown;
580     std::vector<unsigned char>
581     ComplexPat(1, TP.getDAGISelEmitter().getComplexPattern(R).getValueType());
582     return ComplexPat;
583   } else if (R->getName() == "node" || R->getName() == "srcvalue") {
584     // Placeholder.
585     return Unknown;
586   }
587   
588   TP.error("Unknown node flavor used in pattern: " + R->getName());
589   return Other;
590 }
591
592 /// ApplyTypeConstraints - Apply all of the type constraints relevent to
593 /// this node and its children in the tree.  This returns true if it makes a
594 /// change, false otherwise.  If a type contradiction is found, throw an
595 /// exception.
596 bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
597   if (isLeaf()) {
598     if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
599       // If it's a regclass or something else known, include the type.
600       return UpdateNodeType(getIntrinsicType(DI->getDef(), NotRegisters, TP),
601                             TP);
602     } else if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
603       // Int inits are always integers. :)
604       bool MadeChange = UpdateNodeType(MVT::isInt, TP);
605       
606       if (hasTypeSet()) {
607         // At some point, it may make sense for this tree pattern to have
608         // multiple types.  Assert here that it does not, so we revisit this
609         // code when appropriate.
610         assert(getExtTypes().size() == 1 && "TreePattern has too many types!");
611         
612         unsigned Size = MVT::getSizeInBits(getTypeNum(0));
613         // Make sure that the value is representable for this type.
614         if (Size < 32) {
615           int Val = (II->getValue() << (32-Size)) >> (32-Size);
616           if (Val != II->getValue())
617             TP.error("Sign-extended integer value '" + itostr(II->getValue()) +
618                      "' is out of range for type 'MVT::" + 
619                      getEnumName(getTypeNum(0)) + "'!");
620         }
621       }
622       
623       return MadeChange;
624     }
625     return false;
626   }
627   
628   // special handling for set, which isn't really an SDNode.
629   if (getOperator()->getName() == "set") {
630     assert (getNumChildren() == 2 && "Only handle 2 operand set's for now!");
631     bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
632     MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
633     
634     // Types of operands must match.
635     MadeChange |= getChild(0)->UpdateNodeType(getChild(1)->getExtTypes(), TP);
636     MadeChange |= getChild(1)->UpdateNodeType(getChild(0)->getExtTypes(), TP);
637     MadeChange |= UpdateNodeType(MVT::isVoid, TP);
638     return MadeChange;
639   } else if (getOperator()->isSubClassOf("SDNode")) {
640     const SDNodeInfo &NI = TP.getDAGISelEmitter().getSDNodeInfo(getOperator());
641     
642     bool MadeChange = NI.ApplyTypeConstraints(this, TP);
643     for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
644       MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
645     // Branch, etc. do not produce results and top-level forms in instr pattern
646     // must have void types.
647     if (NI.getNumResults() == 0)
648       MadeChange |= UpdateNodeType(MVT::isVoid, TP);
649     return MadeChange;  
650   } else if (getOperator()->isSubClassOf("Instruction")) {
651     const DAGInstruction &Inst =
652       TP.getDAGISelEmitter().getInstruction(getOperator());
653     bool MadeChange = false;
654     unsigned NumResults = Inst.getNumResults();
655     
656     assert(NumResults <= 1 &&
657            "Only supports zero or one result instrs!");
658     // Apply the result type to the node
659     if (NumResults == 0) {
660       MadeChange = UpdateNodeType(MVT::isVoid, TP);
661     } else {
662       Record *ResultNode = Inst.getResult(0);
663       assert(ResultNode->isSubClassOf("RegisterClass") &&
664              "Operands should be register classes!");
665
666       const CodeGenRegisterClass &RC = 
667         TP.getDAGISelEmitter().getTargetInfo().getRegisterClass(ResultNode);
668       MadeChange = UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
669     }
670
671     if (getNumChildren() != Inst.getNumOperands())
672       TP.error("Instruction '" + getOperator()->getName() + " expects " +
673                utostr(Inst.getNumOperands()) + " operands, not " +
674                utostr(getNumChildren()) + " operands!");
675     for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
676       Record *OperandNode = Inst.getOperand(i);
677       MVT::ValueType VT;
678       if (OperandNode->isSubClassOf("RegisterClass")) {
679         const CodeGenRegisterClass &RC = 
680           TP.getDAGISelEmitter().getTargetInfo().getRegisterClass(OperandNode);
681         //VT = RC.getValueTypeNum(0);
682         MadeChange |=getChild(i)->UpdateNodeType(ConvertVTs(RC.getValueTypes()),
683                                                  TP);
684       } else if (OperandNode->isSubClassOf("Operand")) {
685         VT = getValueType(OperandNode->getValueAsDef("Type"));
686         MadeChange |= getChild(i)->UpdateNodeType(VT, TP);
687       } else {
688         assert(0 && "Unknown operand type!");
689         abort();
690       }
691       MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
692     }
693     return MadeChange;
694   } else if (getOperator()->isSubClassOf("Intrinsic")) {
695     const CodeGenIntrinsic &Int = 
696       TP.getDAGISelEmitter().getIntrinsic(getOperator());
697     // FIXME: get type information! 
698     bool MadeChange = false;
699
700     // Apply the result type to the node.
701     MadeChange = UpdateNodeType(Int.ArgVTs[0], TP);
702     
703     if (getNumChildren() != Int.ArgVTs.size()-1)
704       TP.error("Intrinsic '" + getOperator()->getName() + " expects " +
705                utostr(Int.ArgVTs.size()-1) + " operands, not " +
706                utostr(getNumChildren()) + " operands!");
707     for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
708       MVT::ValueType OpVT = Int.ArgVTs[i+1];
709       MadeChange |= getChild(i)->UpdateNodeType(OpVT, TP);
710       MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
711     }
712     return MadeChange;
713   } else {
714     assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
715     
716     // Node transforms always take one operand.
717     if (getNumChildren() != 1)
718       TP.error("Node transform '" + getOperator()->getName() +
719                "' requires one operand!");
720
721     // If either the output or input of the xform does not have exact
722     // type info. We assume they must be the same. Otherwise, it is perfectly
723     // legal to transform from one type to a completely different type.
724     if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
725       bool MadeChange = UpdateNodeType(getChild(0)->getExtTypes(), TP);
726       MadeChange |= getChild(0)->UpdateNodeType(getExtTypes(), TP);
727       return MadeChange;
728     }
729     return false;
730   }
731 }
732
733 /// canPatternMatch - If it is impossible for this pattern to match on this
734 /// target, fill in Reason and return false.  Otherwise, return true.  This is
735 /// used as a santity check for .td files (to prevent people from writing stuff
736 /// that can never possibly work), and to prevent the pattern permuter from
737 /// generating stuff that is useless.
738 bool TreePatternNode::canPatternMatch(std::string &Reason, DAGISelEmitter &ISE){
739   if (isLeaf()) return true;
740
741   for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
742     if (!getChild(i)->canPatternMatch(Reason, ISE))
743       return false;
744
745   // If this is an intrinsic, handle cases that would make it not match.  For
746   // example, if an operand is required to be an immediate.
747   if (getOperator()->isSubClassOf("Intrinsic")) {
748     // TODO:
749     return true;
750   }
751   
752   // If this node is a commutative operator, check that the LHS isn't an
753   // immediate.
754   const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(getOperator());
755   if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
756     // Scan all of the operands of the node and make sure that only the last one
757     // is a constant node.
758     for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i)
759       if (!getChild(i)->isLeaf() && 
760           getChild(i)->getOperator()->getName() == "imm") {
761         Reason = "Immediate value must be on the RHS of commutative operators!";
762         return false;
763       }
764   }
765   
766   return true;
767 }
768
769 //===----------------------------------------------------------------------===//
770 // TreePattern implementation
771 //
772
773 TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
774                          DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
775    isInputPattern = isInput;
776    for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
777      Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
778 }
779
780 TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
781                          DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
782   isInputPattern = isInput;
783   Trees.push_back(ParseTreePattern(Pat));
784 }
785
786 TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
787                          DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
788   isInputPattern = isInput;
789   Trees.push_back(Pat);
790 }
791
792
793
794 void TreePattern::error(const std::string &Msg) const {
795   dump();
796   throw "In " + TheRecord->getName() + ": " + Msg;
797 }
798
799 TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
800   Record *Operator = Dag->getNodeType();
801   
802   if (Operator->isSubClassOf("ValueType")) {
803     // If the operator is a ValueType, then this must be "type cast" of a leaf
804     // node.
805     if (Dag->getNumArgs() != 1)
806       error("Type cast only takes one operand!");
807     
808     Init *Arg = Dag->getArg(0);
809     TreePatternNode *New;
810     if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
811       Record *R = DI->getDef();
812       if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
813         Dag->setArg(0, new DagInit(R,
814                                 std::vector<std::pair<Init*, std::string> >()));
815         return ParseTreePattern(Dag);
816       }
817       New = new TreePatternNode(DI);
818     } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
819       New = ParseTreePattern(DI);
820     } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
821       New = new TreePatternNode(II);
822       if (!Dag->getArgName(0).empty())
823         error("Constant int argument should not have a name!");
824     } else {
825       Arg->dump();
826       error("Unknown leaf value for tree pattern!");
827       return 0;
828     }
829     
830     // Apply the type cast.
831     New->UpdateNodeType(getValueType(Operator), *this);
832     New->setName(Dag->getArgName(0));
833     return New;
834   }
835   
836   // Verify that this is something that makes sense for an operator.
837   if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
838       !Operator->isSubClassOf("Instruction") && 
839       !Operator->isSubClassOf("SDNodeXForm") &&
840       !Operator->isSubClassOf("Intrinsic") &&
841       Operator->getName() != "set")
842     error("Unrecognized node '" + Operator->getName() + "'!");
843   
844   //  Check to see if this is something that is illegal in an input pattern.
845   if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
846       Operator->isSubClassOf("SDNodeXForm")))
847     error("Cannot use '" + Operator->getName() + "' in an input pattern!");
848   
849   std::vector<TreePatternNode*> Children;
850   
851   for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
852     Init *Arg = Dag->getArg(i);
853     if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
854       Children.push_back(ParseTreePattern(DI));
855       if (Children.back()->getName().empty())
856         Children.back()->setName(Dag->getArgName(i));
857     } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
858       Record *R = DefI->getDef();
859       // Direct reference to a leaf DagNode or PatFrag?  Turn it into a
860       // TreePatternNode if its own.
861       if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
862         Dag->setArg(i, new DagInit(R,
863                               std::vector<std::pair<Init*, std::string> >()));
864         --i;  // Revisit this node...
865       } else {
866         TreePatternNode *Node = new TreePatternNode(DefI);
867         Node->setName(Dag->getArgName(i));
868         Children.push_back(Node);
869         
870         // Input argument?
871         if (R->getName() == "node") {
872           if (Dag->getArgName(i).empty())
873             error("'node' argument requires a name to match with operand list");
874           Args.push_back(Dag->getArgName(i));
875         }
876       }
877     } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
878       TreePatternNode *Node = new TreePatternNode(II);
879       if (!Dag->getArgName(i).empty())
880         error("Constant int argument should not have a name!");
881       Children.push_back(Node);
882     } else {
883       std::cerr << '"';
884       Arg->dump();
885       std::cerr << "\": ";
886       error("Unknown leaf value for tree pattern!");
887     }
888   }
889   
890   return new TreePatternNode(Operator, Children);
891 }
892
893 /// InferAllTypes - Infer/propagate as many types throughout the expression
894 /// patterns as possible.  Return true if all types are infered, false
895 /// otherwise.  Throw an exception if a type contradiction is found.
896 bool TreePattern::InferAllTypes() {
897   bool MadeChange = true;
898   while (MadeChange) {
899     MadeChange = false;
900     for (unsigned i = 0, e = Trees.size(); i != e; ++i)
901       MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
902   }
903   
904   bool HasUnresolvedTypes = false;
905   for (unsigned i = 0, e = Trees.size(); i != e; ++i)
906     HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
907   return !HasUnresolvedTypes;
908 }
909
910 void TreePattern::print(std::ostream &OS) const {
911   OS << getRecord()->getName();
912   if (!Args.empty()) {
913     OS << "(" << Args[0];
914     for (unsigned i = 1, e = Args.size(); i != e; ++i)
915       OS << ", " << Args[i];
916     OS << ")";
917   }
918   OS << ": ";
919   
920   if (Trees.size() > 1)
921     OS << "[\n";
922   for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
923     OS << "\t";
924     Trees[i]->print(OS);
925     OS << "\n";
926   }
927
928   if (Trees.size() > 1)
929     OS << "]\n";
930 }
931
932 void TreePattern::dump() const { print(std::cerr); }
933
934
935
936 //===----------------------------------------------------------------------===//
937 // DAGISelEmitter implementation
938 //
939
940 // Parse all of the SDNode definitions for the target, populating SDNodes.
941 void DAGISelEmitter::ParseNodeInfo() {
942   std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
943   while (!Nodes.empty()) {
944     SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
945     Nodes.pop_back();
946   }
947 }
948
949 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
950 /// map, and emit them to the file as functions.
951 void DAGISelEmitter::ParseNodeTransforms(std::ostream &OS) {
952   OS << "\n// Node transformations.\n";
953   std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
954   while (!Xforms.empty()) {
955     Record *XFormNode = Xforms.back();
956     Record *SDNode = XFormNode->getValueAsDef("Opcode");
957     std::string Code = XFormNode->getValueAsCode("XFormFunction");
958     SDNodeXForms.insert(std::make_pair(XFormNode,
959                                        std::make_pair(SDNode, Code)));
960
961     if (!Code.empty()) {
962       std::string ClassName = getSDNodeInfo(SDNode).getSDClassName();
963       const char *C2 = ClassName == "SDNode" ? "N" : "inN";
964
965       OS << "inline SDOperand Transform_" << XFormNode->getName()
966          << "(SDNode *" << C2 << ") {\n";
967       if (ClassName != "SDNode")
968         OS << "  " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
969       OS << Code << "\n}\n";
970     }
971
972     Xforms.pop_back();
973   }
974 }
975
976 void DAGISelEmitter::ParseComplexPatterns() {
977   std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
978   while (!AMs.empty()) {
979     ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
980     AMs.pop_back();
981   }
982 }
983
984
985 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
986 /// file, building up the PatternFragments map.  After we've collected them all,
987 /// inline fragments together as necessary, so that there are no references left
988 /// inside a pattern fragment to a pattern fragment.
989 ///
990 /// This also emits all of the predicate functions to the output file.
991 ///
992 void DAGISelEmitter::ParsePatternFragments(std::ostream &OS) {
993   std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
994   
995   // First step, parse all of the fragments and emit predicate functions.
996   OS << "\n// Predicate functions.\n";
997   for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
998     DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
999     TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
1000     PatternFragments[Fragments[i]] = P;
1001     
1002     // Validate the argument list, converting it to map, to discard duplicates.
1003     std::vector<std::string> &Args = P->getArgList();
1004     std::set<std::string> OperandsMap(Args.begin(), Args.end());
1005     
1006     if (OperandsMap.count(""))
1007       P->error("Cannot have unnamed 'node' values in pattern fragment!");
1008     
1009     // Parse the operands list.
1010     DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
1011     if (OpsList->getNodeType()->getName() != "ops")
1012       P->error("Operands list should start with '(ops ... '!");
1013     
1014     // Copy over the arguments.       
1015     Args.clear();
1016     for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
1017       if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
1018           static_cast<DefInit*>(OpsList->getArg(j))->
1019           getDef()->getName() != "node")
1020         P->error("Operands list should all be 'node' values.");
1021       if (OpsList->getArgName(j).empty())
1022         P->error("Operands list should have names for each operand!");
1023       if (!OperandsMap.count(OpsList->getArgName(j)))
1024         P->error("'" + OpsList->getArgName(j) +
1025                  "' does not occur in pattern or was multiply specified!");
1026       OperandsMap.erase(OpsList->getArgName(j));
1027       Args.push_back(OpsList->getArgName(j));
1028     }
1029     
1030     if (!OperandsMap.empty())
1031       P->error("Operands list does not contain an entry for operand '" +
1032                *OperandsMap.begin() + "'!");
1033
1034     // If there is a code init for this fragment, emit the predicate code and
1035     // keep track of the fact that this fragment uses it.
1036     std::string Code = Fragments[i]->getValueAsCode("Predicate");
1037     if (!Code.empty()) {
1038       assert(!P->getOnlyTree()->isLeaf() && "Can't be a leaf!");
1039       std::string ClassName =
1040         getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
1041       const char *C2 = ClassName == "SDNode" ? "N" : "inN";
1042       
1043       OS << "inline bool Predicate_" << Fragments[i]->getName()
1044          << "(SDNode *" << C2 << ") {\n";
1045       if (ClassName != "SDNode")
1046         OS << "  " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
1047       OS << Code << "\n}\n";
1048       P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
1049     }
1050     
1051     // If there is a node transformation corresponding to this, keep track of
1052     // it.
1053     Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
1054     if (!getSDNodeTransform(Transform).second.empty())    // not noop xform?
1055       P->getOnlyTree()->setTransformFn(Transform);
1056   }
1057   
1058   OS << "\n\n";
1059
1060   // Now that we've parsed all of the tree fragments, do a closure on them so
1061   // that there are not references to PatFrags left inside of them.
1062   for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
1063        E = PatternFragments.end(); I != E; ++I) {
1064     TreePattern *ThePat = I->second;
1065     ThePat->InlinePatternFragments();
1066         
1067     // Infer as many types as possible.  Don't worry about it if we don't infer
1068     // all of them, some may depend on the inputs of the pattern.
1069     try {
1070       ThePat->InferAllTypes();
1071     } catch (...) {
1072       // If this pattern fragment is not supported by this target (no types can
1073       // satisfy its constraints), just ignore it.  If the bogus pattern is
1074       // actually used by instructions, the type consistency error will be
1075       // reported there.
1076     }
1077     
1078     // If debugging, print out the pattern fragment result.
1079     DEBUG(ThePat->dump());
1080   }
1081 }
1082
1083 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
1084 /// instruction input.  Return true if this is a real use.
1085 static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
1086                       std::map<std::string, TreePatternNode*> &InstInputs,
1087                       std::vector<Record*> &InstImpInputs) {
1088   // No name -> not interesting.
1089   if (Pat->getName().empty()) {
1090     if (Pat->isLeaf()) {
1091       DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1092       if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1093         I->error("Input " + DI->getDef()->getName() + " must be named!");
1094       else if (DI && DI->getDef()->isSubClassOf("Register")) 
1095         InstImpInputs.push_back(DI->getDef());
1096     }
1097     return false;
1098   }
1099
1100   Record *Rec;
1101   if (Pat->isLeaf()) {
1102     DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1103     if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
1104     Rec = DI->getDef();
1105   } else {
1106     assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
1107     Rec = Pat->getOperator();
1108   }
1109
1110   // SRCVALUE nodes are ignored.
1111   if (Rec->getName() == "srcvalue")
1112     return false;
1113
1114   TreePatternNode *&Slot = InstInputs[Pat->getName()];
1115   if (!Slot) {
1116     Slot = Pat;
1117   } else {
1118     Record *SlotRec;
1119     if (Slot->isLeaf()) {
1120       SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
1121     } else {
1122       assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
1123       SlotRec = Slot->getOperator();
1124     }
1125     
1126     // Ensure that the inputs agree if we've already seen this input.
1127     if (Rec != SlotRec)
1128       I->error("All $" + Pat->getName() + " inputs must agree with each other");
1129     if (Slot->getExtTypes() != Pat->getExtTypes())
1130       I->error("All $" + Pat->getName() + " inputs must agree with each other");
1131   }
1132   return true;
1133 }
1134
1135 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
1136 /// part of "I", the instruction), computing the set of inputs and outputs of
1137 /// the pattern.  Report errors if we see anything naughty.
1138 void DAGISelEmitter::
1139 FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
1140                             std::map<std::string, TreePatternNode*> &InstInputs,
1141                             std::map<std::string, TreePatternNode*>&InstResults,
1142                             std::vector<Record*> &InstImpInputs,
1143                             std::vector<Record*> &InstImpResults) {
1144   if (Pat->isLeaf()) {
1145     bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1146     if (!isUse && Pat->getTransformFn())
1147       I->error("Cannot specify a transform function for a non-input value!");
1148     return;
1149   } else if (Pat->getOperator()->getName() != "set") {
1150     // If this is not a set, verify that the children nodes are not void typed,
1151     // and recurse.
1152     for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1153       if (Pat->getChild(i)->getExtTypeNum(0) == MVT::isVoid)
1154         I->error("Cannot have void nodes inside of patterns!");
1155       FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
1156                                   InstImpInputs, InstImpResults);
1157     }
1158     
1159     // If this is a non-leaf node with no children, treat it basically as if
1160     // it were a leaf.  This handles nodes like (imm).
1161     bool isUse = false;
1162     if (Pat->getNumChildren() == 0)
1163       isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1164     
1165     if (!isUse && Pat->getTransformFn())
1166       I->error("Cannot specify a transform function for a non-input value!");
1167     return;
1168   } 
1169   
1170   // Otherwise, this is a set, validate and collect instruction results.
1171   if (Pat->getNumChildren() == 0)
1172     I->error("set requires operands!");
1173   else if (Pat->getNumChildren() & 1)
1174     I->error("set requires an even number of operands");
1175   
1176   if (Pat->getTransformFn())
1177     I->error("Cannot specify a transform function on a set node!");
1178   
1179   // Check the set destinations.
1180   unsigned NumValues = Pat->getNumChildren()/2;
1181   for (unsigned i = 0; i != NumValues; ++i) {
1182     TreePatternNode *Dest = Pat->getChild(i);
1183     if (!Dest->isLeaf())
1184       I->error("set destination should be a register!");
1185     
1186     DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1187     if (!Val)
1188       I->error("set destination should be a register!");
1189
1190     if (Val->getDef()->isSubClassOf("RegisterClass")) {
1191       if (Dest->getName().empty())
1192         I->error("set destination must have a name!");
1193       if (InstResults.count(Dest->getName()))
1194         I->error("cannot set '" + Dest->getName() +"' multiple times");
1195       InstResults[Dest->getName()] = Dest;
1196     } else if (Val->getDef()->isSubClassOf("Register")) {
1197       InstImpResults.push_back(Val->getDef());
1198     } else {
1199       I->error("set destination should be a register!");
1200     }
1201     
1202     // Verify and collect info from the computation.
1203     FindPatternInputsAndOutputs(I, Pat->getChild(i+NumValues),
1204                                 InstInputs, InstResults,
1205                                 InstImpInputs, InstImpResults);
1206   }
1207 }
1208
1209 /// ParseInstructions - Parse all of the instructions, inlining and resolving
1210 /// any fragments involved.  This populates the Instructions list with fully
1211 /// resolved instructions.
1212 void DAGISelEmitter::ParseInstructions() {
1213   std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
1214   
1215   for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
1216     ListInit *LI = 0;
1217     
1218     if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
1219       LI = Instrs[i]->getValueAsListInit("Pattern");
1220     
1221     // If there is no pattern, only collect minimal information about the
1222     // instruction for its operand list.  We have to assume that there is one
1223     // result, as we have no detailed info.
1224     if (!LI || LI->getSize() == 0) {
1225       std::vector<Record*> Results;
1226       std::vector<Record*> Operands;
1227       
1228       CodeGenInstruction &InstInfo =Target.getInstruction(Instrs[i]->getName());
1229
1230       if (InstInfo.OperandList.size() != 0) {
1231         // FIXME: temporary hack...
1232         if (InstInfo.noResults) {
1233           // These produce no results
1234           for (unsigned j = 0, e = InstInfo.OperandList.size(); j < e; ++j)
1235             Operands.push_back(InstInfo.OperandList[j].Rec);
1236         } else {
1237           // Assume the first operand is the result.
1238           Results.push_back(InstInfo.OperandList[0].Rec);
1239       
1240           // The rest are inputs.
1241           for (unsigned j = 1, e = InstInfo.OperandList.size(); j < e; ++j)
1242             Operands.push_back(InstInfo.OperandList[j].Rec);
1243         }
1244       }
1245       
1246       // Create and insert the instruction.
1247       std::vector<Record*> ImpResults;
1248       std::vector<Record*> ImpOperands;
1249       Instructions.insert(std::make_pair(Instrs[i], 
1250                           DAGInstruction(0, Results, Operands, ImpResults,
1251                                          ImpOperands)));
1252       continue;  // no pattern.
1253     }
1254     
1255     // Parse the instruction.
1256     TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
1257     // Inline pattern fragments into it.
1258     I->InlinePatternFragments();
1259     
1260     // Infer as many types as possible.  If we cannot infer all of them, we can
1261     // never do anything with this instruction pattern: report it to the user.
1262     if (!I->InferAllTypes())
1263       I->error("Could not infer all types in pattern!");
1264     
1265     // InstInputs - Keep track of all of the inputs of the instruction, along 
1266     // with the record they are declared as.
1267     std::map<std::string, TreePatternNode*> InstInputs;
1268     
1269     // InstResults - Keep track of all the virtual registers that are 'set'
1270     // in the instruction, including what reg class they are.
1271     std::map<std::string, TreePatternNode*> InstResults;
1272
1273     std::vector<Record*> InstImpInputs;
1274     std::vector<Record*> InstImpResults;
1275     
1276     // Verify that the top-level forms in the instruction are of void type, and
1277     // fill in the InstResults map.
1278     for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
1279       TreePatternNode *Pat = I->getTree(j);
1280       if (Pat->getExtTypeNum(0) != MVT::isVoid)
1281         I->error("Top-level forms in instruction pattern should have"
1282                  " void types");
1283
1284       // Find inputs and outputs, and verify the structure of the uses/defs.
1285       FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
1286                                   InstImpInputs, InstImpResults);
1287     }
1288
1289     // Now that we have inputs and outputs of the pattern, inspect the operands
1290     // list for the instruction.  This determines the order that operands are
1291     // added to the machine instruction the node corresponds to.
1292     unsigned NumResults = InstResults.size();
1293
1294     // Parse the operands list from the (ops) list, validating it.
1295     std::vector<std::string> &Args = I->getArgList();
1296     assert(Args.empty() && "Args list should still be empty here!");
1297     CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
1298
1299     // Check that all of the results occur first in the list.
1300     std::vector<Record*> Results;
1301     TreePatternNode *Res0Node = NULL;
1302     for (unsigned i = 0; i != NumResults; ++i) {
1303       if (i == CGI.OperandList.size())
1304         I->error("'" + InstResults.begin()->first +
1305                  "' set but does not appear in operand list!");
1306       const std::string &OpName = CGI.OperandList[i].Name;
1307       
1308       // Check that it exists in InstResults.
1309       TreePatternNode *RNode = InstResults[OpName];
1310       if (i == 0)
1311         Res0Node = RNode;
1312       Record *R = dynamic_cast<DefInit*>(RNode->getLeafValue())->getDef();
1313       if (R == 0)
1314         I->error("Operand $" + OpName + " should be a set destination: all "
1315                  "outputs must occur before inputs in operand list!");
1316       
1317       if (CGI.OperandList[i].Rec != R)
1318         I->error("Operand $" + OpName + " class mismatch!");
1319       
1320       // Remember the return type.
1321       Results.push_back(CGI.OperandList[i].Rec);
1322       
1323       // Okay, this one checks out.
1324       InstResults.erase(OpName);
1325     }
1326
1327     // Loop over the inputs next.  Make a copy of InstInputs so we can destroy
1328     // the copy while we're checking the inputs.
1329     std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
1330
1331     std::vector<TreePatternNode*> ResultNodeOperands;
1332     std::vector<Record*> Operands;
1333     for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
1334       const std::string &OpName = CGI.OperandList[i].Name;
1335       if (OpName.empty())
1336         I->error("Operand #" + utostr(i) + " in operands list has no name!");
1337
1338       if (!InstInputsCheck.count(OpName))
1339         I->error("Operand $" + OpName +
1340                  " does not appear in the instruction pattern");
1341       TreePatternNode *InVal = InstInputsCheck[OpName];
1342       InstInputsCheck.erase(OpName);   // It occurred, remove from map.
1343       
1344       if (InVal->isLeaf() &&
1345           dynamic_cast<DefInit*>(InVal->getLeafValue())) {
1346         Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
1347         if (CGI.OperandList[i].Rec != InRec &&
1348             !InRec->isSubClassOf("ComplexPattern"))
1349           I->error("Operand $" + OpName + "'s register class disagrees"
1350                    " between the operand and pattern");
1351       }
1352       Operands.push_back(CGI.OperandList[i].Rec);
1353       
1354       // Construct the result for the dest-pattern operand list.
1355       TreePatternNode *OpNode = InVal->clone();
1356       
1357       // No predicate is useful on the result.
1358       OpNode->setPredicateFn("");
1359       
1360       // Promote the xform function to be an explicit node if set.
1361       if (Record *Xform = OpNode->getTransformFn()) {
1362         OpNode->setTransformFn(0);
1363         std::vector<TreePatternNode*> Children;
1364         Children.push_back(OpNode);
1365         OpNode = new TreePatternNode(Xform, Children);
1366       }
1367       
1368       ResultNodeOperands.push_back(OpNode);
1369     }
1370     
1371     if (!InstInputsCheck.empty())
1372       I->error("Input operand $" + InstInputsCheck.begin()->first +
1373                " occurs in pattern but not in operands list!");
1374
1375     TreePatternNode *ResultPattern =
1376       new TreePatternNode(I->getRecord(), ResultNodeOperands);
1377     // Copy fully inferred output node type to instruction result pattern.
1378     if (NumResults > 0)
1379       ResultPattern->setTypes(Res0Node->getExtTypes());
1380
1381     // Create and insert the instruction.
1382     DAGInstruction TheInst(I, Results, Operands, InstImpResults, InstImpInputs);
1383     Instructions.insert(std::make_pair(I->getRecord(), TheInst));
1384
1385     // Use a temporary tree pattern to infer all types and make sure that the
1386     // constructed result is correct.  This depends on the instruction already
1387     // being inserted into the Instructions map.
1388     TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
1389     Temp.InferAllTypes();
1390
1391     DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
1392     TheInsertedInst.setResultPattern(Temp.getOnlyTree());
1393     
1394     DEBUG(I->dump());
1395   }
1396    
1397   // If we can, convert the instructions to be patterns that are matched!
1398   for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
1399        E = Instructions.end(); II != E; ++II) {
1400     DAGInstruction &TheInst = II->second;
1401     TreePattern *I = TheInst.getPattern();
1402     if (I == 0) continue;  // No pattern.
1403
1404     if (I->getNumTrees() != 1) {
1405       std::cerr << "CANNOT HANDLE: " << I->getRecord()->getName() << " yet!";
1406       continue;
1407     }
1408     TreePatternNode *Pattern = I->getTree(0);
1409     TreePatternNode *SrcPattern;
1410     if (Pattern->getOperator()->getName() == "set") {
1411       if (Pattern->getNumChildren() != 2)
1412         continue;  // Not a set of a single value (not handled so far)
1413
1414       SrcPattern = Pattern->getChild(1)->clone();    
1415     } else{
1416       // Not a set (store or something?)
1417       SrcPattern = Pattern;
1418     }
1419     
1420     std::string Reason;
1421     if (!SrcPattern->canPatternMatch(Reason, *this))
1422       I->error("Instruction can never match: " + Reason);
1423     
1424     Record *Instr = II->first;
1425     TreePatternNode *DstPattern = TheInst.getResultPattern();
1426     PatternsToMatch.
1427       push_back(PatternToMatch(Instr->getValueAsListInit("Predicates"),
1428                                SrcPattern, DstPattern));
1429   }
1430 }
1431
1432 void DAGISelEmitter::ParsePatterns() {
1433   std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
1434
1435   for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1436     DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
1437     TreePattern *Pattern = new TreePattern(Patterns[i], Tree, true, *this);
1438
1439     // Inline pattern fragments into it.
1440     Pattern->InlinePatternFragments();
1441     
1442     // Infer as many types as possible.  If we cannot infer all of them, we can
1443     // never do anything with this pattern: report it to the user.
1444     if (!Pattern->InferAllTypes())
1445       Pattern->error("Could not infer all types in pattern!");
1446
1447     // Validate that the input pattern is correct.
1448     {
1449       std::map<std::string, TreePatternNode*> InstInputs;
1450       std::map<std::string, TreePatternNode*> InstResults;
1451       std::vector<Record*> InstImpInputs;
1452       std::vector<Record*> InstImpResults;
1453       FindPatternInputsAndOutputs(Pattern, Pattern->getOnlyTree(),
1454                                   InstInputs, InstResults,
1455                                   InstImpInputs, InstImpResults);
1456     }
1457     
1458     ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
1459     if (LI->getSize() == 0) continue;  // no pattern.
1460     
1461     // Parse the instruction.
1462     TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
1463     
1464     // Inline pattern fragments into it.
1465     Result->InlinePatternFragments();
1466     
1467     // Infer as many types as possible.  If we cannot infer all of them, we can
1468     // never do anything with this pattern: report it to the user.
1469     if (!Result->InferAllTypes())
1470       Result->error("Could not infer all types in pattern result!");
1471    
1472     if (Result->getNumTrees() != 1)
1473       Result->error("Cannot handle instructions producing instructions "
1474                     "with temporaries yet!");
1475
1476     // Promote the xform function to be an explicit node if set.
1477     std::vector<TreePatternNode*> ResultNodeOperands;
1478     TreePatternNode *DstPattern = Result->getOnlyTree();
1479     for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
1480       TreePatternNode *OpNode = DstPattern->getChild(ii);
1481       if (Record *Xform = OpNode->getTransformFn()) {
1482         OpNode->setTransformFn(0);
1483         std::vector<TreePatternNode*> Children;
1484         Children.push_back(OpNode);
1485         OpNode = new TreePatternNode(Xform, Children);
1486       }
1487       ResultNodeOperands.push_back(OpNode);
1488     }
1489     DstPattern = Result->getOnlyTree();
1490     if (!DstPattern->isLeaf())
1491       DstPattern = new TreePatternNode(DstPattern->getOperator(),
1492                                        ResultNodeOperands);
1493     DstPattern->setTypes(Result->getOnlyTree()->getExtTypes());
1494     TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
1495     Temp.InferAllTypes();
1496
1497     std::string Reason;
1498     if (!Pattern->getOnlyTree()->canPatternMatch(Reason, *this))
1499       Pattern->error("Pattern can never match: " + Reason);
1500     
1501     PatternsToMatch.
1502       push_back(PatternToMatch(Patterns[i]->getValueAsListInit("Predicates"),
1503                                Pattern->getOnlyTree(),
1504                                Temp.getOnlyTree()));
1505   }
1506 }
1507
1508 /// CombineChildVariants - Given a bunch of permutations of each child of the
1509 /// 'operator' node, put them together in all possible ways.
1510 static void CombineChildVariants(TreePatternNode *Orig, 
1511                const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
1512                                  std::vector<TreePatternNode*> &OutVariants,
1513                                  DAGISelEmitter &ISE) {
1514   // Make sure that each operand has at least one variant to choose from.
1515   for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1516     if (ChildVariants[i].empty())
1517       return;
1518         
1519   // The end result is an all-pairs construction of the resultant pattern.
1520   std::vector<unsigned> Idxs;
1521   Idxs.resize(ChildVariants.size());
1522   bool NotDone = true;
1523   while (NotDone) {
1524     // Create the variant and add it to the output list.
1525     std::vector<TreePatternNode*> NewChildren;
1526     for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1527       NewChildren.push_back(ChildVariants[i][Idxs[i]]);
1528     TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
1529     
1530     // Copy over properties.
1531     R->setName(Orig->getName());
1532     R->setPredicateFn(Orig->getPredicateFn());
1533     R->setTransformFn(Orig->getTransformFn());
1534     R->setTypes(Orig->getExtTypes());
1535     
1536     // If this pattern cannot every match, do not include it as a variant.
1537     std::string ErrString;
1538     if (!R->canPatternMatch(ErrString, ISE)) {
1539       delete R;
1540     } else {
1541       bool AlreadyExists = false;
1542       
1543       // Scan to see if this pattern has already been emitted.  We can get
1544       // duplication due to things like commuting:
1545       //   (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
1546       // which are the same pattern.  Ignore the dups.
1547       for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
1548         if (R->isIsomorphicTo(OutVariants[i])) {
1549           AlreadyExists = true;
1550           break;
1551         }
1552       
1553       if (AlreadyExists)
1554         delete R;
1555       else
1556         OutVariants.push_back(R);
1557     }
1558     
1559     // Increment indices to the next permutation.
1560     NotDone = false;
1561     // Look for something we can increment without causing a wrap-around.
1562     for (unsigned IdxsIdx = 0; IdxsIdx != Idxs.size(); ++IdxsIdx) {
1563       if (++Idxs[IdxsIdx] < ChildVariants[IdxsIdx].size()) {
1564         NotDone = true;   // Found something to increment.
1565         break;
1566       }
1567       Idxs[IdxsIdx] = 0;
1568     }
1569   }
1570 }
1571
1572 /// CombineChildVariants - A helper function for binary operators.
1573 ///
1574 static void CombineChildVariants(TreePatternNode *Orig, 
1575                                  const std::vector<TreePatternNode*> &LHS,
1576                                  const std::vector<TreePatternNode*> &RHS,
1577                                  std::vector<TreePatternNode*> &OutVariants,
1578                                  DAGISelEmitter &ISE) {
1579   std::vector<std::vector<TreePatternNode*> > ChildVariants;
1580   ChildVariants.push_back(LHS);
1581   ChildVariants.push_back(RHS);
1582   CombineChildVariants(Orig, ChildVariants, OutVariants, ISE);
1583 }  
1584
1585
1586 static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
1587                                      std::vector<TreePatternNode *> &Children) {
1588   assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
1589   Record *Operator = N->getOperator();
1590   
1591   // Only permit raw nodes.
1592   if (!N->getName().empty() || !N->getPredicateFn().empty() ||
1593       N->getTransformFn()) {
1594     Children.push_back(N);
1595     return;
1596   }
1597
1598   if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
1599     Children.push_back(N->getChild(0));
1600   else
1601     GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
1602
1603   if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
1604     Children.push_back(N->getChild(1));
1605   else
1606     GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
1607 }
1608
1609 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
1610 /// the (potentially recursive) pattern by using algebraic laws.
1611 ///
1612 static void GenerateVariantsOf(TreePatternNode *N,
1613                                std::vector<TreePatternNode*> &OutVariants,
1614                                DAGISelEmitter &ISE) {
1615   // We cannot permute leaves.
1616   if (N->isLeaf()) {
1617     OutVariants.push_back(N);
1618     return;
1619   }
1620
1621   // Look up interesting info about the node.
1622   const SDNodeInfo *NodeInfo = 0;
1623   
1624   if (!N->getOperator()->isSubClassOf("Intrinsic"))
1625     NodeInfo = &ISE.getSDNodeInfo(N->getOperator());
1626
1627   // If this node is associative, reassociate.
1628   if (NodeInfo && NodeInfo->hasProperty(SDNodeInfo::SDNPAssociative)) {
1629     // Reassociate by pulling together all of the linked operators 
1630     std::vector<TreePatternNode*> MaximalChildren;
1631     GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
1632
1633     // Only handle child sizes of 3.  Otherwise we'll end up trying too many
1634     // permutations.
1635     if (MaximalChildren.size() == 3) {
1636       // Find the variants of all of our maximal children.
1637       std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
1638       GenerateVariantsOf(MaximalChildren[0], AVariants, ISE);
1639       GenerateVariantsOf(MaximalChildren[1], BVariants, ISE);
1640       GenerateVariantsOf(MaximalChildren[2], CVariants, ISE);
1641       
1642       // There are only two ways we can permute the tree:
1643       //   (A op B) op C    and    A op (B op C)
1644       // Within these forms, we can also permute A/B/C.
1645       
1646       // Generate legal pair permutations of A/B/C.
1647       std::vector<TreePatternNode*> ABVariants;
1648       std::vector<TreePatternNode*> BAVariants;
1649       std::vector<TreePatternNode*> ACVariants;
1650       std::vector<TreePatternNode*> CAVariants;
1651       std::vector<TreePatternNode*> BCVariants;
1652       std::vector<TreePatternNode*> CBVariants;
1653       CombineChildVariants(N, AVariants, BVariants, ABVariants, ISE);
1654       CombineChildVariants(N, BVariants, AVariants, BAVariants, ISE);
1655       CombineChildVariants(N, AVariants, CVariants, ACVariants, ISE);
1656       CombineChildVariants(N, CVariants, AVariants, CAVariants, ISE);
1657       CombineChildVariants(N, BVariants, CVariants, BCVariants, ISE);
1658       CombineChildVariants(N, CVariants, BVariants, CBVariants, ISE);
1659
1660       // Combine those into the result: (x op x) op x
1661       CombineChildVariants(N, ABVariants, CVariants, OutVariants, ISE);
1662       CombineChildVariants(N, BAVariants, CVariants, OutVariants, ISE);
1663       CombineChildVariants(N, ACVariants, BVariants, OutVariants, ISE);
1664       CombineChildVariants(N, CAVariants, BVariants, OutVariants, ISE);
1665       CombineChildVariants(N, BCVariants, AVariants, OutVariants, ISE);
1666       CombineChildVariants(N, CBVariants, AVariants, OutVariants, ISE);
1667
1668       // Combine those into the result: x op (x op x)
1669       CombineChildVariants(N, CVariants, ABVariants, OutVariants, ISE);
1670       CombineChildVariants(N, CVariants, BAVariants, OutVariants, ISE);
1671       CombineChildVariants(N, BVariants, ACVariants, OutVariants, ISE);
1672       CombineChildVariants(N, BVariants, CAVariants, OutVariants, ISE);
1673       CombineChildVariants(N, AVariants, BCVariants, OutVariants, ISE);
1674       CombineChildVariants(N, AVariants, CBVariants, OutVariants, ISE);
1675       return;
1676     }
1677   }
1678   
1679   // Compute permutations of all children.
1680   std::vector<std::vector<TreePatternNode*> > ChildVariants;
1681   ChildVariants.resize(N->getNumChildren());
1682   for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1683     GenerateVariantsOf(N->getChild(i), ChildVariants[i], ISE);
1684
1685   // Build all permutations based on how the children were formed.
1686   CombineChildVariants(N, ChildVariants, OutVariants, ISE);
1687
1688   // If this node is commutative, consider the commuted order.
1689   if (NodeInfo && NodeInfo->hasProperty(SDNodeInfo::SDNPCommutative)) {
1690     assert(N->getNumChildren()==2 &&"Commutative but doesn't have 2 children!");
1691     // Consider the commuted order.
1692     CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
1693                          OutVariants, ISE);
1694   }
1695 }
1696
1697
1698 // GenerateVariants - Generate variants.  For example, commutative patterns can
1699 // match multiple ways.  Add them to PatternsToMatch as well.
1700 void DAGISelEmitter::GenerateVariants() {
1701   
1702   DEBUG(std::cerr << "Generating instruction variants.\n");
1703   
1704   // Loop over all of the patterns we've collected, checking to see if we can
1705   // generate variants of the instruction, through the exploitation of
1706   // identities.  This permits the target to provide agressive matching without
1707   // the .td file having to contain tons of variants of instructions.
1708   //
1709   // Note that this loop adds new patterns to the PatternsToMatch list, but we
1710   // intentionally do not reconsider these.  Any variants of added patterns have
1711   // already been added.
1712   //
1713   for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
1714     std::vector<TreePatternNode*> Variants;
1715     GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this);
1716
1717     assert(!Variants.empty() && "Must create at least original variant!");
1718     Variants.erase(Variants.begin());  // Remove the original pattern.
1719
1720     if (Variants.empty())  // No variants for this pattern.
1721       continue;
1722
1723     DEBUG(std::cerr << "FOUND VARIANTS OF: ";
1724           PatternsToMatch[i].getSrcPattern()->dump();
1725           std::cerr << "\n");
1726
1727     for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
1728       TreePatternNode *Variant = Variants[v];
1729
1730       DEBUG(std::cerr << "  VAR#" << v <<  ": ";
1731             Variant->dump();
1732             std::cerr << "\n");
1733       
1734       // Scan to see if an instruction or explicit pattern already matches this.
1735       bool AlreadyExists = false;
1736       for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
1737         // Check to see if this variant already exists.
1738         if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern())) {
1739           DEBUG(std::cerr << "  *** ALREADY EXISTS, ignoring variant.\n");
1740           AlreadyExists = true;
1741           break;
1742         }
1743       }
1744       // If we already have it, ignore the variant.
1745       if (AlreadyExists) continue;
1746
1747       // Otherwise, add it to the list of patterns we have.
1748       PatternsToMatch.
1749         push_back(PatternToMatch(PatternsToMatch[i].getPredicates(),
1750                                  Variant, PatternsToMatch[i].getDstPattern()));
1751     }
1752
1753     DEBUG(std::cerr << "\n");
1754   }
1755 }
1756
1757
1758 // NodeIsComplexPattern - return true if N is a leaf node and a subclass of
1759 // ComplexPattern.
1760 static bool NodeIsComplexPattern(TreePatternNode *N)
1761 {
1762   return (N->isLeaf() &&
1763           dynamic_cast<DefInit*>(N->getLeafValue()) &&
1764           static_cast<DefInit*>(N->getLeafValue())->getDef()->
1765           isSubClassOf("ComplexPattern"));
1766 }
1767
1768 // NodeGetComplexPattern - return the pointer to the ComplexPattern if N
1769 // is a leaf node and a subclass of ComplexPattern, else it returns NULL.
1770 static const ComplexPattern *NodeGetComplexPattern(TreePatternNode *N,
1771                                                    DAGISelEmitter &ISE)
1772 {
1773   if (N->isLeaf() &&
1774       dynamic_cast<DefInit*>(N->getLeafValue()) &&
1775       static_cast<DefInit*>(N->getLeafValue())->getDef()->
1776       isSubClassOf("ComplexPattern")) {
1777     return &ISE.getComplexPattern(static_cast<DefInit*>(N->getLeafValue())
1778                                   ->getDef());
1779   }
1780   return NULL;
1781 }
1782
1783 /// getPatternSize - Return the 'size' of this pattern.  We want to match large
1784 /// patterns before small ones.  This is used to determine the size of a
1785 /// pattern.
1786 static unsigned getPatternSize(TreePatternNode *P, DAGISelEmitter &ISE) {
1787   assert(isExtIntegerInVTs(P->getExtTypes()) || 
1788          isExtFloatingPointInVTs(P->getExtTypes()) ||
1789          P->getExtTypeNum(0) == MVT::isVoid ||
1790          P->getExtTypeNum(0) == MVT::Flag && 
1791          "Not a valid pattern node to size!");
1792   unsigned Size = 2;  // The node itself.
1793   // If the root node is a ConstantSDNode, increases its size.
1794   // e.g. (set R32:$dst, 0).
1795   if (P->isLeaf() && dynamic_cast<IntInit*>(P->getLeafValue()))
1796     Size++;
1797
1798   // FIXME: This is a hack to statically increase the priority of patterns
1799   // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
1800   // Later we can allow complexity / cost for each pattern to be (optionally)
1801   // specified. To get best possible pattern match we'll need to dynamically
1802   // calculate the complexity of all patterns a dag can potentially map to.
1803   const ComplexPattern *AM = NodeGetComplexPattern(P, ISE);
1804   if (AM)
1805     Size += AM->getNumOperands() * 2;
1806
1807   // If this node has some predicate function that must match, it adds to the
1808   // complexity of this node.
1809   if (!P->getPredicateFn().empty())
1810     ++Size;
1811   
1812   // Count children in the count if they are also nodes.
1813   for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
1814     TreePatternNode *Child = P->getChild(i);
1815     if (!Child->isLeaf() && Child->getExtTypeNum(0) != MVT::Other)
1816       Size += getPatternSize(Child, ISE);
1817     else if (Child->isLeaf()) {
1818       if (dynamic_cast<IntInit*>(Child->getLeafValue())) 
1819         Size += 3;  // Matches a ConstantSDNode (+2) and a specific value (+1).
1820       else if (NodeIsComplexPattern(Child))
1821         Size += getPatternSize(Child, ISE);
1822       else if (!Child->getPredicateFn().empty())
1823         ++Size;
1824     }
1825   }
1826   
1827   return Size;
1828 }
1829
1830 /// getResultPatternCost - Compute the number of instructions for this pattern.
1831 /// This is a temporary hack.  We should really include the instruction
1832 /// latencies in this calculation.
1833 static unsigned getResultPatternCost(TreePatternNode *P, DAGISelEmitter &ISE) {
1834   if (P->isLeaf()) return 0;
1835   
1836   unsigned Cost = 0;
1837   Record *Op = P->getOperator();
1838   if (Op->isSubClassOf("Instruction")) {
1839     Cost++;
1840     CodeGenInstruction &II = ISE.getTargetInfo().getInstruction(Op->getName());
1841     if (II.usesCustomDAGSchedInserter)
1842       Cost += 10;
1843   }
1844   for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
1845     Cost += getResultPatternCost(P->getChild(i), ISE);
1846   return Cost;
1847 }
1848
1849 // PatternSortingPredicate - return true if we prefer to match LHS before RHS.
1850 // In particular, we want to match maximal patterns first and lowest cost within
1851 // a particular complexity first.
1852 struct PatternSortingPredicate {
1853   PatternSortingPredicate(DAGISelEmitter &ise) : ISE(ise) {};
1854   DAGISelEmitter &ISE;
1855
1856   bool operator()(PatternToMatch *LHS,
1857                   PatternToMatch *RHS) {
1858     unsigned LHSSize = getPatternSize(LHS->getSrcPattern(), ISE);
1859     unsigned RHSSize = getPatternSize(RHS->getSrcPattern(), ISE);
1860     if (LHSSize > RHSSize) return true;   // LHS -> bigger -> less cost
1861     if (LHSSize < RHSSize) return false;
1862     
1863     // If the patterns have equal complexity, compare generated instruction cost
1864     return getResultPatternCost(LHS->getDstPattern(), ISE) <
1865       getResultPatternCost(RHS->getDstPattern(), ISE);
1866   }
1867 };
1868
1869 /// getRegisterValueType - Look up and return the first ValueType of specified 
1870 /// RegisterClass record
1871 static MVT::ValueType getRegisterValueType(Record *R, const CodeGenTarget &T) {
1872   if (const CodeGenRegisterClass *RC = T.getRegisterClassForRegister(R))
1873     return RC->getValueTypeNum(0);
1874   return MVT::Other;
1875 }
1876
1877
1878 /// RemoveAllTypes - A quick recursive walk over a pattern which removes all
1879 /// type information from it.
1880 static void RemoveAllTypes(TreePatternNode *N) {
1881   N->removeTypes();
1882   if (!N->isLeaf())
1883     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1884       RemoveAllTypes(N->getChild(i));
1885 }
1886
1887 Record *DAGISelEmitter::getSDNodeNamed(const std::string &Name) const {
1888   Record *N = Records.getDef(Name);
1889   assert(N && N->isSubClassOf("SDNode") && "Bad argument");
1890   return N;
1891 }
1892
1893 /// NodeHasProperty - return true if TreePatternNode has the specified
1894 /// property.
1895 static bool NodeHasProperty(TreePatternNode *N, SDNodeInfo::SDNP Property,
1896                             DAGISelEmitter &ISE)
1897 {
1898   if (N->isLeaf()) return false;
1899   Record *Operator = N->getOperator();
1900   if (!Operator->isSubClassOf("SDNode")) return false;
1901
1902   const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(Operator);
1903   return NodeInfo.hasProperty(Property);
1904 }
1905
1906 static bool PatternHasProperty(TreePatternNode *N, SDNodeInfo::SDNP Property,
1907                                DAGISelEmitter &ISE)
1908 {
1909   if (NodeHasProperty(N, Property, ISE))
1910     return true;
1911
1912   for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
1913     TreePatternNode *Child = N->getChild(i);
1914     if (PatternHasProperty(Child, Property, ISE))
1915       return true;
1916   }
1917
1918   return false;
1919 }
1920
1921 class PatternCodeEmitter {
1922 private:
1923   DAGISelEmitter &ISE;
1924
1925   // Predicates.
1926   ListInit *Predicates;
1927   // Instruction selector pattern.
1928   TreePatternNode *Pattern;
1929   // Matched instruction.
1930   TreePatternNode *Instruction;
1931   
1932   // Node to name mapping
1933   std::map<std::string, std::string> VariableMap;
1934   // Node to operator mapping
1935   std::map<std::string, Record*> OperatorMap;
1936   // Names of all the folded nodes which produce chains.
1937   std::vector<std::pair<std::string, unsigned> > FoldedChains;
1938   std::set<std::string> Duplicates;
1939
1940   /// GeneratedCode - This is the buffer that we emit code to.  The first bool
1941   /// indicates whether this is an exit predicate (something that should be
1942   /// tested, and if true, the match fails) [when true] or normal code to emit
1943   /// [when false].
1944   std::vector<std::pair<bool, std::string> > &GeneratedCode;
1945   /// GeneratedDecl - This is the set of all SDOperand declarations needed for
1946   /// the set of patterns for each top-level opcode.
1947   std::set<std::pair<bool, std::string> > &GeneratedDecl;
1948
1949   std::string ChainName;
1950   bool NewTF;
1951   bool DoReplace;
1952   unsigned TmpNo;
1953   
1954   void emitCheck(const std::string &S) {
1955     if (!S.empty())
1956       GeneratedCode.push_back(std::make_pair(true, S));
1957   }
1958   void emitCode(const std::string &S) {
1959     if (!S.empty())
1960       GeneratedCode.push_back(std::make_pair(false, S));
1961   }
1962   void emitDecl(const std::string &S, bool isSDNode=false) {
1963     assert(!S.empty() && "Invalid declaration");
1964     GeneratedDecl.insert(std::make_pair(isSDNode, S));
1965   }
1966 public:
1967   PatternCodeEmitter(DAGISelEmitter &ise, ListInit *preds,
1968                      TreePatternNode *pattern, TreePatternNode *instr,
1969                      std::vector<std::pair<bool, std::string> > &gc,
1970                      std::set<std::pair<bool, std::string> > &gd,
1971                      bool dorep)
1972   : ISE(ise), Predicates(preds), Pattern(pattern), Instruction(instr),
1973     GeneratedCode(gc), GeneratedDecl(gd),
1974     NewTF(false), DoReplace(dorep), TmpNo(0) {}
1975
1976   /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
1977   /// if the match fails. At this point, we already know that the opcode for N
1978   /// matches, and the SDNode for the result has the RootName specified name.
1979   void EmitMatchCode(TreePatternNode *N, TreePatternNode *P,
1980                      const std::string &RootName, const std::string &ParentName,
1981                      const std::string &ChainSuffix, bool &FoundChain) {
1982     bool isRoot = (P == NULL);
1983     // Emit instruction predicates. Each predicate is just a string for now.
1984     if (isRoot) {
1985       std::string PredicateCheck;
1986       for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
1987         if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
1988           Record *Def = Pred->getDef();
1989           if (!Def->isSubClassOf("Predicate")) {
1990             Def->dump();
1991             assert(0 && "Unknown predicate type!");
1992           }
1993           if (!PredicateCheck.empty())
1994             PredicateCheck += " || ";
1995           PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
1996         }
1997       }
1998       
1999       emitCheck(PredicateCheck);
2000     }
2001
2002     if (N->isLeaf()) {
2003       if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
2004         emitCheck("cast<ConstantSDNode>(" + RootName +
2005                   ")->getSignExtended() == " + itostr(II->getValue()));
2006         return;
2007       } else if (!NodeIsComplexPattern(N)) {
2008         assert(0 && "Cannot match this as a leaf value!");
2009         abort();
2010       }
2011     }
2012   
2013     // If this node has a name associated with it, capture it in VariableMap. If
2014     // we already saw this in the pattern, emit code to verify dagness.
2015     if (!N->getName().empty()) {
2016       std::string &VarMapEntry = VariableMap[N->getName()];
2017       if (VarMapEntry.empty()) {
2018         VarMapEntry = RootName;
2019       } else {
2020         // If we get here, this is a second reference to a specific name.  Since
2021         // we already have checked that the first reference is valid, we don't
2022         // have to recursively match it, just check that it's the same as the
2023         // previously named thing.
2024         emitCheck(VarMapEntry + " == " + RootName);
2025         return;
2026       }
2027
2028       if (!N->isLeaf())
2029         OperatorMap[N->getName()] = N->getOperator();
2030     }
2031
2032
2033     // Emit code to load the child nodes and match their contents recursively.
2034     unsigned OpNo = 0;
2035     bool NodeHasChain = NodeHasProperty   (N, SDNodeInfo::SDNPHasChain, ISE);
2036     bool HasChain     = PatternHasProperty(N, SDNodeInfo::SDNPHasChain, ISE);
2037     bool HasOutFlag   = PatternHasProperty(N, SDNodeInfo::SDNPOutFlag,  ISE);
2038     bool EmittedUseCheck = false;
2039     bool EmittedSlctedCheck = false;
2040     if (HasChain) {
2041       if (NodeHasChain)
2042         OpNo = 1;
2043       if (!isRoot) {
2044         const SDNodeInfo &CInfo = ISE.getSDNodeInfo(N->getOperator());
2045         // Multiple uses of actual result?
2046         emitCheck(RootName + ".hasOneUse()");
2047         EmittedUseCheck = true;
2048         // hasOneUse() check is not strong enough. If the original node has
2049         // already been selected, it may have been replaced with another.
2050         for (unsigned j = 0; j != CInfo.getNumResults(); j++)
2051           emitCheck("!CodeGenMap.count(" + RootName + ".getValue(" + utostr(j) +
2052                     "))");
2053         
2054         EmittedSlctedCheck = true;
2055         if (NodeHasChain) {
2056           // FIXME: Don't fold if 1) the parent node writes a flag, 2) the node
2057           // has a chain use.
2058           // This a workaround for this problem:
2059           //
2060           //          [ch, r : ld]
2061           //             ^ ^
2062           //             | |
2063           //      [XX]--/   \- [flag : cmp]
2064           //       ^             ^
2065           //       |             |
2066           //       \---[br flag]-
2067           //
2068           // cmp + br should be considered as a single node as they are flagged
2069           // together. So, if the ld is folded into the cmp, the XX node in the
2070           // graph is now both an operand and a use of the ld/cmp/br node.
2071           if (NodeHasProperty(P, SDNodeInfo::SDNPOutFlag, ISE))
2072             emitCheck(ParentName + ".Val->isOnlyUse(" +  RootName + ".Val)");
2073
2074           // If the immediate use can somehow reach this node through another
2075           // path, then can't fold it either or it will create a cycle.
2076           // e.g. In the following diagram, XX can reach ld through YY. If
2077           // ld is folded into XX, then YY is both a predecessor and a successor
2078           // of XX.
2079           //
2080           //         [ld]
2081           //         ^  ^
2082           //         |  |
2083           //        /   \---
2084           //      /        [YY]
2085           //      |         ^
2086           //     [XX]-------|
2087           const SDNodeInfo &PInfo = ISE.getSDNodeInfo(P->getOperator());
2088           if (PInfo.getNumOperands() > 1 ||
2089               PInfo.hasProperty(SDNodeInfo::SDNPHasChain) ||
2090               PInfo.hasProperty(SDNodeInfo::SDNPInFlag) ||
2091               PInfo.hasProperty(SDNodeInfo::SDNPOptInFlag))
2092             if (PInfo.getNumOperands() > 1) {
2093               emitCheck("!isNonImmUse(" + ParentName + ".Val, " + RootName +
2094                         ".Val)");
2095             } else {
2096               emitCheck("(" + ParentName + ".getNumOperands() == 1 || !" +
2097                         "isNonImmUse(" + ParentName + ".Val, " + RootName +
2098                         ".Val))");
2099             }
2100         }
2101       }
2102
2103       if (NodeHasChain) {
2104         ChainName = "Chain" + ChainSuffix;
2105         emitDecl(ChainName);
2106         if (FoundChain) {
2107          // FIXME: temporary workaround for a common case where chain
2108          // is a TokenFactor and the previous "inner" chain is an operand.
2109           NewTF = true;
2110           emitDecl("OldTF", true);
2111           emitCheck("(" + ChainName + " = UpdateFoldedChain(CurDAG, " +
2112                     RootName + ".Val, Chain.Val, OldTF)).Val");
2113         } else {
2114           FoundChain = true;
2115           emitCode(ChainName + " = " + RootName + ".getOperand(0);");
2116         }
2117       }
2118     }
2119
2120     // Don't fold any node which reads or writes a flag and has multiple uses.
2121     // FIXME: We really need to separate the concepts of flag and "glue". Those
2122     // real flag results, e.g. X86CMP output, can have multiple uses.
2123     // FIXME: If the optional incoming flag does not exist. Then it is ok to
2124     // fold it.
2125     if (!isRoot &&
2126         (PatternHasProperty(N, SDNodeInfo::SDNPInFlag, ISE) ||
2127          PatternHasProperty(N, SDNodeInfo::SDNPOptInFlag, ISE) ||
2128          PatternHasProperty(N, SDNodeInfo::SDNPOutFlag, ISE))) {
2129       const SDNodeInfo &CInfo = ISE.getSDNodeInfo(N->getOperator());
2130       if (!EmittedUseCheck) {
2131         // Multiple uses of actual result?
2132         emitCheck(RootName + ".hasOneUse()");
2133       }
2134       if (!EmittedSlctedCheck)
2135         // hasOneUse() check is not strong enough. If the original node has
2136         // already been selected, it may have been replaced with another.
2137         for (unsigned j = 0; j < CInfo.getNumResults(); j++)
2138           emitCheck("!CodeGenMap.count(" + RootName + ".getValue(" + utostr(j) +
2139                     "))");
2140     }
2141
2142     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
2143       emitDecl(RootName + utostr(OpNo));
2144       emitCode(RootName + utostr(OpNo) + " = " +
2145                RootName + ".getOperand(" +utostr(OpNo) + ");");
2146       TreePatternNode *Child = N->getChild(i);
2147     
2148       if (!Child->isLeaf()) {
2149         // If it's not a leaf, recursively match.
2150         const SDNodeInfo &CInfo = ISE.getSDNodeInfo(Child->getOperator());
2151         emitCheck(RootName + utostr(OpNo) + ".getOpcode() == " +
2152                   CInfo.getEnumName());
2153         EmitMatchCode(Child, N, RootName + utostr(OpNo), RootName,
2154                       ChainSuffix + utostr(OpNo), FoundChain);
2155         if (NodeHasProperty(Child, SDNodeInfo::SDNPHasChain, ISE))
2156           FoldedChains.push_back(std::make_pair(RootName + utostr(OpNo),
2157                                                 CInfo.getNumResults()));
2158       } else {
2159         // If this child has a name associated with it, capture it in VarMap. If
2160         // we already saw this in the pattern, emit code to verify dagness.
2161         if (!Child->getName().empty()) {
2162           std::string &VarMapEntry = VariableMap[Child->getName()];
2163           if (VarMapEntry.empty()) {
2164             VarMapEntry = RootName + utostr(OpNo);
2165           } else {
2166             // If we get here, this is a second reference to a specific name.
2167             // Since we already have checked that the first reference is valid,
2168             // we don't have to recursively match it, just check that it's the
2169             // same as the previously named thing.
2170             emitCheck(VarMapEntry + " == " + RootName + utostr(OpNo));
2171             Duplicates.insert(RootName + utostr(OpNo));
2172             continue;
2173           }
2174         }
2175       
2176         // Handle leaves of various types.
2177         if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2178           Record *LeafRec = DI->getDef();
2179           if (LeafRec->isSubClassOf("RegisterClass")) {
2180             // Handle register references.  Nothing to do here.
2181           } else if (LeafRec->isSubClassOf("Register")) {
2182             // Handle register references.
2183           } else if (LeafRec->isSubClassOf("ComplexPattern")) {
2184             // Handle complex pattern. Nothing to do here.
2185           } else if (LeafRec->getName() == "srcvalue") {
2186             // Place holder for SRCVALUE nodes. Nothing to do here.
2187           } else if (LeafRec->isSubClassOf("ValueType")) {
2188             // Make sure this is the specified value type.
2189             emitCheck("cast<VTSDNode>(" + RootName + utostr(OpNo) +
2190                       ")->getVT() == MVT::" + LeafRec->getName());
2191           } else if (LeafRec->isSubClassOf("CondCode")) {
2192             // Make sure this is the specified cond code.
2193             emitCheck("cast<CondCodeSDNode>(" + RootName + utostr(OpNo) +
2194                       ")->get() == ISD::" + LeafRec->getName());
2195           } else {
2196             Child->dump();
2197             std::cerr << " ";
2198             assert(0 && "Unknown leaf type!");
2199           }
2200         } else if (IntInit *II =
2201                        dynamic_cast<IntInit*>(Child->getLeafValue())) {
2202           emitCheck("isa<ConstantSDNode>(" + RootName + utostr(OpNo) + ")");
2203           unsigned CTmp = TmpNo++;
2204           emitCode("int64_t CN"+utostr(CTmp)+" = cast<ConstantSDNode>("+
2205                    RootName + utostr(OpNo) + ")->getSignExtended();");
2206
2207           emitCheck("CN" + utostr(CTmp) + " == " +itostr(II->getValue()));
2208         } else {
2209           Child->dump();
2210           assert(0 && "Unknown leaf type!");
2211         }
2212       }
2213     }
2214
2215     // If there is a node predicate for this, emit the call.
2216     if (!N->getPredicateFn().empty())
2217       emitCheck(N->getPredicateFn() + "(" + RootName + ".Val)");
2218   }
2219
2220   /// EmitResultCode - Emit the action for a pattern.  Now that it has matched
2221   /// we actually have to build a DAG!
2222   std::pair<unsigned, unsigned>
2223   EmitResultCode(TreePatternNode *N, bool LikeLeaf = false,
2224                  bool isRoot = false) {
2225     // This is something selected from the pattern we matched.
2226     if (!N->getName().empty()) {
2227       std::string &Val = VariableMap[N->getName()];
2228       assert(!Val.empty() &&
2229              "Variable referenced but not defined and not caught earlier!");
2230       if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
2231         // Already selected this operand, just return the tmpval.
2232         return std::make_pair(1, atoi(Val.c_str()+3));
2233       }
2234
2235       const ComplexPattern *CP;
2236       unsigned ResNo = TmpNo++;
2237       unsigned NumRes = 1;
2238       if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
2239         assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
2240         std::string CastType;
2241         switch (N->getTypeNum(0)) {
2242         default: assert(0 && "Unknown type for constant node!");
2243         case MVT::i1:  CastType = "bool"; break;
2244         case MVT::i8:  CastType = "unsigned char"; break;
2245         case MVT::i16: CastType = "unsigned short"; break;
2246         case MVT::i32: CastType = "unsigned"; break;
2247         case MVT::i64: CastType = "uint64_t"; break;
2248         }
2249         emitCode(CastType + " Tmp" + utostr(ResNo) + "C = (" + CastType + 
2250                  ")cast<ConstantSDNode>(" + Val + ")->getValue();");
2251         emitDecl("Tmp" + utostr(ResNo));
2252         emitCode("Tmp" + utostr(ResNo) + 
2253                  " = CurDAG->getTargetConstant(Tmp" + utostr(ResNo) + 
2254                  "C, MVT::" + getEnumName(N->getTypeNum(0)) + ");");
2255       } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
2256         Record *Op = OperatorMap[N->getName()];
2257         // Transform ExternalSymbol to TargetExternalSymbol
2258         if (Op && Op->getName() == "externalsym") {
2259           emitDecl("Tmp" + utostr(ResNo));
2260           emitCode("Tmp" + utostr(ResNo) + " = CurDAG->getTarget"
2261                    "ExternalSymbol(cast<ExternalSymbolSDNode>(" +
2262                    Val + ")->getSymbol(), MVT::" +
2263                    getEnumName(N->getTypeNum(0)) + ");");
2264         } else {
2265           emitDecl("Tmp" + utostr(ResNo));
2266           emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
2267         }
2268       } else if (!N->isLeaf() && N->getOperator()->getName() == "tglobaladdr") {
2269         Record *Op = OperatorMap[N->getName()];
2270         // Transform GlobalAddress to TargetGlobalAddress
2271         if (Op && Op->getName() == "globaladdr") {
2272           emitDecl("Tmp" + utostr(ResNo));
2273           emitCode("Tmp" + utostr(ResNo) + " = CurDAG->getTarget"
2274                    "GlobalAddress(cast<GlobalAddressSDNode>(" + Val +
2275                    ")->getGlobal(), MVT::" + getEnumName(N->getTypeNum(0)) +
2276                    ");");
2277         } else {
2278           emitDecl("Tmp" + utostr(ResNo));
2279           emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
2280         }
2281       } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
2282         emitDecl("Tmp" + utostr(ResNo));
2283         emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
2284       } else if (!N->isLeaf() && N->getOperator()->getName() == "tconstpool") {
2285         emitDecl("Tmp" + utostr(ResNo));
2286         emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
2287       } else if (N->isLeaf() && (CP = NodeGetComplexPattern(N, ISE))) {
2288         std::string Fn = CP->getSelectFunc();
2289         NumRes = CP->getNumOperands();
2290         for (unsigned i = 0; i < NumRes; ++i)
2291           emitDecl("Tmp" + utostr(i+ResNo));
2292
2293         std::string Code = Fn + "(" + Val;
2294         for (unsigned i = 0; i < NumRes; i++)
2295           Code += ", Tmp" + utostr(i + ResNo);
2296         emitCheck(Code + ")");
2297
2298         for (unsigned i = 0; i < NumRes; ++i)
2299           emitCode("Select(Tmp" + utostr(i+ResNo) + ", Tmp" +
2300                    utostr(i+ResNo) + ");");
2301
2302         TmpNo = ResNo + NumRes;
2303       } else {
2304         emitDecl("Tmp" + utostr(ResNo));
2305         // This node, probably wrapped in a SDNodeXForms, behaves like a leaf
2306         // node even if it isn't one. Don't select it.
2307         if (LikeLeaf)
2308           emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
2309         else
2310           emitCode("Select(Tmp" + utostr(ResNo) + ", " + Val + ");");
2311
2312         if (isRoot && N->isLeaf()) {
2313           emitCode("Result = Tmp" + utostr(ResNo) + ";");
2314           emitCode("return;");
2315         }
2316       }
2317       // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
2318       // value if used multiple times by this pattern result.
2319       Val = "Tmp"+utostr(ResNo);
2320       return std::make_pair(NumRes, ResNo);
2321     }
2322     if (N->isLeaf()) {
2323       // If this is an explicit register reference, handle it.
2324       if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
2325         unsigned ResNo = TmpNo++;
2326         if (DI->getDef()->isSubClassOf("Register")) {
2327           emitDecl("Tmp" + utostr(ResNo));
2328           emitCode("Tmp" + utostr(ResNo) + " = CurDAG->getRegister(" +
2329                    ISE.getQualifiedName(DI->getDef()) + ", MVT::" +
2330                    getEnumName(N->getTypeNum(0)) + ");");
2331           return std::make_pair(1, ResNo);
2332         }
2333       } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
2334         unsigned ResNo = TmpNo++;
2335         assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
2336         emitDecl("Tmp" + utostr(ResNo));
2337         emitCode("Tmp" + utostr(ResNo) + 
2338                  " = CurDAG->getTargetConstant(" + itostr(II->getValue()) +
2339                  ", MVT::" + getEnumName(N->getTypeNum(0)) + ");");
2340         return std::make_pair(1, ResNo);
2341       }
2342     
2343       N->dump();
2344       assert(0 && "Unknown leaf type!");
2345       return std::make_pair(1, ~0U);
2346     }
2347
2348     Record *Op = N->getOperator();
2349     if (Op->isSubClassOf("Instruction")) {
2350       const CodeGenTarget &CGT = ISE.getTargetInfo();
2351       CodeGenInstruction &II = CGT.getInstruction(Op->getName());
2352       const DAGInstruction &Inst = ISE.getInstruction(Op);
2353       bool HasImpInputs  = Inst.getNumImpOperands() > 0;
2354       bool HasImpResults = Inst.getNumImpResults() > 0;
2355       bool HasOptInFlag = isRoot &&
2356         PatternHasProperty(Pattern, SDNodeInfo::SDNPOptInFlag, ISE);
2357       bool HasInFlag  = isRoot &&
2358         PatternHasProperty(Pattern, SDNodeInfo::SDNPInFlag, ISE);
2359       bool NodeHasOutFlag = HasImpResults ||
2360         (isRoot && PatternHasProperty(Pattern, SDNodeInfo::SDNPOutFlag, ISE));
2361       bool NodeHasChain =
2362         NodeHasProperty(Pattern, SDNodeInfo::SDNPHasChain, ISE);
2363       bool HasChain   = II.hasCtrlDep ||
2364         (isRoot && PatternHasProperty(Pattern, SDNodeInfo::SDNPHasChain, ISE));
2365
2366       if (HasInFlag || NodeHasOutFlag || HasOptInFlag || HasImpInputs)
2367         emitDecl("InFlag");
2368       if (HasOptInFlag)
2369         emitCode("bool HasOptInFlag = false;");
2370
2371       // How many results is this pattern expected to produce?
2372       unsigned PatResults = 0;
2373       for (unsigned i = 0, e = Pattern->getExtTypes().size(); i != e; i++) {
2374         MVT::ValueType VT = Pattern->getTypeNum(i);
2375         if (VT != MVT::isVoid && VT != MVT::Flag)
2376           PatResults++;
2377       }
2378
2379       // Determine operand emission order. Complex pattern first.
2380       std::vector<std::pair<unsigned, TreePatternNode*> > EmitOrder;
2381       std::vector<std::pair<unsigned, TreePatternNode*> >::iterator OI;
2382       for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2383         TreePatternNode *Child = N->getChild(i);
2384         if (i == 0) {
2385           EmitOrder.push_back(std::make_pair(i, Child));
2386           OI = EmitOrder.begin();
2387         } else if (NodeIsComplexPattern(Child)) {
2388           OI = EmitOrder.insert(OI, std::make_pair(i, Child));
2389         } else {
2390           EmitOrder.push_back(std::make_pair(i, Child));
2391         }
2392       }
2393
2394       // Emit all of the operands.
2395       std::vector<std::pair<unsigned, unsigned> > NumTemps(EmitOrder.size());
2396       for (unsigned i = 0, e = EmitOrder.size(); i != e; ++i) {
2397         unsigned OpOrder       = EmitOrder[i].first;
2398         TreePatternNode *Child = EmitOrder[i].second;
2399         std::pair<unsigned, unsigned> NumTemp =  EmitResultCode(Child);
2400         NumTemps[OpOrder] = NumTemp;
2401       }
2402
2403       // List all the operands in the right order.
2404       std::vector<unsigned> Ops;
2405       for (unsigned i = 0, e = NumTemps.size(); i != e; i++) {
2406         for (unsigned j = 0; j < NumTemps[i].first; j++)
2407           Ops.push_back(NumTemps[i].second + j);
2408       }
2409
2410       // Emit all the chain and CopyToReg stuff.
2411       bool ChainEmitted = HasChain;
2412       if (HasChain)
2413         emitCode("Select(" + ChainName + ", " + ChainName + ");");
2414       if (HasInFlag || HasOptInFlag || HasImpInputs)
2415         EmitInFlagSelectCode(Pattern, "N", ChainEmitted, true);
2416
2417       unsigned NumResults = Inst.getNumResults();    
2418       unsigned ResNo = TmpNo++;
2419       if (!isRoot) {
2420         emitDecl("Tmp" + utostr(ResNo));
2421         std::string Code =
2422           "Tmp" + utostr(ResNo) + " = SDOperand(CurDAG->getTargetNode(" +
2423           II.Namespace + "::" + II.TheDef->getName();
2424         if (N->getTypeNum(0) != MVT::isVoid)
2425           Code += ", MVT::" + getEnumName(N->getTypeNum(0));
2426         if (NodeHasOutFlag)
2427           Code += ", MVT::Flag";
2428
2429         unsigned LastOp = 0;
2430         for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2431           LastOp = Ops[i];
2432           Code += ", Tmp" + utostr(LastOp);
2433         }
2434         emitCode(Code + "), 0);");
2435         if (HasChain) {
2436           // Must have at least one result
2437           emitCode(ChainName + " = Tmp" + utostr(LastOp) + ".getValue(" +
2438                    utostr(NumResults) + ");");
2439         }
2440       } else if (HasChain || NodeHasOutFlag) {
2441         if (HasOptInFlag) {
2442           unsigned FlagNo = (unsigned) NodeHasChain + Pattern->getNumChildren();
2443           emitDecl("ResNode", true);
2444           emitCode("if (HasOptInFlag)");
2445           std::string Code = "  ResNode = CurDAG->getTargetNode(" +
2446              II.Namespace + "::" + II.TheDef->getName();
2447
2448           // Output order: results, chain, flags
2449           // Result types.
2450           if (NumResults > 0) { 
2451             if (N->getTypeNum(0) != MVT::isVoid)
2452               Code += ", MVT::" + getEnumName(N->getTypeNum(0));
2453           }
2454           if (HasChain)
2455             Code += ", MVT::Other";
2456           if (NodeHasOutFlag)
2457             Code += ", MVT::Flag";
2458
2459           // Inputs.
2460           for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2461             Code += ", Tmp" + utostr(Ops[i]);
2462           if (HasChain)  Code += ", " + ChainName;
2463           emitCode(Code + ", InFlag);");
2464
2465           emitCode("else");
2466           Code = "  ResNode = CurDAG->getTargetNode(" + II.Namespace + "::" +
2467                  II.TheDef->getName();
2468
2469           // Output order: results, chain, flags
2470           // Result types.
2471           if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid)
2472             Code += ", MVT::" + getEnumName(N->getTypeNum(0));
2473           if (HasChain)
2474             Code += ", MVT::Other";
2475           if (NodeHasOutFlag)
2476             Code += ", MVT::Flag";
2477
2478           // Inputs.
2479           for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2480             Code += ", Tmp" + utostr(Ops[i]);
2481           if (HasChain) Code += ", " + ChainName + ");";
2482           emitCode(Code);
2483         } else {
2484           emitDecl("ResNode", true);
2485           std::string Code = "ResNode = CurDAG->getTargetNode(" +
2486             II.Namespace + "::" + II.TheDef->getName();
2487
2488           // Output order: results, chain, flags
2489           // Result types.
2490           if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid)
2491             Code += ", MVT::" + getEnumName(N->getTypeNum(0));
2492           if (HasChain)
2493             Code += ", MVT::Other";
2494           if (NodeHasOutFlag)
2495             Code += ", MVT::Flag";
2496
2497           // Inputs.
2498           for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2499             Code += ", Tmp" + utostr(Ops[i]);
2500           if (HasChain) Code += ", " + ChainName;
2501           if (HasInFlag || HasImpInputs) Code += ", InFlag";
2502           emitCode(Code + ");");
2503         }
2504
2505         if (NewTF)
2506           emitCode("if (OldTF) "
2507                    "SelectionDAG::InsertISelMapEntry(CodeGenMap, OldTF, 0, " +
2508                    ChainName + ".Val, 0);");
2509
2510         for (unsigned i = 0; i < NumResults; i++)
2511           emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " +
2512                    utostr(i) + ", ResNode, " + utostr(i) + ");");
2513
2514         if (NodeHasOutFlag)
2515           emitCode("InFlag = SDOperand(ResNode, " + 
2516                    utostr(NumResults + (unsigned)HasChain) + ");");
2517
2518         if (HasImpResults && EmitCopyFromRegs(N, ChainEmitted)) {
2519           emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, "
2520                    "0, ResNode, 0);");
2521           NumResults = 1;
2522         }
2523
2524         if (NodeHasChain) {
2525           emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " + 
2526                    utostr(PatResults) + ", ResNode, " +
2527                    utostr(NumResults) + ");");
2528           if (DoReplace)
2529             emitCode("if (N.ResNo == 0) AddHandleReplacement(N.Val, " +
2530                      utostr(PatResults) + ", " + "ResNode, " +
2531                      utostr(NumResults) + ");");
2532         }
2533
2534         if (FoldedChains.size() > 0) {
2535           std::string Code;
2536           for (unsigned j = 0, e = FoldedChains.size(); j < e; j++)
2537             emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, " +
2538                      FoldedChains[j].first + ".Val, " + 
2539                      utostr(FoldedChains[j].second) + ", ResNode, " +
2540                      utostr(NumResults) + ");");
2541
2542           for (unsigned j = 0, e = FoldedChains.size(); j < e; j++) {
2543             std::string Code =
2544               FoldedChains[j].first + ".Val, " +
2545               utostr(FoldedChains[j].second) + ", ";
2546             emitCode("AddHandleReplacement(" + Code + "ResNode, " +
2547                      utostr(NumResults) + ");");
2548           }
2549         }
2550
2551         if (NodeHasOutFlag)
2552           emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " +
2553                    utostr(PatResults + (unsigned)NodeHasChain) +
2554                    ", InFlag.Val, InFlag.ResNo);");
2555
2556         // User does not expect the instruction would produce a chain!
2557         bool AddedChain = HasChain && !NodeHasChain;
2558         if (AddedChain && NodeHasOutFlag) {
2559           if (PatResults == 0) {
2560             emitCode("Result = SDOperand(ResNode, N.ResNo+1);");
2561           } else {
2562             emitCode("if (N.ResNo < " + utostr(PatResults) + ")");
2563             emitCode("  Result = SDOperand(ResNode, N.ResNo);");
2564             emitCode("else");
2565             emitCode("  Result = SDOperand(ResNode, N.ResNo+1);");
2566           }
2567         } else {
2568           emitCode("Result = SDOperand(ResNode, N.ResNo);");
2569         }
2570       } else {
2571         // If this instruction is the root, and if there is only one use of it,
2572         // use SelectNodeTo instead of getTargetNode to avoid an allocation.
2573         emitCode("if (N.Val->hasOneUse()) {");
2574         std::string Code = "  Result = CurDAG->SelectNodeTo(N.Val, " +
2575           II.Namespace + "::" + II.TheDef->getName();
2576         if (N->getTypeNum(0) != MVT::isVoid)
2577           Code += ", MVT::" + getEnumName(N->getTypeNum(0));
2578         if (NodeHasOutFlag)
2579           Code += ", MVT::Flag";
2580         for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2581           Code += ", Tmp" + utostr(Ops[i]);
2582         if (HasInFlag || HasImpInputs)
2583           Code += ", InFlag";
2584         emitCode(Code + ");");
2585         emitCode("} else {");
2586         emitDecl("ResNode", true);
2587         Code = "  ResNode = CurDAG->getTargetNode(" +
2588                II.Namespace + "::" + II.TheDef->getName();
2589         if (N->getTypeNum(0) != MVT::isVoid)
2590           Code += ", MVT::" + getEnumName(N->getTypeNum(0));
2591         if (NodeHasOutFlag)
2592           Code += ", MVT::Flag";
2593         for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2594           Code += ", Tmp" + utostr(Ops[i]);
2595         if (HasInFlag || HasImpInputs)
2596           Code += ", InFlag";
2597         emitCode(Code + ");");
2598         emitCode("  SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, "
2599                  "ResNode, 0);");
2600         emitCode("  Result = SDOperand(ResNode, 0);");
2601         emitCode("}");
2602       }
2603
2604       if (isRoot)
2605         emitCode("return;");
2606       return std::make_pair(1, ResNo);
2607     } else if (Op->isSubClassOf("SDNodeXForm")) {
2608       assert(N->getNumChildren() == 1 && "node xform should have one child!");
2609       // PatLeaf node - the operand may or may not be a leaf node. But it should
2610       // behave like one.
2611       unsigned OpVal = EmitResultCode(N->getChild(0), true).second;
2612       unsigned ResNo = TmpNo++;
2613       emitDecl("Tmp" + utostr(ResNo));
2614       emitCode("Tmp" + utostr(ResNo) + " = Transform_" + Op->getName()
2615                + "(Tmp" + utostr(OpVal) + ".Val);");
2616       if (isRoot) {
2617         emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val,"
2618                  "N.ResNo, Tmp" + utostr(ResNo) + ".Val, Tmp" +
2619                  utostr(ResNo) + ".ResNo);");
2620         emitCode("Result = Tmp" + utostr(ResNo) + ";");
2621         emitCode("return;");
2622       }
2623       return std::make_pair(1, ResNo);
2624     } else {
2625       N->dump();
2626       std::cerr << "\n";
2627       throw std::string("Unknown node in result pattern!");
2628     }
2629   }
2630
2631   /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat'
2632   /// and add it to the tree. 'Pat' and 'Other' are isomorphic trees except that 
2633   /// 'Pat' may be missing types.  If we find an unresolved type to add a check
2634   /// for, this returns true otherwise false if Pat has all types.
2635   bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
2636                           const std::string &Prefix) {
2637     // Did we find one?
2638     if (!Pat->hasTypeSet()) {
2639       // Move a type over from 'other' to 'pat'.
2640       Pat->setTypes(Other->getExtTypes());
2641       emitCheck(Prefix + ".Val->getValueType(0) == MVT::" +
2642                 getName(Pat->getTypeNum(0)));
2643       return true;
2644     }
2645   
2646     unsigned OpNo =
2647       (unsigned) NodeHasProperty(Pat, SDNodeInfo::SDNPHasChain, ISE);
2648     for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
2649       if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
2650                              Prefix + utostr(OpNo)))
2651         return true;
2652     return false;
2653   }
2654
2655 private:
2656   /// EmitInFlagSelectCode - Emit the flag operands for the DAG that is
2657   /// being built.
2658   void EmitInFlagSelectCode(TreePatternNode *N, const std::string &RootName,
2659                             bool &ChainEmitted, bool isRoot = false) {
2660     const CodeGenTarget &T = ISE.getTargetInfo();
2661     unsigned OpNo =
2662       (unsigned) NodeHasProperty(N, SDNodeInfo::SDNPHasChain, ISE);
2663     bool HasInFlag = NodeHasProperty(N, SDNodeInfo::SDNPInFlag, ISE);
2664     bool HasOptInFlag = NodeHasProperty(N, SDNodeInfo::SDNPOptInFlag, ISE);
2665     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
2666       TreePatternNode *Child = N->getChild(i);
2667       if (!Child->isLeaf()) {
2668         EmitInFlagSelectCode(Child, RootName + utostr(OpNo), ChainEmitted);
2669       } else {
2670         if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2671           if (!Child->getName().empty()) {
2672             std::string Name = RootName + utostr(OpNo);
2673             if (Duplicates.find(Name) != Duplicates.end())
2674               // A duplicate! Do not emit a copy for this node.
2675               continue;
2676           }
2677
2678           Record *RR = DI->getDef();
2679           if (RR->isSubClassOf("Register")) {
2680             MVT::ValueType RVT = getRegisterValueType(RR, T);
2681             if (RVT == MVT::Flag) {
2682               emitCode("Select(InFlag, " + RootName + utostr(OpNo) + ");");
2683             } else {
2684               if (!ChainEmitted) {
2685                 emitDecl("Chain");
2686                 emitCode("Chain = CurDAG->getEntryNode();");
2687                 ChainName = "Chain";
2688                 ChainEmitted = true;
2689               }
2690               emitCode("Select(" + RootName + utostr(OpNo) + ", " +
2691                        RootName + utostr(OpNo) + ");");
2692               emitCode("ResNode = CurDAG->getCopyToReg(" + ChainName +
2693                        ", CurDAG->getRegister(" + ISE.getQualifiedName(RR) +
2694                        ", MVT::" + getEnumName(RVT) + "), " +
2695                        RootName + utostr(OpNo) + ", InFlag).Val;");
2696               emitCode(ChainName + " = SDOperand(ResNode, 0);");
2697               emitCode("InFlag = SDOperand(ResNode, 1);");
2698             }
2699           }
2700         }
2701       }
2702     }
2703
2704     if (HasInFlag || HasOptInFlag) {
2705       std::string Code;
2706       if (HasOptInFlag) {
2707         emitCode("if (" + RootName + ".getNumOperands() == " + utostr(OpNo+1) +
2708                  ") {");
2709         Code = "  ";
2710       }
2711       emitCode(Code + "Select(InFlag, " + RootName +
2712                ".getOperand(" + utostr(OpNo) + "));");
2713       if (HasOptInFlag) {
2714         emitCode("  HasOptInFlag = true;");
2715         emitCode("}");
2716       }
2717     }
2718   }
2719
2720   /// EmitCopyFromRegs - Emit code to copy result to physical registers
2721   /// as specified by the instruction. It returns true if any copy is
2722   /// emitted.
2723   bool EmitCopyFromRegs(TreePatternNode *N, bool &ChainEmitted) {
2724     bool RetVal = false;
2725     Record *Op = N->getOperator();
2726     if (Op->isSubClassOf("Instruction")) {
2727       const DAGInstruction &Inst = ISE.getInstruction(Op);
2728       const CodeGenTarget &CGT = ISE.getTargetInfo();
2729       CodeGenInstruction &II = CGT.getInstruction(Op->getName());
2730       unsigned NumImpResults  = Inst.getNumImpResults();
2731       for (unsigned i = 0; i < NumImpResults; i++) {
2732         Record *RR = Inst.getImpResult(i);
2733         if (RR->isSubClassOf("Register")) {
2734           MVT::ValueType RVT = getRegisterValueType(RR, CGT);
2735           if (RVT != MVT::Flag) {
2736             if (!ChainEmitted) {
2737               emitDecl("Chain");
2738               emitCode("Chain = CurDAG->getEntryNode();");
2739               ChainEmitted = true;
2740               ChainName = "Chain";
2741             }
2742             emitCode("ResNode = CurDAG->getCopyFromReg(" + ChainName + ", " +
2743                      ISE.getQualifiedName(RR) + ", MVT::" + getEnumName(RVT) +
2744                      ", InFlag).Val;");
2745             emitCode(ChainName + " = SDOperand(ResNode, 1);");
2746             emitCode("InFlag = SDOperand(ResNode, 2);");
2747             RetVal = true;
2748           }
2749         }
2750       }
2751     }
2752     return RetVal;
2753   }
2754 };
2755
2756 /// EmitCodeForPattern - Given a pattern to match, emit code to the specified
2757 /// stream to match the pattern, and generate the code for the match if it
2758 /// succeeds.  Returns true if the pattern is not guaranteed to match.
2759 void DAGISelEmitter::GenerateCodeForPattern(PatternToMatch &Pattern,
2760                       std::vector<std::pair<bool, std::string> > &GeneratedCode,
2761                          std::set<std::pair<bool, std::string> > &GeneratedDecl,
2762                                             bool DoReplace) {
2763   PatternCodeEmitter Emitter(*this, Pattern.getPredicates(),
2764                              Pattern.getSrcPattern(), Pattern.getDstPattern(),
2765                              GeneratedCode, GeneratedDecl, DoReplace);
2766
2767   // Emit the matcher, capturing named arguments in VariableMap.
2768   bool FoundChain = false;
2769   Emitter.EmitMatchCode(Pattern.getSrcPattern(), NULL, "N", "", "", FoundChain);
2770
2771   // TP - Get *SOME* tree pattern, we don't care which.
2772   TreePattern &TP = *PatternFragments.begin()->second;
2773   
2774   // At this point, we know that we structurally match the pattern, but the
2775   // types of the nodes may not match.  Figure out the fewest number of type 
2776   // comparisons we need to emit.  For example, if there is only one integer
2777   // type supported by a target, there should be no type comparisons at all for
2778   // integer patterns!
2779   //
2780   // To figure out the fewest number of type checks needed, clone the pattern,
2781   // remove the types, then perform type inference on the pattern as a whole.
2782   // If there are unresolved types, emit an explicit check for those types,
2783   // apply the type to the tree, then rerun type inference.  Iterate until all
2784   // types are resolved.
2785   //
2786   TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
2787   RemoveAllTypes(Pat);
2788   
2789   do {
2790     // Resolve/propagate as many types as possible.
2791     try {
2792       bool MadeChange = true;
2793       while (MadeChange)
2794         MadeChange = Pat->ApplyTypeConstraints(TP,
2795                                                true/*Ignore reg constraints*/);
2796     } catch (...) {
2797       assert(0 && "Error: could not find consistent types for something we"
2798              " already decided was ok!");
2799       abort();
2800     }
2801
2802     // Insert a check for an unresolved type and add it to the tree.  If we find
2803     // an unresolved type to add a check for, this returns true and we iterate,
2804     // otherwise we are done.
2805   } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N"));
2806
2807   Emitter.EmitResultCode(Pattern.getDstPattern(), false, true /*the root*/);
2808   delete Pat;
2809 }
2810
2811 /// EraseCodeLine - Erase one code line from all of the patterns.  If removing
2812 /// a line causes any of them to be empty, remove them and return true when
2813 /// done.
2814 static bool EraseCodeLine(std::vector<std::pair<PatternToMatch*, 
2815                           std::vector<std::pair<bool, std::string> > > >
2816                           &Patterns) {
2817   bool ErasedPatterns = false;
2818   for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
2819     Patterns[i].second.pop_back();
2820     if (Patterns[i].second.empty()) {
2821       Patterns.erase(Patterns.begin()+i);
2822       --i; --e;
2823       ErasedPatterns = true;
2824     }
2825   }
2826   return ErasedPatterns;
2827 }
2828
2829 /// EmitPatterns - Emit code for at least one pattern, but try to group common
2830 /// code together between the patterns.
2831 void DAGISelEmitter::EmitPatterns(std::vector<std::pair<PatternToMatch*, 
2832                                   std::vector<std::pair<bool, std::string> > > >
2833                                   &Patterns, unsigned Indent,
2834                                   std::ostream &OS) {
2835   typedef std::pair<bool, std::string> CodeLine;
2836   typedef std::vector<CodeLine> CodeList;
2837   typedef std::vector<std::pair<PatternToMatch*, CodeList> > PatternList;
2838   
2839   if (Patterns.empty()) return;
2840   
2841   // Figure out how many patterns share the next code line.  Explicitly copy
2842   // FirstCodeLine so that we don't invalidate a reference when changing
2843   // Patterns.
2844   const CodeLine FirstCodeLine = Patterns.back().second.back();
2845   unsigned LastMatch = Patterns.size()-1;
2846   while (LastMatch != 0 && Patterns[LastMatch-1].second.back() == FirstCodeLine)
2847     --LastMatch;
2848   
2849   // If not all patterns share this line, split the list into two pieces.  The
2850   // first chunk will use this line, the second chunk won't.
2851   if (LastMatch != 0) {
2852     PatternList Shared(Patterns.begin()+LastMatch, Patterns.end());
2853     PatternList Other(Patterns.begin(), Patterns.begin()+LastMatch);
2854     
2855     // FIXME: Emit braces?
2856     if (Shared.size() == 1) {
2857       PatternToMatch &Pattern = *Shared.back().first;
2858       OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
2859       Pattern.getSrcPattern()->print(OS);
2860       OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
2861       Pattern.getDstPattern()->print(OS);
2862       OS << "\n";
2863       OS << std::string(Indent, ' ') << "// Pattern complexity = "
2864          << getPatternSize(Pattern.getSrcPattern(), *this) << "  cost = "
2865          << getResultPatternCost(Pattern.getDstPattern(), *this) << "\n";
2866     }
2867     if (!FirstCodeLine.first) {
2868       OS << std::string(Indent, ' ') << "{\n";
2869       Indent += 2;
2870     }
2871     EmitPatterns(Shared, Indent, OS);
2872     if (!FirstCodeLine.first) {
2873       Indent -= 2;
2874       OS << std::string(Indent, ' ') << "}\n";
2875     }
2876     
2877     if (Other.size() == 1) {
2878       PatternToMatch &Pattern = *Other.back().first;
2879       OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
2880       Pattern.getSrcPattern()->print(OS);
2881       OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
2882       Pattern.getDstPattern()->print(OS);
2883       OS << "\n";
2884       OS << std::string(Indent, ' ') << "// Pattern complexity = "
2885          << getPatternSize(Pattern.getSrcPattern(), *this) << "  cost = "
2886          << getResultPatternCost(Pattern.getDstPattern(), *this) << "\n";
2887     }
2888     EmitPatterns(Other, Indent, OS);
2889     return;
2890   }
2891   
2892   // Remove this code from all of the patterns that share it.
2893   bool ErasedPatterns = EraseCodeLine(Patterns);
2894   
2895   bool isPredicate = FirstCodeLine.first;
2896   
2897   // Otherwise, every pattern in the list has this line.  Emit it.
2898   if (!isPredicate) {
2899     // Normal code.
2900     OS << std::string(Indent, ' ') << FirstCodeLine.second << "\n";
2901   } else {
2902     OS << std::string(Indent, ' ') << "if (" << FirstCodeLine.second;
2903     
2904     // If the next code line is another predicate, and if all of the pattern
2905     // in this group share the same next line, emit it inline now.  Do this
2906     // until we run out of common predicates.
2907     while (!ErasedPatterns && Patterns.back().second.back().first) {
2908       // Check that all of fhe patterns in Patterns end with the same predicate.
2909       bool AllEndWithSamePredicate = true;
2910       for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
2911         if (Patterns[i].second.back() != Patterns.back().second.back()) {
2912           AllEndWithSamePredicate = false;
2913           break;
2914         }
2915       // If all of the predicates aren't the same, we can't share them.
2916       if (!AllEndWithSamePredicate) break;
2917       
2918       // Otherwise we can.  Emit it shared now.
2919       OS << " &&\n" << std::string(Indent+4, ' ')
2920          << Patterns.back().second.back().second;
2921       ErasedPatterns = EraseCodeLine(Patterns);
2922     }
2923     
2924     OS << ") {\n";
2925     Indent += 2;
2926   }
2927   
2928   EmitPatterns(Patterns, Indent, OS);
2929   
2930   if (isPredicate)
2931     OS << std::string(Indent-2, ' ') << "}\n";
2932 }
2933
2934
2935
2936 namespace {
2937   /// CompareByRecordName - An ordering predicate that implements less-than by
2938   /// comparing the names records.
2939   struct CompareByRecordName {
2940     bool operator()(const Record *LHS, const Record *RHS) const {
2941       // Sort by name first.
2942       if (LHS->getName() < RHS->getName()) return true;
2943       // If both names are equal, sort by pointer.
2944       return LHS->getName() == RHS->getName() && LHS < RHS;
2945     }
2946   };
2947 }
2948
2949 void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
2950   std::string InstNS = Target.inst_begin()->second.Namespace;
2951   if (!InstNS.empty()) InstNS += "::";
2952   
2953   // Group the patterns by their top-level opcodes.
2954   std::map<Record*, std::vector<PatternToMatch*>,
2955     CompareByRecordName> PatternsByOpcode;
2956   for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
2957     TreePatternNode *Node = PatternsToMatch[i].getSrcPattern();
2958     if (!Node->isLeaf()) {
2959       PatternsByOpcode[Node->getOperator()].push_back(&PatternsToMatch[i]);
2960     } else {
2961       const ComplexPattern *CP;
2962       if (IntInit *II = 
2963           dynamic_cast<IntInit*>(Node->getLeafValue())) {
2964         PatternsByOpcode[getSDNodeNamed("imm")].push_back(&PatternsToMatch[i]);
2965       } else if ((CP = NodeGetComplexPattern(Node, *this))) {
2966         std::vector<Record*> OpNodes = CP->getRootNodes();
2967         for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
2968           PatternsByOpcode[OpNodes[j]]
2969             .insert(PatternsByOpcode[OpNodes[j]].begin(), &PatternsToMatch[i]);
2970         }
2971       } else {
2972         std::cerr << "Unrecognized opcode '";
2973         Node->dump();
2974         std::cerr << "' on tree pattern '";
2975         std::cerr << 
2976            PatternsToMatch[i].getDstPattern()->getOperator()->getName();
2977         std::cerr << "'!\n";
2978         exit(1);
2979       }
2980     }
2981   }
2982   
2983   // Emit one Select_* method for each top-level opcode.  We do this instead of
2984   // emitting one giant switch statement to support compilers where this will
2985   // result in the recursive functions taking less stack space.
2986   for (std::map<Record*, std::vector<PatternToMatch*>,
2987        CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
2988        E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
2989     if (PBOI->first->isSubClassOf("Intrinsic"))
2990       continue;   // Skip intrinsics here.
2991     
2992     const std::string &OpName = PBOI->first->getName();
2993     OS << "void Select_" << OpName << "(SDOperand &Result, SDOperand N) {\n";
2994     
2995     const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
2996     bool OptSlctOrder = 
2997       (OpcodeInfo.hasProperty(SDNodeInfo::SDNPHasChain) &&
2998        OpcodeInfo.getNumResults() > 0);
2999
3000     if (OptSlctOrder) {
3001       OS << "  if (N.ResNo == " << OpcodeInfo.getNumResults()
3002          << " && N.getValue(0).hasOneUse()) {\n"
3003          << "    SDOperand Dummy = "
3004          << "CurDAG->getNode(ISD::HANDLENODE, MVT::Other, N);\n"
3005          << "    SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, "
3006          << OpcodeInfo.getNumResults() << ", Dummy.Val, 0);\n"
3007          << "    SelectionDAG::InsertISelMapEntry(HandleMap, N.Val, "
3008          << OpcodeInfo.getNumResults() << ", Dummy.Val, 0);\n"
3009          << "    Result = Dummy;\n"
3010          << "    return;\n"
3011          << "  }\n";
3012     }
3013
3014     std::vector<PatternToMatch*> &Patterns = PBOI->second;
3015     assert(!Patterns.empty() && "No patterns but map has entry?");
3016     
3017     // We want to emit all of the matching code now.  However, we want to emit
3018     // the matches in order of minimal cost.  Sort the patterns so the least
3019     // cost one is at the start.
3020     std::stable_sort(Patterns.begin(), Patterns.end(),
3021                      PatternSortingPredicate(*this));
3022
3023     typedef std::vector<std::pair<bool, std::string> > CodeList;
3024     typedef std::set<std::string> DeclSet;
3025     
3026     std::vector<std::pair<PatternToMatch*, CodeList> > CodeForPatterns;
3027     std::set<std::pair<bool, std::string> > GeneratedDecl;
3028     for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
3029       CodeList GeneratedCode;
3030       GenerateCodeForPattern(*Patterns[i], GeneratedCode, GeneratedDecl,
3031                              OptSlctOrder);
3032       CodeForPatterns.push_back(std::make_pair(Patterns[i], GeneratedCode));
3033     }
3034     
3035     // Scan the code to see if all of the patterns are reachable and if it is
3036     // possible that the last one might not match.
3037     bool mightNotMatch = true;
3038     for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
3039       CodeList &GeneratedCode = CodeForPatterns[i].second;
3040       mightNotMatch = false;
3041
3042       for (unsigned j = 0, e = GeneratedCode.size(); j != e; ++j) {
3043         if (GeneratedCode[j].first) { // predicate.
3044           mightNotMatch = true;
3045           break;
3046         }
3047       }
3048       
3049       // If this pattern definitely matches, and if it isn't the last one, the
3050       // patterns after it CANNOT ever match.  Error out.
3051       if (mightNotMatch == false && i != CodeForPatterns.size()-1) {
3052         std::cerr << "Pattern '";
3053         CodeForPatterns[i+1].first->getSrcPattern()->print(OS);
3054         std::cerr << "' is impossible to select!\n";
3055         exit(1);
3056       }
3057     }
3058
3059     // Print all declarations.
3060     for (std::set<std::pair<bool, std::string> >::iterator
3061          I = GeneratedDecl.begin(), E = GeneratedDecl.end(); I != E; ++I)
3062       if (I->first)
3063         OS << "  SDNode *" << I->second << ";\n";
3064       else
3065         OS << "  SDOperand " << I->second << "(0, 0);\n";
3066
3067     // Loop through and reverse all of the CodeList vectors, as we will be
3068     // accessing them from their logical front, but accessing the end of a
3069     // vector is more efficient.
3070     for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
3071       CodeList &GeneratedCode = CodeForPatterns[i].second;
3072       std::reverse(GeneratedCode.begin(), GeneratedCode.end());
3073     }
3074     
3075     // Next, reverse the list of patterns itself for the same reason.
3076     std::reverse(CodeForPatterns.begin(), CodeForPatterns.end());
3077     
3078     // Emit all of the patterns now, grouped together to share code.
3079     EmitPatterns(CodeForPatterns, 2, OS);
3080     
3081     // If the last pattern has predicates (which could fail) emit code to catch
3082     // the case where nothing handles a pattern.
3083     if (mightNotMatch)
3084       OS << "  std::cerr << \"Cannot yet select: \";\n"
3085          << "  N.Val->dump(CurDAG);\n"
3086          << "  std::cerr << '\\n';\n"
3087          << "  abort();\n";
3088
3089     OS << "}\n\n";
3090   }
3091   
3092   // Emit boilerplate.
3093   OS << "void Select_INLINEASM(SDOperand& Result, SDOperand N) {\n"
3094      << "  std::vector<SDOperand> Ops(N.Val->op_begin(), N.Val->op_end());\n"
3095      << "  Select(Ops[0], N.getOperand(0)); // Select the chain.\n\n"
3096      << "  // Select the flag operand.\n"
3097      << "  if (Ops.back().getValueType() == MVT::Flag)\n"
3098      << "    Select(Ops.back(), Ops.back());\n"
3099      << "  SelectInlineAsmMemoryOperands(Ops, *CurDAG);\n"
3100      << "  std::vector<MVT::ValueType> VTs;\n"
3101      << "  VTs.push_back(MVT::Other);\n"
3102      << "  VTs.push_back(MVT::Flag);\n"
3103      << "  SDOperand New = CurDAG->getNode(ISD::INLINEASM, VTs, Ops);\n"
3104     << "  SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, New.Val, 0);\n"
3105     << "  SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, New.Val, 1);\n"
3106      << "  Result = New.getValue(N.ResNo);\n"
3107      << "  return;\n"
3108      << "}\n\n";
3109   
3110   OS << "// The main instruction selector code.\n"
3111      << "void SelectCode(SDOperand &Result, SDOperand N) {\n"
3112      << "  if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
3113      << "      N.getOpcode() < (ISD::BUILTIN_OP_END+" << InstNS
3114      << "INSTRUCTION_LIST_END)) {\n"
3115      << "    Result = N;\n"
3116      << "    return;   // Already selected.\n"
3117      << "  }\n\n"
3118     << "  std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(N);\n"
3119      << "  if (CGMI != CodeGenMap.end()) {\n"
3120      << "    Result = CGMI->second;\n"
3121      << "    return;\n"
3122      << "  }\n\n"
3123      << "  switch (N.getOpcode()) {\n"
3124      << "  default: break;\n"
3125      << "  case ISD::EntryToken:       // These leaves remain the same.\n"
3126      << "  case ISD::BasicBlock:\n"
3127      << "  case ISD::Register:\n"
3128      << "  case ISD::HANDLENODE:\n"
3129      << "  case ISD::TargetConstant:\n"
3130      << "  case ISD::TargetConstantPool:\n"
3131      << "  case ISD::TargetFrameIndex:\n"
3132      << "  case ISD::TargetGlobalAddress: {\n"
3133      << "    Result = N;\n"
3134      << "    return;\n"
3135      << "  }\n"
3136      << "  case ISD::AssertSext:\n"
3137      << "  case ISD::AssertZext: {\n"
3138      << "    SDOperand Tmp0;\n"
3139      << "    Select(Tmp0, N.getOperand(0));\n"
3140      << "    if (!N.Val->hasOneUse())\n"
3141      << "      SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, "
3142      << "Tmp0.Val, Tmp0.ResNo);\n"
3143      << "    Result = Tmp0;\n"
3144      << "    return;\n"
3145      << "  }\n"
3146      << "  case ISD::TokenFactor:\n"
3147      << "    if (N.getNumOperands() == 2) {\n"
3148      << "      SDOperand Op0, Op1;\n"
3149      << "      Select(Op0, N.getOperand(0));\n"
3150      << "      Select(Op1, N.getOperand(1));\n"
3151      << "      Result = \n"
3152      << "          CurDAG->getNode(ISD::TokenFactor, MVT::Other, Op0, Op1);\n"
3153      << "      SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, "
3154      << "Result.Val, Result.ResNo);\n"
3155      << "    } else {\n"
3156      << "      std::vector<SDOperand> Ops;\n"
3157      << "      for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i) {\n"
3158      << "        SDOperand Val;\n"
3159      << "        Select(Val, N.getOperand(i));\n"
3160      << "        Ops.push_back(Val);\n"
3161      << "      }\n"
3162      << "      Result = \n"
3163      << "          CurDAG->getNode(ISD::TokenFactor, MVT::Other, Ops);\n"
3164      << "      SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, "
3165      << "Result.Val, Result.ResNo);\n"
3166      << "    }\n"
3167      << "    return;\n"
3168      << "  case ISD::CopyFromReg: {\n"
3169      << "    SDOperand Chain;\n"
3170      << "    Select(Chain, N.getOperand(0));\n"
3171      << "    unsigned Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();\n"
3172      << "    MVT::ValueType VT = N.Val->getValueType(0);\n"
3173      << "    if (N.Val->getNumValues() == 2) {\n"
3174      << "      if (Chain == N.getOperand(0)) {\n"
3175      << "        Result = N; // No change\n"
3176      << "        return;\n"
3177      << "      }\n"
3178      << "      SDOperand New = CurDAG->getCopyFromReg(Chain, Reg, VT);\n"
3179      << "      SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, "
3180      << "New.Val, 0);\n"
3181      << "      SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, "
3182      << "New.Val, 1);\n"
3183      << "      Result = New.getValue(N.ResNo);\n"
3184      << "      return;\n"
3185      << "    } else {\n"
3186      << "      SDOperand Flag;\n"
3187      << "      if (N.getNumOperands() == 3) Select(Flag, N.getOperand(2));\n"
3188      << "      if (Chain == N.getOperand(0) &&\n"
3189      << "          (N.getNumOperands() == 2 || Flag == N.getOperand(2))) {\n"
3190      << "        Result = N; // No change\n"
3191      << "        return;\n"
3192      << "      }\n"
3193      << "      SDOperand New = CurDAG->getCopyFromReg(Chain, Reg, VT, Flag);\n"
3194      << "      SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, "
3195      << "New.Val, 0);\n"
3196      << "      SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, "
3197      << "New.Val, 1);\n"
3198      << "      SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 2, "
3199      << "New.Val, 2);\n"
3200      << "      Result = New.getValue(N.ResNo);\n"
3201      << "      return;\n"
3202      << "    }\n"
3203      << "  }\n"
3204      << "  case ISD::CopyToReg: {\n"
3205      << "    SDOperand Chain;\n"
3206      << "    Select(Chain, N.getOperand(0));\n"
3207      << "    unsigned Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();\n"
3208      << "    SDOperand Val;\n"
3209      << "    Select(Val, N.getOperand(2));\n"
3210      << "    Result = N;\n"
3211      << "    if (N.Val->getNumValues() == 1) {\n"
3212      << "      if (Chain != N.getOperand(0) || Val != N.getOperand(2))\n"
3213      << "        Result = CurDAG->getCopyToReg(Chain, Reg, Val);\n"
3214      << "      SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, "
3215      << "Result.Val, 0);\n"
3216      << "    } else {\n"
3217      << "      SDOperand Flag(0, 0);\n"
3218      << "      if (N.getNumOperands() == 4) Select(Flag, N.getOperand(3));\n"
3219      << "      if (Chain != N.getOperand(0) || Val != N.getOperand(2) ||\n"
3220      << "          (N.getNumOperands() == 4 && Flag != N.getOperand(3)))\n"
3221      << "        Result = CurDAG->getCopyToReg(Chain, Reg, Val, Flag);\n"
3222      << "      SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, "
3223      << "Result.Val, 0);\n"
3224      << "      SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, "
3225      << "Result.Val, 1);\n"
3226      << "      Result = Result.getValue(N.ResNo);\n"
3227      << "    }\n"
3228      << "    return;\n"
3229      << "  }\n"
3230      << "  case ISD::INLINEASM:  Select_INLINEASM(Result, N); return;\n";
3231
3232     
3233   // Loop over all of the case statements, emiting a call to each method we
3234   // emitted above.
3235   for (std::map<Record*, std::vector<PatternToMatch*>,
3236                 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
3237        E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
3238     if (PBOI->first->isSubClassOf("Intrinsic"))
3239       continue;
3240     
3241     const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
3242     OS << "  case " << OpcodeInfo.getEnumName() << ": "
3243        << std::string(std::max(0, int(24-OpcodeInfo.getEnumName().size())), ' ')
3244        << "Select_" << PBOI->first->getName() << "(Result, N); return;\n";
3245   }
3246
3247   OS << "  } // end of big switch.\n\n"
3248      << "  std::cerr << \"Cannot yet select: \";\n"
3249      << "  N.Val->dump(CurDAG);\n"
3250      << "  std::cerr << '\\n';\n"
3251      << "  abort();\n"
3252      << "}\n";
3253 }
3254
3255 void DAGISelEmitter::run(std::ostream &OS) {
3256   EmitSourceFileHeader("DAG Instruction Selector for the " + Target.getName() +
3257                        " target", OS);
3258   
3259   OS << "// *** NOTE: This file is #included into the middle of the target\n"
3260      << "// *** instruction selector class.  These functions are really "
3261      << "methods.\n\n";
3262   
3263   OS << "// Instance var to keep track of multiply used nodes that have \n"
3264      << "// already been selected.\n"
3265      << "std::map<SDOperand, SDOperand> CodeGenMap;\n";
3266
3267   OS << "// Instance var to keep track of mapping of chain generating nodes\n"
3268      << "// and their place handle nodes.\n";
3269   OS << "std::map<SDOperand, SDOperand> HandleMap;\n";
3270   OS << "// Instance var to keep track of mapping of place handle nodes\n"
3271      << "// and their replacement nodes.\n";
3272   OS << "std::map<SDOperand, SDOperand> ReplaceMap;\n";
3273
3274   OS << "\n";
3275   OS << "static void findNonImmUse(SDNode* Use, SDNode* Def, bool &found, "
3276      << "std::set<SDNode *> &Visited) {\n";
3277   OS << "  if (found || !Visited.insert(Use).second) return;\n";
3278   OS << "  for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {\n";
3279   OS << "    SDNode *N = Use->getOperand(i).Val;\n";
3280   OS << "    if (N->getNodeDepth() >= Def->getNodeDepth()) {\n";
3281   OS << "      if (N != Def) {\n";
3282   OS << "        findNonImmUse(N, Def, found, Visited);\n";
3283   OS << "      } else {\n";
3284   OS << "        found = true;\n";
3285   OS << "        break;\n";
3286   OS << "      }\n";
3287   OS << "    }\n";
3288   OS << "  }\n";
3289   OS << "}\n";
3290
3291   OS << "\n";
3292   OS << "static bool isNonImmUse(SDNode* Use, SDNode* Def) {\n";
3293   OS << "  std::set<SDNode *> Visited;\n";
3294   OS << "  bool found = false;\n";
3295   OS << "  for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {\n";
3296   OS << "    SDNode *N = Use->getOperand(i).Val;\n";
3297   OS << "    if (N != Def) {\n";
3298   OS << "      findNonImmUse(N, Def, found, Visited);\n";
3299   OS << "      if (found) break;\n";
3300   OS << "    }\n";
3301   OS << "  }\n";
3302   OS << "  return found;\n";
3303   OS << "}\n";
3304
3305   OS << "\n";
3306   OS << "// AddHandleReplacement - Note the pending replacement node for a\n"
3307      << "// handle node in ReplaceMap.\n";
3308   OS << "void AddHandleReplacement(SDNode *H, unsigned HNum, SDNode *R, "
3309      << "unsigned RNum) {\n";
3310   OS << "  SDOperand N(H, HNum);\n";
3311   OS << "  std::map<SDOperand, SDOperand>::iterator HMI = HandleMap.find(N);\n";
3312   OS << "  if (HMI != HandleMap.end()) {\n";
3313   OS << "    ReplaceMap[HMI->second] = SDOperand(R, RNum);\n";
3314   OS << "    HandleMap.erase(N);\n";
3315   OS << "  }\n";
3316   OS << "}\n";
3317
3318   OS << "\n";
3319   OS << "// SelectDanglingHandles - Select replacements for all `dangling`\n";
3320   OS << "// handles.Some handles do not yet have replacements because the\n";
3321   OS << "// nodes they replacements have only dead readers.\n";
3322   OS << "void SelectDanglingHandles() {\n";
3323   OS << "  for (std::map<SDOperand, SDOperand>::iterator I = "
3324      << "HandleMap.begin(),\n"
3325      << "         E = HandleMap.end(); I != E; ++I) {\n";
3326   OS << "    SDOperand N = I->first;\n";
3327   OS << "    SDOperand R;\n";
3328   OS << "    Select(R, N.getValue(0));\n";
3329   OS << "    AddHandleReplacement(N.Val, N.ResNo, R.Val, R.ResNo);\n";
3330   OS << "  }\n";
3331   OS << "}\n";
3332   OS << "\n";
3333   OS << "// ReplaceHandles - Replace all the handles with the real target\n";
3334   OS << "// specific nodes.\n";
3335   OS << "void ReplaceHandles() {\n";
3336   OS << "  for (std::map<SDOperand, SDOperand>::iterator I = "
3337      << "ReplaceMap.begin(),\n"
3338      << "        E = ReplaceMap.end(); I != E; ++I) {\n";
3339   OS << "    SDOperand From = I->first;\n";
3340   OS << "    SDOperand To   = I->second;\n";
3341   OS << "    for (SDNode::use_iterator UI = From.Val->use_begin(), "
3342      << "E = From.Val->use_end(); UI != E; ++UI) {\n";
3343   OS << "      SDNode *Use = *UI;\n";
3344   OS << "      std::vector<SDOperand> Ops;\n";
3345   OS << "      for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {\n";
3346   OS << "        SDOperand O = Use->getOperand(i);\n";
3347   OS << "        if (O.Val == From.Val)\n";
3348   OS << "          Ops.push_back(To);\n";
3349   OS << "        else\n";
3350   OS << "          Ops.push_back(O);\n";
3351   OS << "      }\n";
3352   OS << "      SDOperand U = SDOperand(Use, 0);\n";
3353   OS << "      CurDAG->UpdateNodeOperands(U, Ops);\n";
3354   OS << "    }\n";
3355   OS << "  }\n";
3356   OS << "}\n";
3357
3358   OS << "\n";
3359   OS << "// UpdateFoldedChain - return a SDOperand of the new chain created\n";
3360   OS << "// if the folding were to happen. This is called when, for example,\n";
3361   OS << "// a load is folded into a store. If the store's chain is the load,\n";
3362   OS << "// then the resulting node's input chain would be the load's input\n";
3363   OS << "// chain. If the store's chain is a TokenFactor and the load's\n";
3364   OS << "// output chain feeds into in, then the new chain is a TokenFactor\n";
3365   OS << "// with the other operands along with the input chain of the load.\n";
3366   OS << "SDOperand UpdateFoldedChain(SelectionDAG *DAG, SDNode *N, "
3367      << "SDNode *Chain, SDNode* &OldTF) {\n";
3368   OS << "  OldTF = NULL;\n";
3369   OS << "  if (N == Chain) {\n";
3370   OS << "    return N->getOperand(0);\n";
3371   OS << "  } else if (Chain->getOpcode() == ISD::TokenFactor &&\n";
3372   OS << "             N->isOperand(Chain)) {\n";
3373   OS << "    SDOperand Ch = SDOperand(Chain, 0);\n";
3374   OS << "    std::map<SDOperand, SDOperand>::iterator CGMI = "
3375      << "CodeGenMap.find(Ch);\n";
3376   OS << "    if (CGMI != CodeGenMap.end())\n";
3377   OS << "      return SDOperand(0, 0);\n";
3378   OS << "    OldTF = Chain;\n";
3379   OS << "    std::vector<SDOperand> Ops;\n";
3380   OS << "    for (unsigned i = 0; i < Chain->getNumOperands(); ++i) {\n";
3381   OS << "      SDOperand Op = Chain->getOperand(i);\n";
3382   OS << "      if (Op.Val == N)\n";
3383   OS << "        Ops.push_back(N->getOperand(0));\n";
3384   OS << "      else\n";
3385   OS << "        Ops.push_back(Op);\n";
3386   OS << "    }\n";
3387   OS << "    return DAG->getNode(ISD::TokenFactor, MVT::Other, Ops);\n";
3388   OS << "  }\n";
3389   OS << "  return SDOperand(0, 0);\n";
3390   OS << "}\n";
3391
3392   OS << "\n";
3393   OS << "// SelectRoot - Top level entry to DAG isel.\n";
3394   OS << "SDOperand SelectRoot(SDOperand N) {\n";
3395   OS << "  SDOperand ResNode;\n";
3396   OS << "  Select(ResNode, N);\n";
3397   OS << "  SelectDanglingHandles();\n";
3398   OS << "  ReplaceHandles();\n";
3399   OS << "  ReplaceMap.clear();\n";
3400   OS << "  return ResNode;\n";
3401   OS << "}\n";
3402   
3403   Intrinsics = LoadIntrinsics(Records);
3404   ParseNodeInfo();
3405   ParseNodeTransforms(OS);
3406   ParseComplexPatterns();
3407   ParsePatternFragments(OS);
3408   ParseInstructions();
3409   ParsePatterns();
3410   
3411   // Generate variants.  For example, commutative patterns can match
3412   // multiple ways.  Add them to PatternsToMatch as well.
3413   GenerateVariants();
3414
3415   
3416   DEBUG(std::cerr << "\n\nALL PATTERNS TO MATCH:\n\n";
3417         for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
3418           std::cerr << "PATTERN: ";  PatternsToMatch[i].getSrcPattern()->dump();
3419           std::cerr << "\nRESULT:  ";PatternsToMatch[i].getDstPattern()->dump();
3420           std::cerr << "\n";
3421         });
3422   
3423   // At this point, we have full information about the 'Patterns' we need to
3424   // parse, both implicitly from instructions as well as from explicit pattern
3425   // definitions.  Emit the resultant instruction selector.
3426   EmitInstructionSelector(OS);  
3427   
3428   for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
3429        E = PatternFragments.end(); I != E; ++I)
3430     delete I->second;
3431   PatternFragments.clear();
3432
3433   Instructions.clear();
3434 }