Fix a fixme by passing around SDOperand's instead of SDNode*'s
[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 value used: " + 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       New = new TreePatternNode(DI);
425       // If it's a regclass or something else known, set the type.
426       New->setType(getIntrinsicType(DI->getDef()));
427     } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
428       New = ParseTreePattern(DI);
429     } else {
430       Arg->dump();
431       error("Unknown leaf value for tree pattern!");
432       return 0;
433     }
434     
435     // Apply the type cast.
436     New->UpdateNodeType(getValueType(Operator), *this);
437     return New;
438   }
439   
440   // Verify that this is something that makes sense for an operator.
441   if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
442       !Operator->isSubClassOf("Instruction") && 
443       !Operator->isSubClassOf("SDNodeXForm") &&
444       Operator->getName() != "set")
445     error("Unrecognized node '" + Operator->getName() + "'!");
446   
447   std::vector<TreePatternNode*> Children;
448   
449   for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
450     Init *Arg = Dag->getArg(i);
451     if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
452       Children.push_back(ParseTreePattern(DI));
453       Children.back()->setName(Dag->getArgName(i));
454     } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
455       Record *R = DefI->getDef();
456       // Direct reference to a leaf DagNode or PatFrag?  Turn it into a
457       // TreePatternNode if its own.
458       if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
459         Dag->setArg(i, new DagInit(R,
460                               std::vector<std::pair<Init*, std::string> >()));
461         --i;  // Revisit this node...
462       } else {
463         TreePatternNode *Node = new TreePatternNode(DefI);
464         Node->setName(Dag->getArgName(i));
465         Children.push_back(Node);
466         
467         // If it's a regclass or something else known, set the type.
468         Node->setType(getIntrinsicType(R));
469         
470         // Input argument?
471         if (R->getName() == "node") {
472           if (Dag->getArgName(i).empty())
473             error("'node' argument requires a name to match with operand list");
474           Args.push_back(Dag->getArgName(i));
475         }
476       }
477     } else {
478       Arg->dump();
479       error("Unknown leaf value for tree pattern!");
480     }
481   }
482   
483   return new TreePatternNode(Operator, Children);
484 }
485
486 /// InferAllTypes - Infer/propagate as many types throughout the expression
487 /// patterns as possible.  Return true if all types are infered, false
488 /// otherwise.  Throw an exception if a type contradiction is found.
489 bool TreePattern::InferAllTypes() {
490   bool MadeChange = true;
491   while (MadeChange) {
492     MadeChange = false;
493     for (unsigned i = 0, e = Trees.size(); i != e; ++i)
494       MadeChange |= Trees[i]->ApplyTypeConstraints(*this);
495   }
496   
497   bool HasUnresolvedTypes = false;
498   for (unsigned i = 0, e = Trees.size(); i != e; ++i)
499     HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
500   return !HasUnresolvedTypes;
501 }
502
503 void TreePattern::print(std::ostream &OS) const {
504   OS << getRecord()->getName();
505   if (!Args.empty()) {
506     OS << "(" << Args[0];
507     for (unsigned i = 1, e = Args.size(); i != e; ++i)
508       OS << ", " << Args[i];
509     OS << ")";
510   }
511   OS << ": ";
512   
513   if (Trees.size() > 1)
514     OS << "[\n";
515   for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
516     OS << "\t";
517     Trees[i]->print(OS);
518     OS << "\n";
519   }
520
521   if (Trees.size() > 1)
522     OS << "]\n";
523 }
524
525 void TreePattern::dump() const { print(std::cerr); }
526
527
528
529 //===----------------------------------------------------------------------===//
530 // DAGISelEmitter implementation
531 //
532
533 // Parse all of the SDNode definitions for the target, populating SDNodes.
534 void DAGISelEmitter::ParseNodeInfo() {
535   std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
536   while (!Nodes.empty()) {
537     SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
538     Nodes.pop_back();
539   }
540 }
541
542 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
543 /// map, and emit them to the file as functions.
544 void DAGISelEmitter::ParseNodeTransforms(std::ostream &OS) {
545   OS << "\n// Node transformations.\n";
546   std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
547   while (!Xforms.empty()) {
548     Record *XFormNode = Xforms.back();
549     Record *SDNode = XFormNode->getValueAsDef("Opcode");
550     std::string Code = XFormNode->getValueAsCode("XFormFunction");
551     SDNodeXForms.insert(std::make_pair(XFormNode,
552                                        std::make_pair(SDNode, Code)));
553
554     if (!Code.empty()) {
555       std::string ClassName = getSDNodeInfo(SDNode).getSDClassName();
556       const char *C2 = ClassName == "SDNode" ? "N" : "inN";
557
558       OS << "inline SDOperand Transform_" << XFormNode->getName()
559          << "(SDNode *" << C2 << ") {\n";
560       if (ClassName != "SDNode")
561         OS << "  " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
562       OS << Code << "\n}\n";
563     }
564
565     Xforms.pop_back();
566   }
567 }
568
569
570
571 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
572 /// file, building up the PatternFragments map.  After we've collected them all,
573 /// inline fragments together as necessary, so that there are no references left
574 /// inside a pattern fragment to a pattern fragment.
575 ///
576 /// This also emits all of the predicate functions to the output file.
577 ///
578 void DAGISelEmitter::ParsePatternFragments(std::ostream &OS) {
579   std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
580   
581   // First step, parse all of the fragments and emit predicate functions.
582   OS << "\n// Predicate functions.\n";
583   for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
584     DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
585     TreePattern *P = new TreePattern(Fragments[i], Tree, *this);
586     PatternFragments[Fragments[i]] = P;
587     
588     // Validate the argument list, converting it to map, to discard duplicates.
589     std::vector<std::string> &Args = P->getArgList();
590     std::set<std::string> OperandsMap(Args.begin(), Args.end());
591     
592     if (OperandsMap.count(""))
593       P->error("Cannot have unnamed 'node' values in pattern fragment!");
594     
595     // Parse the operands list.
596     DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
597     if (OpsList->getNodeType()->getName() != "ops")
598       P->error("Operands list should start with '(ops ... '!");
599     
600     // Copy over the arguments.       
601     Args.clear();
602     for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
603       if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
604           static_cast<DefInit*>(OpsList->getArg(j))->
605           getDef()->getName() != "node")
606         P->error("Operands list should all be 'node' values.");
607       if (OpsList->getArgName(j).empty())
608         P->error("Operands list should have names for each operand!");
609       if (!OperandsMap.count(OpsList->getArgName(j)))
610         P->error("'" + OpsList->getArgName(j) +
611                  "' does not occur in pattern or was multiply specified!");
612       OperandsMap.erase(OpsList->getArgName(j));
613       Args.push_back(OpsList->getArgName(j));
614     }
615     
616     if (!OperandsMap.empty())
617       P->error("Operands list does not contain an entry for operand '" +
618                *OperandsMap.begin() + "'!");
619
620     // If there is a code init for this fragment, emit the predicate code and
621     // keep track of the fact that this fragment uses it.
622     std::string Code = Fragments[i]->getValueAsCode("Predicate");
623     if (!Code.empty()) {
624       assert(!P->getOnlyTree()->isLeaf() && "Can't be a leaf!");
625       std::string ClassName =
626         getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
627       const char *C2 = ClassName == "SDNode" ? "N" : "inN";
628       
629       OS << "inline bool Predicate_" << Fragments[i]->getName()
630          << "(SDNode *" << C2 << ") {\n";
631       if (ClassName != "SDNode")
632         OS << "  " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
633       OS << Code << "\n}\n";
634       P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
635     }
636     
637     // If there is a node transformation corresponding to this, keep track of
638     // it.
639     Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
640     if (!getSDNodeTransform(Transform).second.empty())    // not noop xform?
641       P->getOnlyTree()->setTransformFn(Transform);
642   }
643   
644   OS << "\n\n";
645
646   // Now that we've parsed all of the tree fragments, do a closure on them so
647   // that there are not references to PatFrags left inside of them.
648   for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
649        E = PatternFragments.end(); I != E; ++I) {
650     TreePattern *ThePat = I->second;
651     ThePat->InlinePatternFragments();
652         
653     // Infer as many types as possible.  Don't worry about it if we don't infer
654     // all of them, some may depend on the inputs of the pattern.
655     try {
656       ThePat->InferAllTypes();
657     } catch (...) {
658       // If this pattern fragment is not supported by this target (no types can
659       // satisfy its constraints), just ignore it.  If the bogus pattern is
660       // actually used by instructions, the type consistency error will be
661       // reported there.
662     }
663     
664     // If debugging, print out the pattern fragment result.
665     DEBUG(ThePat->dump());
666   }
667 }
668
669 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
670 /// instruction input.  Return true if this is a real use.
671 static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
672                       std::map<std::string, TreePatternNode*> &InstInputs) {
673   // No name -> not interesting.
674   if (Pat->getName().empty()) {
675     if (Pat->isLeaf()) {
676       DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
677       if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
678         I->error("Input " + DI->getDef()->getName() + " must be named!");
679
680     }
681     return false;
682   }
683
684   Record *Rec;
685   if (Pat->isLeaf()) {
686     DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
687     if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
688     Rec = DI->getDef();
689   } else {
690     assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
691     Rec = Pat->getOperator();
692   }
693
694   TreePatternNode *&Slot = InstInputs[Pat->getName()];
695   if (!Slot) {
696     Slot = Pat;
697   } else {
698     Record *SlotRec;
699     if (Slot->isLeaf()) {
700       SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
701     } else {
702       assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
703       SlotRec = Slot->getOperator();
704     }
705     
706     // Ensure that the inputs agree if we've already seen this input.
707     if (Rec != SlotRec)
708       I->error("All $" + Pat->getName() + " inputs must agree with each other");
709     if (Slot->getType() != Pat->getType())
710       I->error("All $" + Pat->getName() + " inputs must agree with each other");
711   }
712   return true;
713 }
714
715 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
716 /// part of "I", the instruction), computing the set of inputs and outputs of
717 /// the pattern.  Report errors if we see anything naughty.
718 void DAGISelEmitter::
719 FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
720                             std::map<std::string, TreePatternNode*> &InstInputs,
721                             std::map<std::string, Record*> &InstResults) {
722   if (Pat->isLeaf()) {
723     bool isUse = HandleUse(I, Pat, InstInputs);
724     if (!isUse && Pat->getTransformFn())
725       I->error("Cannot specify a transform function for a non-input value!");
726     return;
727   } else if (Pat->getOperator()->getName() != "set") {
728     // If this is not a set, verify that the children nodes are not void typed,
729     // and recurse.
730     for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
731       if (Pat->getChild(i)->getType() == MVT::isVoid)
732         I->error("Cannot have void nodes inside of patterns!");
733       FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults);
734     }
735     
736     // If this is a non-leaf node with no children, treat it basically as if
737     // it were a leaf.  This handles nodes like (imm).
738     bool isUse = false;
739     if (Pat->getNumChildren() == 0)
740       isUse = HandleUse(I, Pat, InstInputs);
741     
742     if (!isUse && Pat->getTransformFn())
743       I->error("Cannot specify a transform function for a non-input value!");
744     return;
745   } 
746   
747   // Otherwise, this is a set, validate and collect instruction results.
748   if (Pat->getNumChildren() == 0)
749     I->error("set requires operands!");
750   else if (Pat->getNumChildren() & 1)
751     I->error("set requires an even number of operands");
752   
753   if (Pat->getTransformFn())
754     I->error("Cannot specify a transform function on a set node!");
755   
756   // Check the set destinations.
757   unsigned NumValues = Pat->getNumChildren()/2;
758   for (unsigned i = 0; i != NumValues; ++i) {
759     TreePatternNode *Dest = Pat->getChild(i);
760     if (!Dest->isLeaf())
761       I->error("set destination should be a virtual register!");
762     
763     DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
764     if (!Val)
765       I->error("set destination should be a virtual register!");
766     
767     if (!Val->getDef()->isSubClassOf("RegisterClass"))
768       I->error("set destination should be a virtual register!");
769     if (Dest->getName().empty())
770       I->error("set destination must have a name!");
771     if (InstResults.count(Dest->getName()))
772       I->error("cannot set '" + Dest->getName() +"' multiple times");
773     InstResults[Dest->getName()] = Val->getDef();
774
775     // Verify and collect info from the computation.
776     FindPatternInputsAndOutputs(I, Pat->getChild(i+NumValues),
777                                 InstInputs, InstResults);
778   }
779 }
780
781
782 /// ParseInstructions - Parse all of the instructions, inlining and resolving
783 /// any fragments involved.  This populates the Instructions list with fully
784 /// resolved instructions.
785 void DAGISelEmitter::ParseInstructions() {
786   std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
787   
788   for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
789     if (!dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
790       continue; // no pattern yet, ignore it.
791     
792     ListInit *LI = Instrs[i]->getValueAsListInit("Pattern");
793     if (LI->getSize() == 0) continue;  // no pattern.
794     
795     // Parse the instruction.
796     TreePattern *I = new TreePattern(Instrs[i], LI, *this);
797     // Inline pattern fragments into it.
798     I->InlinePatternFragments();
799     
800     // Infer as many types as possible.  If we cannot infer all of them, we can
801     // never do anything with this instruction pattern: report it to the user.
802     if (!I->InferAllTypes())
803       I->error("Could not infer all types in pattern!");
804     
805     // InstInputs - Keep track of all of the inputs of the instruction, along 
806     // with the record they are declared as.
807     std::map<std::string, TreePatternNode*> InstInputs;
808     
809     // InstResults - Keep track of all the virtual registers that are 'set'
810     // in the instruction, including what reg class they are.
811     std::map<std::string, Record*> InstResults;
812     
813     // Verify that the top-level forms in the instruction are of void type, and
814     // fill in the InstResults map.
815     for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
816       TreePatternNode *Pat = I->getTree(j);
817       if (Pat->getType() != MVT::isVoid) {
818         I->dump();
819         I->error("Top-level forms in instruction pattern should have"
820                  " void types");
821       }
822
823       // Find inputs and outputs, and verify the structure of the uses/defs.
824       FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults);
825     }
826
827     // Now that we have inputs and outputs of the pattern, inspect the operands
828     // list for the instruction.  This determines the order that operands are
829     // added to the machine instruction the node corresponds to.
830     unsigned NumResults = InstResults.size();
831
832     // Parse the operands list from the (ops) list, validating it.
833     std::vector<std::string> &Args = I->getArgList();
834     assert(Args.empty() && "Args list should still be empty here!");
835     CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
836
837     // Check that all of the results occur first in the list.
838     std::vector<MVT::ValueType> ResultTypes;
839     for (unsigned i = 0; i != NumResults; ++i) {
840       if (i == CGI.OperandList.size())
841         I->error("'" + InstResults.begin()->first +
842                  "' set but does not appear in operand list!");
843       const std::string &OpName = CGI.OperandList[i].Name;
844       
845       // Check that it exists in InstResults.
846       Record *R = InstResults[OpName];
847       if (R == 0)
848         I->error("Operand $" + OpName + " should be a set destination: all "
849                  "outputs must occur before inputs in operand list!");
850       
851       if (CGI.OperandList[i].Rec != R)
852         I->error("Operand $" + OpName + " class mismatch!");
853       
854       // Remember the return type.
855       ResultTypes.push_back(CGI.OperandList[i].Ty);
856       
857       // Okay, this one checks out.
858       InstResults.erase(OpName);
859     }
860
861     // Loop over the inputs next.  Make a copy of InstInputs so we can destroy
862     // the copy while we're checking the inputs.
863     std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
864
865     std::vector<TreePatternNode*> ResultNodeOperands;
866     std::vector<MVT::ValueType> OperandTypes;
867     for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
868       const std::string &OpName = CGI.OperandList[i].Name;
869       if (OpName.empty())
870         I->error("Operand #" + utostr(i) + " in operands list has no name!");
871
872       if (!InstInputsCheck.count(OpName))
873         I->error("Operand $" + OpName +
874                  " does not appear in the instruction pattern");
875       TreePatternNode *InVal = InstInputsCheck[OpName];
876       InstInputsCheck.erase(OpName);   // It occurred, remove from map.
877       if (CGI.OperandList[i].Ty != InVal->getType())
878         I->error("Operand $" + OpName +
879                  "'s type disagrees between the operand and pattern");
880       OperandTypes.push_back(InVal->getType());
881       
882       // Construct the result for the dest-pattern operand list.
883       TreePatternNode *OpNode = InVal->clone();
884       
885       // No predicate is useful on the result.
886       OpNode->setPredicateFn("");
887       
888       // Promote the xform function to be an explicit node if set.
889       if (Record *Xform = OpNode->getTransformFn()) {
890         OpNode->setTransformFn(0);
891         std::vector<TreePatternNode*> Children;
892         Children.push_back(OpNode);
893         OpNode = new TreePatternNode(Xform, Children);
894       }
895       
896       ResultNodeOperands.push_back(OpNode);
897     }
898     
899     if (!InstInputsCheck.empty())
900       I->error("Input operand $" + InstInputsCheck.begin()->first +
901                " occurs in pattern but not in operands list!");
902
903     TreePatternNode *ResultPattern =
904       new TreePatternNode(I->getRecord(), ResultNodeOperands);
905
906     // Create and insert the instruction.
907     DAGInstruction TheInst(I, ResultTypes, OperandTypes);
908     Instructions.insert(std::make_pair(I->getRecord(), TheInst));
909
910     // Use a temporary tree pattern to infer all types and make sure that the
911     // constructed result is correct.  This depends on the instruction already
912     // being inserted into the Instructions map.
913     TreePattern Temp(I->getRecord(), ResultPattern, *this);
914     Temp.InferAllTypes();
915
916     DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
917     TheInsertedInst.setResultPattern(Temp.getOnlyTree());
918     
919     DEBUG(I->dump());
920   }
921    
922   // If we can, convert the instructions to be patterns that are matched!
923   for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
924        E = Instructions.end(); II != E; ++II) {
925     TreePattern *I = II->second.getPattern();
926     
927     if (I->getNumTrees() != 1) {
928       std::cerr << "CANNOT HANDLE: " << I->getRecord()->getName() << " yet!";
929       continue;
930     }
931     TreePatternNode *Pattern = I->getTree(0);
932     if (Pattern->getOperator()->getName() != "set")
933       continue;  // Not a set (store or something?)
934     
935     if (Pattern->getNumChildren() != 2)
936       continue;  // Not a set of a single value (not handled so far)
937     
938     TreePatternNode *SrcPattern = Pattern->getChild(1)->clone();
939     TreePatternNode *DstPattern = II->second.getResultPattern();
940     PatternsToMatch.push_back(std::make_pair(SrcPattern, DstPattern));
941   }
942 }
943
944 void DAGISelEmitter::ParsePatterns() {
945   std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
946
947   for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
948     DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
949     TreePattern *Pattern = new TreePattern(Patterns[i], Tree, *this);
950
951     // Inline pattern fragments into it.
952     Pattern->InlinePatternFragments();
953     
954     // Infer as many types as possible.  If we cannot infer all of them, we can
955     // never do anything with this pattern: report it to the user.
956     if (!Pattern->InferAllTypes())
957       Pattern->error("Could not infer all types in pattern!");
958     
959     ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
960     if (LI->getSize() == 0) continue;  // no pattern.
961     
962     // Parse the instruction.
963     TreePattern *Result = new TreePattern(Patterns[i], LI, *this);
964     
965     // Inline pattern fragments into it.
966     Result->InlinePatternFragments();
967     
968     // Infer as many types as possible.  If we cannot infer all of them, we can
969     // never do anything with this pattern: report it to the user.
970     if (!Result->InferAllTypes())
971       Result->error("Could not infer all types in pattern result!");
972    
973     if (Result->getNumTrees() != 1)
974       Result->error("Cannot handle instructions producing instructions "
975                     "with temporaries yet!");
976     PatternsToMatch.push_back(std::make_pair(Pattern->getOnlyTree(),
977                                              Result->getOnlyTree()));
978   }
979
980   DEBUG(std::cerr << "\n\nPARSED PATTERNS TO MATCH:\n\n";
981         for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
982           std::cerr << "PATTERN: ";  PatternsToMatch[i].first->dump();
983           std::cerr << "\nRESULT:  ";PatternsToMatch[i].second->dump();
984           std::cerr << "\n";
985         });
986 }
987
988 /// EmitMatchForPattern - Emit a matcher for N, going to the label for PatternNo
989 /// if the match fails.  At this point, we already know that the opcode for N
990 /// matches, and the SDNode for the result has the RootName specified name.
991 void DAGISelEmitter::EmitMatchForPattern(TreePatternNode *N,
992                                          const std::string &RootName, 
993                                          unsigned PatternNo, std::ostream &OS) {
994   assert(!N->isLeaf() && "Cannot match against a leaf!");
995   // Emit code to load the child nodes and match their contents recursively.
996   for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
997     OS << "      SDOperand " << RootName << i <<" = " << RootName
998        << ".getOperand(" << i << ");\n";
999     TreePatternNode *Child = N->getChild(i);
1000     if (!Child->isLeaf()) {
1001       // If it's not a leaf, recursively match.
1002       const SDNodeInfo &CInfo = getSDNodeInfo(Child->getOperator());
1003       OS << "      if (" << RootName << i << ".getOpcode() != "
1004          << CInfo.getEnumName() << ") goto P" << PatternNo << "Fail;\n";
1005       EmitMatchForPattern(Child, RootName + utostr(i), PatternNo, OS);
1006     } else {
1007       // Handle leaves of various types.
1008       Init *LeafVal = Child->getLeafValue();
1009       Record *LeafRec = dynamic_cast<DefInit*>(LeafVal)->getDef();
1010       if (LeafRec->isSubClassOf("RegisterClass")) {
1011         // Handle register references.  Nothing to do here.
1012       } else if (LeafRec->isSubClassOf("ValueType")) {
1013         // Make sure this is the specified value type.
1014         OS << "      if (cast<VTSDNode>(" << RootName << i << ")->getVT() != "
1015            << "MVT::" << LeafRec->getName() << ") goto P" << PatternNo
1016            << "Fail;\n";
1017       } else {
1018         Child->dump();
1019         assert(0 && "Unknown leaf type!");
1020       }
1021     }
1022     
1023     // If this child has a name associated with it, capture it as a variable.
1024     if (!Child->getName().empty())
1025       OS << "      SDOperand op" << Child->getName() << " = " << RootName
1026          << i << ";\n";
1027   }
1028   
1029   // If there is a node predicate for this, emit the call.
1030   if (!N->getPredicateFn().empty())
1031     OS << "      if (!" << N->getPredicateFn() << "(" << RootName
1032        << ".Val)) goto P" << PatternNo << "Fail;\n";
1033 }
1034
1035 /// EmitCodeForPattern - Given a pattern to match, emit code to the specified
1036 /// stream to match the pattern, and generate the code for the match if it
1037 /// succeeds.
1038 void DAGISelEmitter::EmitCodeForPattern(PatternToMatch &Pattern,
1039                                         std::ostream &OS) {
1040   static unsigned PatternCount = 0;
1041   unsigned PatternNo = PatternCount++;
1042   OS << "    { // Pattern #" << PatternNo << ": ";
1043   Pattern.first->print(OS);
1044   OS << "\n";
1045
1046   EmitMatchForPattern(Pattern.first, "N", PatternNo, OS);
1047   
1048   OS << "      // Emit: ";
1049   Pattern.second->print(OS);
1050   OS << "\n";
1051   
1052   OS << "    }\n  P" << PatternNo << "Fail:\n";
1053 }
1054
1055 /// getPatternSize - Return the 'size' of this pattern.  We want to match large
1056 /// patterns before small ones.  This is used to determine the size of a
1057 /// pattern.
1058 static unsigned getPatternSize(TreePatternNode *P) {
1059   assert(MVT::isInteger(P->getType()) || MVT::isFloatingPoint(P->getType()) &&
1060          "Not a valid pattern node to size!");
1061   unsigned Size = 1;  // The node itself.
1062   
1063   // Count children in the count if they are also nodes.
1064   for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
1065     TreePatternNode *Child = P->getChild(i);
1066     if (!Child->isLeaf() && Child->getType() != MVT::Other)
1067       Size += getPatternSize(Child);
1068   }
1069   
1070   return Size;
1071 }
1072
1073 // PatternSortingPredicate - return true if we prefer to match LHS before RHS.
1074 // In particular, we want to match maximal patterns first and lowest cost within
1075 // a particular complexity first.
1076 struct PatternSortingPredicate {
1077   bool operator()(DAGISelEmitter::PatternToMatch *LHS,
1078                   DAGISelEmitter::PatternToMatch *RHS) {
1079     unsigned LHSSize = getPatternSize(LHS->first);
1080     unsigned RHSSize = getPatternSize(RHS->first);
1081     if (LHSSize > RHSSize) return true;   // LHS -> bigger -> less cost
1082     if (LHSSize < RHSSize) return false;
1083     
1084     // If they are equal, compare cost.
1085     // FIXME: Compute cost!
1086     return false;
1087   }
1088 };
1089
1090 void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
1091   // Emit boilerplate.
1092   OS << "// The main instruction selector code.\n"
1093      << "SDOperand SelectCode(SDOperand N) {\n"
1094      << "  if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
1095      << "      N.getOpcode() < PPCISD::FIRST_NUMBER)\n"
1096      << "    return N;   // Already selected.\n\n"
1097      << "  switch (N.getOpcode()) {\n"
1098      << "  default: break;\n"
1099      << "  case ISD::EntryToken:       // These leaves remain the same.\n"
1100      << "    return N;\n"
1101      << "  case ISD::AssertSext:\n"
1102      << "  case ISD::AssertZext:\n"
1103      << "    return Select(N.getOperand(0));\n";
1104     
1105   // Group the patterns by their top-level opcodes.
1106   std::map<Record*, std::vector<PatternToMatch*> > PatternsByOpcode;
1107   for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i)
1108     PatternsByOpcode[PatternsToMatch[i].first->getOperator()]
1109       .push_back(&PatternsToMatch[i]);
1110   
1111   // Loop over all of the case statements.
1112   for (std::map<Record*, std::vector<PatternToMatch*> >::iterator
1113        PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end(); PBOI != E;
1114        ++PBOI) {
1115     const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
1116     std::vector<PatternToMatch*> &Patterns = PBOI->second;
1117     
1118     OS << "  case " << OpcodeInfo.getEnumName() << ":\n";
1119
1120     // We want to emit all of the matching code now.  However, we want to emit
1121     // the matches in order of minimal cost.  Sort the patterns so the least
1122     // cost one is at the start.
1123     std::stable_sort(Patterns.begin(), Patterns.end(),
1124                      PatternSortingPredicate());
1125     
1126     for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
1127       EmitCodeForPattern(*Patterns[i], OS);
1128     OS << "    break;\n\n";
1129   }
1130   
1131
1132   OS << "  } // end of big switch.\n\n"
1133      << "  std::cerr << \"Cannot yet select: \";\n"
1134      << "  N.Val->dump();\n"
1135      << "  std::cerr << '\\n';\n"
1136      << "  abort();\n"
1137      << "}\n";
1138 }
1139
1140 void DAGISelEmitter::run(std::ostream &OS) {
1141   EmitSourceFileHeader("DAG Instruction Selector for the " + Target.getName() +
1142                        " target", OS);
1143   
1144   OS << "// *** NOTE: This file is #included into the middle of the target\n"
1145      << "// *** instruction selector class.  These functions are really "
1146      << "methods.\n\n";
1147   
1148   ParseNodeInfo();
1149   ParseNodeTransforms(OS);
1150   ParsePatternFragments(OS);
1151   ParseInstructions();
1152   ParsePatterns();
1153   
1154   // FIXME: Generate variants.  For example, commutative patterns can match
1155   // multiple ways.  Add them to PatternsToMatch as well.
1156
1157   // At this point, we have full information about the 'Patterns' we need to
1158   // parse, both implicitly from instructions as well as from explicit pattern
1159   // definitions.
1160   
1161   EmitInstructionSelector(OS);  
1162   
1163   for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
1164        E = PatternFragments.end(); I != E; ++I)
1165     delete I->second;
1166   PatternFragments.clear();
1167
1168   Instructions.clear();
1169 }