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