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