1 //===- InstrInfoEmitter.cpp - Generate a Instruction Set Desc. ------------===//
3 // This tablegen backend is responsible for emitting a description of the target
4 // instruction set for the code generator.
6 //===----------------------------------------------------------------------===//
8 #include "InstrSelectorEmitter.h"
9 #include "CodeGenWrappers.h"
11 #include "Support/Debug.h"
12 #include "Support/StringExtras.h"
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 + "'!";
25 //===----------------------------------------------------------------------===//
26 // TreePatternNode implementation
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!");
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
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) {
49 throw "Type inferfence contradiction found for pattern " + RecName;
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.
56 void TreePatternNode::InstantiateNonterminals(InstrSelectorEmitter &ISE) {
58 for (unsigned i = 0, e = Children.size(); i != e; ++i)
59 Children[i]->InstantiateNonterminals(ISE);
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,
72 Value = new DefInit(ISE.InstantiateNonterminal(NT, getType()));
78 /// clone - Make a copy of this tree and all of its children.
80 TreePatternNode *TreePatternNode::clone() const {
83 New = new TreePatternNode(Value);
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);
94 std::ostream &operator<<(std::ostream &OS, const TreePatternNode &N) {
96 return OS << N.getType() << ":" << *N.getValue();
97 OS << "(" << N.getType() << ":";
98 OS << N.getOperator()->getName();
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];
109 void TreePatternNode::dump() const { std::cerr << *this; }
111 //===----------------------------------------------------------------------===//
112 // Pattern implementation
115 // Parse the specified DagInit into a TreePattern which we can use.
117 Pattern::Pattern(PatternType pty, DagInit *RawPat, Record *TheRec,
118 InstrSelectorEmitter &ise)
119 : PTy(pty), TheRecord(TheRec), ISE(ise) {
121 // First, parse the pattern...
122 Tree = ParseTreePattern(RawPat);
124 // Run the type-inference engine...
127 if (PTy == Instruction || PTy == Expander) {
128 // Check to make sure there is not any unset types in the tree pattern...
130 std::cerr << "In pattern: " << *Tree << "\n";
131 error("Could not infer all types!");
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);
145 void Pattern::error(const std::string &Msg) const {
146 std::string M = "In ";
148 case Nonterminal: M += "nonterminal "; break;
149 case Instruction: M += "instruction "; break;
150 case Expander : M += "expander "; break;
152 throw M + TheRecord->getName() + ": " + Msg;
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.
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";
170 throw "Error: Unknown value used: " + R->getName();
173 TreePatternNode *Pattern::ParseTreePattern(DagInit *DI) {
174 Record *Operator = DI->getNodeType();
175 const std::vector<Init*> &Args = DI->getArgs();
177 if (Operator->isSubClassOf("ValueType")) {
178 // If the operator is a ValueType, then this must be "type cast" of a leaf
180 if (Args.size() != 1)
181 error("Type cast only valid for a leaf node!");
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()));
191 error("Unknown leaf value for tree pattern!");
194 // Apply the type cast...
195 New->updateNodeType(getValueType(Operator), TheRecord->getName());
199 if (!ISE.getNodeTypes().count(Operator))
200 error("Unrecognized node '" + Operator->getName() + "'!");
202 std::vector<TreePatternNode*> Children;
204 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
206 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
207 Children.push_back(ParseTreePattern(DI));
208 } else if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
209 Children.push_back(new TreePatternNode(DI));
210 // If it's a regclass or something else known, set the type.
211 Children.back()->setType(getIntrinsicType(DI->getDef()));
214 error("Unknown leaf value for tree pattern!");
218 return new TreePatternNode(Operator, Children);
221 void Pattern::InferAllTypes() {
222 bool MadeChange, AnyUnset;
225 AnyUnset = InferTypes(Tree, MadeChange);
226 } while ((AnyUnset || MadeChange) && !(AnyUnset && !MadeChange));
227 Resolved = !AnyUnset;
231 // InferTypes - Perform type inference on the tree, returning true if there
232 // are any remaining untyped nodes and setting MadeChange if any changes were
234 bool Pattern::InferTypes(TreePatternNode *N, bool &MadeChange) {
235 if (N->isLeaf()) return N->getType() == MVT::Other;
237 bool AnyUnset = false;
238 Record *Operator = N->getOperator();
239 const NodeType &NT = ISE.getNodeType(Operator);
241 // Check to see if we can infer anything about the argument types from the
243 const std::vector<TreePatternNode*> &Children = N->getChildren();
244 if (Children.size() != NT.ArgTypes.size())
245 error("Incorrect number of children for " + Operator->getName() + " node!");
247 for (unsigned i = 0, e = Children.size(); i != e; ++i) {
248 TreePatternNode *Child = Children[i];
249 AnyUnset |= InferTypes(Child, MadeChange);
251 switch (NT.ArgTypes[i]) {
253 MadeChange |= Child->updateNodeType(Children[0]->getType(),
254 TheRecord->getName());
257 if (Child->getType() == MVT::isVoid)
258 error("Inferred a void node in an illegal place!");
261 MadeChange |= Child->updateNodeType(ISE.getTarget().getPointerType(),
262 TheRecord->getName());
264 default: assert(0 && "Invalid argument ArgType!");
268 // See if we can infer anything about the return type now...
269 switch (NT.ResultType) {
271 MadeChange |= N->updateNodeType(MVT::isVoid, TheRecord->getName());
274 MadeChange |= N->updateNodeType(Children[0]->getType(),
275 TheRecord->getName());
279 MadeChange |= N->updateNodeType(ISE.getTarget().getPointerType(),
280 TheRecord->getName());
283 if (N->getType() == MVT::isVoid)
284 error("Inferred a void node in an illegal place!");
287 assert(0 && "Unhandled type constraint!");
291 return AnyUnset | N->getType() == MVT::Other;
294 /// clone - This method is used to make an exact copy of the current pattern,
295 /// then change the "TheRecord" instance variable to the specified record.
297 Pattern *Pattern::clone(Record *R) const {
298 assert(PTy == Nonterminal && "Can only clone nonterminals");
299 return new Pattern(Tree->clone(), R, Resolved, ISE);
304 std::ostream &operator<<(std::ostream &OS, const Pattern &P) {
305 switch (P.getPatternType()) {
306 case Pattern::Nonterminal: OS << "Nonterminal pattern "; break;
307 case Pattern::Instruction: OS << "Instruction pattern "; break;
308 case Pattern::Expander: OS << "Expander pattern "; break;
311 OS << P.getRecord()->getName() << ":\t";
313 if (Record *Result = P.getResult())
314 OS << Result->getName() << " = ";
318 OS << " [not completely resolved]";
322 void Pattern::dump() const { std::cerr << *this; }
326 /// getSlotName - If this is a leaf node, return the slot name that the operand
328 std::string Pattern::getSlotName() const {
329 if (getPatternType() == Pattern::Nonterminal) {
330 // Just use the nonterminal name, which will already include the type if
331 // it has been cloned.
332 return getRecord()->getName();
334 std::string SlotName;
336 SlotName = getResult()->getName()+"_";
339 return SlotName + getName(getTree()->getType());
343 /// getSlotName - If this is a leaf node, return the slot name that the
344 /// operand will update.
345 std::string Pattern::getSlotName(Record *R) {
346 if (R->isSubClassOf("Nonterminal")) {
347 // Just use the nonterminal name, which will already include the type if
348 // it has been cloned.
350 } else if (R->isSubClassOf("RegisterClass")) {
351 MVT::ValueType Ty = getValueType(R->getValueAsDef("RegType"));
352 return R->getName() + "_" + getName(Ty);
354 assert(0 && "Don't know how to get a slot name for this!");
358 //===----------------------------------------------------------------------===//
359 // PatternOrganizer implementation
362 /// addPattern - Add the specified pattern to the appropriate location in the
364 void PatternOrganizer::addPattern(Pattern *P) {
365 NodesForSlot &Nodes = AllPatterns[P->getSlotName()];
366 if (!P->getTree()->isLeaf())
367 Nodes[P->getTree()->getOperator()].push_back(P);
369 // Right now we only support DefInit's with node types...
370 Nodes[P->getTree()->getValueRecord()].push_back(P);
376 //===----------------------------------------------------------------------===//
377 // InstrSelectorEmitter implementation
380 /// ReadNodeTypes - Read in all of the node types in the current RecordKeeper,
381 /// turning them into the more accessible NodeTypes data structure.
383 void InstrSelectorEmitter::ReadNodeTypes() {
384 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("DagNode");
385 DEBUG(std::cerr << "Getting node types: ");
386 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
387 Record *Node = Nodes[i];
389 // Translate the return type...
390 NodeType::ArgResultTypes RetTy =
391 NodeType::Translate(Node->getValueAsDef("RetType"));
393 // Translate the arguments...
394 ListInit *Args = Node->getValueAsListInit("ArgTypes");
395 std::vector<NodeType::ArgResultTypes> ArgTypes;
397 for (unsigned a = 0, e = Args->getSize(); a != e; ++a) {
398 if (DefInit *DI = dynamic_cast<DefInit*>(Args->getElement(a)))
399 ArgTypes.push_back(NodeType::Translate(DI->getDef()));
401 throw "In node " + Node->getName() + ", argument is not a Def!";
403 if (a == 0 && ArgTypes.back() == NodeType::Arg0)
404 throw "In node " + Node->getName() + ", arg 0 cannot have type 'arg0'!";
405 if (ArgTypes.back() == NodeType::Void)
406 throw "In node " + Node->getName() + ", args cannot be void type!";
408 if (RetTy == NodeType::Arg0 && Args->getSize() == 0)
409 throw "In node " + Node->getName() +
410 ", invalid return type for nullary node!";
412 // Add the node type mapping now...
413 NodeTypes[Node] = NodeType(RetTy, ArgTypes);
414 DEBUG(std::cerr << Node->getName() << ", ");
416 DEBUG(std::cerr << "DONE!\n");
419 Pattern *InstrSelectorEmitter::ReadNonterminal(Record *R) {
420 Pattern *&P = Patterns[R];
421 if (P) return P; // Don't reread it!
423 DagInit *DI = R->getValueAsDag("Pattern");
424 P = new Pattern(Pattern::Nonterminal, DI, R, *this);
425 DEBUG(std::cerr << "Parsed " << *P << "\n");
430 // ReadNonTerminals - Read in all nonterminals and incorporate them into our
432 void InstrSelectorEmitter::ReadNonterminals() {
433 std::vector<Record*> NTs = Records.getAllDerivedDefinitions("Nonterminal");
434 for (unsigned i = 0, e = NTs.size(); i != e; ++i)
435 ReadNonterminal(NTs[i]);
439 /// ReadInstructionPatterns - Read in all subclasses of Instruction, and process
440 /// those with a useful Pattern field.
442 void InstrSelectorEmitter::ReadInstructionPatterns() {
443 std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction");
444 for (unsigned i = 0, e = Insts.size(); i != e; ++i) {
445 Record *Inst = Insts[i];
446 if (DagInit *DI = dynamic_cast<DagInit*>(Inst->getValueInit("Pattern"))) {
447 Patterns[Inst] = new Pattern(Pattern::Instruction, DI, Inst, *this);
448 DEBUG(std::cerr << "Parsed " << *Patterns[Inst] << "\n");
453 /// ReadExpanderPatterns - Read in all expander patterns...
455 void InstrSelectorEmitter::ReadExpanderPatterns() {
456 std::vector<Record*> Expanders = Records.getAllDerivedDefinitions("Expander");
457 for (unsigned i = 0, e = Expanders.size(); i != e; ++i) {
458 Record *Expander = Expanders[i];
459 DagInit *DI = Expander->getValueAsDag("Pattern");
460 Patterns[Expander] = new Pattern(Pattern::Expander, DI, Expander, *this);
461 DEBUG(std::cerr << "Parsed " << *Patterns[Expander] << "\n");
466 // InstantiateNonterminals - Instantiate any unresolved nonterminals with
467 // information from the context that they are used in.
469 void InstrSelectorEmitter::InstantiateNonterminals() {
470 DEBUG(std::cerr << "Instantiating nonterminals:\n");
471 for (std::map<Record*, Pattern*>::iterator I = Patterns.begin(),
472 E = Patterns.end(); I != E; ++I)
473 if (I->second->isResolved())
474 I->second->InstantiateNonterminals();
477 /// InstantiateNonterminal - This method takes the nonterminal specified by
478 /// NT, which should not be completely resolved, clones it, applies ResultTy
479 /// to its root, then runs the type inference stuff on it. This should
480 /// produce a newly resolved nonterminal, which we make a record for and
481 /// return. To be extra fancy and efficient, this only makes one clone for
482 /// each type it is instantiated with.
483 Record *InstrSelectorEmitter::InstantiateNonterminal(Pattern *NT,
484 MVT::ValueType ResultTy) {
485 assert(!NT->isResolved() && "Nonterminal is already resolved!");
487 // Check to see if we have already instantiated this pair...
488 Record* &Slot = InstantiatedNTs[std::make_pair(NT, ResultTy)];
489 if (Slot) return Slot;
491 Record *New = new Record(NT->getRecord()->getName()+"_"+getName(ResultTy));
493 // Copy over the superclasses...
494 const std::vector<Record*> &SCs = NT->getRecord()->getSuperClasses();
495 for (unsigned i = 0, e = SCs.size(); i != e; ++i)
496 New->addSuperClass(SCs[i]);
498 DEBUG(std::cerr << " Nonterminal '" << NT->getRecord()->getName()
499 << "' for type '" << getName(ResultTy) << "', producing '"
500 << New->getName() << "'\n");
502 // Copy the pattern...
503 Pattern *NewPat = NT->clone(New);
505 // Apply the type to the root...
506 NewPat->getTree()->updateNodeType(ResultTy, New->getName());
509 NewPat->InferAllTypes();
511 // Make sure everything is good to go now...
512 if (!NewPat->isResolved())
513 NewPat->error("Instantiating nonterminal did not resolve all types!");
515 // Add the pattern to the patterns map, add the record to the RecordKeeper,
516 // return the new record.
517 Patterns[New] = NewPat;
522 // CalculateComputableValues - Fill in the ComputableValues map through
523 // analysis of the patterns we are playing with.
524 void InstrSelectorEmitter::CalculateComputableValues() {
525 // Loop over all of the patterns, adding them to the ComputableValues map
526 for (std::map<Record*, Pattern*>::iterator I = Patterns.begin(),
527 E = Patterns.end(); I != E; ++I)
528 if (I->second->isResolved())
529 ComputableValues.addPattern(I->second);
533 // MoveIdenticalPatterns - Given a tree pattern 'P', move all of the tree
534 // patterns which have the same top-level structure as P from the 'From' list to
536 static void MoveIdenticalPatterns(TreePatternNode *P,
537 std::vector<std::pair<Pattern*, TreePatternNode*> > &From,
538 std::vector<std::pair<Pattern*, TreePatternNode*> > &To) {
539 assert(!P->isLeaf() && "All leaves are identical!");
541 const std::vector<TreePatternNode*> &PChildren = P->getChildren();
542 for (unsigned i = 0; i != From.size(); ++i) {
543 TreePatternNode *N = From[i].second;
544 assert(P->getOperator() == N->getOperator() &&"Differing operators?");
545 assert(PChildren.size() == N->getChildren().size() &&
546 "Nodes with different arity??");
547 bool isDifferent = false;
548 for (unsigned c = 0, e = PChildren.size(); c != e; ++c) {
549 TreePatternNode *PC = PChildren[c];
550 TreePatternNode *NC = N->getChild(c);
551 if (PC->isLeaf() != NC->isLeaf()) {
557 if (PC->getOperator() != NC->getOperator()) {
561 } else { // It's a leaf!
562 if (PC->getValueRecord() != NC->getValueRecord()) {
568 // If it's the same as the reference one, move it over now...
570 To.push_back(std::make_pair(From[i].first, N));
571 From.erase(From.begin()+i);
572 --i; // Don't skip an entry...
578 static std::string getNodeName(Record *R) {
579 RecordVal *RV = R->getValue("EnumName");
581 if (Init *I = RV->getValue())
582 if (StringInit *SI = dynamic_cast<StringInit*>(I))
583 return SI->getValue();
588 static void EmitPatternPredicates(TreePatternNode *Tree,
589 const std::string &VarName, std::ostream &OS){
590 OS << " && " << VarName << "->getNodeType() == ISD::"
591 << getNodeName(Tree->getOperator());
593 for (unsigned c = 0, e = Tree->getNumChildren(); c != e; ++c)
594 if (!Tree->getChild(c)->isLeaf())
595 EmitPatternPredicates(Tree->getChild(c),
596 VarName + "->getUse(" + utostr(c)+")", OS);
599 static void EmitPatternCosts(TreePatternNode *Tree, const std::string &VarName,
601 for (unsigned c = 0, e = Tree->getNumChildren(); c != e; ++c)
602 if (Tree->getChild(c)->isLeaf()) {
604 << Pattern::getSlotName(Tree->getChild(c)->getValueRecord()) << "("
605 << VarName << "->getUse(" << c << "))";
607 EmitPatternCosts(Tree->getChild(c),
608 VarName + "->getUse(" + utostr(c) + ")", OS);
613 // EmitMatchCosters - Given a list of patterns, which all have the same root
614 // pattern operator, emit an efficient decision tree to decide which one to
615 // pick. This is structured this way to avoid reevaluations of non-obvious
617 void InstrSelectorEmitter::EmitMatchCosters(std::ostream &OS,
618 const std::vector<std::pair<Pattern*, TreePatternNode*> > &Patterns,
619 const std::string &VarPrefix,
620 unsigned IndentAmt) {
621 assert(!Patterns.empty() && "No patterns to emit matchers for!");
622 std::string Indent(IndentAmt, ' ');
624 // Load all of the operands of the root node into scalars for fast access
625 const NodeType &ONT = getNodeType(Patterns[0].second->getOperator());
626 for (unsigned i = 0, e = ONT.ArgTypes.size(); i != e; ++i)
627 OS << Indent << "SelectionDAGNode *" << VarPrefix << "_Op" << i
628 << " = N->getUse(" << i << ");\n";
630 // Compute the costs of computing the various nonterminals/registers, which
631 // are directly used at this level.
632 OS << "\n" << Indent << "// Operand matching costs...\n";
633 std::set<std::string> ComputedValues; // Avoid duplicate computations...
634 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
635 const std::vector<TreePatternNode*> &Children =
636 Patterns[i].second->getChildren();
637 for (unsigned c = 0, e = Children.size(); c != e; ++c) {
638 TreePatternNode *N = Children[c];
640 Record *VR = N->getValueRecord();
641 const std::string &LeafName = VR->getName();
642 std::string OpName = VarPrefix + "_Op" + utostr(c);
643 std::string ValName = OpName + "_" + LeafName + "_Cost";
644 if (!ComputedValues.count(ValName)) {
645 OS << Indent << "unsigned " << ValName << " = Match_"
646 << Pattern::getSlotName(VR) << "(" << OpName << ");\n";
647 ComputedValues.insert(ValName);
655 std::string LocCostName = VarPrefix + "_Cost";
656 OS << Indent << "unsigned " << LocCostName << "Min = ~0U >> 1;\n"
657 << Indent << "unsigned " << VarPrefix << "_PatternMin = NoMatchPattern;\n";
660 // Separate out all of the patterns into groups based on what their top-level
661 // signature looks like...
662 std::vector<std::pair<Pattern*, TreePatternNode*> > PatternsLeft(Patterns);
663 while (!PatternsLeft.empty()) {
664 // Process all of the patterns that have the same signature as the last
666 std::vector<std::pair<Pattern*, TreePatternNode*> > Group;
667 MoveIdenticalPatterns(PatternsLeft.back().second, PatternsLeft, Group);
668 assert(!Group.empty() && "Didn't at least pick the source pattern?");
671 OS << "PROCESSING GROUP:\n";
672 for (unsigned i = 0, e = Group.size(); i != e; ++i)
673 OS << " " << *Group[i].first << "\n";
677 OS << Indent << "{ // ";
679 if (Group.size() != 1) {
680 OS << Group.size() << " size group...\n";
681 OS << Indent << " unsigned " << VarPrefix << "_Pattern = NoMatch;\n";
683 OS << *Group[0].first << "\n";
684 OS << Indent << " unsigned " << VarPrefix << "_Pattern = "
685 << Group[0].first->getRecord()->getName() << "_Pattern;\n";
688 OS << Indent << " unsigned " << LocCostName << " = ";
689 if (Group.size() == 1)
690 OS << "1;\n"; // Add inst cost if at individual rec
694 // Loop over all of the operands, adding in their costs...
695 TreePatternNode *N = Group[0].second;
696 const std::vector<TreePatternNode*> &Children = N->getChildren();
698 // If necessary, emit conditionals to check for the appropriate tree
700 for (unsigned i = 0, e = Children.size(); i != e; ++i) {
701 TreePatternNode *C = Children[i];
703 // We already calculated the cost for this leaf, add it in now...
704 OS << Indent << " " << LocCostName << " += "
705 << VarPrefix << "_Op" << utostr(i) << "_"
706 << C->getValueRecord()->getName() << "_Cost;\n";
708 // If it's not a leaf, we have to check to make sure that the current
709 // node has the appropriate structure, then recurse into it...
710 OS << Indent << " if (" << VarPrefix << "_Op" << i
711 << "->getNodeType() == ISD::" << getNodeName(C->getOperator())
713 std::vector<std::pair<Pattern*, TreePatternNode*> > SubPatterns;
714 for (unsigned n = 0, e = Group.size(); n != e; ++n)
715 SubPatterns.push_back(std::make_pair(Group[n].first,
716 Group[n].second->getChild(i)));
717 EmitMatchCosters(OS, SubPatterns, VarPrefix+"_Op"+utostr(i),
719 OS << Indent << " }\n";
723 // If the cost for this match is less than the minimum computed cost so far,
724 // update the minimum cost and selected pattern.
725 OS << Indent << " if (" << LocCostName << " < " << LocCostName << "Min) { "
726 << LocCostName << "Min = " << LocCostName << "; " << VarPrefix
727 << "_PatternMin = " << VarPrefix << "_Pattern; }\n";
729 OS << Indent << "}\n";
733 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
734 Pattern *P = Patterns[i].first;
735 TreePatternNode *PTree = P->getTree();
736 unsigned PatternCost = 1;
738 // Check to see if there are any non-leaf elements in the pattern. If so,
739 // we need to emit a predicate for this match.
740 bool AnyNonLeaf = false;
741 for (unsigned c = 0, e = PTree->getNumChildren(); c != e; ++c)
742 if (!PTree->getChild(c)->isLeaf()) {
747 if (!AnyNonLeaf) { // No predicate necessary, just output a scope...
748 OS << " {// " << *P << "\n";
750 // We need to emit a predicate to make sure the tree pattern matches, do
753 for (unsigned c = 0, e = PTree->getNumChildren(); c != e; ++c)
754 if (!PTree->getChild(c)->isLeaf())
755 EmitPatternPredicates(PTree->getChild(c),
756 VarPrefix + "_Op" + utostr(c), OS);
758 OS << ") {\n // " << *P << "\n";
761 OS << " unsigned PatCost = " << PatternCost;
763 for (unsigned c = 0, e = PTree->getNumChildren(); c != e; ++c)
764 if (PTree->getChild(c)->isLeaf()) {
765 OS << " + " << VarPrefix << "_Op" << c << "_"
766 << PTree->getChild(c)->getValueRecord()->getName() << "_Cost";
768 EmitPatternCosts(PTree->getChild(c), VarPrefix + "_Op" + utostr(c), OS);
771 OS << " if (PatCost < MinCost) { MinCost = PatCost; Pattern = "
772 << P->getRecord()->getName() << "_Pattern; }\n"
777 void InstrSelectorEmitter::run(std::ostream &OS) {
778 // Type-check all of the node types to ensure we "understand" them.
781 // Read in all of the nonterminals, instructions, and expanders...
783 ReadInstructionPatterns();
784 ReadExpanderPatterns();
786 // Instantiate any unresolved nonterminals with information from the context
787 // that they are used in.
788 InstantiateNonterminals();
790 // Clear InstantiatedNTs, we don't need it anymore...
791 InstantiatedNTs.clear();
793 std::cerr << "Patterns aquired:\n";
794 for (std::map<Record*, Pattern*>::iterator I = Patterns.begin(),
795 E = Patterns.end(); I != E; ++I)
796 if (I->second->isResolved())
797 std::cerr << " " << *I->second << "\n";
799 CalculateComputableValues();
801 EmitSourceFileHeader("Instruction Selector for the " + Target.getName() +
804 // Output the slot number enums...
805 OS << "\nenum { // Slot numbers...\n"
806 << " LastBuiltinSlot = ISD::NumBuiltinSlots-1, // Start numbering here\n";
807 for (PatternOrganizer::iterator I = ComputableValues.begin(),
808 E = ComputableValues.end(); I != E; ++I)
809 OS << " " << I->first << "_Slot,\n";
810 OS << " NumSlots\n};\n\n// Reduction value typedefs...\n";
812 // Output the reduction value typedefs...
813 for (PatternOrganizer::iterator I = ComputableValues.begin(),
814 E = ComputableValues.end(); I != E; ++I) {
816 OS << "typedef ReducedValue<unsigned, " << I->first
817 << "_Slot> ReducedValue_" << I->first << ";\n";
820 // Output the pattern enums...
822 << "enum { // Patterns...\n"
823 << " NotComputed = 0,\n"
824 << " NoMatchPattern, \n";
825 for (PatternOrganizer::iterator I = ComputableValues.begin(),
826 E = ComputableValues.end(); I != E; ++I) {
827 OS << " // " << I->first << " patterns...\n";
828 for (PatternOrganizer::NodesForSlot::iterator J = I->second.begin(),
829 E = I->second.end(); J != E; ++J)
830 for (unsigned i = 0, e = J->second.size(); i != e; ++i)
831 OS << " " << J->second[i]->getRecord()->getName() << "_Pattern,\n";
835 // Start emitting the class...
836 OS << "namespace {\n"
837 << " class " << Target.getName() << "ISel {\n"
838 << " SelectionDAG &DAG;\n"
840 << " X86ISel(SelectionDAG &D) : DAG(D) {}\n"
841 << " void generateCode();\n"
843 << " unsigned makeAnotherReg(const TargetRegisterClass *RC) {\n"
844 << " return DAG.getMachineFunction().getSSARegMap()->createVirt"
847 << " // DAG matching methods for classes... all of these methods"
849 << " // of producing a value of the specified class and type, which"
851 << " // added to the DAG node.\n";
853 // Output all of the matching prototypes for slots...
854 for (PatternOrganizer::iterator I = ComputableValues.begin(),
855 E = ComputableValues.end(); I != E; ++I)
856 OS << " unsigned Match_" << I->first << "(SelectionDAGNode *N);\n";
857 OS << "\n // DAG matching methods for DAG nodes...\n";
859 // Output all of the matching prototypes for slot/node pairs
860 for (PatternOrganizer::iterator I = ComputableValues.begin(),
861 E = ComputableValues.end(); I != E; ++I)
862 for (PatternOrganizer::NodesForSlot::iterator J = I->second.begin(),
863 E = I->second.end(); J != E; ++J)
864 OS << " unsigned Match_" << I->first << "_" << getNodeName(J->first)
865 << "(SelectionDAGNode *N);\n";
867 // Output all of the dag reduction methods prototypes...
868 OS << "\n // DAG reduction methods...\n";
869 for (PatternOrganizer::iterator I = ComputableValues.begin(),
870 E = ComputableValues.end(); I != E; ++I)
871 OS << " ReducedValue_" << I->first << " *Reduce_" << I->first
872 << "(SelectionDAGNode *N,\n" << std::string(27+2*I->first.size(), ' ')
873 << "MachineBasicBlock *MBB);\n";
876 OS << "void X86ISel::generateCode() {\n"
877 << " SelectionDAGNode *Root = DAG.getRoot();\n"
878 << " assert(Root->getValueType() == MVT::isVoid && "
879 "\"Root of DAG produces value??\");\n\n"
880 << " std::cerr << \"\\n\";\n"
881 << " unsigned Cost = Match_Void_void(Root);\n"
882 << " if (Cost >= ~0U >> 1) {\n"
883 << " std::cerr << \"Match failed!\\n\";\n"
884 << " Root->dump();\n"
887 << " std::cerr << \"Total DAG Cost: \" << Cost << \"\\n\\n\";\n\n"
888 << " Reduce_Void_void(Root, 0);\n"
890 << "//===" << std::string(70, '-') << "===//\n"
891 << "// Matching methods...\n"
894 for (PatternOrganizer::iterator I = ComputableValues.begin(),
895 E = ComputableValues.end(); I != E; ++I) {
896 const std::string &SlotName = I->first;
897 OS << "unsigned " << Target.getName() << "ISel::Match_" << SlotName
898 << "(SelectionDAGNode *N) {\n"
899 << " assert(N->getValueType() == MVT::"
900 << getEnumName((*I->second.begin()).second[0]->getTree()->getType())
901 << ");\n" << " // If we already have a cost available for " << SlotName
903 << " if (N->getPatternFor(" << SlotName << "_Slot))\n"
904 << " return N->getCostFor(" << SlotName << "_Slot);\n\n"
905 << " unsigned Cost;\n"
906 << " switch (N->getNodeType()) {\n"
907 << " default: assert(0 && \"Unhandled node type for " << SlotName
910 for (PatternOrganizer::NodesForSlot::iterator J = I->second.begin(),
911 E = I->second.end(); J != E; ++J)
912 if (!J->first->isSubClassOf("Nonterminal"))
913 OS << " case ISD::" << getNodeName(J->first) << ":\tCost = Match_"
914 << SlotName << "_" << getNodeName(J->first) << "(N); break;\n";
915 OS << " }\n"; // End of the switch statement
917 // Emit any patterns which have a nonterminal leaf as the RHS. These may
918 // match multiple root nodes, so they cannot be handled with the switch...
919 for (PatternOrganizer::NodesForSlot::iterator J = I->second.begin(),
920 E = I->second.end(); J != E; ++J)
921 if (J->first->isSubClassOf("Nonterminal")) {
922 OS << " unsigned " << J->first->getName() << "_Cost = Match_"
923 << getNodeName(J->first) << "(N);\n"
924 << " if (" << getNodeName(J->first) << "_Cost < Cost) Cost = "
925 << getNodeName(J->first) << "_Cost;\n";
928 OS << " return Cost;\n}\n\n";
930 for (PatternOrganizer::NodesForSlot::iterator J = I->second.begin(),
931 E = I->second.end(); J != E; ++J) {
932 Record *Operator = J->first;
933 bool isNonterm = Operator->isSubClassOf("Nonterminal");
935 OS << "unsigned " << Target.getName() << "ISel::Match_";
936 if (!isNonterm) OS << SlotName << "_";
937 OS << getNodeName(Operator) << "(SelectionDAGNode *N) {\n"
938 << " unsigned Pattern = NoMatchPattern;\n"
939 << " unsigned MinCost = ~0U >> 1;\n";
941 std::vector<std::pair<Pattern*, TreePatternNode*> > Patterns;
942 for (unsigned i = 0, e = J->second.size(); i != e; ++i)
943 Patterns.push_back(std::make_pair(J->second[i],
944 J->second[i]->getTree()));
945 EmitMatchCosters(OS, Patterns, "N", 2);
947 OS << "\n N->setPatternCostFor(" << SlotName
948 << "_Slot, Pattern, MinCost, NumSlots);\n"
949 << " return MinCost;\n"