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