Add support for a bool argty
[oota-llvm.git] / utils / TableGen / InstrSelectorEmitter.cpp
1 //===- InstrInfoEmitter.cpp - Generate a Instruction Set Desc. ------------===//
2 //
3 // This tablegen backend is responsible for emitting a description of the target
4 // instruction set for the code generator.
5 //
6 //===----------------------------------------------------------------------===//
7
8 #include "InstrSelectorEmitter.h"
9 #include "CodeGenWrappers.h"
10 #include "Record.h"
11 #include "Support/Debug.h"
12 #include "Support/StringExtras.h"
13 #include <set>
14
15 NodeType::ArgResultTypes NodeType::Translate(Record *R) {
16   const std::string &Name = R->getName();
17   if (Name == "DNVT_void") return Void;
18   if (Name == "DNVT_val" ) return Val;
19   if (Name == "DNVT_arg0") return Arg0;
20   if (Name == "DNVT_arg1") return Arg1;
21   if (Name == "DNVT_ptr" ) return Ptr;
22   if (Name == "DNVT_bool") return Bool;
23   throw "Unknown DagNodeValType '" + Name + "'!";
24 }
25
26
27 //===----------------------------------------------------------------------===//
28 // TreePatternNode implementation
29 //
30
31 /// getValueRecord - Returns the value of this tree node as a record.  For now
32 /// we only allow DefInit's as our leaf values, so this is used.
33 Record *TreePatternNode::getValueRecord() const {
34   DefInit *DI = dynamic_cast<DefInit*>(getValue());
35   assert(DI && "Instruction Selector does not yet support non-def leaves!");
36   return DI->getDef();
37 }
38
39
40 // updateNodeType - Set the node type of N to VT if VT contains information.  If
41 // N already contains a conflicting type, then throw an exception
42 //
43 bool TreePatternNode::updateNodeType(MVT::ValueType VT,
44                                      const std::string &RecName) {
45   if (VT == MVT::Other || getType() == VT) return false;
46   if (getType() == MVT::Other) {
47     setType(VT);
48     return true;
49   }
50
51   throw "Type inferfence contradiction found for pattern " + RecName;
52 }
53
54 /// InstantiateNonterminals - If this pattern refers to any nonterminals which
55 /// are not themselves completely resolved, clone the nonterminal and resolve it
56 /// with the using context we provide.
57 ///
58 void TreePatternNode::InstantiateNonterminals(InstrSelectorEmitter &ISE) {
59   if (!isLeaf()) {
60     for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
61       getChild(i)->InstantiateNonterminals(ISE);
62     return;
63   }
64   
65   // If this is a leaf, it might be a reference to a nonterminal!  Check now.
66   Record *R = getValueRecord();
67   if (R->isSubClassOf("Nonterminal")) {
68     Pattern *NT = ISE.getPattern(R);
69     if (!NT->isResolved()) {
70       // We found an unresolved nonterminal reference.  Ask the ISE to clone
71       // it for us, then update our reference to the fresh, new, resolved,
72       // nonterminal.
73       
74       Value = new DefInit(ISE.InstantiateNonterminal(NT, getType()));
75     }
76   }
77 }
78
79
80 /// clone - Make a copy of this tree and all of its children.
81 ///
82 TreePatternNode *TreePatternNode::clone() const {
83   TreePatternNode *New;
84   if (isLeaf()) {
85     New = new TreePatternNode(Value);
86   } else {
87     std::vector<std::pair<TreePatternNode*, std::string> > CChildren;
88     CChildren.reserve(Children.size());
89     for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
90       CChildren.push_back(std::make_pair(getChild(i)->clone(),getChildName(i)));
91     New = new TreePatternNode(Operator, CChildren);
92   }
93   New->setType(Type);
94   return New;
95 }
96
97 std::ostream &operator<<(std::ostream &OS, const TreePatternNode &N) {
98   if (N.isLeaf())
99     return OS << N.getType() << ":" << *N.getValue();
100   OS << "(" << N.getType() << ":";
101   OS << N.getOperator()->getName();
102   
103   if (N.getNumChildren() != 0) {
104     OS << " " << *N.getChild(0);
105     for (unsigned i = 1, e = N.getNumChildren(); i != e; ++i)
106       OS << ", " << *N.getChild(i);
107   }  
108   return OS << ")";
109 }
110
111 void TreePatternNode::dump() const { std::cerr << *this; }
112
113 //===----------------------------------------------------------------------===//
114 // Pattern implementation
115 //
116
117 // Parse the specified DagInit into a TreePattern which we can use.
118 //
119 Pattern::Pattern(PatternType pty, DagInit *RawPat, Record *TheRec,
120                  InstrSelectorEmitter &ise)
121   : PTy(pty), ResultNode(0), TheRecord(TheRec), ISE(ise) {
122
123   // First, parse the pattern...
124   Tree = ParseTreePattern(RawPat);
125
126   // Run the type-inference engine...
127   InferAllTypes();
128
129   if (PTy == Instruction || PTy == Expander) {
130     // Check to make sure there is not any unset types in the tree pattern...
131     if (!isResolved()) {
132       std::cerr << "In pattern: " << *Tree << "\n";
133       error("Could not infer all types!");
134     }
135
136     // Check to see if we have a top-level (set) of a register.
137     if (Tree->getOperator()->getName() == "set") {
138       assert(Tree->getNumChildren() == 2 && "Set with != 2 arguments?");
139       if (!Tree->getChild(0)->isLeaf())
140         error("Arg #0 of set should be a register or register class!");
141       ResultNode = Tree->getChild(0);
142       ResultName = Tree->getChildName(0);
143       Tree = Tree->getChild(1);
144     }
145   }
146
147   calculateArgs(Tree, "");
148 }
149
150 void Pattern::error(const std::string &Msg) const {
151   std::string M = "In ";
152   switch (PTy) {
153   case Nonterminal: M += "nonterminal "; break;
154   case Instruction: M += "instruction "; break;
155   case Expander   : M += "expander "; break;
156   }
157   throw M + TheRecord->getName() + ": " + Msg;  
158 }
159
160 /// calculateArgs - Compute the list of all of the arguments to this pattern,
161 /// which are the non-void leaf nodes in this pattern.
162 ///
163 void Pattern::calculateArgs(TreePatternNode *N, const std::string &Name) {
164   if (N->isLeaf() || N->getNumChildren() == 0) {
165     if (N->getType() != MVT::isVoid)
166       Args.push_back(std::make_pair(N, Name));
167   } else {
168     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
169       calculateArgs(N->getChild(i), N->getChildName(i));
170   }
171 }
172
173 /// getIntrinsicType - Check to see if the specified record has an intrinsic
174 /// type which should be applied to it.  This infer the type of register
175 /// references from the register file information, for example.
176 ///
177 MVT::ValueType Pattern::getIntrinsicType(Record *R) const {
178   // Check to see if this is a register or a register class...
179   if (R->isSubClassOf("RegisterClass"))
180     return getValueType(R->getValueAsDef("RegType"));
181   else if (R->isSubClassOf("Nonterminal"))
182     return ISE.ReadNonterminal(R)->getTree()->getType();
183   else if (R->isSubClassOf("Register")) {
184     std::cerr << "WARNING: Explicit registers not handled yet!\n";
185     return MVT::Other;
186   }
187
188   error("Unknown value used: " + R->getName());
189   return MVT::Other;
190 }
191
192 TreePatternNode *Pattern::ParseTreePattern(DagInit *Dag) {
193   Record *Operator = Dag->getNodeType();
194
195   if (Operator->isSubClassOf("ValueType")) {
196     // If the operator is a ValueType, then this must be "type cast" of a leaf
197     // node.
198     if (Dag->getNumArgs() != 1)
199       error("Type cast only valid for a leaf node!");
200     
201     Init *Arg = Dag->getArg(0);
202     TreePatternNode *New;
203     if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
204       New = new TreePatternNode(DI);
205       // If it's a regclass or something else known, set the type.
206       New->setType(getIntrinsicType(DI->getDef()));
207     } else {
208       Arg->dump();
209       error("Unknown leaf value for tree pattern!");
210     }
211
212     // Apply the type cast...
213     New->updateNodeType(getValueType(Operator), TheRecord->getName());
214     return New;
215   }
216
217   if (!ISE.getNodeTypes().count(Operator))
218     error("Unrecognized node '" + Operator->getName() + "'!");
219
220   std::vector<std::pair<TreePatternNode*, std::string> > Children;
221   
222   for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
223     Init *Arg = Dag->getArg(i);
224     if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
225       Children.push_back(std::make_pair(ParseTreePattern(DI),
226                                         Dag->getArgName(i)));
227     } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
228       Record *R = DefI->getDef();
229       // Direct reference to a leaf DagNode?  Turn it into a DagNode if its own.
230       if (R->isSubClassOf("DagNode")) {
231         Dag->setArg(i, new DagInit(R,
232                                 std::vector<std::pair<Init*, std::string> >()));
233         --i;  // Revisit this node...
234       } else {
235         Children.push_back(std::make_pair(new TreePatternNode(DefI),
236                                           Dag->getArgName(i)));
237         // If it's a regclass or something else known, set the type.
238         Children.back().first->setType(getIntrinsicType(R));
239       }
240     } else {
241       Arg->dump();
242       error("Unknown leaf value for tree pattern!");
243     }
244   }
245
246   return new TreePatternNode(Operator, Children);
247 }
248
249 void Pattern::InferAllTypes() {
250   bool MadeChange, AnyUnset;
251   do {
252     MadeChange = false;
253     AnyUnset = InferTypes(Tree, MadeChange);
254   } while ((AnyUnset || MadeChange) && !(AnyUnset && !MadeChange));
255   Resolved = !AnyUnset;
256 }
257
258
259 // InferTypes - Perform type inference on the tree, returning true if there
260 // are any remaining untyped nodes and setting MadeChange if any changes were
261 // made.
262 bool Pattern::InferTypes(TreePatternNode *N, bool &MadeChange) {
263   if (N->isLeaf()) return N->getType() == MVT::Other;
264
265   bool AnyUnset = false;
266   Record *Operator = N->getOperator();
267   const NodeType &NT = ISE.getNodeType(Operator);
268
269   // Check to see if we can infer anything about the argument types from the
270   // return types...
271   if (N->getNumChildren() != NT.ArgTypes.size())
272     error("Incorrect number of children for " + Operator->getName() + " node!");
273
274   for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
275     TreePatternNode *Child = N->getChild(i);
276     AnyUnset |= InferTypes(Child, MadeChange);
277
278     switch (NT.ArgTypes[i]) {
279     case NodeType::Bool:
280       MadeChange |= Child->updateNodeType(MVT::i1, TheRecord->getName());
281       break;
282     case NodeType::Arg0:
283       MadeChange |= Child->updateNodeType(N->getChild(0)->getType(),
284                                           TheRecord->getName());
285       break;
286     case NodeType::Arg1:
287       MadeChange |= Child->updateNodeType(N->getChild(1)->getType(),
288                                           TheRecord->getName());
289       break;
290     case NodeType::Val:
291       if (Child->getType() == MVT::isVoid)
292         error("Inferred a void node in an illegal place!");
293       break;
294     case NodeType::Ptr:
295       MadeChange |= Child->updateNodeType(ISE.getTarget().getPointerType(),
296                                           TheRecord->getName());
297       break;
298     default: assert(0 && "Invalid argument ArgType!");
299     }
300   }
301
302   // See if we can infer anything about the return type now...
303   switch (NT.ResultType) {
304   case NodeType::Void:
305     MadeChange |= N->updateNodeType(MVT::isVoid, TheRecord->getName());
306     break;
307   case NodeType::Bool:
308     MadeChange |= N->updateNodeType(MVT::i1, TheRecord->getName());
309     break;
310   case NodeType::Arg0:
311     MadeChange |= N->updateNodeType(N->getChild(0)->getType(),
312                                     TheRecord->getName());
313     break;
314   case NodeType::Arg1:
315     MadeChange |= N->updateNodeType(N->getChild(1)->getType(),
316                                     TheRecord->getName());
317     break;
318   case NodeType::Ptr:
319     MadeChange |= N->updateNodeType(ISE.getTarget().getPointerType(),
320                                     TheRecord->getName());
321     break;
322   case NodeType::Val:
323     if (N->getType() == MVT::isVoid)
324       error("Inferred a void node in an illegal place!");
325     break;
326   default:
327     assert(0 && "Unhandled type constraint!");
328     break;
329   }
330
331   return AnyUnset | N->getType() == MVT::Other;
332 }
333
334 /// clone - This method is used to make an exact copy of the current pattern,
335 /// then change the "TheRecord" instance variable to the specified record.
336 ///
337 Pattern *Pattern::clone(Record *R) const {
338   assert(PTy == Nonterminal && "Can only clone nonterminals");
339   return new Pattern(Tree->clone(), R, Resolved, ISE);
340 }
341
342
343
344 std::ostream &operator<<(std::ostream &OS, const Pattern &P) {
345   switch (P.getPatternType()) {
346   case Pattern::Nonterminal: OS << "Nonterminal pattern "; break;
347   case Pattern::Instruction: OS << "Instruction pattern "; break;
348   case Pattern::Expander:    OS << "Expander pattern    "; break;
349   }
350
351   OS << P.getRecord()->getName() << ":\t";
352
353   if (Record *Result = P.getResult())
354     OS << Result->getName() << " = ";
355   OS << *P.getTree();
356
357   if (!P.isResolved())
358     OS << " [not completely resolved]";
359   return OS;
360 }
361
362 void Pattern::dump() const { std::cerr << *this; }
363
364
365
366 /// getSlotName - If this is a leaf node, return the slot name that the operand
367 /// will update.
368 std::string Pattern::getSlotName() const {
369   if (getPatternType() == Pattern::Nonterminal) {
370     // Just use the nonterminal name, which will already include the type if
371     // it has been cloned.
372     return getRecord()->getName();
373   } else {
374     std::string SlotName;
375     if (getResult())
376       SlotName = getResult()->getName()+"_";
377     else
378       SlotName = "Void_";
379     return SlotName + getName(getTree()->getType());
380   }
381 }
382
383 /// getSlotName - If this is a leaf node, return the slot name that the
384 /// operand will update.
385 std::string Pattern::getSlotName(Record *R) {
386   if (R->isSubClassOf("Nonterminal")) {
387     // Just use the nonterminal name, which will already include the type if
388     // it has been cloned.
389     return R->getName();
390   } else if (R->isSubClassOf("RegisterClass")) {
391     MVT::ValueType Ty = getValueType(R->getValueAsDef("RegType"));
392     return R->getName() + "_" + getName(Ty);
393   } else {
394     assert(0 && "Don't know how to get a slot name for this!");
395   }
396 }
397
398 //===----------------------------------------------------------------------===//
399 // PatternOrganizer implementation
400 //
401
402 /// addPattern - Add the specified pattern to the appropriate location in the
403 /// collection.
404 void PatternOrganizer::addPattern(Pattern *P) {
405   NodesForSlot &Nodes = AllPatterns[P->getSlotName()];
406   if (!P->getTree()->isLeaf())
407     Nodes[P->getTree()->getOperator()].push_back(P);
408   else {
409     // Right now we only support DefInit's with node types...
410     Nodes[P->getTree()->getValueRecord()].push_back(P);
411   }
412 }
413
414
415
416 //===----------------------------------------------------------------------===//
417 // InstrSelectorEmitter implementation
418 //
419
420 /// ReadNodeTypes - Read in all of the node types in the current RecordKeeper,
421 /// turning them into the more accessible NodeTypes data structure.
422 ///
423 void InstrSelectorEmitter::ReadNodeTypes() {
424   std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("DagNode");
425   DEBUG(std::cerr << "Getting node types: ");
426   for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
427     Record *Node = Nodes[i];
428     
429     // Translate the return type...
430     NodeType::ArgResultTypes RetTy =
431       NodeType::Translate(Node->getValueAsDef("RetType"));
432
433     // Translate the arguments...
434     ListInit *Args = Node->getValueAsListInit("ArgTypes");
435     std::vector<NodeType::ArgResultTypes> ArgTypes;
436
437     for (unsigned a = 0, e = Args->getSize(); a != e; ++a) {
438       if (DefInit *DI = dynamic_cast<DefInit*>(Args->getElement(a)))
439         ArgTypes.push_back(NodeType::Translate(DI->getDef()));
440       else
441         throw "In node " + Node->getName() + ", argument is not a Def!";
442
443       if (a == 0 && ArgTypes.back() == NodeType::Arg0)
444         throw "In node " + Node->getName() + ", arg 0 cannot have type 'arg0'!";
445       if (a == 1 && ArgTypes.back() == NodeType::Arg1)
446         throw "In node " + Node->getName() + ", arg 1 cannot have type 'arg1'!";
447       if (ArgTypes.back() == NodeType::Void)
448         throw "In node " + Node->getName() + ", args cannot be void type!";
449     }
450     if ((RetTy == NodeType::Arg0 && Args->getSize() == 0) ||
451         (RetTy == NodeType::Arg1 && Args->getSize() < 2))
452       throw "In node " + Node->getName() +
453             ", invalid return type for node with this many operands!";
454
455     // Add the node type mapping now...
456     NodeTypes[Node] = NodeType(RetTy, ArgTypes);
457     DEBUG(std::cerr << Node->getName() << ", ");
458   }
459   DEBUG(std::cerr << "DONE!\n");
460 }
461
462 Pattern *InstrSelectorEmitter::ReadNonterminal(Record *R) {
463   Pattern *&P = Patterns[R];
464   if (P) return P;  // Don't reread it!
465
466   DagInit *DI = R->getValueAsDag("Pattern");
467   P = new Pattern(Pattern::Nonterminal, DI, R, *this);
468   DEBUG(std::cerr << "Parsed " << *P << "\n");
469   return P;
470 }
471
472
473 // ReadNonTerminals - Read in all nonterminals and incorporate them into our
474 // pattern database.
475 void InstrSelectorEmitter::ReadNonterminals() {
476   std::vector<Record*> NTs = Records.getAllDerivedDefinitions("Nonterminal");
477   for (unsigned i = 0, e = NTs.size(); i != e; ++i)
478     ReadNonterminal(NTs[i]);
479 }
480
481
482 /// ReadInstructionPatterns - Read in all subclasses of Instruction, and process
483 /// those with a useful Pattern field.
484 ///
485 void InstrSelectorEmitter::ReadInstructionPatterns() {
486   std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction");
487   for (unsigned i = 0, e = Insts.size(); i != e; ++i) {
488     Record *Inst = Insts[i];
489     if (DagInit *DI = dynamic_cast<DagInit*>(Inst->getValueInit("Pattern"))) {
490       Patterns[Inst] = new Pattern(Pattern::Instruction, DI, Inst, *this);
491       DEBUG(std::cerr << "Parsed " << *Patterns[Inst] << "\n");
492     }
493   }
494 }
495
496 /// ReadExpanderPatterns - Read in all expander patterns...
497 ///
498 void InstrSelectorEmitter::ReadExpanderPatterns() {
499   std::vector<Record*> Expanders = Records.getAllDerivedDefinitions("Expander");
500   for (unsigned i = 0, e = Expanders.size(); i != e; ++i) {
501     Record *Expander = Expanders[i];
502     DagInit *DI = Expander->getValueAsDag("Pattern");
503     Patterns[Expander] = new Pattern(Pattern::Expander, DI, Expander, *this);
504     DEBUG(std::cerr << "Parsed " << *Patterns[Expander] << "\n");
505   }
506 }
507
508
509 // InstantiateNonterminals - Instantiate any unresolved nonterminals with
510 // information from the context that they are used in.
511 //
512 void InstrSelectorEmitter::InstantiateNonterminals() {
513   DEBUG(std::cerr << "Instantiating nonterminals:\n");
514   for (std::map<Record*, Pattern*>::iterator I = Patterns.begin(),
515          E = Patterns.end(); I != E; ++I)
516     if (I->second->isResolved())
517       I->second->InstantiateNonterminals();
518 }
519
520 /// InstantiateNonterminal - This method takes the nonterminal specified by
521 /// NT, which should not be completely resolved, clones it, applies ResultTy
522 /// to its root, then runs the type inference stuff on it.  This should
523 /// produce a newly resolved nonterminal, which we make a record for and
524 /// return.  To be extra fancy and efficient, this only makes one clone for
525 /// each type it is instantiated with.
526 Record *InstrSelectorEmitter::InstantiateNonterminal(Pattern *NT,
527                                                      MVT::ValueType ResultTy) {
528   assert(!NT->isResolved() && "Nonterminal is already resolved!");
529
530   // Check to see if we have already instantiated this pair...
531   Record* &Slot = InstantiatedNTs[std::make_pair(NT, ResultTy)];
532   if (Slot) return Slot;
533   
534   Record *New = new Record(NT->getRecord()->getName()+"_"+getName(ResultTy));
535
536   // Copy over the superclasses...
537   const std::vector<Record*> &SCs = NT->getRecord()->getSuperClasses();
538   for (unsigned i = 0, e = SCs.size(); i != e; ++i)
539     New->addSuperClass(SCs[i]);
540
541   DEBUG(std::cerr << "  Nonterminal '" << NT->getRecord()->getName()
542                   << "' for type '" << getName(ResultTy) << "', producing '"
543                   << New->getName() << "'\n");
544
545   // Copy the pattern...
546   Pattern *NewPat = NT->clone(New);
547
548   // Apply the type to the root...
549   NewPat->getTree()->updateNodeType(ResultTy, New->getName());
550
551   // Infer types...
552   NewPat->InferAllTypes();
553
554   // Make sure everything is good to go now...
555   if (!NewPat->isResolved())
556     NewPat->error("Instantiating nonterminal did not resolve all types!");
557
558   // Add the pattern to the patterns map, add the record to the RecordKeeper,
559   // return the new record.
560   Patterns[New] = NewPat;
561   Records.addDef(New);
562   return Slot = New;
563 }
564
565 // CalculateComputableValues - Fill in the ComputableValues map through
566 // analysis of the patterns we are playing with.
567 void InstrSelectorEmitter::CalculateComputableValues() {
568   // Loop over all of the patterns, adding them to the ComputableValues map
569   for (std::map<Record*, Pattern*>::iterator I = Patterns.begin(),
570          E = Patterns.end(); I != E; ++I)
571     if (I->second->isResolved()) {
572       // We don't want to add patterns like R32 = R32.  This is a hack working
573       // around a special case of a general problem, but for now we explicitly
574       // forbid these patterns.  They can never match anyway.
575       Pattern *P = I->second;
576       if (!P->getResult() || !P->getTree()->isLeaf() ||
577           P->getResult() != P->getTree()->getValueRecord())
578         ComputableValues.addPattern(P);
579     }
580 }
581
582 #if 0
583 // MoveIdenticalPatterns - Given a tree pattern 'P', move all of the tree
584 // patterns which have the same top-level structure as P from the 'From' list to
585 // the 'To' list.
586 static void MoveIdenticalPatterns(TreePatternNode *P,
587                     std::vector<std::pair<Pattern*, TreePatternNode*> > &From,
588                     std::vector<std::pair<Pattern*, TreePatternNode*> > &To) {
589   assert(!P->isLeaf() && "All leaves are identical!");
590
591   const std::vector<TreePatternNode*> &PChildren = P->getChildren();
592   for (unsigned i = 0; i != From.size(); ++i) {
593     TreePatternNode *N = From[i].second;
594     assert(P->getOperator() == N->getOperator() &&"Differing operators?");
595     assert(PChildren.size() == N->getChildren().size() &&
596            "Nodes with different arity??");
597     bool isDifferent = false;
598     for (unsigned c = 0, e = PChildren.size(); c != e; ++c) {
599       TreePatternNode *PC = PChildren[c];
600       TreePatternNode *NC = N->getChild(c);
601       if (PC->isLeaf() != NC->isLeaf()) {
602         isDifferent = true;
603         break;
604       }
605
606       if (!PC->isLeaf()) {
607         if (PC->getOperator() != NC->getOperator()) {
608           isDifferent = true;
609           break;
610         }
611       } else {  // It's a leaf!
612         if (PC->getValueRecord() != NC->getValueRecord()) {
613           isDifferent = true;
614           break;
615         }
616       }
617     }
618     // If it's the same as the reference one, move it over now...
619     if (!isDifferent) {
620       To.push_back(std::make_pair(From[i].first, N));
621       From.erase(From.begin()+i);
622       --i;   // Don't skip an entry...
623     }
624   }
625 }
626 #endif
627
628 static std::string getNodeName(Record *R) {
629   RecordVal *RV = R->getValue("EnumName");
630   if (RV)
631     if (Init *I = RV->getValue())
632       if (StringInit *SI = dynamic_cast<StringInit*>(I))
633         return SI->getValue();
634   return R->getName();
635 }
636
637
638 static void EmitPatternPredicates(TreePatternNode *Tree,
639                                   const std::string &VarName, std::ostream &OS){
640   OS << " && " << VarName << "->getNodeType() == ISD::"
641      << getNodeName(Tree->getOperator());
642
643   for (unsigned c = 0, e = Tree->getNumChildren(); c != e; ++c)
644     if (!Tree->getChild(c)->isLeaf())
645       EmitPatternPredicates(Tree->getChild(c),
646                             VarName + "->getUse(" + utostr(c)+")", OS);
647 }
648
649 static void EmitPatternCosts(TreePatternNode *Tree, const std::string &VarName,
650                              std::ostream &OS) {
651   for (unsigned c = 0, e = Tree->getNumChildren(); c != e; ++c)
652     if (Tree->getChild(c)->isLeaf()) {
653       OS << " + Match_"
654          << Pattern::getSlotName(Tree->getChild(c)->getValueRecord()) << "("
655          << VarName << "->getUse(" << c << "))";
656     } else {
657       EmitPatternCosts(Tree->getChild(c),
658                        VarName + "->getUse(" + utostr(c) + ")", OS);
659     }
660 }
661
662
663 // EmitMatchCosters - Given a list of patterns, which all have the same root
664 // pattern operator, emit an efficient decision tree to decide which one to
665 // pick.  This is structured this way to avoid reevaluations of non-obvious
666 // subexpressions.
667 void InstrSelectorEmitter::EmitMatchCosters(std::ostream &OS,
668            const std::vector<std::pair<Pattern*, TreePatternNode*> > &Patterns,
669                                             const std::string &VarPrefix,
670                                             unsigned IndentAmt) {
671   assert(!Patterns.empty() && "No patterns to emit matchers for!");
672   std::string Indent(IndentAmt, ' ');
673   
674   // Load all of the operands of the root node into scalars for fast access
675   const NodeType &ONT = getNodeType(Patterns[0].second->getOperator());
676   for (unsigned i = 0, e = ONT.ArgTypes.size(); i != e; ++i)
677     OS << Indent << "SelectionDAGNode *" << VarPrefix << "_Op" << i
678        << " = N->getUse(" << i << ");\n";
679
680   // Compute the costs of computing the various nonterminals/registers, which
681   // are directly used at this level.
682   OS << "\n" << Indent << "// Operand matching costs...\n";
683   std::set<std::string> ComputedValues;   // Avoid duplicate computations...
684   for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
685     TreePatternNode *NParent = Patterns[i].second;
686     for (unsigned c = 0, e = NParent->getNumChildren(); c != e; ++c) {
687       TreePatternNode *N = NParent->getChild(c);
688       if (N->isLeaf()) {
689         Record *VR = N->getValueRecord();
690         const std::string &LeafName = VR->getName();
691         std::string OpName  = VarPrefix + "_Op" + utostr(c);
692         std::string ValName = OpName + "_" + LeafName + "_Cost";
693         if (!ComputedValues.count(ValName)) {
694           OS << Indent << "unsigned " << ValName << " = Match_"
695              << Pattern::getSlotName(VR) << "(" << OpName << ");\n";
696           ComputedValues.insert(ValName);
697         }
698       }
699     }
700   }
701   OS << "\n";
702
703
704   std::string LocCostName = VarPrefix + "_Cost";
705   OS << Indent << "unsigned " << LocCostName << "Min = ~0U >> 1;\n"
706      << Indent << "unsigned " << VarPrefix << "_PatternMin = NoMatchPattern;\n";
707   
708 #if 0
709   // Separate out all of the patterns into groups based on what their top-level
710   // signature looks like...
711   std::vector<std::pair<Pattern*, TreePatternNode*> > PatternsLeft(Patterns);
712   while (!PatternsLeft.empty()) {
713     // Process all of the patterns that have the same signature as the last
714     // element...
715     std::vector<std::pair<Pattern*, TreePatternNode*> > Group;
716     MoveIdenticalPatterns(PatternsLeft.back().second, PatternsLeft, Group);
717     assert(!Group.empty() && "Didn't at least pick the source pattern?");
718
719 #if 0
720     OS << "PROCESSING GROUP:\n";
721     for (unsigned i = 0, e = Group.size(); i != e; ++i)
722       OS << "  " << *Group[i].first << "\n";
723     OS << "\n\n";
724 #endif
725
726     OS << Indent << "{ // ";
727
728     if (Group.size() != 1) {
729       OS << Group.size() << " size group...\n";
730       OS << Indent << "  unsigned " << VarPrefix << "_Pattern = NoMatch;\n";
731     } else {
732       OS << *Group[0].first << "\n";
733       OS << Indent << "  unsigned " << VarPrefix << "_Pattern = "
734          << Group[0].first->getRecord()->getName() << "_Pattern;\n";
735     }
736
737     OS << Indent << "  unsigned " << LocCostName << " = ";
738     if (Group.size() == 1)
739       OS << "1;\n";    // Add inst cost if at individual rec
740     else
741       OS << "0;\n";
742
743     // Loop over all of the operands, adding in their costs...
744     TreePatternNode *N = Group[0].second;
745     const std::vector<TreePatternNode*> &Children = N->getChildren();
746
747     // If necessary, emit conditionals to check for the appropriate tree
748     // structure here...
749     for (unsigned i = 0, e = Children.size(); i != e; ++i) {
750       TreePatternNode *C = Children[i];
751       if (C->isLeaf()) {
752         // We already calculated the cost for this leaf, add it in now...
753         OS << Indent << "  " << LocCostName << " += "
754            << VarPrefix << "_Op" << utostr(i) << "_"
755            << C->getValueRecord()->getName() << "_Cost;\n";
756       } else {
757         // If it's not a leaf, we have to check to make sure that the current
758         // node has the appropriate structure, then recurse into it...
759         OS << Indent << "  if (" << VarPrefix << "_Op" << i
760            << "->getNodeType() == ISD::" << getNodeName(C->getOperator())
761            << ") {\n";
762         std::vector<std::pair<Pattern*, TreePatternNode*> > SubPatterns;
763         for (unsigned n = 0, e = Group.size(); n != e; ++n)
764           SubPatterns.push_back(std::make_pair(Group[n].first,
765                                                Group[n].second->getChild(i)));
766         EmitMatchCosters(OS, SubPatterns, VarPrefix+"_Op"+utostr(i),
767                          IndentAmt + 4);
768         OS << Indent << "  }\n";
769       }
770     }
771
772     // If the cost for this match is less than the minimum computed cost so far,
773     // update the minimum cost and selected pattern.
774     OS << Indent << "  if (" << LocCostName << " < " << LocCostName << "Min) { "
775        << LocCostName << "Min = " << LocCostName << "; " << VarPrefix
776        << "_PatternMin = " << VarPrefix << "_Pattern; }\n";
777     
778     OS << Indent << "}\n";
779   }
780 #endif
781
782   for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
783     Pattern *P = Patterns[i].first;
784     TreePatternNode *PTree = P->getTree();
785     unsigned PatternCost = 1;
786
787     // Check to see if there are any non-leaf elements in the pattern.  If so,
788     // we need to emit a predicate for this match.
789     bool AnyNonLeaf = false;
790     for (unsigned c = 0, e = PTree->getNumChildren(); c != e; ++c)
791       if (!PTree->getChild(c)->isLeaf()) {
792         AnyNonLeaf = true;
793         break;
794       }
795
796     if (!AnyNonLeaf) {   // No predicate necessary, just output a scope...
797       OS << "  {// " << *P << "\n";
798     } else {
799       // We need to emit a predicate to make sure the tree pattern matches, do
800       // so now...
801       OS << "  if (1";
802       for (unsigned c = 0, e = PTree->getNumChildren(); c != e; ++c)
803         if (!PTree->getChild(c)->isLeaf())
804           EmitPatternPredicates(PTree->getChild(c),
805                                 VarPrefix + "_Op" + utostr(c), OS);
806
807       OS << ") {\n    // " << *P << "\n";
808     }
809
810     OS << "    unsigned PatCost = " << PatternCost;
811
812     for (unsigned c = 0, e = PTree->getNumChildren(); c != e; ++c)
813       if (PTree->getChild(c)->isLeaf()) {
814         OS << " + " << VarPrefix << "_Op" << c << "_"
815            << PTree->getChild(c)->getValueRecord()->getName() << "_Cost";
816       } else {
817         EmitPatternCosts(PTree->getChild(c), VarPrefix + "_Op" + utostr(c), OS);
818       }
819     OS << ";\n";
820     OS << "    if (PatCost < MinCost) { MinCost = PatCost; Pattern = "
821        << P->getRecord()->getName() << "_Pattern; }\n"
822        << "  }\n";
823   }
824 }
825
826 static void ReduceAllOperands(TreePatternNode *N, const std::string &Name,
827              std::vector<std::pair<TreePatternNode*, std::string> > &Operands,
828                               std::ostream &OS) {
829   if (N->isLeaf()) {
830     // If this is a leaf, register or nonterminal reference...
831     std::string SlotName = Pattern::getSlotName(N->getValueRecord());
832     OS << "    ReducedValue_" << SlotName << " *" << Name << "Val = Reduce_"
833        << SlotName << "(" << Name << ", MBB);\n";
834     Operands.push_back(std::make_pair(N, Name+"Val"));
835   } else if (N->getNumChildren() == 0) {
836     // This is a reference to a leaf tree node, like an immediate or frame
837     // index.
838     if (N->getType() != MVT::isVoid) {
839       std::string SlotName =
840         getNodeName(N->getOperator()) + "_" + getName(N->getType());
841       OS << "    ReducedValue_" << SlotName << " *" << Name << "Val = "
842          << Name << "->getValue<ReducedValue_" << SlotName << ">(ISD::"
843          << SlotName << "_Slot);\n";
844       Operands.push_back(std::make_pair(N, Name+"Val"));
845     }
846   } else {
847     // Otherwise this is an interior node...
848     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
849       std::string ChildName = Name + "_Op" + utostr(i);
850       OS << "    SelectionDAGNode *" << ChildName << " = " << Name
851          << "->getUse(" << i << ");\n";
852       ReduceAllOperands(N->getChild(i), ChildName, Operands, OS);
853     }
854   }
855 }
856
857 /// PrintExpanderOperand - Print out Arg as part of the instruction emission
858 /// process for the expander pattern P.  This argument may be referencing some
859 /// values defined in P, or may just be physical register references or
860 /// something like that.  If PrintArg is true, we are printing out arguments to
861 /// the BuildMI call.  If it is false, we are printing the result register
862 /// name.
863 void InstrSelectorEmitter::PrintExpanderOperand(Init *Arg,
864                                                 const std::string &NameVar,
865                                                 TreePatternNode *ArgDeclNode,
866                                                 Pattern *P, bool PrintArg,
867                                                 std::ostream &OS) {
868   if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
869     Record *Arg = DI->getDef();
870     if (!ArgDeclNode->isLeaf())
871       P->error("Expected leaf node as argument!");
872     Record *ArgDecl = ArgDeclNode->getValueRecord();
873     if (Arg->isSubClassOf("Register")) {
874       // This is a physical register reference... make sure that the instruction
875       // requested a register!
876       if (!ArgDecl->isSubClassOf("RegisterClass"))
877         P->error("Argument mismatch for instruction pattern!");
878
879       // FIXME: This should check to see if the register is in the specified
880       // register class!
881       if (PrintArg) OS << ".addReg(";
882       OS << getQualifiedName(Arg);
883       if (PrintArg) OS << ")";
884       return;
885     } else if (Arg->isSubClassOf("RegisterClass")) {
886       // If this is a symbolic register class reference, we must be using a
887       // named value.
888       if (NameVar.empty()) P->error("Did not specify WHICH register to pass!");
889       if (Arg != ArgDecl) P->error("Instruction pattern mismatch!");
890
891       if (PrintArg) OS << ".addReg(";
892       OS << NameVar;
893       if (PrintArg) OS << ")";
894       return;
895     } else if (Arg->getName() == "frameidx") {
896       if (!PrintArg) P->error("Cannot define a new frameidx value!");
897       OS << ".addFrameIndex(" << NameVar << ")";
898       return;
899     }
900     P->error("Unknown operand type '" + Arg->getName() + "' to expander!");
901   } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
902     if (!NameVar.empty())
903       P->error("Illegal to specify a name for a constant initializer arg!");
904
905     // Hack this check to allow R32 values with 0 as the initializer for memory
906     // references... FIXME!
907     if (ArgDeclNode->isLeaf() && II->getValue() == 0 &&
908         ArgDeclNode->getValueRecord()->getName() == "R32") {
909       OS << ".addReg(0)";
910     } else {
911       if (ArgDeclNode->isLeaf() || ArgDeclNode->getOperator()->getName()!="imm")
912         P->error("Illegal immediate int value '" + itostr(II->getValue()) +
913                "' operand!");
914       OS << ".addZImm(" << II->getValue() << ")";
915     }
916     return;
917   }
918   P->error("Unknown operand type to expander!");
919 }
920
921 static std::string getArgName(Pattern *P, const std::string &ArgName, 
922        const std::vector<std::pair<TreePatternNode*, std::string> > &Operands) {
923   assert(P->getNumArgs() == Operands.size() &&"Argument computation mismatch!");
924   if (ArgName.empty()) return "";
925
926   for (unsigned i = 0, e = P->getNumArgs(); i != e; ++i)
927     if (P->getArgName(i) == ArgName)
928       return Operands[i].second + "->Val";
929
930   if (ArgName == P->getResultName())
931     return "NewReg";
932   P->error("Pattern does not define a value named $" + ArgName + "!");
933   return "";
934 }
935
936
937 void InstrSelectorEmitter::run(std::ostream &OS) {
938   // Type-check all of the node types to ensure we "understand" them.
939   ReadNodeTypes();
940   
941   // Read in all of the nonterminals, instructions, and expanders...
942   ReadNonterminals();
943   ReadInstructionPatterns();
944   ReadExpanderPatterns();
945
946   // Instantiate any unresolved nonterminals with information from the context
947   // that they are used in.
948   InstantiateNonterminals();
949
950   // Clear InstantiatedNTs, we don't need it anymore...
951   InstantiatedNTs.clear();
952
953   DEBUG(std::cerr << "Patterns acquired:\n");
954   for (std::map<Record*, Pattern*>::iterator I = Patterns.begin(),
955          E = Patterns.end(); I != E; ++I)
956     if (I->second->isResolved())
957       DEBUG(std::cerr << "  " << *I->second << "\n");
958
959   CalculateComputableValues();
960   
961   EmitSourceFileHeader("Instruction Selector for the " + Target.getName() +
962                        " target", OS);
963   OS << "#include \"llvm/CodeGen/MachineInstrBuilder.h\"\n";
964
965   // Output the slot number enums...
966   OS << "\nenum { // Slot numbers...\n"
967      << "  LastBuiltinSlot = ISD::NumBuiltinSlots-1, // Start numbering here\n";
968   for (PatternOrganizer::iterator I = ComputableValues.begin(),
969          E = ComputableValues.end(); I != E; ++I)
970     OS << "  " << I->first << "_Slot,\n";
971   OS << "  NumSlots\n};\n\n// Reduction value typedefs...\n";
972
973   // Output the reduction value typedefs...
974   for (PatternOrganizer::iterator I = ComputableValues.begin(),
975          E = ComputableValues.end(); I != E; ++I) {
976
977     OS << "typedef ReducedValue<unsigned, " << I->first
978        << "_Slot> ReducedValue_" << I->first << ";\n";
979   }
980
981   // Output the pattern enums...
982   OS << "\n\n"
983      << "enum { // Patterns...\n"
984      << "  NotComputed = 0,\n"
985      << "  NoMatchPattern, \n";
986   for (PatternOrganizer::iterator I = ComputableValues.begin(),
987          E = ComputableValues.end(); I != E; ++I) {
988     OS << "  // " << I->first << " patterns...\n";
989     for (PatternOrganizer::NodesForSlot::iterator J = I->second.begin(),
990            E = I->second.end(); J != E; ++J)
991       for (unsigned i = 0, e = J->second.size(); i != e; ++i)
992         OS << "  " << J->second[i]->getRecord()->getName() << "_Pattern,\n";
993   }
994   OS << "};\n\n";
995
996   //===--------------------------------------------------------------------===//
997   // Emit the class definition...
998   //
999   OS << "namespace {\n"
1000      << "  class " << Target.getName() << "ISel {\n"
1001      << "    SelectionDAG &DAG;\n"
1002      << "  public:\n"
1003      << "    X86ISel(SelectionDAG &D) : DAG(D) {}\n"
1004      << "    void generateCode();\n"
1005      << "  private:\n"
1006      << "    unsigned makeAnotherReg(const TargetRegisterClass *RC) {\n"
1007      << "      return DAG.getMachineFunction().getSSARegMap()->createVirt"
1008                                        "ualRegister(RC);\n"
1009      << "    }\n\n"
1010      << "    // DAG matching methods for classes... all of these methods"
1011                                        " return the cost\n"
1012      << "    // of producing a value of the specified class and type, which"
1013                                        " also gets\n"
1014      << "    // added to the DAG node.\n";
1015
1016   // Output all of the matching prototypes for slots...
1017   for (PatternOrganizer::iterator I = ComputableValues.begin(),
1018          E = ComputableValues.end(); I != E; ++I)
1019     OS << "    unsigned Match_" << I->first << "(SelectionDAGNode *N);\n";
1020   OS << "\n    // DAG matching methods for DAG nodes...\n";
1021
1022   // Output all of the matching prototypes for slot/node pairs
1023   for (PatternOrganizer::iterator I = ComputableValues.begin(),
1024          E = ComputableValues.end(); I != E; ++I)
1025     for (PatternOrganizer::NodesForSlot::iterator J = I->second.begin(),
1026            E = I->second.end(); J != E; ++J)
1027       OS << "    unsigned Match_" << I->first << "_" << getNodeName(J->first)
1028          << "(SelectionDAGNode *N);\n";
1029
1030   // Output all of the dag reduction methods prototypes...
1031   OS << "\n    // DAG reduction methods...\n";
1032   for (PatternOrganizer::iterator I = ComputableValues.begin(),
1033          E = ComputableValues.end(); I != E; ++I)
1034     OS << "    ReducedValue_" << I->first << " *Reduce_" << I->first
1035        << "(SelectionDAGNode *N,\n" << std::string(27+2*I->first.size(), ' ')
1036        << "MachineBasicBlock *MBB);\n";
1037   OS << "  };\n}\n\n";
1038
1039   // Emit the generateCode entry-point...
1040   OS << "void X86ISel::generateCode() {\n"
1041      << "  SelectionDAGNode *Root = DAG.getRoot();\n"
1042      << "  assert(Root->getValueType() == MVT::isVoid && "
1043                                        "\"Root of DAG produces value??\");\n\n"
1044      << "  std::cerr << \"\\n\";\n"
1045      << "  unsigned Cost = Match_Void_void(Root);\n"
1046      << "  if (Cost >= ~0U >> 1) {\n"
1047      << "    std::cerr << \"Match failed!\\n\";\n"
1048      << "    Root->dump();\n"
1049      << "    abort();\n"
1050      << "  }\n\n"
1051      << "  std::cerr << \"Total DAG Cost: \" << Cost << \"\\n\\n\";\n\n"
1052      << "  Reduce_Void_void(Root, 0);\n"
1053      << "}\n\n"
1054      << "//===" << std::string(70, '-') << "===//\n"
1055      << "//  Matching methods...\n"
1056      << "//\n\n";
1057
1058   //===--------------------------------------------------------------------===//
1059   // Emit all of the matcher methods...
1060   //
1061   for (PatternOrganizer::iterator I = ComputableValues.begin(),
1062          E = ComputableValues.end(); I != E; ++I) {
1063     const std::string &SlotName = I->first;
1064     OS << "unsigned " << Target.getName() << "ISel::Match_" << SlotName
1065        << "(SelectionDAGNode *N) {\n"
1066        << "  assert(N->getValueType() == MVT::"
1067        << getEnumName((*I->second.begin()).second[0]->getTree()->getType())
1068        << ");\n" << "  // If we already have a cost available for " << SlotName
1069        << " use it!\n"
1070        << "  if (N->getPatternFor(" << SlotName << "_Slot))\n"
1071        << "    return N->getCostFor(" << SlotName << "_Slot);\n\n"
1072        << "  unsigned Cost;\n"
1073        << "  switch (N->getNodeType()) {\n"
1074        << "  default: Cost = ~0U >> 1;   // Match failed\n"
1075        << "           N->setPatternCostFor(" << SlotName << "_Slot, NoMatchPattern, Cost, NumSlots);\n"
1076        << "           break;\n";
1077
1078     for (PatternOrganizer::NodesForSlot::iterator J = I->second.begin(),
1079            E = I->second.end(); J != E; ++J)
1080       if (!J->first->isSubClassOf("Nonterminal"))
1081         OS << "  case ISD::" << getNodeName(J->first) << ":\tCost = Match_"
1082            << SlotName << "_" << getNodeName(J->first) << "(N); break;\n";
1083     OS << "  }\n";  // End of the switch statement
1084
1085     // Emit any patterns which have a nonterminal leaf as the RHS.  These may
1086     // match multiple root nodes, so they cannot be handled with the switch...
1087     for (PatternOrganizer::NodesForSlot::iterator J = I->second.begin(),
1088            E = I->second.end(); J != E; ++J)
1089       if (J->first->isSubClassOf("Nonterminal")) {
1090         OS << "  unsigned " << J->first->getName() << "_Cost = Match_"
1091            << getNodeName(J->first) << "(N);\n"
1092            << "  if (" << getNodeName(J->first) << "_Cost < Cost) Cost = "
1093            << getNodeName(J->first) << "_Cost;\n";
1094       }
1095
1096     OS << "  return Cost;\n}\n\n";
1097
1098     for (PatternOrganizer::NodesForSlot::iterator J = I->second.begin(),
1099            E = I->second.end(); J != E; ++J) {
1100       Record *Operator = J->first;
1101       bool isNonterm = Operator->isSubClassOf("Nonterminal");
1102       if (!isNonterm) {
1103         OS << "unsigned " << Target.getName() << "ISel::Match_";
1104         if (!isNonterm) OS << SlotName << "_";
1105         OS << getNodeName(Operator) << "(SelectionDAGNode *N) {\n"
1106            << "  unsigned Pattern = NoMatchPattern;\n"
1107            << "  unsigned MinCost = ~0U >> 1;\n";
1108         
1109         std::vector<std::pair<Pattern*, TreePatternNode*> > Patterns;
1110         for (unsigned i = 0, e = J->second.size(); i != e; ++i)
1111           Patterns.push_back(std::make_pair(J->second[i],
1112                                             J->second[i]->getTree()));
1113         EmitMatchCosters(OS, Patterns, "N", 2);
1114         
1115         OS << "\n  N->setPatternCostFor(" << SlotName
1116            << "_Slot, Pattern, MinCost, NumSlots);\n"
1117            << "  return MinCost;\n"
1118            << "}\n";
1119       }
1120     }
1121   }
1122
1123   //===--------------------------------------------------------------------===//
1124   // Emit all of the reducer methods...
1125   //
1126   OS << "\n\n//===" << std::string(70, '-') << "===//\n"
1127      << "// Reducer methods...\n"
1128      << "//\n";
1129
1130   for (PatternOrganizer::iterator I = ComputableValues.begin(),
1131          E = ComputableValues.end(); I != E; ++I) {
1132     const std::string &SlotName = I->first;
1133     OS << "ReducedValue_" << SlotName << " *" << Target.getName()
1134        << "ISel::Reduce_" << SlotName
1135        << "(SelectionDAGNode *N, MachineBasicBlock *MBB) {\n"
1136        << "  ReducedValue_" << SlotName << " *Val = N->hasValue<ReducedValue_"
1137        << SlotName << ">(" << SlotName << "_Slot);\n"
1138        << "  if (Val) return Val;\n"
1139        << "  if (N->getBB()) MBB = N->getBB();\n\n"
1140        << "  switch (N->getPatternFor(" << SlotName << "_Slot)) {\n";
1141
1142     // Loop over all of the patterns that can produce a value for this slot...
1143     PatternOrganizer::NodesForSlot &NodesForSlot = I->second;
1144     for (PatternOrganizer::NodesForSlot::iterator J = NodesForSlot.begin(),
1145            E = NodesForSlot.end(); J != E; ++J)
1146       for (unsigned i = 0, e = J->second.size(); i != e; ++i) {
1147         Pattern *P = J->second[i];
1148         OS << "  case " << P->getRecord()->getName() << "_Pattern: {\n"
1149            << "    // " << *P << "\n";
1150         // Loop over the operands, reducing them...
1151         std::vector<std::pair<TreePatternNode*, std::string> > Operands;
1152         ReduceAllOperands(P->getTree(), "N", Operands, OS);
1153         
1154         // Now that we have reduced all of our operands, and have the values
1155         // that reduction produces, perform the reduction action for this
1156         // pattern.
1157         std::string Result;
1158
1159         // If the pattern produces a register result, generate a new register
1160         // now.
1161         if (Record *R = P->getResult()) {
1162           assert(R->isSubClassOf("RegisterClass") &&
1163                  "Only handle register class results so far!");
1164           OS << "    unsigned NewReg = makeAnotherReg(" << Target.getName()
1165              << "::" << R->getName() << "RegisterClass);\n";
1166           Result = "NewReg";
1167           DEBUG(OS << "    std::cerr << \"%reg\" << NewReg << \" =\t\";\n");
1168         } else {
1169           DEBUG(OS << "    std::cerr << \"\t\t\";\n");
1170           Result = "0";
1171         }
1172
1173         // Print out the pattern that matched...
1174         DEBUG(OS << "    std::cerr << \"  " << P->getRecord()->getName() <<'"');
1175         DEBUG(for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1176                 if (Operands[i].first->isLeaf()) {
1177                   Record *RV = Operands[i].first->getValueRecord();
1178                   assert(RV->isSubClassOf("RegisterClass") &&
1179                          "Only handles registers here so far!");
1180                   OS << " << \" %reg\" << " << Operands[i].second
1181                      << "->Val";
1182                 } else {
1183                   OS << " << ' ' << " << Operands[i].second
1184                      << "->Val";
1185                 });
1186         DEBUG(OS << " << \"\\n\";\n");
1187         
1188         // Generate the reduction code appropriate to the particular type of
1189         // pattern that this is...
1190         switch (P->getPatternType()) {
1191         case Pattern::Instruction:
1192           // Instruction patterns just emit a single MachineInstr, using BuildMI
1193           OS << "    BuildMI(MBB, " << Target.getName() << "::"
1194              << P->getRecord()->getName() << ", " << Operands.size();
1195           if (P->getResult()) OS << ", NewReg";
1196           OS << ")";
1197
1198           for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1199             if (Operands[i].first->isLeaf()) {
1200               Record *RV = Operands[i].first->getValueRecord();
1201               assert(RV->isSubClassOf("RegisterClass") &&
1202                      "Only handles registers here so far!");
1203               OS << ".addReg(" << Operands[i].second << "->Val)";
1204             } else {
1205               OS << ".addZImm(" << Operands[i].second << "->Val)";
1206             }
1207           OS << ";\n";
1208           break;
1209         case Pattern::Expander: {
1210           // Expander patterns emit one machine instr for each instruction in
1211           // the list of instructions expanded to.
1212           ListInit *Insts = P->getRecord()->getValueAsListInit("Result");
1213           for (unsigned IN = 0, e = Insts->getSize(); IN != e; ++IN) {
1214             DagInit *DIInst = dynamic_cast<DagInit*>(Insts->getElement(IN));
1215             if (!DIInst) P->error("Result list must contain instructions!");
1216             Pattern *InstPat = getPattern(DIInst->getNodeType());
1217             if (!InstPat || InstPat->getPatternType() != Pattern::Instruction)
1218               P->error("Instruction list must contain Instruction patterns!");
1219             
1220             bool hasResult = InstPat->getResult() != 0;
1221             if (InstPat->getNumArgs() != DIInst->getNumArgs()-hasResult) {
1222               P->error("Incorrect number of arguments specified for inst '" +
1223                        InstPat->getRecord()->getName() + "' in result list!");
1224             }
1225
1226             // Start emission of the instruction...
1227             OS << "    BuildMI(MBB, " << Target.getName() << "::"
1228                << InstPat->getRecord()->getName() << ", "
1229                << DIInst->getNumArgs()-hasResult;
1230             // Emit register result if necessary..
1231             if (Record *R = InstPat->getResult()) {
1232               std::string ArgNameVal =
1233                 getArgName(P, DIInst->getArgName(0), Operands);
1234               PrintExpanderOperand(DIInst->getArg(0), ArgNameVal,
1235                                    InstPat->getResultNode(), P, false,
1236                                    OS << ", ");
1237             }
1238             OS << ")";
1239
1240             for (unsigned i = hasResult, e = DIInst->getNumArgs(); i != e; ++i){
1241               std::string ArgNameVal =
1242                 getArgName(P, DIInst->getArgName(i), Operands);
1243
1244               PrintExpanderOperand(DIInst->getArg(i), ArgNameVal,
1245                                    InstPat->getArg(i-hasResult), P, true, OS);
1246             }
1247
1248             OS << ";\n";
1249           }
1250           break;
1251         }
1252         default:
1253           assert(0 && "Reduction of this type of pattern not implemented!");
1254         }
1255
1256         OS << "    Val = new ReducedValue_" << SlotName << "(" << Result<<");\n"
1257            << "    break;\n"
1258            << "  }\n";
1259       }
1260     
1261     
1262     OS << "  default: assert(0 && \"Unknown " << SlotName << " pattern!\");\n"
1263        << "  }\n\n  N->addValue(Val);  // Do not ever recalculate this\n"
1264        << "  return Val;\n}\n\n";
1265   }
1266 }
1267