memoize translations
[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 <set>
19 using namespace llvm;
20
21 //===----------------------------------------------------------------------===//
22 // SDTypeConstraint implementation
23 //
24
25 SDTypeConstraint::SDTypeConstraint(Record *R) {
26   OperandNo = R->getValueAsInt("OperandNum");
27   
28   if (R->isSubClassOf("SDTCisVT")) {
29     ConstraintType = SDTCisVT;
30     x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
31   } else if (R->isSubClassOf("SDTCisInt")) {
32     ConstraintType = SDTCisInt;
33   } else if (R->isSubClassOf("SDTCisFP")) {
34     ConstraintType = SDTCisFP;
35   } else if (R->isSubClassOf("SDTCisSameAs")) {
36     ConstraintType = SDTCisSameAs;
37     x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
38   } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
39     ConstraintType = SDTCisVTSmallerThanOp;
40     x.SDTCisVTSmallerThanOp_Info.OtherOperandNum = 
41       R->getValueAsInt("OtherOperandNum");
42   } else {
43     std::cerr << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
44     exit(1);
45   }
46 }
47
48 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
49 /// N, which has NumResults results.
50 TreePatternNode *SDTypeConstraint::getOperandNum(unsigned OpNo,
51                                                  TreePatternNode *N,
52                                                  unsigned NumResults) const {
53   assert(NumResults == 1 && "We only work with single result nodes so far!");
54   
55   if (OpNo < NumResults)
56     return N;  // FIXME: need value #
57   else
58     return N->getChild(OpNo-NumResults);
59 }
60
61 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
62 /// constraint to the nodes operands.  This returns true if it makes a
63 /// change, false otherwise.  If a type contradiction is found, throw an
64 /// exception.
65 bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
66                                            const SDNodeInfo &NodeInfo,
67                                            TreePattern &TP) const {
68   unsigned NumResults = NodeInfo.getNumResults();
69   assert(NumResults == 1 && "We only work with single result nodes so far!");
70   
71   // Check that the number of operands is sane.
72   if (NodeInfo.getNumOperands() >= 0) {
73     if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands())
74       TP.error(N->getOperator()->getName() + " node requires exactly " +
75                itostr(NodeInfo.getNumOperands()) + " operands!");
76   }
77   
78   TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NumResults);
79   
80   switch (ConstraintType) {
81   default: assert(0 && "Unknown constraint type!");
82   case SDTCisVT:
83     // Operand must be a particular type.
84     return NodeToApply->UpdateNodeType(x.SDTCisVT_Info.VT, TP);
85   case SDTCisInt:
86     if (NodeToApply->hasTypeSet() && !MVT::isInteger(NodeToApply->getType()))
87       NodeToApply->UpdateNodeType(MVT::i1, TP);  // throw an error.
88
89     // FIXME: can tell from the target if there is only one Int type supported.
90     return false;
91   case SDTCisFP:
92     if (NodeToApply->hasTypeSet() &&
93         !MVT::isFloatingPoint(NodeToApply->getType()))
94       NodeToApply->UpdateNodeType(MVT::f32, TP);  // throw an error.
95     // FIXME: can tell from the target if there is only one FP type supported.
96     return false;
97   case SDTCisSameAs: {
98     TreePatternNode *OtherNode =
99       getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NumResults);
100     return NodeToApply->UpdateNodeType(OtherNode->getType(), TP) |
101            OtherNode->UpdateNodeType(NodeToApply->getType(), TP);
102   }
103   case SDTCisVTSmallerThanOp: {
104     // The NodeToApply must be a leaf node that is a VT.  OtherOperandNum must
105     // have an integer type that is smaller than the VT.
106     if (!NodeToApply->isLeaf() ||
107         !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
108         !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
109                ->isSubClassOf("ValueType"))
110       TP.error(N->getOperator()->getName() + " expects a VT operand!");
111     MVT::ValueType VT =
112      getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
113     if (!MVT::isInteger(VT))
114       TP.error(N->getOperator()->getName() + " VT operand must be integer!");
115     
116     TreePatternNode *OtherNode =
117       getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N,NumResults);
118     if (OtherNode->hasTypeSet() &&
119         (!MVT::isInteger(OtherNode->getType()) ||
120          OtherNode->getType() <= VT))
121       OtherNode->UpdateNodeType(MVT::Other, TP);  // Throw an error.
122     return false;
123   }
124   }  
125   return false;
126 }
127
128
129 //===----------------------------------------------------------------------===//
130 // SDNodeInfo implementation
131 //
132 SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
133   EnumName    = R->getValueAsString("Opcode");
134   SDClassName = R->getValueAsString("SDClass");
135   Record *TypeProfile = R->getValueAsDef("TypeProfile");
136   NumResults = TypeProfile->getValueAsInt("NumResults");
137   NumOperands = TypeProfile->getValueAsInt("NumOperands");
138   
139   // Parse the type constraints.
140   ListInit *Constraints = TypeProfile->getValueAsListInit("Constraints");
141   for (unsigned i = 0, e = Constraints->getSize(); i != e; ++i) {
142     assert(dynamic_cast<DefInit*>(Constraints->getElement(i)) &&
143            "Constraints list should contain constraint definitions!");
144     Record *Constraint = 
145       static_cast<DefInit*>(Constraints->getElement(i))->getDef();
146     TypeConstraints.push_back(Constraint);
147   }
148 }
149
150 //===----------------------------------------------------------------------===//
151 // TreePatternNode implementation
152 //
153
154 TreePatternNode::~TreePatternNode() {
155 #if 0 // FIXME: implement refcounted tree nodes!
156   for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
157     delete getChild(i);
158 #endif
159 }
160
161 /// UpdateNodeType - Set the node type of N to VT if VT contains
162 /// information.  If N already contains a conflicting type, then throw an
163 /// exception.  This returns true if any information was updated.
164 ///
165 bool TreePatternNode::UpdateNodeType(MVT::ValueType VT, TreePattern &TP) {
166   if (VT == MVT::LAST_VALUETYPE || getType() == VT) return false;
167   if (getType() == MVT::LAST_VALUETYPE) {
168     setType(VT);
169     return true;
170   }
171   
172   TP.error("Type inference contradiction found in node " + 
173            getOperator()->getName() + "!");
174   return true; // unreachable
175 }
176
177
178 void TreePatternNode::print(std::ostream &OS) const {
179   if (isLeaf()) {
180     OS << *getLeafValue();
181   } else {
182     OS << "(" << getOperator()->getName();
183   }
184   
185   if (getType() == MVT::Other)
186     OS << ":Other";
187   else if (getType() == MVT::LAST_VALUETYPE)
188     ;//OS << ":?";
189   else
190     OS << ":" << getType();
191
192   if (!isLeaf()) {
193     if (getNumChildren() != 0) {
194       OS << " ";
195       getChild(0)->print(OS);
196       for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
197         OS << ", ";
198         getChild(i)->print(OS);
199       }
200     }
201     OS << ")";
202   }
203   
204   if (!PredicateFn.empty())
205     OS << "<<P:" << PredicateFn << ">>";
206   if (TransformFn)
207     OS << "<<X:" << TransformFn->getName() << ">>";
208   if (!getName().empty())
209     OS << ":$" << getName();
210
211 }
212 void TreePatternNode::dump() const {
213   print(std::cerr);
214 }
215
216 /// clone - Make a copy of this tree and all of its children.
217 ///
218 TreePatternNode *TreePatternNode::clone() const {
219   TreePatternNode *New;
220   if (isLeaf()) {
221     New = new TreePatternNode(getLeafValue());
222   } else {
223     std::vector<TreePatternNode*> CChildren;
224     CChildren.reserve(Children.size());
225     for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
226       CChildren.push_back(getChild(i)->clone());
227     New = new TreePatternNode(getOperator(), CChildren);
228   }
229   New->setName(getName());
230   New->setType(getType());
231   New->setPredicateFn(getPredicateFn());
232   New->setTransformFn(getTransformFn());
233   return New;
234 }
235
236 /// SubstituteFormalArguments - Replace the formal arguments in this tree
237 /// with actual values specified by ArgMap.
238 void TreePatternNode::
239 SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
240   if (isLeaf()) return;
241   
242   for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
243     TreePatternNode *Child = getChild(i);
244     if (Child->isLeaf()) {
245       Init *Val = Child->getLeafValue();
246       if (dynamic_cast<DefInit*>(Val) &&
247           static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
248         // We found a use of a formal argument, replace it with its value.
249         Child = ArgMap[Child->getName()];
250         assert(Child && "Couldn't find formal argument!");
251         setChild(i, Child);
252       }
253     } else {
254       getChild(i)->SubstituteFormalArguments(ArgMap);
255     }
256   }
257 }
258
259
260 /// InlinePatternFragments - If this pattern refers to any pattern
261 /// fragments, inline them into place, giving us a pattern without any
262 /// PatFrag references.
263 TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
264   if (isLeaf()) return this;  // nothing to do.
265   Record *Op = getOperator();
266   
267   if (!Op->isSubClassOf("PatFrag")) {
268     // Just recursively inline children nodes.
269     for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
270       setChild(i, getChild(i)->InlinePatternFragments(TP));
271     return this;
272   }
273
274   // Otherwise, we found a reference to a fragment.  First, look up its
275   // TreePattern record.
276   TreePattern *Frag = TP.getDAGISelEmitter().getPatternFragment(Op);
277   
278   // Verify that we are passing the right number of operands.
279   if (Frag->getNumArgs() != Children.size())
280     TP.error("'" + Op->getName() + "' fragment requires " +
281              utostr(Frag->getNumArgs()) + " operands!");
282
283   TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
284
285   // Resolve formal arguments to their actual value.
286   if (Frag->getNumArgs()) {
287     // Compute the map of formal to actual arguments.
288     std::map<std::string, TreePatternNode*> ArgMap;
289     for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
290       ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
291   
292     FragTree->SubstituteFormalArguments(ArgMap);
293   }
294   
295   FragTree->setName(getName());
296   
297   // Get a new copy of this fragment to stitch into here.
298   //delete this;    // FIXME: implement refcounting!
299   return FragTree;
300 }
301
302 /// ApplyTypeConstraints - Apply all of the type constraints relevent to
303 /// this node and its children in the tree.  This returns true if it makes a
304 /// change, false otherwise.  If a type contradiction is found, throw an
305 /// exception.
306 bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP) {
307   if (isLeaf()) return false;
308   
309   // special handling for set, which isn't really an SDNode.
310   if (getOperator()->getName() == "set") {
311     assert (getNumChildren() == 2 && "Only handle 2 operand set's for now!");
312     bool MadeChange = getChild(0)->ApplyTypeConstraints(TP);
313     MadeChange |= getChild(1)->ApplyTypeConstraints(TP);
314     
315     // Types of operands must match.
316     MadeChange |= getChild(0)->UpdateNodeType(getChild(1)->getType(), TP);
317     MadeChange |= getChild(1)->UpdateNodeType(getChild(0)->getType(), TP);
318     MadeChange |= UpdateNodeType(MVT::isVoid, TP);
319     return MadeChange;
320   } else if (getOperator()->isSubClassOf("SDNode")) {
321     const SDNodeInfo &NI = TP.getDAGISelEmitter().getSDNodeInfo(getOperator());
322     
323     bool MadeChange = NI.ApplyTypeConstraints(this, TP);
324     for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
325       MadeChange |= getChild(i)->ApplyTypeConstraints(TP);
326     return MadeChange;  
327   } else if (getOperator()->isSubClassOf("Instruction")) {
328     const DAGInstruction &Inst =
329       TP.getDAGISelEmitter().getInstruction(getOperator());
330     
331     assert(Inst.getNumResults() == 1 && "Only supports one result instrs!");
332     // Apply the result type to the node
333     bool MadeChange = UpdateNodeType(Inst.getResultType(0), TP);
334
335     if (getNumChildren() != Inst.getNumOperands())
336       TP.error("Instruction '" + getOperator()->getName() + " expects " +
337                utostr(Inst.getNumOperands()) + " operands, not " +
338                utostr(getNumChildren()) + " operands!");
339     for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
340       MadeChange |= getChild(i)->UpdateNodeType(Inst.getOperandType(i), TP);
341       MadeChange |= getChild(i)->ApplyTypeConstraints(TP);
342     }
343     return MadeChange;
344   } else {
345     assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
346     
347     // Node transforms always take one operand, and take and return the same
348     // type.
349     if (getNumChildren() != 1)
350       TP.error("Node transform '" + getOperator()->getName() +
351                "' requires one operand!");
352     bool MadeChange = UpdateNodeType(getChild(0)->getType(), TP);
353     MadeChange |= getChild(0)->UpdateNodeType(getType(), TP);
354     return MadeChange;
355   }
356 }
357
358
359 //===----------------------------------------------------------------------===//
360 // TreePattern implementation
361 //
362
363 TreePattern::TreePattern(Record *TheRec, ListInit *RawPat,
364                          DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
365    for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
366      Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
367 }
368
369 TreePattern::TreePattern(Record *TheRec, DagInit *Pat,
370                          DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
371   Trees.push_back(ParseTreePattern(Pat));
372 }
373
374 TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, 
375                          DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
376   Trees.push_back(Pat);
377 }
378
379
380
381 void TreePattern::error(const std::string &Msg) const {
382   dump();
383   throw "In " + TheRecord->getName() + ": " + Msg;
384 }
385
386 /// getIntrinsicType - Check to see if the specified record has an intrinsic
387 /// type which should be applied to it.  This infer the type of register
388 /// references from the register file information, for example.
389 ///
390 MVT::ValueType TreePattern::getIntrinsicType(Record *R) const {
391   // Check to see if this is a register or a register class...
392   if (R->isSubClassOf("RegisterClass"))
393     return getValueType(R->getValueAsDef("RegType"));
394   else if (R->isSubClassOf("PatFrag")) {
395     // Pattern fragment types will be resolved when they are inlined.
396     return MVT::LAST_VALUETYPE;
397   } else if (R->isSubClassOf("Register")) {
398     assert(0 && "Explicit registers not handled here yet!\n");
399     return MVT::LAST_VALUETYPE;
400   } else if (R->isSubClassOf("ValueType")) {
401     // Using a VTSDNode.
402     return MVT::Other;
403   } else if (R->getName() == "node") {
404     // Placeholder.
405     return MVT::LAST_VALUETYPE;
406   }
407   
408   error("Unknown node flavor used in pattern: " + R->getName());
409   return MVT::Other;
410 }
411
412 TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
413   Record *Operator = Dag->getNodeType();
414   
415   if (Operator->isSubClassOf("ValueType")) {
416     // If the operator is a ValueType, then this must be "type cast" of a leaf
417     // node.
418     if (Dag->getNumArgs() != 1)
419       error("Type cast only valid for a leaf node!");
420     
421     Init *Arg = Dag->getArg(0);
422     TreePatternNode *New;
423     if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
424       Record *R = DI->getDef();
425       if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
426         Dag->setArg(0, new DagInit(R,
427                                 std::vector<std::pair<Init*, std::string> >()));
428         TreePatternNode *TPN = ParseTreePattern(Dag);
429         TPN->setName(Dag->getArgName(0));
430         return TPN;
431       }   
432       
433       New = new TreePatternNode(DI);
434       // If it's a regclass or something else known, set the type.
435       New->setType(getIntrinsicType(DI->getDef()));
436     } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
437       New = ParseTreePattern(DI);
438     } else {
439       Arg->dump();
440       error("Unknown leaf value for tree pattern!");
441       return 0;
442     }
443     
444     // Apply the type cast.
445     New->UpdateNodeType(getValueType(Operator), *this);
446     return New;
447   }
448   
449   // Verify that this is something that makes sense for an operator.
450   if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
451       !Operator->isSubClassOf("Instruction") && 
452       !Operator->isSubClassOf("SDNodeXForm") &&
453       Operator->getName() != "set")
454     error("Unrecognized node '" + Operator->getName() + "'!");
455   
456   std::vector<TreePatternNode*> Children;
457   
458   for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
459     Init *Arg = Dag->getArg(i);
460     if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
461       Children.push_back(ParseTreePattern(DI));
462       Children.back()->setName(Dag->getArgName(i));
463     } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
464       Record *R = DefI->getDef();
465       // Direct reference to a leaf DagNode or PatFrag?  Turn it into a
466       // TreePatternNode if its own.
467       if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
468         Dag->setArg(i, new DagInit(R,
469                               std::vector<std::pair<Init*, std::string> >()));
470         --i;  // Revisit this node...
471       } else {
472         TreePatternNode *Node = new TreePatternNode(DefI);
473         Node->setName(Dag->getArgName(i));
474         Children.push_back(Node);
475         
476         // If it's a regclass or something else known, set the type.
477         Node->setType(getIntrinsicType(R));
478         
479         // Input argument?
480         if (R->getName() == "node") {
481           if (Dag->getArgName(i).empty())
482             error("'node' argument requires a name to match with operand list");
483           Args.push_back(Dag->getArgName(i));
484         }
485       }
486     } else {
487       Arg->dump();
488       error("Unknown leaf value for tree pattern!");
489     }
490   }
491   
492   return new TreePatternNode(Operator, Children);
493 }
494
495 /// InferAllTypes - Infer/propagate as many types throughout the expression
496 /// patterns as possible.  Return true if all types are infered, false
497 /// otherwise.  Throw an exception if a type contradiction is found.
498 bool TreePattern::InferAllTypes() {
499   bool MadeChange = true;
500   while (MadeChange) {
501     MadeChange = false;
502     for (unsigned i = 0, e = Trees.size(); i != e; ++i)
503       MadeChange |= Trees[i]->ApplyTypeConstraints(*this);
504   }
505   
506   bool HasUnresolvedTypes = false;
507   for (unsigned i = 0, e = Trees.size(); i != e; ++i)
508     HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
509   return !HasUnresolvedTypes;
510 }
511
512 void TreePattern::print(std::ostream &OS) const {
513   OS << getRecord()->getName();
514   if (!Args.empty()) {
515     OS << "(" << Args[0];
516     for (unsigned i = 1, e = Args.size(); i != e; ++i)
517       OS << ", " << Args[i];
518     OS << ")";
519   }
520   OS << ": ";
521   
522   if (Trees.size() > 1)
523     OS << "[\n";
524   for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
525     OS << "\t";
526     Trees[i]->print(OS);
527     OS << "\n";
528   }
529
530   if (Trees.size() > 1)
531     OS << "]\n";
532 }
533
534 void TreePattern::dump() const { print(std::cerr); }
535
536
537
538 //===----------------------------------------------------------------------===//
539 // DAGISelEmitter implementation
540 //
541
542 // Parse all of the SDNode definitions for the target, populating SDNodes.
543 void DAGISelEmitter::ParseNodeInfo() {
544   std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
545   while (!Nodes.empty()) {
546     SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
547     Nodes.pop_back();
548   }
549 }
550
551 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
552 /// map, and emit them to the file as functions.
553 void DAGISelEmitter::ParseNodeTransforms(std::ostream &OS) {
554   OS << "\n// Node transformations.\n";
555   std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
556   while (!Xforms.empty()) {
557     Record *XFormNode = Xforms.back();
558     Record *SDNode = XFormNode->getValueAsDef("Opcode");
559     std::string Code = XFormNode->getValueAsCode("XFormFunction");
560     SDNodeXForms.insert(std::make_pair(XFormNode,
561                                        std::make_pair(SDNode, Code)));
562
563     if (!Code.empty()) {
564       std::string ClassName = getSDNodeInfo(SDNode).getSDClassName();
565       const char *C2 = ClassName == "SDNode" ? "N" : "inN";
566
567       OS << "inline SDOperand Transform_" << XFormNode->getName()
568          << "(SDNode *" << C2 << ") {\n";
569       if (ClassName != "SDNode")
570         OS << "  " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
571       OS << Code << "\n}\n";
572     }
573
574     Xforms.pop_back();
575   }
576 }
577
578
579
580 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
581 /// file, building up the PatternFragments map.  After we've collected them all,
582 /// inline fragments together as necessary, so that there are no references left
583 /// inside a pattern fragment to a pattern fragment.
584 ///
585 /// This also emits all of the predicate functions to the output file.
586 ///
587 void DAGISelEmitter::ParsePatternFragments(std::ostream &OS) {
588   std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
589   
590   // First step, parse all of the fragments and emit predicate functions.
591   OS << "\n// Predicate functions.\n";
592   for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
593     DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
594     TreePattern *P = new TreePattern(Fragments[i], Tree, *this);
595     PatternFragments[Fragments[i]] = P;
596     
597     // Validate the argument list, converting it to map, to discard duplicates.
598     std::vector<std::string> &Args = P->getArgList();
599     std::set<std::string> OperandsMap(Args.begin(), Args.end());
600     
601     if (OperandsMap.count(""))
602       P->error("Cannot have unnamed 'node' values in pattern fragment!");
603     
604     // Parse the operands list.
605     DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
606     if (OpsList->getNodeType()->getName() != "ops")
607       P->error("Operands list should start with '(ops ... '!");
608     
609     // Copy over the arguments.       
610     Args.clear();
611     for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
612       if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
613           static_cast<DefInit*>(OpsList->getArg(j))->
614           getDef()->getName() != "node")
615         P->error("Operands list should all be 'node' values.");
616       if (OpsList->getArgName(j).empty())
617         P->error("Operands list should have names for each operand!");
618       if (!OperandsMap.count(OpsList->getArgName(j)))
619         P->error("'" + OpsList->getArgName(j) +
620                  "' does not occur in pattern or was multiply specified!");
621       OperandsMap.erase(OpsList->getArgName(j));
622       Args.push_back(OpsList->getArgName(j));
623     }
624     
625     if (!OperandsMap.empty())
626       P->error("Operands list does not contain an entry for operand '" +
627                *OperandsMap.begin() + "'!");
628
629     // If there is a code init for this fragment, emit the predicate code and
630     // keep track of the fact that this fragment uses it.
631     std::string Code = Fragments[i]->getValueAsCode("Predicate");
632     if (!Code.empty()) {
633       assert(!P->getOnlyTree()->isLeaf() && "Can't be a leaf!");
634       std::string ClassName =
635         getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
636       const char *C2 = ClassName == "SDNode" ? "N" : "inN";
637       
638       OS << "inline bool Predicate_" << Fragments[i]->getName()
639          << "(SDNode *" << C2 << ") {\n";
640       if (ClassName != "SDNode")
641         OS << "  " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
642       OS << Code << "\n}\n";
643       P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
644     }
645     
646     // If there is a node transformation corresponding to this, keep track of
647     // it.
648     Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
649     if (!getSDNodeTransform(Transform).second.empty())    // not noop xform?
650       P->getOnlyTree()->setTransformFn(Transform);
651   }
652   
653   OS << "\n\n";
654
655   // Now that we've parsed all of the tree fragments, do a closure on them so
656   // that there are not references to PatFrags left inside of them.
657   for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
658        E = PatternFragments.end(); I != E; ++I) {
659     TreePattern *ThePat = I->second;
660     ThePat->InlinePatternFragments();
661         
662     // Infer as many types as possible.  Don't worry about it if we don't infer
663     // all of them, some may depend on the inputs of the pattern.
664     try {
665       ThePat->InferAllTypes();
666     } catch (...) {
667       // If this pattern fragment is not supported by this target (no types can
668       // satisfy its constraints), just ignore it.  If the bogus pattern is
669       // actually used by instructions, the type consistency error will be
670       // reported there.
671     }
672     
673     // If debugging, print out the pattern fragment result.
674     DEBUG(ThePat->dump());
675   }
676 }
677
678 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
679 /// instruction input.  Return true if this is a real use.
680 static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
681                       std::map<std::string, TreePatternNode*> &InstInputs) {
682   // No name -> not interesting.
683   if (Pat->getName().empty()) {
684     if (Pat->isLeaf()) {
685       DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
686       if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
687         I->error("Input " + DI->getDef()->getName() + " must be named!");
688
689     }
690     return false;
691   }
692
693   Record *Rec;
694   if (Pat->isLeaf()) {
695     DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
696     if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
697     Rec = DI->getDef();
698   } else {
699     assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
700     Rec = Pat->getOperator();
701   }
702
703   TreePatternNode *&Slot = InstInputs[Pat->getName()];
704   if (!Slot) {
705     Slot = Pat;
706   } else {
707     Record *SlotRec;
708     if (Slot->isLeaf()) {
709       SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
710     } else {
711       assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
712       SlotRec = Slot->getOperator();
713     }
714     
715     // Ensure that the inputs agree if we've already seen this input.
716     if (Rec != SlotRec)
717       I->error("All $" + Pat->getName() + " inputs must agree with each other");
718     if (Slot->getType() != Pat->getType())
719       I->error("All $" + Pat->getName() + " inputs must agree with each other");
720   }
721   return true;
722 }
723
724 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
725 /// part of "I", the instruction), computing the set of inputs and outputs of
726 /// the pattern.  Report errors if we see anything naughty.
727 void DAGISelEmitter::
728 FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
729                             std::map<std::string, TreePatternNode*> &InstInputs,
730                             std::map<std::string, Record*> &InstResults) {
731   if (Pat->isLeaf()) {
732     bool isUse = HandleUse(I, Pat, InstInputs);
733     if (!isUse && Pat->getTransformFn())
734       I->error("Cannot specify a transform function for a non-input value!");
735     return;
736   } else if (Pat->getOperator()->getName() != "set") {
737     // If this is not a set, verify that the children nodes are not void typed,
738     // and recurse.
739     for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
740       if (Pat->getChild(i)->getType() == MVT::isVoid)
741         I->error("Cannot have void nodes inside of patterns!");
742       FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults);
743     }
744     
745     // If this is a non-leaf node with no children, treat it basically as if
746     // it were a leaf.  This handles nodes like (imm).
747     bool isUse = false;
748     if (Pat->getNumChildren() == 0)
749       isUse = HandleUse(I, Pat, InstInputs);
750     
751     if (!isUse && Pat->getTransformFn())
752       I->error("Cannot specify a transform function for a non-input value!");
753     return;
754   } 
755   
756   // Otherwise, this is a set, validate and collect instruction results.
757   if (Pat->getNumChildren() == 0)
758     I->error("set requires operands!");
759   else if (Pat->getNumChildren() & 1)
760     I->error("set requires an even number of operands");
761   
762   if (Pat->getTransformFn())
763     I->error("Cannot specify a transform function on a set node!");
764   
765   // Check the set destinations.
766   unsigned NumValues = Pat->getNumChildren()/2;
767   for (unsigned i = 0; i != NumValues; ++i) {
768     TreePatternNode *Dest = Pat->getChild(i);
769     if (!Dest->isLeaf())
770       I->error("set destination should be a virtual register!");
771     
772     DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
773     if (!Val)
774       I->error("set destination should be a virtual register!");
775     
776     if (!Val->getDef()->isSubClassOf("RegisterClass"))
777       I->error("set destination should be a virtual register!");
778     if (Dest->getName().empty())
779       I->error("set destination must have a name!");
780     if (InstResults.count(Dest->getName()))
781       I->error("cannot set '" + Dest->getName() +"' multiple times");
782     InstResults[Dest->getName()] = Val->getDef();
783
784     // Verify and collect info from the computation.
785     FindPatternInputsAndOutputs(I, Pat->getChild(i+NumValues),
786                                 InstInputs, InstResults);
787   }
788 }
789
790
791 /// ParseInstructions - Parse all of the instructions, inlining and resolving
792 /// any fragments involved.  This populates the Instructions list with fully
793 /// resolved instructions.
794 void DAGISelEmitter::ParseInstructions() {
795   std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
796   
797   for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
798     if (!dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
799       continue; // no pattern yet, ignore it.
800     
801     ListInit *LI = Instrs[i]->getValueAsListInit("Pattern");
802     if (LI->getSize() == 0) continue;  // no pattern.
803     
804     // Parse the instruction.
805     TreePattern *I = new TreePattern(Instrs[i], LI, *this);
806     // Inline pattern fragments into it.
807     I->InlinePatternFragments();
808     
809     // Infer as many types as possible.  If we cannot infer all of them, we can
810     // never do anything with this instruction pattern: report it to the user.
811     if (!I->InferAllTypes())
812       I->error("Could not infer all types in pattern!");
813     
814     // InstInputs - Keep track of all of the inputs of the instruction, along 
815     // with the record they are declared as.
816     std::map<std::string, TreePatternNode*> InstInputs;
817     
818     // InstResults - Keep track of all the virtual registers that are 'set'
819     // in the instruction, including what reg class they are.
820     std::map<std::string, Record*> InstResults;
821     
822     // Verify that the top-level forms in the instruction are of void type, and
823     // fill in the InstResults map.
824     for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
825       TreePatternNode *Pat = I->getTree(j);
826       if (Pat->getType() != MVT::isVoid) {
827         I->dump();
828         I->error("Top-level forms in instruction pattern should have"
829                  " void types");
830       }
831
832       // Find inputs and outputs, and verify the structure of the uses/defs.
833       FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults);
834     }
835
836     // Now that we have inputs and outputs of the pattern, inspect the operands
837     // list for the instruction.  This determines the order that operands are
838     // added to the machine instruction the node corresponds to.
839     unsigned NumResults = InstResults.size();
840
841     // Parse the operands list from the (ops) list, validating it.
842     std::vector<std::string> &Args = I->getArgList();
843     assert(Args.empty() && "Args list should still be empty here!");
844     CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
845
846     // Check that all of the results occur first in the list.
847     std::vector<MVT::ValueType> ResultTypes;
848     for (unsigned i = 0; i != NumResults; ++i) {
849       if (i == CGI.OperandList.size())
850         I->error("'" + InstResults.begin()->first +
851                  "' set but does not appear in operand list!");
852       const std::string &OpName = CGI.OperandList[i].Name;
853       
854       // Check that it exists in InstResults.
855       Record *R = InstResults[OpName];
856       if (R == 0)
857         I->error("Operand $" + OpName + " should be a set destination: all "
858                  "outputs must occur before inputs in operand list!");
859       
860       if (CGI.OperandList[i].Rec != R)
861         I->error("Operand $" + OpName + " class mismatch!");
862       
863       // Remember the return type.
864       ResultTypes.push_back(CGI.OperandList[i].Ty);
865       
866       // Okay, this one checks out.
867       InstResults.erase(OpName);
868     }
869
870     // Loop over the inputs next.  Make a copy of InstInputs so we can destroy
871     // the copy while we're checking the inputs.
872     std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
873
874     std::vector<TreePatternNode*> ResultNodeOperands;
875     std::vector<MVT::ValueType> OperandTypes;
876     for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
877       const std::string &OpName = CGI.OperandList[i].Name;
878       if (OpName.empty())
879         I->error("Operand #" + utostr(i) + " in operands list has no name!");
880
881       if (!InstInputsCheck.count(OpName))
882         I->error("Operand $" + OpName +
883                  " does not appear in the instruction pattern");
884       TreePatternNode *InVal = InstInputsCheck[OpName];
885       InstInputsCheck.erase(OpName);   // It occurred, remove from map.
886       if (CGI.OperandList[i].Ty != InVal->getType())
887         I->error("Operand $" + OpName +
888                  "'s type disagrees between the operand and pattern");
889       OperandTypes.push_back(InVal->getType());
890       
891       // Construct the result for the dest-pattern operand list.
892       TreePatternNode *OpNode = InVal->clone();
893       
894       // No predicate is useful on the result.
895       OpNode->setPredicateFn("");
896       
897       // Promote the xform function to be an explicit node if set.
898       if (Record *Xform = OpNode->getTransformFn()) {
899         OpNode->setTransformFn(0);
900         std::vector<TreePatternNode*> Children;
901         Children.push_back(OpNode);
902         OpNode = new TreePatternNode(Xform, Children);
903       }
904       
905       ResultNodeOperands.push_back(OpNode);
906     }
907     
908     if (!InstInputsCheck.empty())
909       I->error("Input operand $" + InstInputsCheck.begin()->first +
910                " occurs in pattern but not in operands list!");
911
912     TreePatternNode *ResultPattern =
913       new TreePatternNode(I->getRecord(), ResultNodeOperands);
914
915     // Create and insert the instruction.
916     DAGInstruction TheInst(I, ResultTypes, OperandTypes);
917     Instructions.insert(std::make_pair(I->getRecord(), TheInst));
918
919     // Use a temporary tree pattern to infer all types and make sure that the
920     // constructed result is correct.  This depends on the instruction already
921     // being inserted into the Instructions map.
922     TreePattern Temp(I->getRecord(), ResultPattern, *this);
923     Temp.InferAllTypes();
924
925     DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
926     TheInsertedInst.setResultPattern(Temp.getOnlyTree());
927     
928     DEBUG(I->dump());
929   }
930    
931   // If we can, convert the instructions to be patterns that are matched!
932   for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
933        E = Instructions.end(); II != E; ++II) {
934     TreePattern *I = II->second.getPattern();
935     
936     if (I->getNumTrees() != 1) {
937       std::cerr << "CANNOT HANDLE: " << I->getRecord()->getName() << " yet!";
938       continue;
939     }
940     TreePatternNode *Pattern = I->getTree(0);
941     if (Pattern->getOperator()->getName() != "set")
942       continue;  // Not a set (store or something?)
943     
944     if (Pattern->getNumChildren() != 2)
945       continue;  // Not a set of a single value (not handled so far)
946     
947     TreePatternNode *SrcPattern = Pattern->getChild(1)->clone();
948     TreePatternNode *DstPattern = II->second.getResultPattern();
949     PatternsToMatch.push_back(std::make_pair(SrcPattern, DstPattern));
950   }
951 }
952
953 void DAGISelEmitter::ParsePatterns() {
954   std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
955
956   for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
957     DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
958     TreePattern *Pattern = new TreePattern(Patterns[i], Tree, *this);
959
960     // Inline pattern fragments into it.
961     Pattern->InlinePatternFragments();
962     
963     // Infer as many types as possible.  If we cannot infer all of them, we can
964     // never do anything with this pattern: report it to the user.
965     if (!Pattern->InferAllTypes())
966       Pattern->error("Could not infer all types in pattern!");
967     
968     ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
969     if (LI->getSize() == 0) continue;  // no pattern.
970     
971     // Parse the instruction.
972     TreePattern *Result = new TreePattern(Patterns[i], LI, *this);
973     
974     // Inline pattern fragments into it.
975     Result->InlinePatternFragments();
976     
977     // Infer as many types as possible.  If we cannot infer all of them, we can
978     // never do anything with this pattern: report it to the user.
979     if (!Result->InferAllTypes())
980       Result->error("Could not infer all types in pattern result!");
981    
982     if (Result->getNumTrees() != 1)
983       Result->error("Cannot handle instructions producing instructions "
984                     "with temporaries yet!");
985     PatternsToMatch.push_back(std::make_pair(Pattern->getOnlyTree(),
986                                              Result->getOnlyTree()));
987   }
988
989   DEBUG(std::cerr << "\n\nPARSED PATTERNS TO MATCH:\n\n";
990         for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
991           std::cerr << "PATTERN: ";  PatternsToMatch[i].first->dump();
992           std::cerr << "\nRESULT:  ";PatternsToMatch[i].second->dump();
993           std::cerr << "\n";
994         });
995 }
996
997 /// EmitMatchForPattern - Emit a matcher for N, going to the label for PatternNo
998 /// if the match fails.  At this point, we already know that the opcode for N
999 /// matches, and the SDNode for the result has the RootName specified name.
1000 void DAGISelEmitter::EmitMatchForPattern(TreePatternNode *N,
1001                                          const std::string &RootName,
1002                                      std::map<std::string,std::string> &VarMap,
1003                                          unsigned PatternNo, std::ostream &OS) {
1004   assert(!N->isLeaf() && "Cannot match against a leaf!");
1005   
1006   // If this node has a name associated with it, capture it in VarMap.  If
1007   // we already saw this in the pattern, emit code to verify dagness.
1008   if (!N->getName().empty()) {
1009     std::string &VarMapEntry = VarMap[N->getName()];
1010     if (VarMapEntry.empty()) {
1011       VarMapEntry = RootName;
1012     } else {
1013       // If we get here, this is a second reference to a specific name.  Since
1014       // we already have checked that the first reference is valid, we don't
1015       // have to recursively match it, just check that it's the same as the
1016       // previously named thing.
1017       OS << "      if (" << VarMapEntry << " != " << RootName
1018          << ") goto P" << PatternNo << "Fail;\n";
1019       return;
1020     }
1021   }
1022   
1023   // Emit code to load the child nodes and match their contents recursively.
1024   for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
1025     OS << "      SDOperand " << RootName << i <<" = " << RootName
1026        << ".getOperand(" << i << ");\n";
1027     TreePatternNode *Child = N->getChild(i);
1028     
1029     if (!Child->isLeaf()) {
1030       // If it's not a leaf, recursively match.
1031       const SDNodeInfo &CInfo = getSDNodeInfo(Child->getOperator());
1032       OS << "      if (" << RootName << i << ".getOpcode() != "
1033          << CInfo.getEnumName() << ") goto P" << PatternNo << "Fail;\n";
1034       EmitMatchForPattern(Child, RootName + utostr(i), VarMap, PatternNo, OS);
1035     } else {
1036       // If this child has a name associated with it, capture it in VarMap.  If
1037       // we already saw this in the pattern, emit code to verify dagness.
1038       if (!Child->getName().empty()) {
1039         std::string &VarMapEntry = VarMap[Child->getName()];
1040         if (VarMapEntry.empty()) {
1041           VarMapEntry = RootName + utostr(i);
1042         } else {
1043           // If we get here, this is a second reference to a specific name.  Since
1044           // we already have checked that the first reference is valid, we don't
1045           // have to recursively match it, just check that it's the same as the
1046           // previously named thing.
1047           OS << "      if (" << VarMapEntry << " != " << RootName << i
1048           << ") goto P" << PatternNo << "Fail;\n";
1049           continue;
1050         }
1051       }
1052       
1053       // Handle leaves of various types.
1054       Init *LeafVal = Child->getLeafValue();
1055       Record *LeafRec = dynamic_cast<DefInit*>(LeafVal)->getDef();
1056       if (LeafRec->isSubClassOf("RegisterClass")) {
1057         // Handle register references.  Nothing to do here.
1058       } else if (LeafRec->isSubClassOf("ValueType")) {
1059         // Make sure this is the specified value type.
1060         OS << "      if (cast<VTSDNode>(" << RootName << i << ")->getVT() != "
1061            << "MVT::" << LeafRec->getName() << ") goto P" << PatternNo
1062            << "Fail;\n";
1063       } else {
1064         Child->dump();
1065         assert(0 && "Unknown leaf type!");
1066       }
1067     }
1068   }
1069   
1070   // If there is a node predicate for this, emit the call.
1071   if (!N->getPredicateFn().empty())
1072     OS << "      if (!" << N->getPredicateFn() << "(" << RootName
1073        << ".Val)) goto P" << PatternNo << "Fail;\n";
1074 }
1075
1076
1077 unsigned DAGISelEmitter::
1078 CodeGenPatternResult(TreePatternNode *N, unsigned &Ctr,
1079                      std::map<std::string,std::string> &VariableMap, 
1080                      std::ostream &OS){
1081   // This is something selected from the pattern we matched.
1082   if (!N->getName().empty()) {
1083     const std::string &Val = VariableMap[N->getName()];
1084     assert(!Val.empty() &&
1085            "Variable referenced but not defined and not caught earlier!");
1086     if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
1087       // Already selected this operand, just return the tmpval.
1088       // FIXME: DO THIS.
1089     } else {
1090       unsigned ResNo = Ctr++;
1091       OS << "      SDOperand Tmp" << ResNo << " = Select(" << Val << ");\n";
1092       // FIXME: Add Tmp<ResNo> to VariableMap.
1093       return ResNo;
1094     }
1095   }
1096   
1097   if (N->isLeaf()) {
1098     N->dump();
1099     assert(0 && "Unknown leaf type!");
1100     return ~0U;
1101   }
1102
1103   Record *Op = N->getOperator();
1104   if (Op->isSubClassOf("Instruction")) {
1105     // Emit all of the operands.
1106     std::vector<unsigned> Ops;
1107     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1108       Ops.push_back(CodeGenPatternResult(N->getChild(i), Ctr, VariableMap, OS));
1109
1110     CodeGenInstruction &II = Target.getInstruction(Op->getName());
1111     unsigned ResNo = Ctr++;
1112     
1113     OS << "      SDOperand Tmp" << ResNo << " = CurDAG->getTargetNode("
1114        << II.Namespace << "::" << II.TheDef->getName() << ", MVT::"
1115        << getEnumName(N->getType());
1116     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1117       OS << ", Tmp" << Ops[i];
1118     OS << ");\n";
1119     return ResNo;
1120   } else if (Op->isSubClassOf("SDNodeXForm")) {
1121     assert(N->getNumChildren() == 1 && "node xform should have one child!");
1122     unsigned OpVal = CodeGenPatternResult(N->getChild(0), Ctr, VariableMap, OS);
1123     
1124     unsigned ResNo = Ctr++;
1125     OS << "      SDOperand Tmp" << ResNo << " = Transform_" << Op->getName()
1126        << "(Tmp" << OpVal << ".Val);\n";
1127     return ResNo;
1128   } else {
1129     N->dump();
1130     assert(0 && "Unknown node in result pattern!");
1131   }
1132 }
1133
1134
1135 /// EmitCodeForPattern - Given a pattern to match, emit code to the specified
1136 /// stream to match the pattern, and generate the code for the match if it
1137 /// succeeds.
1138 void DAGISelEmitter::EmitCodeForPattern(PatternToMatch &Pattern,
1139                                         std::ostream &OS) {
1140   static unsigned PatternCount = 0;
1141   unsigned PatternNo = PatternCount++;
1142   OS << "    { // Pattern #" << PatternNo << ": ";
1143   Pattern.first->print(OS);
1144   OS << "\n";
1145
1146   // Emit the matcher, capturing named arguments in VariableMap.
1147   std::map<std::string,std::string> VariableMap;
1148   EmitMatchForPattern(Pattern.first, "N", VariableMap, PatternNo, OS);
1149   
1150   OS << "      // Emit: ";
1151   Pattern.second->print(OS);
1152   OS << "\n";
1153   
1154   unsigned TmpNo = 0;
1155   unsigned Res = CodeGenPatternResult(Pattern.second, TmpNo, VariableMap, OS);
1156   
1157   // Add the result to the map if it has multiple uses.
1158   OS << "      if (!N.Val->hasOneUse()) CodeGenMap[N] = Tmp" << Res << ";\n";
1159   OS << "      return Tmp" << Res << ";\n";
1160   OS << "    }\n  P" << PatternNo << "Fail:\n";
1161 }
1162
1163 /// getPatternSize - Return the 'size' of this pattern.  We want to match large
1164 /// patterns before small ones.  This is used to determine the size of a
1165 /// pattern.
1166 static unsigned getPatternSize(TreePatternNode *P) {
1167   assert(MVT::isInteger(P->getType()) || MVT::isFloatingPoint(P->getType()) &&
1168          "Not a valid pattern node to size!");
1169   unsigned Size = 1;  // The node itself.
1170   
1171   // Count children in the count if they are also nodes.
1172   for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
1173     TreePatternNode *Child = P->getChild(i);
1174     if (!Child->isLeaf() && Child->getType() != MVT::Other)
1175       Size += getPatternSize(Child);
1176   }
1177   
1178   return Size;
1179 }
1180
1181 // PatternSortingPredicate - return true if we prefer to match LHS before RHS.
1182 // In particular, we want to match maximal patterns first and lowest cost within
1183 // a particular complexity first.
1184 struct PatternSortingPredicate {
1185   bool operator()(DAGISelEmitter::PatternToMatch *LHS,
1186                   DAGISelEmitter::PatternToMatch *RHS) {
1187     unsigned LHSSize = getPatternSize(LHS->first);
1188     unsigned RHSSize = getPatternSize(RHS->first);
1189     if (LHSSize > RHSSize) return true;   // LHS -> bigger -> less cost
1190     if (LHSSize < RHSSize) return false;
1191     
1192     // If they are equal, compare cost.
1193     // FIXME: Compute cost!
1194     return false;
1195   }
1196 };
1197
1198 void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
1199   // Emit boilerplate.
1200   OS << "// The main instruction selector code.\n"
1201      << "SDOperand SelectCode(SDOperand N) {\n"
1202      << "  if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
1203      << "      N.getOpcode() < PPCISD::FIRST_NUMBER)\n"
1204      << "    return N;   // Already selected.\n\n"
1205      << "  if (!N.Val->hasOneUse()) {\n"
1206   << "    std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(N);\n"
1207      << "    if (CGMI != CodeGenMap.end()) return CGMI->second;\n"
1208      << "  }\n"
1209      << "  switch (N.getOpcode()) {\n"
1210      << "  default: break;\n"
1211      << "  case ISD::EntryToken:       // These leaves remain the same.\n"
1212      << "    return N;\n"
1213      << "  case ISD::AssertSext:\n"
1214      << "  case ISD::AssertZext:\n"
1215      << "    return Select(N.getOperand(0));\n";
1216     
1217   // Group the patterns by their top-level opcodes.
1218   std::map<Record*, std::vector<PatternToMatch*> > PatternsByOpcode;
1219   for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i)
1220     PatternsByOpcode[PatternsToMatch[i].first->getOperator()]
1221       .push_back(&PatternsToMatch[i]);
1222   
1223   // Loop over all of the case statements.
1224   for (std::map<Record*, std::vector<PatternToMatch*> >::iterator
1225        PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end(); PBOI != E;
1226        ++PBOI) {
1227     const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
1228     std::vector<PatternToMatch*> &Patterns = PBOI->second;
1229     
1230     OS << "  case " << OpcodeInfo.getEnumName() << ":\n";
1231
1232     // We want to emit all of the matching code now.  However, we want to emit
1233     // the matches in order of minimal cost.  Sort the patterns so the least
1234     // cost one is at the start.
1235     std::stable_sort(Patterns.begin(), Patterns.end(),
1236                      PatternSortingPredicate());
1237     
1238     for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
1239       EmitCodeForPattern(*Patterns[i], OS);
1240     OS << "    break;\n\n";
1241   }
1242   
1243
1244   OS << "  } // end of big switch.\n\n"
1245      << "  std::cerr << \"Cannot yet select: \";\n"
1246      << "  N.Val->dump();\n"
1247      << "  std::cerr << '\\n';\n"
1248      << "  abort();\n"
1249      << "}\n";
1250 }
1251
1252 void DAGISelEmitter::run(std::ostream &OS) {
1253   EmitSourceFileHeader("DAG Instruction Selector for the " + Target.getName() +
1254                        " target", OS);
1255   
1256   OS << "// *** NOTE: This file is #included into the middle of the target\n"
1257      << "// *** instruction selector class.  These functions are really "
1258      << "methods.\n\n";
1259   
1260   OS << "// Instance var to keep track of multiply used nodes that have \n"
1261      << "// already been selected.\n"
1262      << "std::map<SDOperand, SDOperand> CodeGenMap;\n";
1263   
1264   ParseNodeInfo();
1265   ParseNodeTransforms(OS);
1266   ParsePatternFragments(OS);
1267   ParseInstructions();
1268   ParsePatterns();
1269   
1270   // FIXME: Generate variants.  For example, commutative patterns can match
1271   // multiple ways.  Add them to PatternsToMatch as well.
1272
1273   // At this point, we have full information about the 'Patterns' we need to
1274   // parse, both implicitly from instructions as well as from explicit pattern
1275   // definitions.
1276   
1277   EmitInstructionSelector(OS);  
1278   
1279   for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
1280        E = PatternFragments.end(); I != E; ++I)
1281     delete I->second;
1282   PatternFragments.clear();
1283
1284   Instructions.clear();
1285 }