Fix the semantic of Requires<[cond]> to mean if (!cond) goto PXXFail;
[oota-llvm.git] / utils / TableGen / DAGISelEmitter.cpp
1 //===- DAGISelEmitter.cpp - Generate an instruction selector --------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Chris Lattner and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This tablegen backend emits a DAG instruction selector.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "DAGISelEmitter.h"
15 #include "Record.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/Support/Debug.h"
18 #include <algorithm>
19 #include <set>
20 using namespace llvm;
21
22 //===----------------------------------------------------------------------===//
23 // Helpers for working with extended types.
24
25 /// FilterVTs - Filter a list of VT's according to a predicate.
26 ///
27 template<typename T>
28 static std::vector<MVT::ValueType> 
29 FilterVTs(const std::vector<MVT::ValueType> &InVTs, T Filter) {
30   std::vector<MVT::ValueType> Result;
31   for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
32     if (Filter(InVTs[i]))
33       Result.push_back(InVTs[i]);
34   return Result;
35 }
36
37 /// isExtIntegerVT - Return true if the specified extended value type is
38 /// integer, or isInt.
39 static bool isExtIntegerVT(unsigned char VT) {
40   return VT == MVT::isInt ||
41         (VT < MVT::LAST_VALUETYPE && MVT::isInteger((MVT::ValueType)VT));
42 }
43
44 /// isExtFloatingPointVT - Return true if the specified extended value type is
45 /// floating point, or isFP.
46 static bool isExtFloatingPointVT(unsigned char VT) {
47   return VT == MVT::isFP ||
48         (VT < MVT::LAST_VALUETYPE && MVT::isFloatingPoint((MVT::ValueType)VT));
49 }
50
51 //===----------------------------------------------------------------------===//
52 // SDTypeConstraint implementation
53 //
54
55 SDTypeConstraint::SDTypeConstraint(Record *R) {
56   OperandNo = R->getValueAsInt("OperandNum");
57   
58   if (R->isSubClassOf("SDTCisVT")) {
59     ConstraintType = SDTCisVT;
60     x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
61   } else if (R->isSubClassOf("SDTCisPtrTy")) {
62     ConstraintType = SDTCisPtrTy;
63   } else if (R->isSubClassOf("SDTCisInt")) {
64     ConstraintType = SDTCisInt;
65   } else if (R->isSubClassOf("SDTCisFP")) {
66     ConstraintType = SDTCisFP;
67   } else if (R->isSubClassOf("SDTCisSameAs")) {
68     ConstraintType = SDTCisSameAs;
69     x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
70   } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
71     ConstraintType = SDTCisVTSmallerThanOp;
72     x.SDTCisVTSmallerThanOp_Info.OtherOperandNum = 
73       R->getValueAsInt("OtherOperandNum");
74   } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
75     ConstraintType = SDTCisOpSmallerThanOp;
76     x.SDTCisOpSmallerThanOp_Info.BigOperandNum = 
77       R->getValueAsInt("BigOperandNum");
78   } else {
79     std::cerr << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
80     exit(1);
81   }
82 }
83
84 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
85 /// N, which has NumResults results.
86 TreePatternNode *SDTypeConstraint::getOperandNum(unsigned OpNo,
87                                                  TreePatternNode *N,
88                                                  unsigned NumResults) const {
89   assert(NumResults <= 1 &&
90          "We only work with nodes with zero or one result so far!");
91   
92   if (OpNo < NumResults)
93     return N;  // FIXME: need value #
94   else
95     return N->getChild(OpNo-NumResults);
96 }
97
98 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
99 /// constraint to the nodes operands.  This returns true if it makes a
100 /// change, false otherwise.  If a type contradiction is found, throw an
101 /// exception.
102 bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
103                                            const SDNodeInfo &NodeInfo,
104                                            TreePattern &TP) const {
105   unsigned NumResults = NodeInfo.getNumResults();
106   assert(NumResults <= 1 &&
107          "We only work with nodes with zero or one result so far!");
108   
109   // Check that the number of operands is sane.
110   if (NodeInfo.getNumOperands() >= 0) {
111     if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands())
112       TP.error(N->getOperator()->getName() + " node requires exactly " +
113                itostr(NodeInfo.getNumOperands()) + " operands!");
114   }
115
116   const CodeGenTarget &CGT = TP.getDAGISelEmitter().getTargetInfo();
117   
118   TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NumResults);
119   
120   switch (ConstraintType) {
121   default: assert(0 && "Unknown constraint type!");
122   case SDTCisVT:
123     // Operand must be a particular type.
124     return NodeToApply->UpdateNodeType(x.SDTCisVT_Info.VT, TP);
125   case SDTCisPtrTy: {
126     // Operand must be same as target pointer type.
127     return NodeToApply->UpdateNodeType(CGT.getPointerType(), TP);
128   }
129   case SDTCisInt: {
130     // If there is only one integer type supported, this must be it.
131     std::vector<MVT::ValueType> IntVTs =
132       FilterVTs(CGT.getLegalValueTypes(), MVT::isInteger);
133
134     // If we found exactly one supported integer type, apply it.
135     if (IntVTs.size() == 1)
136       return NodeToApply->UpdateNodeType(IntVTs[0], TP);
137     return NodeToApply->UpdateNodeType(MVT::isInt, TP);
138   }
139   case SDTCisFP: {
140     // If there is only one FP type supported, this must be it.
141     std::vector<MVT::ValueType> FPVTs =
142       FilterVTs(CGT.getLegalValueTypes(), MVT::isFloatingPoint);
143         
144     // If we found exactly one supported FP type, apply it.
145     if (FPVTs.size() == 1)
146       return NodeToApply->UpdateNodeType(FPVTs[0], TP);
147     return NodeToApply->UpdateNodeType(MVT::isFP, TP);
148   }
149   case SDTCisSameAs: {
150     TreePatternNode *OtherNode =
151       getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NumResults);
152     return NodeToApply->UpdateNodeType(OtherNode->getExtType(), TP) |
153            OtherNode->UpdateNodeType(NodeToApply->getExtType(), TP);
154   }
155   case SDTCisVTSmallerThanOp: {
156     // The NodeToApply must be a leaf node that is a VT.  OtherOperandNum must
157     // have an integer type that is smaller than the VT.
158     if (!NodeToApply->isLeaf() ||
159         !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
160         !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
161                ->isSubClassOf("ValueType"))
162       TP.error(N->getOperator()->getName() + " expects a VT operand!");
163     MVT::ValueType VT =
164      getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
165     if (!MVT::isInteger(VT))
166       TP.error(N->getOperator()->getName() + " VT operand must be integer!");
167     
168     TreePatternNode *OtherNode =
169       getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N,NumResults);
170     
171     // It must be integer.
172     bool MadeChange = false;
173     MadeChange |= OtherNode->UpdateNodeType(MVT::isInt, TP);
174     
175     if (OtherNode->hasTypeSet() && OtherNode->getType() <= VT)
176       OtherNode->UpdateNodeType(MVT::Other, TP);  // Throw an error.
177     return false;
178   }
179   case SDTCisOpSmallerThanOp: {
180     TreePatternNode *BigOperand =
181       getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NumResults);
182
183     // Both operands must be integer or FP, but we don't care which.
184     bool MadeChange = false;
185     
186     if (isExtIntegerVT(NodeToApply->getExtType()))
187       MadeChange |= BigOperand->UpdateNodeType(MVT::isInt, TP);
188     else if (isExtFloatingPointVT(NodeToApply->getExtType()))
189       MadeChange |= BigOperand->UpdateNodeType(MVT::isFP, TP);
190     if (isExtIntegerVT(BigOperand->getExtType()))
191       MadeChange |= NodeToApply->UpdateNodeType(MVT::isInt, TP);
192     else if (isExtFloatingPointVT(BigOperand->getExtType()))
193       MadeChange |= NodeToApply->UpdateNodeType(MVT::isFP, TP);
194
195     std::vector<MVT::ValueType> VTs = CGT.getLegalValueTypes();
196     
197     if (isExtIntegerVT(NodeToApply->getExtType())) {
198       VTs = FilterVTs(VTs, MVT::isInteger);
199     } else if (isExtFloatingPointVT(NodeToApply->getExtType())) {
200       VTs = FilterVTs(VTs, MVT::isFloatingPoint);
201     } else {
202       VTs.clear();
203     }
204
205     switch (VTs.size()) {
206     default:         // Too many VT's to pick from.
207     case 0: break;   // No info yet.
208     case 1: 
209       // Only one VT of this flavor.  Cannot ever satisify the constraints.
210       return NodeToApply->UpdateNodeType(MVT::Other, TP);  // throw
211     case 2:
212       // If we have exactly two possible types, the little operand must be the
213       // small one, the big operand should be the big one.  Common with 
214       // float/double for example.
215       assert(VTs[0] < VTs[1] && "Should be sorted!");
216       MadeChange |= NodeToApply->UpdateNodeType(VTs[0], TP);
217       MadeChange |= BigOperand->UpdateNodeType(VTs[1], TP);
218       break;
219     }    
220     return MadeChange;
221   }
222   }  
223   return false;
224 }
225
226
227 //===----------------------------------------------------------------------===//
228 // SDNodeInfo implementation
229 //
230 SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
231   EnumName    = R->getValueAsString("Opcode");
232   SDClassName = R->getValueAsString("SDClass");
233   Record *TypeProfile = R->getValueAsDef("TypeProfile");
234   NumResults = TypeProfile->getValueAsInt("NumResults");
235   NumOperands = TypeProfile->getValueAsInt("NumOperands");
236   
237   // Parse the properties.
238   Properties = 0;
239   std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
240   for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
241     if (PropList[i]->getName() == "SDNPCommutative") {
242       Properties |= 1 << SDNPCommutative;
243     } else if (PropList[i]->getName() == "SDNPAssociative") {
244       Properties |= 1 << SDNPAssociative;
245     } else if (PropList[i]->getName() == "SDNPHasChain") {
246       Properties |= 1 << SDNPHasChain;
247     } else {
248       std::cerr << "Unknown SD Node property '" << PropList[i]->getName()
249                 << "' on node '" << R->getName() << "'!\n";
250       exit(1);
251     }
252   }
253   
254   
255   // Parse the type constraints.
256   std::vector<Record*> ConstraintList =
257     TypeProfile->getValueAsListOfDefs("Constraints");
258   TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
259 }
260
261 //===----------------------------------------------------------------------===//
262 // TreePatternNode implementation
263 //
264
265 TreePatternNode::~TreePatternNode() {
266 #if 0 // FIXME: implement refcounted tree nodes!
267   for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
268     delete getChild(i);
269 #endif
270 }
271
272 /// UpdateNodeType - Set the node type of N to VT if VT contains
273 /// information.  If N already contains a conflicting type, then throw an
274 /// exception.  This returns true if any information was updated.
275 ///
276 bool TreePatternNode::UpdateNodeType(unsigned char VT, TreePattern &TP) {
277   if (VT == MVT::isUnknown || getExtType() == VT) return false;
278   if (getExtType() == MVT::isUnknown) {
279     setType(VT);
280     return true;
281   }
282   
283   // If we are told this is to be an int or FP type, and it already is, ignore
284   // the advice.
285   if ((VT == MVT::isInt && isExtIntegerVT(getExtType())) ||
286       (VT == MVT::isFP  && isExtFloatingPointVT(getExtType())))
287     return false;
288       
289   // If we know this is an int or fp type, and we are told it is a specific one,
290   // take the advice.
291   if ((getExtType() == MVT::isInt && isExtIntegerVT(VT)) ||
292       (getExtType() == MVT::isFP  && isExtFloatingPointVT(VT))) {
293     setType(VT);
294     return true;
295   }      
296
297   if (isLeaf()) {
298     dump();
299     std::cerr << " ";
300     TP.error("Type inference contradiction found in node!");
301   } else {
302     TP.error("Type inference contradiction found in node " + 
303              getOperator()->getName() + "!");
304   }
305   return true; // unreachable
306 }
307
308
309 void TreePatternNode::print(std::ostream &OS) const {
310   if (isLeaf()) {
311     OS << *getLeafValue();
312   } else {
313     OS << "(" << getOperator()->getName();
314   }
315   
316   switch (getExtType()) {
317   case MVT::Other: OS << ":Other"; break;
318   case MVT::isInt: OS << ":isInt"; break;
319   case MVT::isFP : OS << ":isFP"; break;
320   case MVT::isUnknown: ; /*OS << ":?";*/ break;
321   default:  OS << ":" << getType(); break;
322   }
323
324   if (!isLeaf()) {
325     if (getNumChildren() != 0) {
326       OS << " ";
327       getChild(0)->print(OS);
328       for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
329         OS << ", ";
330         getChild(i)->print(OS);
331       }
332     }
333     OS << ")";
334   }
335   
336   if (!PredicateFn.empty())
337     OS << "<<P:" << PredicateFn << ">>";
338   if (TransformFn)
339     OS << "<<X:" << TransformFn->getName() << ">>";
340   if (!getName().empty())
341     OS << ":$" << getName();
342
343 }
344 void TreePatternNode::dump() const {
345   print(std::cerr);
346 }
347
348 /// isIsomorphicTo - Return true if this node is recursively isomorphic to
349 /// the specified node.  For this comparison, all of the state of the node
350 /// is considered, except for the assigned name.  Nodes with differing names
351 /// that are otherwise identical are considered isomorphic.
352 bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N) const {
353   if (N == this) return true;
354   if (N->isLeaf() != isLeaf() || getExtType() != N->getExtType() ||
355       getPredicateFn() != N->getPredicateFn() ||
356       getTransformFn() != N->getTransformFn())
357     return false;
358
359   if (isLeaf()) {
360     if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue()))
361       if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue()))
362         return DI->getDef() == NDI->getDef();
363     return getLeafValue() == N->getLeafValue();
364   }
365   
366   if (N->getOperator() != getOperator() ||
367       N->getNumChildren() != getNumChildren()) return false;
368   for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
369     if (!getChild(i)->isIsomorphicTo(N->getChild(i)))
370       return false;
371   return true;
372 }
373
374 /// clone - Make a copy of this tree and all of its children.
375 ///
376 TreePatternNode *TreePatternNode::clone() const {
377   TreePatternNode *New;
378   if (isLeaf()) {
379     New = new TreePatternNode(getLeafValue());
380   } else {
381     std::vector<TreePatternNode*> CChildren;
382     CChildren.reserve(Children.size());
383     for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
384       CChildren.push_back(getChild(i)->clone());
385     New = new TreePatternNode(getOperator(), CChildren);
386   }
387   New->setName(getName());
388   New->setType(getExtType());
389   New->setPredicateFn(getPredicateFn());
390   New->setTransformFn(getTransformFn());
391   return New;
392 }
393
394 /// SubstituteFormalArguments - Replace the formal arguments in this tree
395 /// with actual values specified by ArgMap.
396 void TreePatternNode::
397 SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
398   if (isLeaf()) return;
399   
400   for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
401     TreePatternNode *Child = getChild(i);
402     if (Child->isLeaf()) {
403       Init *Val = Child->getLeafValue();
404       if (dynamic_cast<DefInit*>(Val) &&
405           static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
406         // We found a use of a formal argument, replace it with its value.
407         Child = ArgMap[Child->getName()];
408         assert(Child && "Couldn't find formal argument!");
409         setChild(i, Child);
410       }
411     } else {
412       getChild(i)->SubstituteFormalArguments(ArgMap);
413     }
414   }
415 }
416
417
418 /// InlinePatternFragments - If this pattern refers to any pattern
419 /// fragments, inline them into place, giving us a pattern without any
420 /// PatFrag references.
421 TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
422   if (isLeaf()) return this;  // nothing to do.
423   Record *Op = getOperator();
424   
425   if (!Op->isSubClassOf("PatFrag")) {
426     // Just recursively inline children nodes.
427     for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
428       setChild(i, getChild(i)->InlinePatternFragments(TP));
429     return this;
430   }
431
432   // Otherwise, we found a reference to a fragment.  First, look up its
433   // TreePattern record.
434   TreePattern *Frag = TP.getDAGISelEmitter().getPatternFragment(Op);
435   
436   // Verify that we are passing the right number of operands.
437   if (Frag->getNumArgs() != Children.size())
438     TP.error("'" + Op->getName() + "' fragment requires " +
439              utostr(Frag->getNumArgs()) + " operands!");
440
441   TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
442
443   // Resolve formal arguments to their actual value.
444   if (Frag->getNumArgs()) {
445     // Compute the map of formal to actual arguments.
446     std::map<std::string, TreePatternNode*> ArgMap;
447     for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
448       ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
449   
450     FragTree->SubstituteFormalArguments(ArgMap);
451   }
452   
453   FragTree->setName(getName());
454   FragTree->UpdateNodeType(getExtType(), TP);
455   
456   // Get a new copy of this fragment to stitch into here.
457   //delete this;    // FIXME: implement refcounting!
458   return FragTree;
459 }
460
461 /// getIntrinsicType - Check to see if the specified record has an intrinsic
462 /// type which should be applied to it.  This infer the type of register
463 /// references from the register file information, for example.
464 ///
465 static unsigned char getIntrinsicType(Record *R, bool NotRegisters,
466                                       TreePattern &TP) {
467   // Check to see if this is a register or a register class...
468   if (R->isSubClassOf("RegisterClass")) {
469     if (NotRegisters) return MVT::isUnknown;
470     const CodeGenRegisterClass &RC = 
471       TP.getDAGISelEmitter().getTargetInfo().getRegisterClass(R);
472     return RC.getValueTypeNum(0);
473   } else if (R->isSubClassOf("PatFrag")) {
474     // Pattern fragment types will be resolved when they are inlined.
475     return MVT::isUnknown;
476   } else if (R->isSubClassOf("Register")) {
477     // If the register appears in exactly one regclass, and the regclass has one
478     // value type, use it as the known type.
479     const CodeGenTarget &T = TP.getDAGISelEmitter().getTargetInfo();
480     if (const CodeGenRegisterClass *RC = T.getRegisterClassForRegister(R))
481       if (RC->getNumValueTypes() == 1)
482         return RC->getValueTypeNum(0);
483     return MVT::isUnknown;
484   } else if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
485     // Using a VTSDNode or CondCodeSDNode.
486     return MVT::Other;
487   } else if (R->isSubClassOf("ComplexPattern")) {
488     return TP.getDAGISelEmitter().getComplexPattern(R).getValueType();
489   } else if (R->getName() == "node" || R->getName() == "srcvalue") {
490     // Placeholder.
491     return MVT::isUnknown;
492   }
493   
494   TP.error("Unknown node flavor used in pattern: " + R->getName());
495   return MVT::Other;
496 }
497
498 /// ApplyTypeConstraints - Apply all of the type constraints relevent to
499 /// this node and its children in the tree.  This returns true if it makes a
500 /// change, false otherwise.  If a type contradiction is found, throw an
501 /// exception.
502 bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
503   if (isLeaf()) {
504     if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
505       // If it's a regclass or something else known, include the type.
506       return UpdateNodeType(getIntrinsicType(DI->getDef(), NotRegisters, TP),
507                             TP);
508     } else if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
509       // Int inits are always integers. :)
510       bool MadeChange = UpdateNodeType(MVT::isInt, TP);
511       
512       if (hasTypeSet()) {
513         unsigned Size = MVT::getSizeInBits(getType());
514         // Make sure that the value is representable for this type.
515         if (Size < 32) {
516           int Val = (II->getValue() << (32-Size)) >> (32-Size);
517           if (Val != II->getValue())
518             TP.error("Sign-extended integer value '" + itostr(II->getValue()) +
519                      "' is out of range for type 'MVT::" + 
520                      getEnumName(getType()) + "'!");
521         }
522       }
523       
524       return MadeChange;
525     }
526     return false;
527   }
528   
529   // special handling for set, which isn't really an SDNode.
530   if (getOperator()->getName() == "set") {
531     assert (getNumChildren() == 2 && "Only handle 2 operand set's for now!");
532     bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
533     MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
534     
535     // Types of operands must match.
536     MadeChange |= getChild(0)->UpdateNodeType(getChild(1)->getExtType(), TP);
537     MadeChange |= getChild(1)->UpdateNodeType(getChild(0)->getExtType(), TP);
538     MadeChange |= UpdateNodeType(MVT::isVoid, TP);
539     return MadeChange;
540   } else if (getOperator()->isSubClassOf("SDNode")) {
541     const SDNodeInfo &NI = TP.getDAGISelEmitter().getSDNodeInfo(getOperator());
542     
543     bool MadeChange = NI.ApplyTypeConstraints(this, TP);
544     for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
545       MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
546     // Branch, etc. do not produce results and top-level forms in instr pattern
547     // must have void types.
548     if (NI.getNumResults() == 0)
549       MadeChange |= UpdateNodeType(MVT::isVoid, TP);
550     return MadeChange;  
551   } else if (getOperator()->isSubClassOf("Instruction")) {
552     const DAGInstruction &Inst =
553       TP.getDAGISelEmitter().getInstruction(getOperator());
554     bool MadeChange = false;
555     unsigned NumResults = Inst.getNumResults();
556     
557     assert(NumResults <= 1 &&
558            "Only supports zero or one result instrs!");
559     // Apply the result type to the node
560     if (NumResults == 0) {
561       MadeChange = UpdateNodeType(MVT::isVoid, TP);
562     } else {
563       Record *ResultNode = Inst.getResult(0);
564       assert(ResultNode->isSubClassOf("RegisterClass") &&
565              "Operands should be register classes!");
566
567       const CodeGenRegisterClass &RC = 
568         TP.getDAGISelEmitter().getTargetInfo().getRegisterClass(ResultNode);
569
570       // Get the first ValueType in the RegClass, it's as good as any.
571       MadeChange = UpdateNodeType(RC.getValueTypeNum(0), TP);
572     }
573
574     if (getNumChildren() != Inst.getNumOperands())
575       TP.error("Instruction '" + getOperator()->getName() + " expects " +
576                utostr(Inst.getNumOperands()) + " operands, not " +
577                utostr(getNumChildren()) + " operands!");
578     for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
579       Record *OperandNode = Inst.getOperand(i);
580       MVT::ValueType VT;
581       if (OperandNode->isSubClassOf("RegisterClass")) {
582         const CodeGenRegisterClass &RC = 
583           TP.getDAGISelEmitter().getTargetInfo().getRegisterClass(OperandNode);
584         VT = RC.getValueTypeNum(0);
585       } else if (OperandNode->isSubClassOf("Operand")) {
586         VT = getValueType(OperandNode->getValueAsDef("Type"));
587       } else {
588         assert(0 && "Unknown operand type!");
589         abort();
590       }
591       
592       MadeChange |= getChild(i)->UpdateNodeType(VT, TP);
593       MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
594     }
595     return MadeChange;
596   } else {
597     assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
598     
599     // Node transforms always take one operand, and take and return the same
600     // type.
601     if (getNumChildren() != 1)
602       TP.error("Node transform '" + getOperator()->getName() +
603                "' requires one operand!");
604     bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
605     MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
606     return MadeChange;
607   }
608 }
609
610 /// canPatternMatch - If it is impossible for this pattern to match on this
611 /// target, fill in Reason and return false.  Otherwise, return true.  This is
612 /// used as a santity check for .td files (to prevent people from writing stuff
613 /// that can never possibly work), and to prevent the pattern permuter from
614 /// generating stuff that is useless.
615 bool TreePatternNode::canPatternMatch(std::string &Reason, DAGISelEmitter &ISE){
616   if (isLeaf()) return true;
617
618   for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
619     if (!getChild(i)->canPatternMatch(Reason, ISE))
620       return false;
621
622   // If this node is a commutative operator, check that the LHS isn't an
623   // immediate.
624   const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(getOperator());
625   if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
626     // Scan all of the operands of the node and make sure that only the last one
627     // is a constant node.
628     for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i)
629       if (!getChild(i)->isLeaf() && 
630           getChild(i)->getOperator()->getName() == "imm") {
631         Reason = "Immediate value must be on the RHS of commutative operators!";
632         return false;
633       }
634   }
635   
636   return true;
637 }
638
639 //===----------------------------------------------------------------------===//
640 // TreePattern implementation
641 //
642
643 TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
644                          DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
645    isInputPattern = isInput;
646    for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
647      Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
648 }
649
650 TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
651                          DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
652   isInputPattern = isInput;
653   Trees.push_back(ParseTreePattern(Pat));
654 }
655
656 TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
657                          DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
658   isInputPattern = isInput;
659   Trees.push_back(Pat);
660 }
661
662
663
664 void TreePattern::error(const std::string &Msg) const {
665   dump();
666   throw "In " + TheRecord->getName() + ": " + Msg;
667 }
668
669 TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
670   Record *Operator = Dag->getNodeType();
671   
672   if (Operator->isSubClassOf("ValueType")) {
673     // If the operator is a ValueType, then this must be "type cast" of a leaf
674     // node.
675     if (Dag->getNumArgs() != 1)
676       error("Type cast only takes one operand!");
677     
678     Init *Arg = Dag->getArg(0);
679     TreePatternNode *New;
680     if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
681       Record *R = DI->getDef();
682       if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
683         Dag->setArg(0, new DagInit(R,
684                                 std::vector<std::pair<Init*, std::string> >()));
685         return ParseTreePattern(Dag);
686       }
687       New = new TreePatternNode(DI);
688     } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
689       New = ParseTreePattern(DI);
690     } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
691       New = new TreePatternNode(II);
692       if (!Dag->getArgName(0).empty())
693         error("Constant int argument should not have a name!");
694     } else {
695       Arg->dump();
696       error("Unknown leaf value for tree pattern!");
697       return 0;
698     }
699     
700     // Apply the type cast.
701     New->UpdateNodeType(getValueType(Operator), *this);
702     New->setName(Dag->getArgName(0));
703     return New;
704   }
705   
706   // Verify that this is something that makes sense for an operator.
707   if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
708       !Operator->isSubClassOf("Instruction") && 
709       !Operator->isSubClassOf("SDNodeXForm") &&
710       Operator->getName() != "set")
711     error("Unrecognized node '" + Operator->getName() + "'!");
712   
713   //  Check to see if this is something that is illegal in an input pattern.
714   if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
715       Operator->isSubClassOf("SDNodeXForm")))
716     error("Cannot use '" + Operator->getName() + "' in an input pattern!");
717   
718   std::vector<TreePatternNode*> Children;
719   
720   for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
721     Init *Arg = Dag->getArg(i);
722     if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
723       Children.push_back(ParseTreePattern(DI));
724       if (Children.back()->getName().empty())
725         Children.back()->setName(Dag->getArgName(i));
726     } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
727       Record *R = DefI->getDef();
728       // Direct reference to a leaf DagNode or PatFrag?  Turn it into a
729       // TreePatternNode if its own.
730       if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
731         Dag->setArg(i, new DagInit(R,
732                               std::vector<std::pair<Init*, std::string> >()));
733         --i;  // Revisit this node...
734       } else {
735         TreePatternNode *Node = new TreePatternNode(DefI);
736         Node->setName(Dag->getArgName(i));
737         Children.push_back(Node);
738         
739         // Input argument?
740         if (R->getName() == "node") {
741           if (Dag->getArgName(i).empty())
742             error("'node' argument requires a name to match with operand list");
743           Args.push_back(Dag->getArgName(i));
744         }
745       }
746     } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
747       TreePatternNode *Node = new TreePatternNode(II);
748       if (!Dag->getArgName(i).empty())
749         error("Constant int argument should not have a name!");
750       Children.push_back(Node);
751     } else {
752       std::cerr << '"';
753       Arg->dump();
754       std::cerr << "\": ";
755       error("Unknown leaf value for tree pattern!");
756     }
757   }
758   
759   return new TreePatternNode(Operator, Children);
760 }
761
762 /// InferAllTypes - Infer/propagate as many types throughout the expression
763 /// patterns as possible.  Return true if all types are infered, false
764 /// otherwise.  Throw an exception if a type contradiction is found.
765 bool TreePattern::InferAllTypes() {
766   bool MadeChange = true;
767   while (MadeChange) {
768     MadeChange = false;
769     for (unsigned i = 0, e = Trees.size(); i != e; ++i)
770       MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
771   }
772   
773   bool HasUnresolvedTypes = false;
774   for (unsigned i = 0, e = Trees.size(); i != e; ++i)
775     HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
776   return !HasUnresolvedTypes;
777 }
778
779 void TreePattern::print(std::ostream &OS) const {
780   OS << getRecord()->getName();
781   if (!Args.empty()) {
782     OS << "(" << Args[0];
783     for (unsigned i = 1, e = Args.size(); i != e; ++i)
784       OS << ", " << Args[i];
785     OS << ")";
786   }
787   OS << ": ";
788   
789   if (Trees.size() > 1)
790     OS << "[\n";
791   for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
792     OS << "\t";
793     Trees[i]->print(OS);
794     OS << "\n";
795   }
796
797   if (Trees.size() > 1)
798     OS << "]\n";
799 }
800
801 void TreePattern::dump() const { print(std::cerr); }
802
803
804
805 //===----------------------------------------------------------------------===//
806 // DAGISelEmitter implementation
807 //
808
809 // Parse all of the SDNode definitions for the target, populating SDNodes.
810 void DAGISelEmitter::ParseNodeInfo() {
811   std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
812   while (!Nodes.empty()) {
813     SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
814     Nodes.pop_back();
815   }
816 }
817
818 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
819 /// map, and emit them to the file as functions.
820 void DAGISelEmitter::ParseNodeTransforms(std::ostream &OS) {
821   OS << "\n// Node transformations.\n";
822   std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
823   while (!Xforms.empty()) {
824     Record *XFormNode = Xforms.back();
825     Record *SDNode = XFormNode->getValueAsDef("Opcode");
826     std::string Code = XFormNode->getValueAsCode("XFormFunction");
827     SDNodeXForms.insert(std::make_pair(XFormNode,
828                                        std::make_pair(SDNode, Code)));
829
830     if (!Code.empty()) {
831       std::string ClassName = getSDNodeInfo(SDNode).getSDClassName();
832       const char *C2 = ClassName == "SDNode" ? "N" : "inN";
833
834       OS << "inline SDOperand Transform_" << XFormNode->getName()
835          << "(SDNode *" << C2 << ") {\n";
836       if (ClassName != "SDNode")
837         OS << "  " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
838       OS << Code << "\n}\n";
839     }
840
841     Xforms.pop_back();
842   }
843 }
844
845 void DAGISelEmitter::ParseComplexPatterns() {
846   std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
847   while (!AMs.empty()) {
848     ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
849     AMs.pop_back();
850   }
851 }
852
853
854 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
855 /// file, building up the PatternFragments map.  After we've collected them all,
856 /// inline fragments together as necessary, so that there are no references left
857 /// inside a pattern fragment to a pattern fragment.
858 ///
859 /// This also emits all of the predicate functions to the output file.
860 ///
861 void DAGISelEmitter::ParsePatternFragments(std::ostream &OS) {
862   std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
863   
864   // First step, parse all of the fragments and emit predicate functions.
865   OS << "\n// Predicate functions.\n";
866   for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
867     DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
868     TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
869     PatternFragments[Fragments[i]] = P;
870     
871     // Validate the argument list, converting it to map, to discard duplicates.
872     std::vector<std::string> &Args = P->getArgList();
873     std::set<std::string> OperandsMap(Args.begin(), Args.end());
874     
875     if (OperandsMap.count(""))
876       P->error("Cannot have unnamed 'node' values in pattern fragment!");
877     
878     // Parse the operands list.
879     DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
880     if (OpsList->getNodeType()->getName() != "ops")
881       P->error("Operands list should start with '(ops ... '!");
882     
883     // Copy over the arguments.       
884     Args.clear();
885     for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
886       if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
887           static_cast<DefInit*>(OpsList->getArg(j))->
888           getDef()->getName() != "node")
889         P->error("Operands list should all be 'node' values.");
890       if (OpsList->getArgName(j).empty())
891         P->error("Operands list should have names for each operand!");
892       if (!OperandsMap.count(OpsList->getArgName(j)))
893         P->error("'" + OpsList->getArgName(j) +
894                  "' does not occur in pattern or was multiply specified!");
895       OperandsMap.erase(OpsList->getArgName(j));
896       Args.push_back(OpsList->getArgName(j));
897     }
898     
899     if (!OperandsMap.empty())
900       P->error("Operands list does not contain an entry for operand '" +
901                *OperandsMap.begin() + "'!");
902
903     // If there is a code init for this fragment, emit the predicate code and
904     // keep track of the fact that this fragment uses it.
905     std::string Code = Fragments[i]->getValueAsCode("Predicate");
906     if (!Code.empty()) {
907       assert(!P->getOnlyTree()->isLeaf() && "Can't be a leaf!");
908       std::string ClassName =
909         getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
910       const char *C2 = ClassName == "SDNode" ? "N" : "inN";
911       
912       OS << "inline bool Predicate_" << Fragments[i]->getName()
913          << "(SDNode *" << C2 << ") {\n";
914       if (ClassName != "SDNode")
915         OS << "  " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
916       OS << Code << "\n}\n";
917       P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
918     }
919     
920     // If there is a node transformation corresponding to this, keep track of
921     // it.
922     Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
923     if (!getSDNodeTransform(Transform).second.empty())    // not noop xform?
924       P->getOnlyTree()->setTransformFn(Transform);
925   }
926   
927   OS << "\n\n";
928
929   // Now that we've parsed all of the tree fragments, do a closure on them so
930   // that there are not references to PatFrags left inside of them.
931   for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
932        E = PatternFragments.end(); I != E; ++I) {
933     TreePattern *ThePat = I->second;
934     ThePat->InlinePatternFragments();
935         
936     // Infer as many types as possible.  Don't worry about it if we don't infer
937     // all of them, some may depend on the inputs of the pattern.
938     try {
939       ThePat->InferAllTypes();
940     } catch (...) {
941       // If this pattern fragment is not supported by this target (no types can
942       // satisfy its constraints), just ignore it.  If the bogus pattern is
943       // actually used by instructions, the type consistency error will be
944       // reported there.
945     }
946     
947     // If debugging, print out the pattern fragment result.
948     DEBUG(ThePat->dump());
949   }
950 }
951
952 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
953 /// instruction input.  Return true if this is a real use.
954 static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
955                       std::map<std::string, TreePatternNode*> &InstInputs,
956                       std::vector<Record*> &InstImpInputs) {
957   // No name -> not interesting.
958   if (Pat->getName().empty()) {
959     if (Pat->isLeaf()) {
960       DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
961       if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
962         I->error("Input " + DI->getDef()->getName() + " must be named!");
963       else if (DI && DI->getDef()->isSubClassOf("Register")) {
964         InstImpInputs.push_back(DI->getDef());
965       }
966     }
967     return false;
968   }
969
970   Record *Rec;
971   if (Pat->isLeaf()) {
972     DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
973     if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
974     Rec = DI->getDef();
975   } else {
976     assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
977     Rec = Pat->getOperator();
978   }
979
980   // SRCVALUE nodes are ignored.
981   if (Rec->getName() == "srcvalue")
982     return false;
983
984   TreePatternNode *&Slot = InstInputs[Pat->getName()];
985   if (!Slot) {
986     Slot = Pat;
987   } else {
988     Record *SlotRec;
989     if (Slot->isLeaf()) {
990       SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
991     } else {
992       assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
993       SlotRec = Slot->getOperator();
994     }
995     
996     // Ensure that the inputs agree if we've already seen this input.
997     if (Rec != SlotRec)
998       I->error("All $" + Pat->getName() + " inputs must agree with each other");
999     if (Slot->getExtType() != Pat->getExtType())
1000       I->error("All $" + Pat->getName() + " inputs must agree with each other");
1001   }
1002   return true;
1003 }
1004
1005 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
1006 /// part of "I", the instruction), computing the set of inputs and outputs of
1007 /// the pattern.  Report errors if we see anything naughty.
1008 void DAGISelEmitter::
1009 FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
1010                             std::map<std::string, TreePatternNode*> &InstInputs,
1011                             std::map<std::string, Record*> &InstResults,
1012                             std::vector<Record*> &InstImpInputs,
1013                             std::vector<Record*> &InstImpResults) {
1014   if (Pat->isLeaf()) {
1015     bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1016     if (!isUse && Pat->getTransformFn())
1017       I->error("Cannot specify a transform function for a non-input value!");
1018     return;
1019   } else if (Pat->getOperator()->getName() != "set") {
1020     // If this is not a set, verify that the children nodes are not void typed,
1021     // and recurse.
1022     for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1023       if (Pat->getChild(i)->getExtType() == MVT::isVoid)
1024         I->error("Cannot have void nodes inside of patterns!");
1025       FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
1026                                   InstImpInputs, InstImpResults);
1027     }
1028     
1029     // If this is a non-leaf node with no children, treat it basically as if
1030     // it were a leaf.  This handles nodes like (imm).
1031     bool isUse = false;
1032     if (Pat->getNumChildren() == 0)
1033       isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1034     
1035     if (!isUse && Pat->getTransformFn())
1036       I->error("Cannot specify a transform function for a non-input value!");
1037     return;
1038   } 
1039   
1040   // Otherwise, this is a set, validate and collect instruction results.
1041   if (Pat->getNumChildren() == 0)
1042     I->error("set requires operands!");
1043   else if (Pat->getNumChildren() & 1)
1044     I->error("set requires an even number of operands");
1045   
1046   if (Pat->getTransformFn())
1047     I->error("Cannot specify a transform function on a set node!");
1048   
1049   // Check the set destinations.
1050   unsigned NumValues = Pat->getNumChildren()/2;
1051   for (unsigned i = 0; i != NumValues; ++i) {
1052     TreePatternNode *Dest = Pat->getChild(i);
1053     if (!Dest->isLeaf())
1054       I->error("set destination should be a register!");
1055     
1056     DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1057     if (!Val)
1058       I->error("set destination should be a register!");
1059
1060     if (Val->getDef()->isSubClassOf("RegisterClass")) {
1061       if (Dest->getName().empty())
1062         I->error("set destination must have a name!");
1063       if (InstResults.count(Dest->getName()))
1064         I->error("cannot set '" + Dest->getName() +"' multiple times");
1065       InstResults[Dest->getName()] = Val->getDef();
1066     } else if (Val->getDef()->isSubClassOf("Register")) {
1067       InstImpResults.push_back(Val->getDef());
1068     } else {
1069       I->error("set destination should be a register!");
1070     }
1071     
1072     // Verify and collect info from the computation.
1073     FindPatternInputsAndOutputs(I, Pat->getChild(i+NumValues),
1074                                 InstInputs, InstResults, InstImpInputs, InstImpResults);
1075   }
1076 }
1077
1078 /// NodeHasChain - return true if TreePatternNode has the property
1079 /// 'hasChain', meaning it reads a ctrl-flow chain operand and writes
1080 /// a chain result.
1081 static bool NodeHasChain(TreePatternNode *N, DAGISelEmitter &ISE)
1082 {
1083   if (N->isLeaf()) return false;
1084   Record *Operator = N->getOperator();
1085   if (!Operator->isSubClassOf("SDNode")) return false;
1086
1087   const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(Operator);
1088   return NodeInfo.hasProperty(SDNodeInfo::SDNPHasChain);
1089 }
1090
1091 static bool PatternHasCtrlDep(TreePatternNode *N, DAGISelEmitter &ISE)
1092 {
1093   if (NodeHasChain(N, ISE))
1094     return true;
1095   else {
1096     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
1097       TreePatternNode *Child = N->getChild(i);
1098       if (PatternHasCtrlDep(Child, ISE))
1099         return true;
1100     }
1101   }
1102
1103   return false;
1104 }
1105
1106
1107 /// ParseInstructions - Parse all of the instructions, inlining and resolving
1108 /// any fragments involved.  This populates the Instructions list with fully
1109 /// resolved instructions.
1110 void DAGISelEmitter::ParseInstructions() {
1111   std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
1112   
1113   for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
1114     ListInit *LI = 0;
1115     
1116     if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
1117       LI = Instrs[i]->getValueAsListInit("Pattern");
1118     
1119     // If there is no pattern, only collect minimal information about the
1120     // instruction for its operand list.  We have to assume that there is one
1121     // result, as we have no detailed info.
1122     if (!LI || LI->getSize() == 0) {
1123       std::vector<Record*> Results;
1124       std::vector<Record*> Operands;
1125       
1126       CodeGenInstruction &InstInfo =Target.getInstruction(Instrs[i]->getName());
1127       
1128       // Doesn't even define a result?
1129       if (InstInfo.OperandList.size() == 0)
1130         continue;
1131
1132       // FIXME: temporary hack...
1133       if (InstInfo.isReturn || InstInfo.isBranch || InstInfo.isCall ||
1134           InstInfo.isStore) {
1135         // These produce no results
1136         for (unsigned j = 0, e = InstInfo.OperandList.size(); j != e; ++j)
1137           Operands.push_back(InstInfo.OperandList[j].Rec);
1138       } else {
1139         // Assume the first operand is the result.
1140         Results.push_back(InstInfo.OperandList[0].Rec);
1141       
1142         // The rest are inputs.
1143         for (unsigned j = 1, e = InstInfo.OperandList.size(); j != e; ++j)
1144           Operands.push_back(InstInfo.OperandList[j].Rec);
1145       }
1146       
1147       // Create and insert the instruction.
1148       std::vector<Record*> ImpResults;
1149       std::vector<Record*> ImpOperands;
1150       Instructions.insert(std::make_pair(Instrs[i], 
1151                           DAGInstruction(0, Results, Operands,
1152                                          ImpResults, ImpOperands)));
1153       continue;  // no pattern.
1154     }
1155     
1156     // Parse the instruction.
1157     TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
1158     // Inline pattern fragments into it.
1159     I->InlinePatternFragments();
1160     
1161     // Infer as many types as possible.  If we cannot infer all of them, we can
1162     // never do anything with this instruction pattern: report it to the user.
1163     if (!I->InferAllTypes())
1164       I->error("Could not infer all types in pattern!");
1165     
1166     // InstInputs - Keep track of all of the inputs of the instruction, along 
1167     // with the record they are declared as.
1168     std::map<std::string, TreePatternNode*> InstInputs;
1169     
1170     // InstResults - Keep track of all the virtual registers that are 'set'
1171     // in the instruction, including what reg class they are.
1172     std::map<std::string, Record*> InstResults;
1173
1174     std::vector<Record*> InstImpInputs;
1175     std::vector<Record*> InstImpResults;
1176     
1177     // Verify that the top-level forms in the instruction are of void type, and
1178     // fill in the InstResults map.
1179     for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
1180       TreePatternNode *Pat = I->getTree(j);
1181       if (Pat->getExtType() != MVT::isVoid)
1182         I->error("Top-level forms in instruction pattern should have"
1183                  " void types");
1184
1185       // Find inputs and outputs, and verify the structure of the uses/defs.
1186       FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
1187                                   InstImpInputs, InstImpResults);
1188     }
1189
1190     // Now that we have inputs and outputs of the pattern, inspect the operands
1191     // list for the instruction.  This determines the order that operands are
1192     // added to the machine instruction the node corresponds to.
1193     unsigned NumResults = InstResults.size();
1194
1195     // Parse the operands list from the (ops) list, validating it.
1196     std::vector<std::string> &Args = I->getArgList();
1197     assert(Args.empty() && "Args list should still be empty here!");
1198     CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
1199
1200     // Check that all of the results occur first in the list.
1201     std::vector<Record*> Results;
1202     for (unsigned i = 0; i != NumResults; ++i) {
1203       if (i == CGI.OperandList.size())
1204         I->error("'" + InstResults.begin()->first +
1205                  "' set but does not appear in operand list!");
1206       const std::string &OpName = CGI.OperandList[i].Name;
1207       
1208       // Check that it exists in InstResults.
1209       Record *R = InstResults[OpName];
1210       if (R == 0)
1211         I->error("Operand $" + OpName + " should be a set destination: all "
1212                  "outputs must occur before inputs in operand list!");
1213       
1214       if (CGI.OperandList[i].Rec != R)
1215         I->error("Operand $" + OpName + " class mismatch!");
1216       
1217       // Remember the return type.
1218       Results.push_back(CGI.OperandList[i].Rec);
1219       
1220       // Okay, this one checks out.
1221       InstResults.erase(OpName);
1222     }
1223
1224     // Loop over the inputs next.  Make a copy of InstInputs so we can destroy
1225     // the copy while we're checking the inputs.
1226     std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
1227
1228     std::vector<TreePatternNode*> ResultNodeOperands;
1229     std::vector<Record*> Operands;
1230     for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
1231       const std::string &OpName = CGI.OperandList[i].Name;
1232       if (OpName.empty())
1233         I->error("Operand #" + utostr(i) + " in operands list has no name!");
1234
1235       if (!InstInputsCheck.count(OpName))
1236         I->error("Operand $" + OpName +
1237                  " does not appear in the instruction pattern");
1238       TreePatternNode *InVal = InstInputsCheck[OpName];
1239       InstInputsCheck.erase(OpName);   // It occurred, remove from map.
1240       
1241       if (InVal->isLeaf() &&
1242           dynamic_cast<DefInit*>(InVal->getLeafValue())) {
1243         Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
1244         if (CGI.OperandList[i].Rec != InRec &&
1245             !InRec->isSubClassOf("ComplexPattern"))
1246           I->error("Operand $" + OpName +
1247                    "'s register class disagrees between the operand and pattern");
1248       }
1249       Operands.push_back(CGI.OperandList[i].Rec);
1250       
1251       // Construct the result for the dest-pattern operand list.
1252       TreePatternNode *OpNode = InVal->clone();
1253       
1254       // No predicate is useful on the result.
1255       OpNode->setPredicateFn("");
1256       
1257       // Promote the xform function to be an explicit node if set.
1258       if (Record *Xform = OpNode->getTransformFn()) {
1259         OpNode->setTransformFn(0);
1260         std::vector<TreePatternNode*> Children;
1261         Children.push_back(OpNode);
1262         OpNode = new TreePatternNode(Xform, Children);
1263       }
1264       
1265       ResultNodeOperands.push_back(OpNode);
1266     }
1267     
1268     if (!InstInputsCheck.empty())
1269       I->error("Input operand $" + InstInputsCheck.begin()->first +
1270                " occurs in pattern but not in operands list!");
1271
1272     TreePatternNode *ResultPattern =
1273       new TreePatternNode(I->getRecord(), ResultNodeOperands);
1274
1275     // Create and insert the instruction.
1276     DAGInstruction TheInst(I, Results, Operands, InstImpResults, InstImpInputs);
1277     Instructions.insert(std::make_pair(I->getRecord(), TheInst));
1278
1279     // Use a temporary tree pattern to infer all types and make sure that the
1280     // constructed result is correct.  This depends on the instruction already
1281     // being inserted into the Instructions map.
1282     TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
1283     Temp.InferAllTypes();
1284
1285     DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
1286     TheInsertedInst.setResultPattern(Temp.getOnlyTree());
1287     
1288     DEBUG(I->dump());
1289   }
1290    
1291   // If we can, convert the instructions to be patterns that are matched!
1292   for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
1293        E = Instructions.end(); II != E; ++II) {
1294     DAGInstruction &TheInst = II->second;
1295     TreePattern *I = TheInst.getPattern();
1296     if (I == 0) continue;  // No pattern.
1297
1298     if (I->getNumTrees() != 1) {
1299       std::cerr << "CANNOT HANDLE: " << I->getRecord()->getName() << " yet!";
1300       continue;
1301     }
1302     TreePatternNode *Pattern = I->getTree(0);
1303     TreePatternNode *SrcPattern;
1304     if (Pattern->getOperator()->getName() == "set") {
1305       if (Pattern->getNumChildren() != 2)
1306         continue;  // Not a set of a single value (not handled so far)
1307
1308       SrcPattern = Pattern->getChild(1)->clone();    
1309     } else{
1310       // Not a set (store or something?)
1311       SrcPattern = Pattern;
1312     }
1313     
1314     std::string Reason;
1315     if (!SrcPattern->canPatternMatch(Reason, *this))
1316       I->error("Instruction can never match: " + Reason);
1317     
1318     Record *Instr = II->first;
1319     TreePatternNode *DstPattern = TheInst.getResultPattern();
1320     PatternsToMatch.
1321       push_back(PatternToMatch(Instr->getValueAsListInit("Predicates"),
1322                                SrcPattern, DstPattern));
1323
1324     if (PatternHasCtrlDep(Pattern, *this)) {
1325       CodeGenInstruction &InstInfo = Target.getInstruction(Instr->getName());
1326       InstInfo.hasCtrlDep = true;
1327     }
1328   }
1329 }
1330
1331 void DAGISelEmitter::ParsePatterns() {
1332   std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
1333
1334   for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1335     DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
1336     TreePattern *Pattern = new TreePattern(Patterns[i], Tree, true, *this);
1337
1338     // Inline pattern fragments into it.
1339     Pattern->InlinePatternFragments();
1340     
1341     // Infer as many types as possible.  If we cannot infer all of them, we can
1342     // never do anything with this pattern: report it to the user.
1343     if (!Pattern->InferAllTypes())
1344       Pattern->error("Could not infer all types in pattern!");
1345
1346     // Validate that the input pattern is correct.
1347     {
1348       std::map<std::string, TreePatternNode*> InstInputs;
1349       std::map<std::string, Record*> InstResults;
1350       std::vector<Record*> InstImpInputs;
1351       std::vector<Record*> InstImpResults;
1352       FindPatternInputsAndOutputs(Pattern, Pattern->getOnlyTree(),
1353                                   InstInputs, InstResults,
1354                                   InstImpInputs, InstImpResults);
1355     }
1356     
1357     ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
1358     if (LI->getSize() == 0) continue;  // no pattern.
1359     
1360     // Parse the instruction.
1361     TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
1362     
1363     // Inline pattern fragments into it.
1364     Result->InlinePatternFragments();
1365     
1366     // Infer as many types as possible.  If we cannot infer all of them, we can
1367     // never do anything with this pattern: report it to the user.
1368     if (!Result->InferAllTypes())
1369       Result->error("Could not infer all types in pattern result!");
1370    
1371     if (Result->getNumTrees() != 1)
1372       Result->error("Cannot handle instructions producing instructions "
1373                     "with temporaries yet!");
1374
1375     std::string Reason;
1376     if (!Pattern->getOnlyTree()->canPatternMatch(Reason, *this))
1377       Pattern->error("Pattern can never match: " + Reason);
1378     
1379     PatternsToMatch.
1380       push_back(PatternToMatch(Patterns[i]->getValueAsListInit("Predicates"),
1381                                Pattern->getOnlyTree(),
1382                                Result->getOnlyTree()));
1383   }
1384 }
1385
1386 /// CombineChildVariants - Given a bunch of permutations of each child of the
1387 /// 'operator' node, put them together in all possible ways.
1388 static void CombineChildVariants(TreePatternNode *Orig, 
1389                const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
1390                                  std::vector<TreePatternNode*> &OutVariants,
1391                                  DAGISelEmitter &ISE) {
1392   // Make sure that each operand has at least one variant to choose from.
1393   for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1394     if (ChildVariants[i].empty())
1395       return;
1396         
1397   // The end result is an all-pairs construction of the resultant pattern.
1398   std::vector<unsigned> Idxs;
1399   Idxs.resize(ChildVariants.size());
1400   bool NotDone = true;
1401   while (NotDone) {
1402     // Create the variant and add it to the output list.
1403     std::vector<TreePatternNode*> NewChildren;
1404     for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1405       NewChildren.push_back(ChildVariants[i][Idxs[i]]);
1406     TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
1407     
1408     // Copy over properties.
1409     R->setName(Orig->getName());
1410     R->setPredicateFn(Orig->getPredicateFn());
1411     R->setTransformFn(Orig->getTransformFn());
1412     R->setType(Orig->getExtType());
1413     
1414     // If this pattern cannot every match, do not include it as a variant.
1415     std::string ErrString;
1416     if (!R->canPatternMatch(ErrString, ISE)) {
1417       delete R;
1418     } else {
1419       bool AlreadyExists = false;
1420       
1421       // Scan to see if this pattern has already been emitted.  We can get
1422       // duplication due to things like commuting:
1423       //   (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
1424       // which are the same pattern.  Ignore the dups.
1425       for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
1426         if (R->isIsomorphicTo(OutVariants[i])) {
1427           AlreadyExists = true;
1428           break;
1429         }
1430       
1431       if (AlreadyExists)
1432         delete R;
1433       else
1434         OutVariants.push_back(R);
1435     }
1436     
1437     // Increment indices to the next permutation.
1438     NotDone = false;
1439     // Look for something we can increment without causing a wrap-around.
1440     for (unsigned IdxsIdx = 0; IdxsIdx != Idxs.size(); ++IdxsIdx) {
1441       if (++Idxs[IdxsIdx] < ChildVariants[IdxsIdx].size()) {
1442         NotDone = true;   // Found something to increment.
1443         break;
1444       }
1445       Idxs[IdxsIdx] = 0;
1446     }
1447   }
1448 }
1449
1450 /// CombineChildVariants - A helper function for binary operators.
1451 ///
1452 static void CombineChildVariants(TreePatternNode *Orig, 
1453                                  const std::vector<TreePatternNode*> &LHS,
1454                                  const std::vector<TreePatternNode*> &RHS,
1455                                  std::vector<TreePatternNode*> &OutVariants,
1456                                  DAGISelEmitter &ISE) {
1457   std::vector<std::vector<TreePatternNode*> > ChildVariants;
1458   ChildVariants.push_back(LHS);
1459   ChildVariants.push_back(RHS);
1460   CombineChildVariants(Orig, ChildVariants, OutVariants, ISE);
1461 }  
1462
1463
1464 static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
1465                                      std::vector<TreePatternNode *> &Children) {
1466   assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
1467   Record *Operator = N->getOperator();
1468   
1469   // Only permit raw nodes.
1470   if (!N->getName().empty() || !N->getPredicateFn().empty() ||
1471       N->getTransformFn()) {
1472     Children.push_back(N);
1473     return;
1474   }
1475
1476   if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
1477     Children.push_back(N->getChild(0));
1478   else
1479     GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
1480
1481   if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
1482     Children.push_back(N->getChild(1));
1483   else
1484     GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
1485 }
1486
1487 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
1488 /// the (potentially recursive) pattern by using algebraic laws.
1489 ///
1490 static void GenerateVariantsOf(TreePatternNode *N,
1491                                std::vector<TreePatternNode*> &OutVariants,
1492                                DAGISelEmitter &ISE) {
1493   // We cannot permute leaves.
1494   if (N->isLeaf()) {
1495     OutVariants.push_back(N);
1496     return;
1497   }
1498
1499   // Look up interesting info about the node.
1500   const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(N->getOperator());
1501
1502   // If this node is associative, reassociate.
1503   if (NodeInfo.hasProperty(SDNodeInfo::SDNPAssociative)) {
1504     // Reassociate by pulling together all of the linked operators 
1505     std::vector<TreePatternNode*> MaximalChildren;
1506     GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
1507
1508     // Only handle child sizes of 3.  Otherwise we'll end up trying too many
1509     // permutations.
1510     if (MaximalChildren.size() == 3) {
1511       // Find the variants of all of our maximal children.
1512       std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
1513       GenerateVariantsOf(MaximalChildren[0], AVariants, ISE);
1514       GenerateVariantsOf(MaximalChildren[1], BVariants, ISE);
1515       GenerateVariantsOf(MaximalChildren[2], CVariants, ISE);
1516       
1517       // There are only two ways we can permute the tree:
1518       //   (A op B) op C    and    A op (B op C)
1519       // Within these forms, we can also permute A/B/C.
1520       
1521       // Generate legal pair permutations of A/B/C.
1522       std::vector<TreePatternNode*> ABVariants;
1523       std::vector<TreePatternNode*> BAVariants;
1524       std::vector<TreePatternNode*> ACVariants;
1525       std::vector<TreePatternNode*> CAVariants;
1526       std::vector<TreePatternNode*> BCVariants;
1527       std::vector<TreePatternNode*> CBVariants;
1528       CombineChildVariants(N, AVariants, BVariants, ABVariants, ISE);
1529       CombineChildVariants(N, BVariants, AVariants, BAVariants, ISE);
1530       CombineChildVariants(N, AVariants, CVariants, ACVariants, ISE);
1531       CombineChildVariants(N, CVariants, AVariants, CAVariants, ISE);
1532       CombineChildVariants(N, BVariants, CVariants, BCVariants, ISE);
1533       CombineChildVariants(N, CVariants, BVariants, CBVariants, ISE);
1534
1535       // Combine those into the result: (x op x) op x
1536       CombineChildVariants(N, ABVariants, CVariants, OutVariants, ISE);
1537       CombineChildVariants(N, BAVariants, CVariants, OutVariants, ISE);
1538       CombineChildVariants(N, ACVariants, BVariants, OutVariants, ISE);
1539       CombineChildVariants(N, CAVariants, BVariants, OutVariants, ISE);
1540       CombineChildVariants(N, BCVariants, AVariants, OutVariants, ISE);
1541       CombineChildVariants(N, CBVariants, AVariants, OutVariants, ISE);
1542
1543       // Combine those into the result: x op (x op x)
1544       CombineChildVariants(N, CVariants, ABVariants, OutVariants, ISE);
1545       CombineChildVariants(N, CVariants, BAVariants, OutVariants, ISE);
1546       CombineChildVariants(N, BVariants, ACVariants, OutVariants, ISE);
1547       CombineChildVariants(N, BVariants, CAVariants, OutVariants, ISE);
1548       CombineChildVariants(N, AVariants, BCVariants, OutVariants, ISE);
1549       CombineChildVariants(N, AVariants, CBVariants, OutVariants, ISE);
1550       return;
1551     }
1552   }
1553   
1554   // Compute permutations of all children.
1555   std::vector<std::vector<TreePatternNode*> > ChildVariants;
1556   ChildVariants.resize(N->getNumChildren());
1557   for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1558     GenerateVariantsOf(N->getChild(i), ChildVariants[i], ISE);
1559
1560   // Build all permutations based on how the children were formed.
1561   CombineChildVariants(N, ChildVariants, OutVariants, ISE);
1562
1563   // If this node is commutative, consider the commuted order.
1564   if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
1565     assert(N->getNumChildren()==2 &&"Commutative but doesn't have 2 children!");
1566     // Consider the commuted order.
1567     CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
1568                          OutVariants, ISE);
1569   }
1570 }
1571
1572
1573 // GenerateVariants - Generate variants.  For example, commutative patterns can
1574 // match multiple ways.  Add them to PatternsToMatch as well.
1575 void DAGISelEmitter::GenerateVariants() {
1576   
1577   DEBUG(std::cerr << "Generating instruction variants.\n");
1578   
1579   // Loop over all of the patterns we've collected, checking to see if we can
1580   // generate variants of the instruction, through the exploitation of
1581   // identities.  This permits the target to provide agressive matching without
1582   // the .td file having to contain tons of variants of instructions.
1583   //
1584   // Note that this loop adds new patterns to the PatternsToMatch list, but we
1585   // intentionally do not reconsider these.  Any variants of added patterns have
1586   // already been added.
1587   //
1588   for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
1589     std::vector<TreePatternNode*> Variants;
1590     GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this);
1591
1592     assert(!Variants.empty() && "Must create at least original variant!");
1593     Variants.erase(Variants.begin());  // Remove the original pattern.
1594
1595     if (Variants.empty())  // No variants for this pattern.
1596       continue;
1597
1598     DEBUG(std::cerr << "FOUND VARIANTS OF: ";
1599           PatternsToMatch[i].getSrcPattern()->dump();
1600           std::cerr << "\n");
1601
1602     for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
1603       TreePatternNode *Variant = Variants[v];
1604
1605       DEBUG(std::cerr << "  VAR#" << v <<  ": ";
1606             Variant->dump();
1607             std::cerr << "\n");
1608       
1609       // Scan to see if an instruction or explicit pattern already matches this.
1610       bool AlreadyExists = false;
1611       for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
1612         // Check to see if this variant already exists.
1613         if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern())) {
1614           DEBUG(std::cerr << "  *** ALREADY EXISTS, ignoring variant.\n");
1615           AlreadyExists = true;
1616           break;
1617         }
1618       }
1619       // If we already have it, ignore the variant.
1620       if (AlreadyExists) continue;
1621
1622       // Otherwise, add it to the list of patterns we have.
1623       PatternsToMatch.
1624         push_back(PatternToMatch(PatternsToMatch[i].getPredicates(),
1625                                  Variant, PatternsToMatch[i].getDstPattern()));
1626     }
1627
1628     DEBUG(std::cerr << "\n");
1629   }
1630 }
1631
1632
1633 // NodeIsComplexPattern - return true if N is a leaf node and a subclass of
1634 // ComplexPattern.
1635 static bool NodeIsComplexPattern(TreePatternNode *N)
1636 {
1637   return (N->isLeaf() &&
1638           dynamic_cast<DefInit*>(N->getLeafValue()) &&
1639           static_cast<DefInit*>(N->getLeafValue())->getDef()->
1640           isSubClassOf("ComplexPattern"));
1641 }
1642
1643 // NodeGetComplexPattern - return the pointer to the ComplexPattern if N
1644 // is a leaf node and a subclass of ComplexPattern, else it returns NULL.
1645 static const ComplexPattern *NodeGetComplexPattern(TreePatternNode *N,
1646                                                    DAGISelEmitter &ISE)
1647 {
1648   if (N->isLeaf() &&
1649       dynamic_cast<DefInit*>(N->getLeafValue()) &&
1650       static_cast<DefInit*>(N->getLeafValue())->getDef()->
1651       isSubClassOf("ComplexPattern")) {
1652     return &ISE.getComplexPattern(static_cast<DefInit*>(N->getLeafValue())
1653                                   ->getDef());
1654   }
1655   return NULL;
1656 }
1657
1658 /// getPatternSize - Return the 'size' of this pattern.  We want to match large
1659 /// patterns before small ones.  This is used to determine the size of a
1660 /// pattern.
1661 static unsigned getPatternSize(TreePatternNode *P, DAGISelEmitter &ISE) {
1662   assert(isExtIntegerVT(P->getExtType()) || 
1663          isExtFloatingPointVT(P->getExtType()) ||
1664          P->getExtType() == MVT::isVoid ||
1665          P->getExtType() == MVT::Flag && "Not a valid pattern node to size!");
1666   unsigned Size = 1;  // The node itself.
1667
1668   // FIXME: This is a hack to statically increase the priority of patterns
1669   // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
1670   // Later we can allow complexity / cost for each pattern to be (optionally)
1671   // specified. To get best possible pattern match we'll need to dynamically
1672   // calculate the complexity of all patterns a dag can potentially map to.
1673   const ComplexPattern *AM = NodeGetComplexPattern(P, ISE);
1674   if (AM)
1675     Size += AM->getNumOperands();
1676     
1677   // Count children in the count if they are also nodes.
1678   for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
1679     TreePatternNode *Child = P->getChild(i);
1680     if (!Child->isLeaf() && Child->getExtType() != MVT::Other)
1681       Size += getPatternSize(Child, ISE);
1682     else if (Child->isLeaf()) {
1683       if (dynamic_cast<IntInit*>(Child->getLeafValue())) 
1684         ++Size;  // Matches a ConstantSDNode.
1685       else if (NodeIsComplexPattern(Child))
1686         Size += getPatternSize(Child, ISE);
1687     }
1688   }
1689   
1690   return Size;
1691 }
1692
1693 /// getResultPatternCost - Compute the number of instructions for this pattern.
1694 /// This is a temporary hack.  We should really include the instruction
1695 /// latencies in this calculation.
1696 static unsigned getResultPatternCost(TreePatternNode *P) {
1697   if (P->isLeaf()) return 0;
1698   
1699   unsigned Cost = P->getOperator()->isSubClassOf("Instruction");
1700   for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
1701     Cost += getResultPatternCost(P->getChild(i));
1702   return Cost;
1703 }
1704
1705 // PatternSortingPredicate - return true if we prefer to match LHS before RHS.
1706 // In particular, we want to match maximal patterns first and lowest cost within
1707 // a particular complexity first.
1708 struct PatternSortingPredicate {
1709   PatternSortingPredicate(DAGISelEmitter &ise) : ISE(ise) {};
1710   DAGISelEmitter &ISE;
1711
1712   bool operator()(PatternToMatch *LHS,
1713                   PatternToMatch *RHS) {
1714     unsigned LHSSize = getPatternSize(LHS->getSrcPattern(), ISE);
1715     unsigned RHSSize = getPatternSize(RHS->getSrcPattern(), ISE);
1716     if (LHSSize > RHSSize) return true;   // LHS -> bigger -> less cost
1717     if (LHSSize < RHSSize) return false;
1718     
1719     // If the patterns have equal complexity, compare generated instruction cost
1720     return getResultPatternCost(LHS->getDstPattern()) <
1721       getResultPatternCost(RHS->getDstPattern());
1722   }
1723 };
1724
1725 /// getRegisterValueType - Look up and return the first ValueType of specified 
1726 /// RegisterClass record
1727 static MVT::ValueType getRegisterValueType(Record *R, const CodeGenTarget &T) {
1728   if (const CodeGenRegisterClass *RC = T.getRegisterClassForRegister(R))
1729     return RC->getValueTypeNum(0);
1730   return MVT::Other;
1731 }
1732
1733
1734 /// RemoveAllTypes - A quick recursive walk over a pattern which removes all
1735 /// type information from it.
1736 static void RemoveAllTypes(TreePatternNode *N) {
1737   N->setType(MVT::isUnknown);
1738   if (!N->isLeaf())
1739     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1740       RemoveAllTypes(N->getChild(i));
1741 }
1742
1743 Record *DAGISelEmitter::getSDNodeNamed(const std::string &Name) const {
1744   Record *N = Records.getDef(Name);
1745   assert(N && N->isSubClassOf("SDNode") && "Bad argument");
1746   return N;
1747 }
1748
1749 class PatternCodeEmitter {
1750 private:
1751   DAGISelEmitter &ISE;
1752
1753   // Predicates.
1754   ListInit *Predicates;
1755   // Instruction selector pattern.
1756   TreePatternNode *Pattern;
1757   // Matched instruction.
1758   TreePatternNode *Instruction;
1759   unsigned PatternNo;
1760   std::ostream &OS;
1761   // Node to name mapping
1762   std::map<std::string,std::string> VariableMap;
1763   // Names of all the folded nodes which produce chains.
1764   std::vector<std::pair<std::string, unsigned> > FoldedChains;
1765   bool FoundChain;
1766   unsigned TmpNo;
1767
1768 public:
1769   PatternCodeEmitter(DAGISelEmitter &ise, ListInit *preds,
1770                      TreePatternNode *pattern, TreePatternNode *instr,
1771                      unsigned PatNum, std::ostream &os) :
1772     ISE(ise), Predicates(preds), Pattern(pattern), Instruction(instr),
1773     PatternNo(PatNum), OS(os), FoundChain(false), TmpNo(0) {};
1774
1775   /// DeclareSDOperand - Emit "SDOperand <opname>" or "<opname>".  This works
1776   /// around an ugly GCC bug where SelectCode is using too much stack space
1777   void DeclareSDOperand(const std::string &OpName) const {
1778     // If it's one of the common cases declared at the top of SelectCode, just
1779     // use the existing declaration.
1780     if (OpName == "N0" || OpName == "N1" || OpName == "N2" || 
1781         OpName == "N00" || OpName == "N01" || 
1782         OpName == "N10" || OpName == "N11" || 
1783         OpName == "Tmp0" || OpName == "Tmp1" || 
1784         OpName == "Tmp2" || OpName == "Tmp3")
1785       OS << OpName;
1786     else
1787       OS << "SDOperand " << OpName;
1788   }
1789   
1790   /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
1791   /// if the match fails. At this point, we already know that the opcode for N
1792   /// matches, and the SDNode for the result has the RootName specified name.
1793   void EmitMatchCode(TreePatternNode *N, const std::string &RootName,
1794                      bool isRoot = false) {
1795
1796     // Emit instruction predicates. Each predicate is just a string for now.
1797     if (isRoot) {
1798       for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
1799         if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
1800           Record *Def = Pred->getDef();
1801           if (Def->isSubClassOf("Predicate")) {
1802             if (i == 0)
1803               OS << "      if (";
1804             else
1805               OS << " && ";
1806             OS << "!(" << Def->getValueAsString("CondString") << ")";
1807             if (i == e-1)
1808               OS << ") goto P" << PatternNo << "Fail;\n";
1809           } else {
1810             Def->dump();
1811             assert(0 && "Unknown predicate type!");
1812           }
1813         }
1814       }
1815     }
1816
1817     if (N->isLeaf()) {
1818       if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
1819         OS << "      if (cast<ConstantSDNode>(" << RootName
1820            << ")->getSignExtended() != " << II->getValue() << ")\n"
1821            << "        goto P" << PatternNo << "Fail;\n";
1822         return;
1823       } else if (!NodeIsComplexPattern(N)) {
1824         assert(0 && "Cannot match this as a leaf value!");
1825         abort();
1826       }
1827     }
1828   
1829     // If this node has a name associated with it, capture it in VariableMap.  If
1830     // we already saw this in the pattern, emit code to verify dagness.
1831     if (!N->getName().empty()) {
1832       std::string &VarMapEntry = VariableMap[N->getName()];
1833       if (VarMapEntry.empty()) {
1834         VarMapEntry = RootName;
1835       } else {
1836         // If we get here, this is a second reference to a specific name.  Since
1837         // we already have checked that the first reference is valid, we don't
1838         // have to recursively match it, just check that it's the same as the
1839         // previously named thing.
1840         OS << "      if (" << VarMapEntry << " != " << RootName
1841            << ") goto P" << PatternNo << "Fail;\n";
1842         return;
1843       }
1844     }
1845
1846
1847     // Emit code to load the child nodes and match their contents recursively.
1848     unsigned OpNo = 0;
1849     bool HasChain = NodeHasChain(N, ISE);
1850     if (HasChain) {
1851       OpNo = 1;
1852       if (!isRoot) {
1853         const SDNodeInfo &CInfo = ISE.getSDNodeInfo(N->getOperator());
1854         OS << "      if (!" << RootName << ".hasOneUse()) goto P"
1855            << PatternNo << "Fail;   // Multiple uses of actual result?\n";
1856         OS << "      if (CodeGenMap.count(" << RootName
1857            << ".getValue(" << CInfo.getNumResults() << "))) goto P"
1858            << PatternNo << "Fail;   // Already selected for a chain use?\n";
1859       }
1860     }
1861
1862     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
1863       OS << "      ";
1864       DeclareSDOperand(RootName+utostr(OpNo));
1865       OS << " = " << RootName << ".getOperand(" << OpNo << ");\n";
1866       TreePatternNode *Child = N->getChild(i);
1867     
1868       if (!Child->isLeaf()) {
1869         // If it's not a leaf, recursively match.
1870         const SDNodeInfo &CInfo = ISE.getSDNodeInfo(Child->getOperator());
1871         OS << "      if (" << RootName << OpNo << ".getOpcode() != "
1872            << CInfo.getEnumName() << ") goto P" << PatternNo << "Fail;\n";
1873         EmitMatchCode(Child, RootName + utostr(OpNo));
1874         if (NodeHasChain(Child, ISE)) {
1875           FoldedChains.push_back(std::make_pair(RootName + utostr(OpNo),
1876                                                 CInfo.getNumResults()));
1877         }
1878       } else {
1879         // If this child has a name associated with it, capture it in VarMap.  If
1880         // we already saw this in the pattern, emit code to verify dagness.
1881         if (!Child->getName().empty()) {
1882           std::string &VarMapEntry = VariableMap[Child->getName()];
1883           if (VarMapEntry.empty()) {
1884             VarMapEntry = RootName + utostr(OpNo);
1885           } else {
1886             // If we get here, this is a second reference to a specific name.  Since
1887             // we already have checked that the first reference is valid, we don't
1888             // have to recursively match it, just check that it's the same as the
1889             // previously named thing.
1890             OS << "      if (" << VarMapEntry << " != " << RootName << OpNo
1891                << ") goto P" << PatternNo << "Fail;\n";
1892             continue;
1893           }
1894         }
1895       
1896         // Handle leaves of various types.
1897         if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
1898           Record *LeafRec = DI->getDef();
1899           if (LeafRec->isSubClassOf("RegisterClass")) {
1900             // Handle register references.  Nothing to do here.
1901           } else if (LeafRec->isSubClassOf("Register")) {
1902           } else if (LeafRec->isSubClassOf("ComplexPattern")) {
1903             // Handle complex pattern. Nothing to do here.
1904           } else if (LeafRec->getName() == "srcvalue") {
1905             // Place holder for SRCVALUE nodes. Nothing to do here.
1906           } else if (LeafRec->isSubClassOf("ValueType")) {
1907             // Make sure this is the specified value type.
1908             OS << "      if (cast<VTSDNode>(" << RootName << OpNo << ")->getVT() != "
1909                << "MVT::" << LeafRec->getName() << ") goto P" << PatternNo
1910                << "Fail;\n";
1911           } else if (LeafRec->isSubClassOf("CondCode")) {
1912             // Make sure this is the specified cond code.
1913             OS << "      if (cast<CondCodeSDNode>(" << RootName << OpNo
1914                << ")->get() != " << "ISD::" << LeafRec->getName()
1915                << ") goto P" << PatternNo << "Fail;\n";
1916           } else {
1917             Child->dump();
1918             assert(0 && "Unknown leaf type!");
1919           }
1920         } else if (IntInit *II = dynamic_cast<IntInit*>(Child->getLeafValue())) {
1921           OS << "      if (!isa<ConstantSDNode>(" << RootName << OpNo << ") ||\n"
1922              << "          cast<ConstantSDNode>(" << RootName << OpNo
1923              << ")->getSignExtended() != " << II->getValue() << ")\n"
1924              << "        goto P" << PatternNo << "Fail;\n";
1925         } else {
1926           Child->dump();
1927           assert(0 && "Unknown leaf type!");
1928         }
1929       }
1930     }
1931
1932     if (HasChain) {
1933       if (!FoundChain) {
1934         OS << "      Chain = " << RootName << ".getOperand(0);\n";
1935         FoundChain = true;
1936       }
1937     }
1938
1939     // If there is a node predicate for this, emit the call.
1940     if (!N->getPredicateFn().empty())
1941       OS << "      if (!" << N->getPredicateFn() << "(" << RootName
1942          << ".Val)) goto P" << PatternNo << "Fail;\n";
1943   }
1944
1945   /// EmitResultCode - Emit the action for a pattern.  Now that it has matched
1946   /// we actually have to build a DAG!
1947   std::pair<unsigned, unsigned>
1948   EmitResultCode(TreePatternNode *N, bool isRoot = false) {
1949     // This is something selected from the pattern we matched.
1950     if (!N->getName().empty()) {
1951       assert(!isRoot && "Root of pattern cannot be a leaf!");
1952       std::string &Val = VariableMap[N->getName()];
1953       assert(!Val.empty() &&
1954              "Variable referenced but not defined and not caught earlier!");
1955       if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
1956         // Already selected this operand, just return the tmpval.
1957         return std::make_pair(1, atoi(Val.c_str()+3));
1958       }
1959
1960       const ComplexPattern *CP;
1961       unsigned ResNo = TmpNo++;
1962       unsigned NumRes = 1;
1963       if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
1964         switch (N->getType()) {
1965           default: assert(0 && "Unknown type for constant node!");
1966           case MVT::i1:  OS << "      bool Tmp"; break;
1967           case MVT::i8:  OS << "      unsigned char Tmp"; break;
1968           case MVT::i16: OS << "      unsigned short Tmp"; break;
1969           case MVT::i32: OS << "      unsigned Tmp"; break;
1970           case MVT::i64: OS << "      uint64_t Tmp"; break;
1971         }
1972         OS << ResNo << "C = cast<ConstantSDNode>(" << Val << ")->getValue();\n";
1973         OS << "      ";
1974         DeclareSDOperand("Tmp"+utostr(ResNo));
1975         OS << " = CurDAG->getTargetConstant(Tmp"
1976            << ResNo << "C, MVT::" << getEnumName(N->getType()) << ");\n";
1977       } else if (!N->isLeaf() && N->getOperator()->getName() == "tglobaladdr") {
1978         OS << "      ";
1979         DeclareSDOperand("Tmp"+utostr(ResNo));
1980         OS << " = " << Val << ";\n";
1981       } else if (!N->isLeaf() && N->getOperator()->getName() == "tconstpool") {
1982         OS << "      ";
1983         DeclareSDOperand("Tmp"+utostr(ResNo));
1984         OS << " = " << Val << ";\n";
1985       } else if (N->isLeaf() && (CP = NodeGetComplexPattern(N, ISE))) {
1986         std::string Fn = CP->getSelectFunc();
1987         NumRes = CP->getNumOperands();
1988         for (unsigned i = 0; i != NumRes; ++i) {
1989           OS << "      ";
1990           DeclareSDOperand("Tmp" + utostr(i+ResNo));
1991           OS << ";\n";
1992         }
1993         OS << "      if (!" << Fn << "(" << Val;
1994         for (unsigned i = 0; i < NumRes; i++)
1995           OS << ", Tmp" << i + ResNo;
1996         OS << ")) goto P" << PatternNo << "Fail;\n";
1997         TmpNo = ResNo + NumRes;
1998       } else {
1999         OS << "      ";
2000         DeclareSDOperand("Tmp"+utostr(ResNo));
2001         OS << " = Select(" << Val << ");\n";
2002       }
2003       // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
2004       // value if used multiple times by this pattern result.
2005       Val = "Tmp"+utostr(ResNo);
2006       return std::make_pair(NumRes, ResNo);
2007     }
2008   
2009     if (N->isLeaf()) {
2010       // If this is an explicit register reference, handle it.
2011       if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
2012         unsigned ResNo = TmpNo++;
2013         if (DI->getDef()->isSubClassOf("Register")) {
2014           OS << "      ";
2015           DeclareSDOperand("Tmp"+utostr(ResNo));
2016           OS << " = CurDAG->getRegister("
2017              << ISE.getQualifiedName(DI->getDef()) << ", MVT::"
2018              << getEnumName(N->getType())
2019              << ");\n";
2020           return std::make_pair(1, ResNo);
2021         }
2022       } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
2023         unsigned ResNo = TmpNo++;
2024         OS << "      ";
2025         DeclareSDOperand("Tmp"+utostr(ResNo));
2026         OS << " = CurDAG->getTargetConstant("
2027            << II->getValue() << ", MVT::"
2028            << getEnumName(N->getType())
2029            << ");\n";
2030         return std::make_pair(1, ResNo);
2031       }
2032     
2033       N->dump();
2034       assert(0 && "Unknown leaf type!");
2035       return std::make_pair(1, ~0U);
2036     }
2037
2038     Record *Op = N->getOperator();
2039     if (Op->isSubClassOf("Instruction")) {
2040       const DAGInstruction &Inst = ISE.getInstruction(Op);
2041       unsigned NumImpResults  = Inst.getNumImpResults();
2042       unsigned NumImpOperands = Inst.getNumImpOperands();
2043       bool InFlag  = NumImpOperands > 0;
2044       bool OutFlag = NumImpResults > 0;
2045       bool IsCopyFromReg = false;
2046
2047       if (InFlag || OutFlag)
2048         OS << "      InFlag = SDOperand(0, 0);\n";
2049
2050       // Determine operand emission order. Complex pattern first.
2051       std::vector<std::pair<unsigned, TreePatternNode*> > EmitOrder;
2052       std::vector<std::pair<unsigned, TreePatternNode*> >::iterator OI;
2053       for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2054         TreePatternNode *Child = N->getChild(i);
2055         if (i == 0) {
2056           EmitOrder.push_back(std::make_pair(i, Child));
2057           OI = EmitOrder.begin();
2058         } else if (NodeIsComplexPattern(Child)) {
2059           OI = EmitOrder.insert(OI, std::make_pair(i, Child));
2060         } else {
2061           EmitOrder.push_back(std::make_pair(i, Child));
2062         }
2063       }
2064
2065       // Emit all of the operands.
2066       std::vector<std::pair<unsigned, unsigned> > NumTemps(EmitOrder.size());
2067       for (unsigned i = 0, e = EmitOrder.size(); i != e; ++i) {
2068         unsigned OpOrder       = EmitOrder[i].first;
2069         TreePatternNode *Child = EmitOrder[i].second;
2070         std::pair<unsigned, unsigned> NumTemp =  EmitResultCode(Child);
2071         NumTemps[OpOrder] = NumTemp;
2072       }
2073
2074       // List all the operands in the right order.
2075       std::vector<unsigned> Ops;
2076       for (unsigned i = 0, e = NumTemps.size(); i != e; i++) {
2077         for (unsigned j = 0; j < NumTemps[i].first; j++)
2078           Ops.push_back(NumTemps[i].second + j);
2079       }
2080
2081       const CodeGenTarget &CGT = ISE.getTargetInfo();
2082       CodeGenInstruction &II = CGT.getInstruction(Op->getName());
2083
2084       // Emit all the chain and CopyToReg stuff.
2085       if (II.hasCtrlDep)
2086         OS << "      Chain = Select(Chain);\n";
2087       if (InFlag)
2088         EmitCopyToRegs(Pattern, "N", II.hasCtrlDep);
2089
2090       unsigned NumResults = Inst.getNumResults();    
2091       unsigned ResNo = TmpNo++;
2092       if (!isRoot) {
2093         OS << "      ";
2094         DeclareSDOperand("Tmp"+utostr(ResNo));
2095         OS << " = CurDAG->getTargetNode("
2096            << II.Namespace << "::" << II.TheDef->getName();
2097         if (N->getType() != MVT::isVoid)
2098           OS << ", MVT::" << getEnumName(N->getType());
2099         if (OutFlag)
2100           OS << ", MVT::Flag";
2101
2102         unsigned LastOp = 0;
2103         for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2104           LastOp = Ops[i];
2105           OS << ", Tmp" << LastOp;
2106         }
2107         OS << ");\n";
2108         if (II.hasCtrlDep) {
2109           // Must have at least one result
2110           OS << "      Chain = Tmp" << LastOp << ".getValue("
2111              << NumResults << ");\n";
2112         }
2113       } else if (II.hasCtrlDep || OutFlag) {
2114         OS << "      Result = CurDAG->getTargetNode("
2115            << II.Namespace << "::" << II.TheDef->getName();
2116
2117         // Output order: results, chain, flags
2118         // Result types.
2119         if (NumResults > 0) { 
2120           // TODO: multiple results?
2121           if (N->getType() != MVT::isVoid)
2122             OS << ", MVT::" << getEnumName(N->getType());
2123         }
2124         if (II.hasCtrlDep)
2125           OS << ", MVT::Other";
2126         if (OutFlag)
2127           OS << ", MVT::Flag";
2128
2129         // Inputs.
2130         for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2131           OS << ", Tmp" << Ops[i];
2132         if (II.hasCtrlDep) OS << ", Chain";
2133         if (InFlag)        OS << ", InFlag";
2134         OS << ");\n";
2135
2136         unsigned ValNo = 0;
2137         for (unsigned i = 0; i < NumResults; i++) {
2138           OS << "      CodeGenMap[N.getValue(" << ValNo << ")] = Result"
2139              << ".getValue(" << ValNo << ");\n";
2140           ValNo++;
2141         }
2142
2143         if (II.hasCtrlDep) {
2144           OS << "      Chain = Result.getValue(" << ValNo << ");\n";
2145           if (OutFlag)
2146             OS << "      InFlag = Result.getValue(" << ValNo+1 << ");\n";
2147         } else if (OutFlag) 
2148             OS << "      InFlag = Result.getValue(" << ValNo << ");\n";
2149
2150         if (OutFlag)
2151           IsCopyFromReg = EmitCopyFromRegs(N, II.hasCtrlDep);
2152         if (IsCopyFromReg)
2153           OS << "      CodeGenMap[N.getValue(" << ValNo++ << ")] = Result;\n";
2154
2155         if (OutFlag)
2156           OS << "      CodeGenMap[N.getValue(" << ValNo++ << ")] = InFlag;\n";
2157
2158         if (IsCopyFromReg || II.hasCtrlDep) {
2159           OS << "      ";
2160           if (IsCopyFromReg || NodeHasChain(Pattern, ISE))
2161             OS << "CodeGenMap[N.getValue(" << ValNo   << ")] = ";
2162           for (unsigned j = 0, e = FoldedChains.size(); j < e; j++)
2163             OS << "CodeGenMap[" << FoldedChains[j].first << ".getValue("
2164                << FoldedChains[j].second << ")] = ";
2165           OS << "Chain;\n";
2166         }
2167
2168         // FIXME: this only works because (for now) an instruction can either
2169         // produce a single result or a single flag.
2170         if (II.hasCtrlDep && OutFlag) {
2171           if (IsCopyFromReg)
2172             OS << "      return (N.ResNo == 0) ? Result : "
2173                << "((N.ResNo == 2) ? Chain : InFlag);"
2174                << "   // Chain comes before flag.\n";
2175           else
2176             OS << "      return (N.ResNo) ? Chain : InFlag;"
2177                << "   // Chain comes before flag.\n";
2178         } else {
2179           OS << "      return Result.getValue(N.ResNo);\n";
2180         }
2181       } else {
2182         // If this instruction is the root, and if there is only one use of it,
2183         // use SelectNodeTo instead of getTargetNode to avoid an allocation.
2184         OS << "      if (N.Val->hasOneUse()) {\n";
2185         OS << "        return CurDAG->SelectNodeTo(N.Val, "
2186            << II.Namespace << "::" << II.TheDef->getName();
2187         if (N->getType() != MVT::isVoid)
2188           OS << ", MVT::" << getEnumName(N->getType());
2189         if (OutFlag)
2190           OS << ", MVT::Flag";
2191         for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2192           OS << ", Tmp" << Ops[i];
2193         if (InFlag)
2194           OS << ", InFlag";
2195         OS << ");\n";
2196         OS << "      } else {\n";
2197         OS << "        return CodeGenMap[N] = CurDAG->getTargetNode("
2198            << II.Namespace << "::" << II.TheDef->getName();
2199         if (N->getType() != MVT::isVoid)
2200           OS << ", MVT::" << getEnumName(N->getType());
2201         if (OutFlag)
2202           OS << ", MVT::Flag";
2203         for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2204           OS << ", Tmp" << Ops[i];
2205         if (InFlag)
2206           OS << ", InFlag";
2207         OS << ");\n";
2208         OS << "      }\n";
2209       }
2210
2211       return std::make_pair(1, ResNo);
2212     } else if (Op->isSubClassOf("SDNodeXForm")) {
2213       assert(N->getNumChildren() == 1 && "node xform should have one child!");
2214       unsigned OpVal = EmitResultCode(N->getChild(0)).second;
2215       unsigned ResNo = TmpNo++;
2216       OS << "      ";
2217       DeclareSDOperand("Tmp"+utostr(ResNo));
2218       OS << " = Transform_" << Op->getName()
2219          << "(Tmp" << OpVal << ".Val);\n";
2220       if (isRoot) {
2221         OS << "      CodeGenMap[N] = Tmp" << ResNo << ";\n";
2222         OS << "      return Tmp" << ResNo << ";\n";
2223       }
2224       return std::make_pair(1, ResNo);
2225     } else {
2226       N->dump();
2227       assert(0 && "Unknown node in result pattern!");
2228       return std::make_pair(1, ~0U);
2229     }
2230   }
2231
2232   /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat' and
2233   /// add it to the tree.  'Pat' and 'Other' are isomorphic trees except that 
2234   /// 'Pat' may be missing types.  If we find an unresolved type to add a check
2235   /// for, this returns true otherwise false if Pat has all types.
2236   bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
2237                           const std::string &Prefix) {
2238     // Did we find one?
2239     if (!Pat->hasTypeSet()) {
2240       // Move a type over from 'other' to 'pat'.
2241       Pat->setType(Other->getType());
2242       OS << "      if (" << Prefix << ".Val->getValueType(0) != MVT::"
2243          << getName(Pat->getType()) << ") goto P" << PatternNo << "Fail;\n";
2244       return true;
2245     }
2246   
2247     unsigned OpNo = (unsigned) NodeHasChain(Pat, ISE);
2248     for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
2249       if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
2250                              Prefix + utostr(OpNo)))
2251         return true;
2252     return false;
2253   }
2254
2255 private:
2256   /// EmitCopyToRegs - Emit the flag operands for the DAG that is
2257   /// being built.
2258   void EmitCopyToRegs(TreePatternNode *N, const std::string &RootName,
2259                       bool HasCtrlDep) {
2260     const CodeGenTarget &T = ISE.getTargetInfo();
2261     unsigned OpNo = (unsigned) NodeHasChain(N, ISE);
2262     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
2263       TreePatternNode *Child = N->getChild(i);
2264       if (!Child->isLeaf()) {
2265         EmitCopyToRegs(Child, RootName + utostr(OpNo), HasCtrlDep);
2266       } else {
2267         if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2268           Record *RR = DI->getDef();
2269           if (RR->isSubClassOf("Register")) {
2270             MVT::ValueType RVT = getRegisterValueType(RR, T);
2271             if (RVT == MVT::Flag) {
2272               OS << "      InFlag = Select(" << RootName << OpNo << ");\n";
2273             } else if (HasCtrlDep) {
2274               OS << "      SDOperand " << RootName << "CR" << i << ";\n";
2275               OS << "      " << RootName << "CR" << i
2276                  << "  = CurDAG->getCopyToReg(Chain, CurDAG->getRegister("
2277                  << ISE.getQualifiedName(RR) << ", MVT::"
2278                  << getEnumName(RVT) << ")"
2279                  << ", Select(" << RootName << OpNo << "), InFlag);\n";
2280               OS << "      Chain  = " << RootName << "CR" << i
2281                  << ".getValue(0);\n";
2282               OS << "      InFlag = " << RootName << "CR" << i
2283                  << ".getValue(1);\n";
2284             } else {
2285               OS << "      InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode()"
2286                  << ", CurDAG->getRegister(" << ISE.getQualifiedName(RR)
2287                  << ", MVT::" << getEnumName(RVT) << ")"
2288                  << ", Select(" << RootName << OpNo
2289                  << "), InFlag).getValue(1);\n";
2290             }
2291           }
2292         }
2293       }
2294     }
2295   }
2296
2297   /// EmitCopyFromRegs - Emit code to copy result to physical registers
2298   /// as specified by the instruction.
2299   bool EmitCopyFromRegs(TreePatternNode *N, bool HasCtrlDep) {
2300     bool RetVal = false;
2301     Record *Op = N->getOperator();
2302     if (Op->isSubClassOf("Instruction")) {
2303       const DAGInstruction &Inst = ISE.getInstruction(Op);
2304       const CodeGenTarget &CGT = ISE.getTargetInfo();
2305       CodeGenInstruction &II = CGT.getInstruction(Op->getName());
2306       unsigned NumImpResults  = Inst.getNumImpResults();
2307       for (unsigned i = 0; i < NumImpResults; i++) {
2308         Record *RR = Inst.getImpResult(i);
2309         if (RR->isSubClassOf("Register")) {
2310           MVT::ValueType RVT = getRegisterValueType(RR, CGT);
2311           if (RVT != MVT::Flag) {
2312             if (HasCtrlDep) {
2313               OS << "      Result = CurDAG->getCopyFromReg(Chain, "
2314                  << ISE.getQualifiedName(RR)
2315                  << ", MVT::" << getEnumName(RVT) << ", InFlag);\n";
2316               OS << "      Chain  = Result.getValue(1);\n";
2317               OS << "      InFlag = Result.getValue(2);\n";
2318             } else {
2319               OS << "      Chain;\n";
2320               OS << "      Result = CurDAG->getCopyFromReg("
2321                  << "CurDAG->getEntryNode(), ISE.getQualifiedName(RR)"
2322                  << ", MVT::" << getEnumName(RVT) << ", InFlag);\n";
2323               OS << "      Chain  = Result.getValue(1);\n";
2324               OS << "      InFlag = Result.getValue(2);\n";
2325             }
2326             RetVal = true;
2327           }
2328         }
2329       }
2330     }
2331     return RetVal;
2332   }
2333 };
2334
2335 /// EmitCodeForPattern - Given a pattern to match, emit code to the specified
2336 /// stream to match the pattern, and generate the code for the match if it
2337 /// succeeds.
2338 void DAGISelEmitter::EmitCodeForPattern(PatternToMatch &Pattern,
2339                                         std::ostream &OS) {
2340   static unsigned PatternCount = 0;
2341   unsigned PatternNo = PatternCount++;
2342   OS << "    { // Pattern #" << PatternNo << ": ";
2343   Pattern.getSrcPattern()->print(OS);
2344   OS << "\n      // Emits: ";
2345   Pattern.getDstPattern()->print(OS);
2346   OS << "\n";
2347   OS << "      // Pattern complexity = "
2348      << getPatternSize(Pattern.getSrcPattern(), *this)
2349      << "  cost = "
2350      << getResultPatternCost(Pattern.getDstPattern()) << "\n";
2351
2352   PatternCodeEmitter Emitter(*this, Pattern.getPredicates(),
2353                              Pattern.getSrcPattern(), Pattern.getDstPattern(),
2354                              PatternNo, OS);
2355
2356   // Emit the matcher, capturing named arguments in VariableMap.
2357   Emitter.EmitMatchCode(Pattern.getSrcPattern(), "N", true /*the root*/);
2358
2359   // TP - Get *SOME* tree pattern, we don't care which.
2360   TreePattern &TP = *PatternFragments.begin()->second;
2361   
2362   // At this point, we know that we structurally match the pattern, but the
2363   // types of the nodes may not match.  Figure out the fewest number of type 
2364   // comparisons we need to emit.  For example, if there is only one integer
2365   // type supported by a target, there should be no type comparisons at all for
2366   // integer patterns!
2367   //
2368   // To figure out the fewest number of type checks needed, clone the pattern,
2369   // remove the types, then perform type inference on the pattern as a whole.
2370   // If there are unresolved types, emit an explicit check for those types,
2371   // apply the type to the tree, then rerun type inference.  Iterate until all
2372   // types are resolved.
2373   //
2374   TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
2375   RemoveAllTypes(Pat);
2376   
2377   do {
2378     // Resolve/propagate as many types as possible.
2379     try {
2380       bool MadeChange = true;
2381       while (MadeChange)
2382         MadeChange = Pat->ApplyTypeConstraints(TP,true/*Ignore reg constraints*/);
2383     } catch (...) {
2384       assert(0 && "Error: could not find consistent types for something we"
2385              " already decided was ok!");
2386       abort();
2387     }
2388
2389     // Insert a check for an unresolved type and add it to the tree.  If we find
2390     // an unresolved type to add a check for, this returns true and we iterate,
2391     // otherwise we are done.
2392   } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N"));
2393
2394   Emitter.EmitResultCode(Pattern.getDstPattern(), true /*the root*/);
2395
2396   delete Pat;
2397   
2398   OS << "    }\n  P" << PatternNo << "Fail:\n";
2399 }
2400
2401
2402 namespace {
2403   /// CompareByRecordName - An ordering predicate that implements less-than by
2404   /// comparing the names records.
2405   struct CompareByRecordName {
2406     bool operator()(const Record *LHS, const Record *RHS) const {
2407       // Sort by name first.
2408       if (LHS->getName() < RHS->getName()) return true;
2409       // If both names are equal, sort by pointer.
2410       return LHS->getName() == RHS->getName() && LHS < RHS;
2411     }
2412   };
2413 }
2414
2415 void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
2416   std::string InstNS = Target.inst_begin()->second.Namespace;
2417   if (!InstNS.empty()) InstNS += "::";
2418   
2419   // Emit boilerplate.
2420   OS << "// The main instruction selector code.\n"
2421      << "SDOperand SelectCode(SDOperand N) {\n"
2422      << "  if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
2423      << "      N.getOpcode() < (ISD::BUILTIN_OP_END+" << InstNS
2424      << "INSTRUCTION_LIST_END))\n"
2425      << "    return N;   // Already selected.\n\n"
2426     << "  std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(N);\n"
2427      << "  if (CGMI != CodeGenMap.end()) return CGMI->second;\n"
2428      << "  // Work arounds for GCC stack overflow bugs.\n"
2429      << "  SDOperand N0, N1, N2, N00, N01, N10, N11, Tmp0, Tmp1, Tmp2, Tmp3;\n"
2430      << "  SDOperand Chain, InFlag, Result;\n"
2431      << "  switch (N.getOpcode()) {\n"
2432      << "  default: break;\n"
2433      << "  case ISD::EntryToken:       // These leaves remain the same.\n"
2434      << "  case ISD::BasicBlock:\n"
2435      << "    return N;\n"
2436      << "  case ISD::AssertSext:\n"
2437      << "  case ISD::AssertZext: {\n"
2438      << "    SDOperand Tmp0 = Select(N.getOperand(0));\n"
2439      << "    if (!N.Val->hasOneUse()) CodeGenMap[N] = Tmp0;\n"
2440      << "    return Tmp0;\n"
2441      << "  }\n"
2442      << "  case ISD::TokenFactor:\n"
2443      << "    if (N.getNumOperands() == 2) {\n"
2444      << "      SDOperand Op0 = Select(N.getOperand(0));\n"
2445      << "      SDOperand Op1 = Select(N.getOperand(1));\n"
2446      << "      return CodeGenMap[N] =\n"
2447      << "          CurDAG->getNode(ISD::TokenFactor, MVT::Other, Op0, Op1);\n"
2448      << "    } else {\n"
2449      << "      std::vector<SDOperand> Ops;\n"
2450      << "      for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i)\n"
2451      << "        Ops.push_back(Select(N.getOperand(i)));\n"
2452      << "       return CodeGenMap[N] = \n"
2453      << "               CurDAG->getNode(ISD::TokenFactor, MVT::Other, Ops);\n"
2454      << "    }\n"
2455      << "  case ISD::CopyFromReg: {\n"
2456      << "    Chain = Select(N.getOperand(0));\n"
2457      << "    unsigned Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();\n"
2458      << "    MVT::ValueType VT = N.Val->getValueType(0);\n"
2459      << "    if (N.Val->getNumValues() == 2) {\n"
2460      << "      if (Chain == N.getOperand(0)) return N; // No change\n"
2461      << "      SDOperand New = CurDAG->getCopyFromReg(Chain, Reg, VT);\n"
2462      << "      CodeGenMap[N.getValue(0)] = New;\n"
2463      << "      CodeGenMap[N.getValue(1)] = New.getValue(1);\n"
2464      << "      return New.getValue(N.ResNo);\n"
2465      << "    } else {\n"
2466      << "      SDOperand Flag;\n"
2467      << "      if (N.getNumOperands() == 3) Flag = Select(N.getOperand(2));\n"
2468      << "      if (Chain == N.getOperand(0) &&\n"
2469      << "          (N.getNumOperands() == 2 || Flag == N.getOperand(2)))\n"
2470      << "        return N; // No change\n"
2471      << "      SDOperand New = CurDAG->getCopyFromReg(Chain, Reg, VT, Flag);\n"
2472      << "      CodeGenMap[N.getValue(0)] = New;\n"
2473      << "      CodeGenMap[N.getValue(1)] = New.getValue(1);\n"
2474      << "      CodeGenMap[N.getValue(2)] = New.getValue(2);\n"
2475      << "      return New.getValue(N.ResNo);\n"
2476      << "    }\n"
2477      << "  }\n"
2478      << "  case ISD::CopyToReg: {\n"
2479      << "    Chain = Select(N.getOperand(0));\n"
2480      << "    unsigned Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();\n"
2481      << "    SDOperand Val = Select(N.getOperand(2));\n"
2482      << "    Result = N;\n"
2483      << "    if (N.Val->getNumValues() == 1) {\n"
2484      << "      if (Chain != N.getOperand(0) || Val != N.getOperand(2))\n"
2485      << "        Result = CurDAG->getCopyToReg(Chain, Reg, Val);\n"
2486      << "      return CodeGenMap[N] = Result;\n"
2487      << "    } else {\n"
2488      << "      SDOperand Flag;\n"
2489      << "      if (N.getNumOperands() == 4) Flag = Select(N.getOperand(3));\n"
2490      << "      if (Chain != N.getOperand(0) || Val != N.getOperand(2) ||\n"
2491      << "          (N.getNumOperands() == 4 && Flag != N.getOperand(3)))\n"
2492      << "        Result = CurDAG->getCopyToReg(Chain, Reg, Val, Flag);\n"
2493      << "      CodeGenMap[N.getValue(0)] = Result;\n"
2494      << "      CodeGenMap[N.getValue(1)] = Result.getValue(1);\n"
2495      << "      return Result.getValue(N.ResNo);\n"
2496      << "    }\n"
2497      << "  }\n";
2498     
2499   // Group the patterns by their top-level opcodes.
2500   std::map<Record*, std::vector<PatternToMatch*>,
2501            CompareByRecordName> PatternsByOpcode;
2502   for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
2503     TreePatternNode *Node = PatternsToMatch[i].getSrcPattern();
2504     if (!Node->isLeaf()) {
2505       PatternsByOpcode[Node->getOperator()].push_back(&PatternsToMatch[i]);
2506     } else {
2507       const ComplexPattern *CP;
2508       if (IntInit *II = 
2509              dynamic_cast<IntInit*>(Node->getLeafValue())) {
2510         PatternsByOpcode[getSDNodeNamed("imm")].push_back(&PatternsToMatch[i]);
2511       } else if ((CP = NodeGetComplexPattern(Node, *this))) {
2512         std::vector<Record*> OpNodes = CP->getRootNodes();
2513         for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
2514           PatternsByOpcode[OpNodes[j]].insert(PatternsByOpcode[OpNodes[j]].begin(),
2515                                               &PatternsToMatch[i]);
2516         }
2517       } else {
2518         std::cerr << "Unrecognized opcode '";
2519         Node->dump();
2520         std::cerr << "' on tree pattern '";
2521         std::cerr << PatternsToMatch[i].getDstPattern()->getOperator()->getName();
2522         std::cerr << "'!\n";
2523         exit(1);
2524       }
2525     }
2526   }
2527   
2528   // Loop over all of the case statements.
2529   for (std::map<Record*, std::vector<PatternToMatch*>,
2530                 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
2531        E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
2532     const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
2533     std::vector<PatternToMatch*> &Patterns = PBOI->second;
2534     
2535     OS << "  case " << OpcodeInfo.getEnumName() << ":\n";
2536
2537     // We want to emit all of the matching code now.  However, we want to emit
2538     // the matches in order of minimal cost.  Sort the patterns so the least
2539     // cost one is at the start.
2540     std::stable_sort(Patterns.begin(), Patterns.end(),
2541                      PatternSortingPredicate(*this));
2542     
2543     for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
2544       EmitCodeForPattern(*Patterns[i], OS);
2545     OS << "    break;\n\n";
2546   }
2547   
2548
2549   OS << "  } // end of big switch.\n\n"
2550      << "  std::cerr << \"Cannot yet select: \";\n"
2551      << "  N.Val->dump();\n"
2552      << "  std::cerr << '\\n';\n"
2553      << "  abort();\n"
2554      << "}\n";
2555 }
2556
2557 void DAGISelEmitter::run(std::ostream &OS) {
2558   EmitSourceFileHeader("DAG Instruction Selector for the " + Target.getName() +
2559                        " target", OS);
2560   
2561   OS << "// *** NOTE: This file is #included into the middle of the target\n"
2562      << "// *** instruction selector class.  These functions are really "
2563      << "methods.\n\n";
2564   
2565   OS << "// Instance var to keep track of multiply used nodes that have \n"
2566      << "// already been selected.\n"
2567      << "std::map<SDOperand, SDOperand> CodeGenMap;\n";
2568   
2569   ParseNodeInfo();
2570   ParseNodeTransforms(OS);
2571   ParseComplexPatterns();
2572   ParsePatternFragments(OS);
2573   ParseInstructions();
2574   ParsePatterns();
2575   
2576   // Generate variants.  For example, commutative patterns can match
2577   // multiple ways.  Add them to PatternsToMatch as well.
2578   GenerateVariants();
2579
2580   
2581   DEBUG(std::cerr << "\n\nALL PATTERNS TO MATCH:\n\n";
2582         for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
2583           std::cerr << "PATTERN: ";  PatternsToMatch[i].getSrcPattern()->dump();
2584           std::cerr << "\nRESULT:  ";PatternsToMatch[i].getDstPattern()->dump();
2585           std::cerr << "\n";
2586         });
2587   
2588   // At this point, we have full information about the 'Patterns' we need to
2589   // parse, both implicitly from instructions as well as from explicit pattern
2590   // definitions.  Emit the resultant instruction selector.
2591   EmitInstructionSelector(OS);  
2592   
2593   for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
2594        E = PatternFragments.end(); I != E; ++I)
2595     delete I->second;
2596   PatternFragments.clear();
2597
2598   Instructions.clear();
2599 }