1 //===- DAGISelEmitter.cpp - Generate an instruction selector --------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Chris Lattner and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This tablegen backend emits a DAG instruction selector.
12 //===----------------------------------------------------------------------===//
14 #include "DAGISelEmitter.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/Support/Debug.h"
22 //===----------------------------------------------------------------------===//
23 // Helpers for working with extended types.
25 /// FilterVTs - Filter a list of VT's according to a predicate.
28 static std::vector<MVT::ValueType>
29 FilterVTs(const std::vector<MVT::ValueType> &InVTs, T Filter) {
30 std::vector<MVT::ValueType> Result;
31 for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
33 Result.push_back(InVTs[i]);
37 /// isExtIntegerVT - Return true if the specified extended value type is
38 /// integer, or isInt.
39 static bool isExtIntegerVT(unsigned char VT) {
40 return VT == MVT::isInt ||
41 (VT < MVT::LAST_VALUETYPE && MVT::isInteger((MVT::ValueType)VT));
44 /// isExtFloatingPointVT - Return true if the specified extended value type is
45 /// floating point, or isFP.
46 static bool isExtFloatingPointVT(unsigned char VT) {
47 return VT == MVT::isFP ||
48 (VT < MVT::LAST_VALUETYPE && MVT::isFloatingPoint((MVT::ValueType)VT));
51 //===----------------------------------------------------------------------===//
52 // SDTypeConstraint implementation
55 SDTypeConstraint::SDTypeConstraint(Record *R) {
56 OperandNo = R->getValueAsInt("OperandNum");
58 if (R->isSubClassOf("SDTCisVT")) {
59 ConstraintType = SDTCisVT;
60 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
61 } else if (R->isSubClassOf("SDTCisInt")) {
62 ConstraintType = SDTCisInt;
63 } else if (R->isSubClassOf("SDTCisFP")) {
64 ConstraintType = SDTCisFP;
65 } else if (R->isSubClassOf("SDTCisSameAs")) {
66 ConstraintType = SDTCisSameAs;
67 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
68 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
69 ConstraintType = SDTCisVTSmallerThanOp;
70 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
71 R->getValueAsInt("OtherOperandNum");
72 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
73 ConstraintType = SDTCisOpSmallerThanOp;
74 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
75 R->getValueAsInt("BigOperandNum");
77 std::cerr << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
82 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
83 /// N, which has NumResults results.
84 TreePatternNode *SDTypeConstraint::getOperandNum(unsigned OpNo,
86 unsigned NumResults) const {
87 assert(NumResults == 1 && "We only work with single result nodes so far!");
89 if (OpNo < NumResults)
90 return N; // FIXME: need value #
92 return N->getChild(OpNo-NumResults);
95 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
96 /// constraint to the nodes operands. This returns true if it makes a
97 /// change, false otherwise. If a type contradiction is found, throw an
99 bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
100 const SDNodeInfo &NodeInfo,
101 TreePattern &TP) const {
102 unsigned NumResults = NodeInfo.getNumResults();
103 assert(NumResults == 1 && "We only work with single result nodes so far!");
105 // Check that the number of operands is sane.
106 if (NodeInfo.getNumOperands() >= 0) {
107 if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands())
108 TP.error(N->getOperator()->getName() + " node requires exactly " +
109 itostr(NodeInfo.getNumOperands()) + " operands!");
112 const CodeGenTarget &CGT = TP.getDAGISelEmitter().getTargetInfo();
114 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NumResults);
116 switch (ConstraintType) {
117 default: assert(0 && "Unknown constraint type!");
119 // Operand must be a particular type.
120 return NodeToApply->UpdateNodeType(x.SDTCisVT_Info.VT, TP);
122 // If there is only one integer type supported, this must be it.
123 std::vector<MVT::ValueType> IntVTs =
124 FilterVTs(CGT.getLegalValueTypes(), MVT::isInteger);
126 // If we found exactly one supported integer type, apply it.
127 if (IntVTs.size() == 1)
128 return NodeToApply->UpdateNodeType(IntVTs[0], TP);
129 return NodeToApply->UpdateNodeType(MVT::isInt, TP);
132 // If there is only one FP type supported, this must be it.
133 std::vector<MVT::ValueType> FPVTs =
134 FilterVTs(CGT.getLegalValueTypes(), MVT::isFloatingPoint);
136 // If we found exactly one supported FP type, apply it.
137 if (FPVTs.size() == 1)
138 return NodeToApply->UpdateNodeType(FPVTs[0], TP);
139 return NodeToApply->UpdateNodeType(MVT::isFP, TP);
142 TreePatternNode *OtherNode =
143 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NumResults);
144 return NodeToApply->UpdateNodeType(OtherNode->getExtType(), TP) |
145 OtherNode->UpdateNodeType(NodeToApply->getExtType(), TP);
147 case SDTCisVTSmallerThanOp: {
148 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
149 // have an integer type that is smaller than the VT.
150 if (!NodeToApply->isLeaf() ||
151 !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
152 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
153 ->isSubClassOf("ValueType"))
154 TP.error(N->getOperator()->getName() + " expects a VT operand!");
156 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
157 if (!MVT::isInteger(VT))
158 TP.error(N->getOperator()->getName() + " VT operand must be integer!");
160 TreePatternNode *OtherNode =
161 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N,NumResults);
163 // It must be integer.
164 bool MadeChange = false;
165 MadeChange |= OtherNode->UpdateNodeType(MVT::isInt, TP);
167 if (OtherNode->hasTypeSet() && OtherNode->getType() <= VT)
168 OtherNode->UpdateNodeType(MVT::Other, TP); // Throw an error.
171 case SDTCisOpSmallerThanOp: {
172 TreePatternNode *BigOperand =
173 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NumResults);
175 // Both operands must be integer or FP, but we don't care which.
176 bool MadeChange = false;
178 if (isExtIntegerVT(NodeToApply->getExtType()))
179 MadeChange |= BigOperand->UpdateNodeType(MVT::isInt, TP);
180 else if (isExtFloatingPointVT(NodeToApply->getExtType()))
181 MadeChange |= BigOperand->UpdateNodeType(MVT::isFP, TP);
182 if (isExtIntegerVT(BigOperand->getExtType()))
183 MadeChange |= NodeToApply->UpdateNodeType(MVT::isInt, TP);
184 else if (isExtFloatingPointVT(BigOperand->getExtType()))
185 MadeChange |= NodeToApply->UpdateNodeType(MVT::isFP, TP);
187 std::vector<MVT::ValueType> VTs = CGT.getLegalValueTypes();
189 if (isExtIntegerVT(NodeToApply->getExtType())) {
190 VTs = FilterVTs(VTs, MVT::isInteger);
191 } else if (isExtFloatingPointVT(NodeToApply->getExtType())) {
192 VTs = FilterVTs(VTs, MVT::isFloatingPoint);
197 switch (VTs.size()) {
198 default: // Too many VT's to pick from.
199 case 0: break; // No info yet.
201 // Only one VT of this flavor. Cannot ever satisify the constraints.
202 return NodeToApply->UpdateNodeType(MVT::Other, TP); // throw
204 // If we have exactly two possible types, the little operand must be the
205 // small one, the big operand should be the big one. Common with
206 // float/double for example.
207 assert(VTs[0] < VTs[1] && "Should be sorted!");
208 MadeChange |= NodeToApply->UpdateNodeType(VTs[0], TP);
209 MadeChange |= BigOperand->UpdateNodeType(VTs[1], TP);
219 //===----------------------------------------------------------------------===//
220 // SDNodeInfo implementation
222 SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
223 EnumName = R->getValueAsString("Opcode");
224 SDClassName = R->getValueAsString("SDClass");
225 Record *TypeProfile = R->getValueAsDef("TypeProfile");
226 NumResults = TypeProfile->getValueAsInt("NumResults");
227 NumOperands = TypeProfile->getValueAsInt("NumOperands");
229 // Parse the properties.
231 ListInit *LI = R->getValueAsListInit("Properties");
232 for (unsigned i = 0, e = LI->getSize(); i != e; ++i) {
233 DefInit *DI = dynamic_cast<DefInit*>(LI->getElement(i));
234 assert(DI && "Properties list must be list of defs!");
235 if (DI->getDef()->getName() == "SDNPCommutative") {
236 Properties |= 1 << SDNPCommutative;
237 } else if (DI->getDef()->getName() == "SDNPAssociative") {
238 Properties |= 1 << SDNPAssociative;
240 std::cerr << "Unknown SD Node property '" << DI->getDef()->getName()
241 << "' on node '" << R->getName() << "'!\n";
247 // Parse the type constraints.
248 ListInit *Constraints = TypeProfile->getValueAsListInit("Constraints");
249 for (unsigned i = 0, e = Constraints->getSize(); i != e; ++i) {
250 assert(dynamic_cast<DefInit*>(Constraints->getElement(i)) &&
251 "Constraints list should contain constraint definitions!");
253 static_cast<DefInit*>(Constraints->getElement(i))->getDef();
254 TypeConstraints.push_back(Constraint);
258 //===----------------------------------------------------------------------===//
259 // TreePatternNode implementation
262 TreePatternNode::~TreePatternNode() {
263 #if 0 // FIXME: implement refcounted tree nodes!
264 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
269 /// UpdateNodeType - Set the node type of N to VT if VT contains
270 /// information. If N already contains a conflicting type, then throw an
271 /// exception. This returns true if any information was updated.
273 bool TreePatternNode::UpdateNodeType(unsigned char VT, TreePattern &TP) {
274 if (VT == MVT::isUnknown || getExtType() == VT) return false;
275 if (getExtType() == MVT::isUnknown) {
280 // If we are told this is to be an int or FP type, and it already is, ignore
282 if ((VT == MVT::isInt && isExtIntegerVT(getExtType())) ||
283 (VT == MVT::isFP && isExtFloatingPointVT(getExtType())))
286 // If we know this is an int or fp type, and we are told it is a specific one,
288 if ((getExtType() == MVT::isInt && isExtIntegerVT(VT)) ||
289 (getExtType() == MVT::isFP && isExtFloatingPointVT(VT))) {
294 TP.error("Type inference contradiction found in node " +
295 getOperator()->getName() + "!");
296 return true; // unreachable
300 void TreePatternNode::print(std::ostream &OS) const {
302 OS << *getLeafValue();
304 OS << "(" << getOperator()->getName();
307 switch (getExtType()) {
308 case MVT::Other: OS << ":Other"; break;
309 case MVT::isInt: OS << ":isInt"; break;
310 case MVT::isFP : OS << ":isFP"; break;
311 case MVT::isUnknown: ; /*OS << ":?";*/ break;
312 default: OS << ":" << getType(); break;
316 if (getNumChildren() != 0) {
318 getChild(0)->print(OS);
319 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
321 getChild(i)->print(OS);
327 if (!PredicateFn.empty())
328 OS << "<<P:" << PredicateFn << ">>";
330 OS << "<<X:" << TransformFn->getName() << ">>";
331 if (!getName().empty())
332 OS << ":$" << getName();
335 void TreePatternNode::dump() const {
339 /// isIsomorphicTo - Return true if this node is recursively isomorphic to
340 /// the specified node. For this comparison, all of the state of the node
341 /// is considered, except for the assigned name. Nodes with differing names
342 /// that are otherwise identical are considered isomorphic.
343 bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N) const {
344 if (N == this) return true;
345 if (N->isLeaf() != isLeaf() || getExtType() != N->getExtType() ||
346 getPredicateFn() != N->getPredicateFn() ||
347 getTransformFn() != N->getTransformFn())
351 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue()))
352 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue()))
353 return DI->getDef() == NDI->getDef();
354 return getLeafValue() == N->getLeafValue();
357 if (N->getOperator() != getOperator() ||
358 N->getNumChildren() != getNumChildren()) return false;
359 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
360 if (!getChild(i)->isIsomorphicTo(N->getChild(i)))
365 /// clone - Make a copy of this tree and all of its children.
367 TreePatternNode *TreePatternNode::clone() const {
368 TreePatternNode *New;
370 New = new TreePatternNode(getLeafValue());
372 std::vector<TreePatternNode*> CChildren;
373 CChildren.reserve(Children.size());
374 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
375 CChildren.push_back(getChild(i)->clone());
376 New = new TreePatternNode(getOperator(), CChildren);
378 New->setName(getName());
379 New->setType(getExtType());
380 New->setPredicateFn(getPredicateFn());
381 New->setTransformFn(getTransformFn());
385 /// SubstituteFormalArguments - Replace the formal arguments in this tree
386 /// with actual values specified by ArgMap.
387 void TreePatternNode::
388 SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
389 if (isLeaf()) return;
391 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
392 TreePatternNode *Child = getChild(i);
393 if (Child->isLeaf()) {
394 Init *Val = Child->getLeafValue();
395 if (dynamic_cast<DefInit*>(Val) &&
396 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
397 // We found a use of a formal argument, replace it with its value.
398 Child = ArgMap[Child->getName()];
399 assert(Child && "Couldn't find formal argument!");
403 getChild(i)->SubstituteFormalArguments(ArgMap);
409 /// InlinePatternFragments - If this pattern refers to any pattern
410 /// fragments, inline them into place, giving us a pattern without any
411 /// PatFrag references.
412 TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
413 if (isLeaf()) return this; // nothing to do.
414 Record *Op = getOperator();
416 if (!Op->isSubClassOf("PatFrag")) {
417 // Just recursively inline children nodes.
418 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
419 setChild(i, getChild(i)->InlinePatternFragments(TP));
423 // Otherwise, we found a reference to a fragment. First, look up its
424 // TreePattern record.
425 TreePattern *Frag = TP.getDAGISelEmitter().getPatternFragment(Op);
427 // Verify that we are passing the right number of operands.
428 if (Frag->getNumArgs() != Children.size())
429 TP.error("'" + Op->getName() + "' fragment requires " +
430 utostr(Frag->getNumArgs()) + " operands!");
432 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
434 // Resolve formal arguments to their actual value.
435 if (Frag->getNumArgs()) {
436 // Compute the map of formal to actual arguments.
437 std::map<std::string, TreePatternNode*> ArgMap;
438 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
439 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
441 FragTree->SubstituteFormalArguments(ArgMap);
444 FragTree->setName(getName());
446 // Get a new copy of this fragment to stitch into here.
447 //delete this; // FIXME: implement refcounting!
451 /// getIntrinsicType - Check to see if the specified record has an intrinsic
452 /// type which should be applied to it. This infer the type of register
453 /// references from the register file information, for example.
455 static unsigned char getIntrinsicType(Record *R, bool NotRegisters,
457 // Check to see if this is a register or a register class...
458 if (R->isSubClassOf("RegisterClass")) {
459 if (NotRegisters) return MVT::isUnknown;
460 return getValueType(R->getValueAsDef("RegType"));
461 } else if (R->isSubClassOf("PatFrag")) {
462 // Pattern fragment types will be resolved when they are inlined.
463 return MVT::isUnknown;
464 } else if (R->isSubClassOf("Register")) {
465 //const CodeGenTarget &T = TP.getDAGISelEmitter().getTargetInfo();
466 // TODO: if a register appears in exactly one regclass, we could use that
468 return MVT::isUnknown;
469 } else if (R->isSubClassOf("ValueType")) {
472 } else if (R->getName() == "node") {
474 return MVT::isUnknown;
477 TP.error("Unknown node flavor used in pattern: " + R->getName());
481 /// ApplyTypeConstraints - Apply all of the type constraints relevent to
482 /// this node and its children in the tree. This returns true if it makes a
483 /// change, false otherwise. If a type contradiction is found, throw an
485 bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
487 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue()))
488 // If it's a regclass or something else known, include the type.
489 return UpdateNodeType(getIntrinsicType(DI->getDef(), NotRegisters, TP),
494 // special handling for set, which isn't really an SDNode.
495 if (getOperator()->getName() == "set") {
496 assert (getNumChildren() == 2 && "Only handle 2 operand set's for now!");
497 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
498 MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
500 // Types of operands must match.
501 MadeChange |= getChild(0)->UpdateNodeType(getChild(1)->getExtType(), TP);
502 MadeChange |= getChild(1)->UpdateNodeType(getChild(0)->getExtType(), TP);
503 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
505 } else if (getOperator()->isSubClassOf("SDNode")) {
506 const SDNodeInfo &NI = TP.getDAGISelEmitter().getSDNodeInfo(getOperator());
508 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
509 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
510 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
512 } else if (getOperator()->isSubClassOf("Instruction")) {
513 const DAGInstruction &Inst =
514 TP.getDAGISelEmitter().getInstruction(getOperator());
516 assert(Inst.getNumResults() == 1 && "Only supports one result instrs!");
517 // Apply the result type to the node
518 bool MadeChange = UpdateNodeType(Inst.getResultType(0), TP);
520 if (getNumChildren() != Inst.getNumOperands())
521 TP.error("Instruction '" + getOperator()->getName() + " expects " +
522 utostr(Inst.getNumOperands()) + " operands, not " +
523 utostr(getNumChildren()) + " operands!");
524 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
525 MadeChange |= getChild(i)->UpdateNodeType(Inst.getOperandType(i), TP);
526 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
530 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
532 // Node transforms always take one operand, and take and return the same
534 if (getNumChildren() != 1)
535 TP.error("Node transform '" + getOperator()->getName() +
536 "' requires one operand!");
537 bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
538 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
543 /// canPatternMatch - If it is impossible for this pattern to match on this
544 /// target, fill in Reason and return false. Otherwise, return true. This is
545 /// used as a santity check for .td files (to prevent people from writing stuff
546 /// that can never possibly work), and to prevent the pattern permuter from
547 /// generating stuff that is useless.
548 bool TreePatternNode::canPatternMatch(std::string &Reason, DAGISelEmitter &ISE){
549 if (isLeaf()) return true;
551 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
552 if (!getChild(i)->canPatternMatch(Reason, ISE))
555 // If this node is a commutative operator, check that the LHS isn't an
557 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(getOperator());
558 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
559 // Scan all of the operands of the node and make sure that only the last one
560 // is a constant node.
561 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i)
562 if (!getChild(i)->isLeaf() &&
563 getChild(i)->getOperator()->getName() == "imm") {
564 Reason = "Immediate value must be on the RHS of commutative operators!";
572 //===----------------------------------------------------------------------===//
573 // TreePattern implementation
576 TreePattern::TreePattern(Record *TheRec, ListInit *RawPat,
577 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
578 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
579 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
582 TreePattern::TreePattern(Record *TheRec, DagInit *Pat,
583 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
584 Trees.push_back(ParseTreePattern(Pat));
587 TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat,
588 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
589 Trees.push_back(Pat);
594 void TreePattern::error(const std::string &Msg) const {
596 throw "In " + TheRecord->getName() + ": " + Msg;
599 TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
600 Record *Operator = Dag->getNodeType();
602 if (Operator->isSubClassOf("ValueType")) {
603 // If the operator is a ValueType, then this must be "type cast" of a leaf
605 if (Dag->getNumArgs() != 1)
606 error("Type cast only takes one operand!");
608 Init *Arg = Dag->getArg(0);
609 TreePatternNode *New;
610 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
611 Record *R = DI->getDef();
612 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
613 Dag->setArg(0, new DagInit(R,
614 std::vector<std::pair<Init*, std::string> >()));
615 TreePatternNode *TPN = ParseTreePattern(Dag);
616 TPN->setName(Dag->getArgName(0));
620 New = new TreePatternNode(DI);
621 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
622 New = ParseTreePattern(DI);
625 error("Unknown leaf value for tree pattern!");
629 // Apply the type cast.
630 New->UpdateNodeType(getValueType(Operator), *this);
634 // Verify that this is something that makes sense for an operator.
635 if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
636 !Operator->isSubClassOf("Instruction") &&
637 !Operator->isSubClassOf("SDNodeXForm") &&
638 Operator->getName() != "set")
639 error("Unrecognized node '" + Operator->getName() + "'!");
641 std::vector<TreePatternNode*> Children;
643 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
644 Init *Arg = Dag->getArg(i);
645 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
646 Children.push_back(ParseTreePattern(DI));
647 Children.back()->setName(Dag->getArgName(i));
648 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
649 Record *R = DefI->getDef();
650 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
651 // TreePatternNode if its own.
652 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
653 Dag->setArg(i, new DagInit(R,
654 std::vector<std::pair<Init*, std::string> >()));
655 --i; // Revisit this node...
657 TreePatternNode *Node = new TreePatternNode(DefI);
658 Node->setName(Dag->getArgName(i));
659 Children.push_back(Node);
662 if (R->getName() == "node") {
663 if (Dag->getArgName(i).empty())
664 error("'node' argument requires a name to match with operand list");
665 Args.push_back(Dag->getArgName(i));
668 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
669 TreePatternNode *Node = new TreePatternNode(II);
670 if (!Dag->getArgName(i).empty())
671 error("Constant int argument should not have a name!");
672 Children.push_back(Node);
677 error("Unknown leaf value for tree pattern!");
681 return new TreePatternNode(Operator, Children);
684 /// InferAllTypes - Infer/propagate as many types throughout the expression
685 /// patterns as possible. Return true if all types are infered, false
686 /// otherwise. Throw an exception if a type contradiction is found.
687 bool TreePattern::InferAllTypes() {
688 bool MadeChange = true;
691 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
692 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
695 bool HasUnresolvedTypes = false;
696 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
697 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
698 return !HasUnresolvedTypes;
701 void TreePattern::print(std::ostream &OS) const {
702 OS << getRecord()->getName();
704 OS << "(" << Args[0];
705 for (unsigned i = 1, e = Args.size(); i != e; ++i)
706 OS << ", " << Args[i];
711 if (Trees.size() > 1)
713 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
719 if (Trees.size() > 1)
723 void TreePattern::dump() const { print(std::cerr); }
727 //===----------------------------------------------------------------------===//
728 // DAGISelEmitter implementation
731 // Parse all of the SDNode definitions for the target, populating SDNodes.
732 void DAGISelEmitter::ParseNodeInfo() {
733 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
734 while (!Nodes.empty()) {
735 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
740 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
741 /// map, and emit them to the file as functions.
742 void DAGISelEmitter::ParseNodeTransforms(std::ostream &OS) {
743 OS << "\n// Node transformations.\n";
744 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
745 while (!Xforms.empty()) {
746 Record *XFormNode = Xforms.back();
747 Record *SDNode = XFormNode->getValueAsDef("Opcode");
748 std::string Code = XFormNode->getValueAsCode("XFormFunction");
749 SDNodeXForms.insert(std::make_pair(XFormNode,
750 std::make_pair(SDNode, Code)));
753 std::string ClassName = getSDNodeInfo(SDNode).getSDClassName();
754 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
756 OS << "inline SDOperand Transform_" << XFormNode->getName()
757 << "(SDNode *" << C2 << ") {\n";
758 if (ClassName != "SDNode")
759 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
760 OS << Code << "\n}\n";
769 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
770 /// file, building up the PatternFragments map. After we've collected them all,
771 /// inline fragments together as necessary, so that there are no references left
772 /// inside a pattern fragment to a pattern fragment.
774 /// This also emits all of the predicate functions to the output file.
776 void DAGISelEmitter::ParsePatternFragments(std::ostream &OS) {
777 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
779 // First step, parse all of the fragments and emit predicate functions.
780 OS << "\n// Predicate functions.\n";
781 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
782 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
783 TreePattern *P = new TreePattern(Fragments[i], Tree, *this);
784 PatternFragments[Fragments[i]] = P;
786 // Validate the argument list, converting it to map, to discard duplicates.
787 std::vector<std::string> &Args = P->getArgList();
788 std::set<std::string> OperandsMap(Args.begin(), Args.end());
790 if (OperandsMap.count(""))
791 P->error("Cannot have unnamed 'node' values in pattern fragment!");
793 // Parse the operands list.
794 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
795 if (OpsList->getNodeType()->getName() != "ops")
796 P->error("Operands list should start with '(ops ... '!");
798 // Copy over the arguments.
800 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
801 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
802 static_cast<DefInit*>(OpsList->getArg(j))->
803 getDef()->getName() != "node")
804 P->error("Operands list should all be 'node' values.");
805 if (OpsList->getArgName(j).empty())
806 P->error("Operands list should have names for each operand!");
807 if (!OperandsMap.count(OpsList->getArgName(j)))
808 P->error("'" + OpsList->getArgName(j) +
809 "' does not occur in pattern or was multiply specified!");
810 OperandsMap.erase(OpsList->getArgName(j));
811 Args.push_back(OpsList->getArgName(j));
814 if (!OperandsMap.empty())
815 P->error("Operands list does not contain an entry for operand '" +
816 *OperandsMap.begin() + "'!");
818 // If there is a code init for this fragment, emit the predicate code and
819 // keep track of the fact that this fragment uses it.
820 std::string Code = Fragments[i]->getValueAsCode("Predicate");
822 assert(!P->getOnlyTree()->isLeaf() && "Can't be a leaf!");
823 std::string ClassName =
824 getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
825 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
827 OS << "inline bool Predicate_" << Fragments[i]->getName()
828 << "(SDNode *" << C2 << ") {\n";
829 if (ClassName != "SDNode")
830 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
831 OS << Code << "\n}\n";
832 P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
835 // If there is a node transformation corresponding to this, keep track of
837 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
838 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
839 P->getOnlyTree()->setTransformFn(Transform);
844 // Now that we've parsed all of the tree fragments, do a closure on them so
845 // that there are not references to PatFrags left inside of them.
846 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
847 E = PatternFragments.end(); I != E; ++I) {
848 TreePattern *ThePat = I->second;
849 ThePat->InlinePatternFragments();
851 // Infer as many types as possible. Don't worry about it if we don't infer
852 // all of them, some may depend on the inputs of the pattern.
854 ThePat->InferAllTypes();
856 // If this pattern fragment is not supported by this target (no types can
857 // satisfy its constraints), just ignore it. If the bogus pattern is
858 // actually used by instructions, the type consistency error will be
862 // If debugging, print out the pattern fragment result.
863 DEBUG(ThePat->dump());
867 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
868 /// instruction input. Return true if this is a real use.
869 static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
870 std::map<std::string, TreePatternNode*> &InstInputs) {
871 // No name -> not interesting.
872 if (Pat->getName().empty()) {
874 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
875 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
876 I->error("Input " + DI->getDef()->getName() + " must be named!");
884 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
885 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
888 assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
889 Rec = Pat->getOperator();
892 TreePatternNode *&Slot = InstInputs[Pat->getName()];
897 if (Slot->isLeaf()) {
898 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
900 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
901 SlotRec = Slot->getOperator();
904 // Ensure that the inputs agree if we've already seen this input.
906 I->error("All $" + Pat->getName() + " inputs must agree with each other");
907 if (Slot->getExtType() != Pat->getExtType())
908 I->error("All $" + Pat->getName() + " inputs must agree with each other");
913 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
914 /// part of "I", the instruction), computing the set of inputs and outputs of
915 /// the pattern. Report errors if we see anything naughty.
916 void DAGISelEmitter::
917 FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
918 std::map<std::string, TreePatternNode*> &InstInputs,
919 std::map<std::string, Record*> &InstResults) {
921 bool isUse = HandleUse(I, Pat, InstInputs);
922 if (!isUse && Pat->getTransformFn())
923 I->error("Cannot specify a transform function for a non-input value!");
925 } else if (Pat->getOperator()->getName() != "set") {
926 // If this is not a set, verify that the children nodes are not void typed,
928 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
929 if (Pat->getChild(i)->getExtType() == MVT::isVoid)
930 I->error("Cannot have void nodes inside of patterns!");
931 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults);
934 // If this is a non-leaf node with no children, treat it basically as if
935 // it were a leaf. This handles nodes like (imm).
937 if (Pat->getNumChildren() == 0)
938 isUse = HandleUse(I, Pat, InstInputs);
940 if (!isUse && Pat->getTransformFn())
941 I->error("Cannot specify a transform function for a non-input value!");
945 // Otherwise, this is a set, validate and collect instruction results.
946 if (Pat->getNumChildren() == 0)
947 I->error("set requires operands!");
948 else if (Pat->getNumChildren() & 1)
949 I->error("set requires an even number of operands");
951 if (Pat->getTransformFn())
952 I->error("Cannot specify a transform function on a set node!");
954 // Check the set destinations.
955 unsigned NumValues = Pat->getNumChildren()/2;
956 for (unsigned i = 0; i != NumValues; ++i) {
957 TreePatternNode *Dest = Pat->getChild(i);
959 I->error("set destination should be a virtual register!");
961 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
963 I->error("set destination should be a virtual register!");
965 if (!Val->getDef()->isSubClassOf("RegisterClass"))
966 I->error("set destination should be a virtual register!");
967 if (Dest->getName().empty())
968 I->error("set destination must have a name!");
969 if (InstResults.count(Dest->getName()))
970 I->error("cannot set '" + Dest->getName() +"' multiple times");
971 InstResults[Dest->getName()] = Val->getDef();
973 // Verify and collect info from the computation.
974 FindPatternInputsAndOutputs(I, Pat->getChild(i+NumValues),
975 InstInputs, InstResults);
980 /// ParseInstructions - Parse all of the instructions, inlining and resolving
981 /// any fragments involved. This populates the Instructions list with fully
982 /// resolved instructions.
983 void DAGISelEmitter::ParseInstructions() {
984 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
986 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
989 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
990 LI = Instrs[i]->getValueAsListInit("Pattern");
992 // If there is no pattern, only collect minimal information about the
993 // instruction for its operand list. We have to assume that there is one
994 // result, as we have no detailed info.
995 if (!LI || LI->getSize() == 0) {
996 std::vector<MVT::ValueType> ResultTypes;
997 std::vector<MVT::ValueType> OperandTypes;
999 CodeGenInstruction &InstInfo =Target.getInstruction(Instrs[i]->getName());
1001 // Doesn't even define a result?
1002 if (InstInfo.OperandList.size() == 0)
1005 // Assume the first operand is the result.
1006 ResultTypes.push_back(InstInfo.OperandList[0].Ty);
1008 // The rest are inputs.
1009 for (unsigned j = 1, e = InstInfo.OperandList.size(); j != e; ++j)
1010 OperandTypes.push_back(InstInfo.OperandList[j].Ty);
1012 // Create and insert the instruction.
1013 Instructions.insert(std::make_pair(Instrs[i],
1014 DAGInstruction(0, ResultTypes, OperandTypes)));
1015 continue; // no pattern.
1018 // Parse the instruction.
1019 TreePattern *I = new TreePattern(Instrs[i], LI, *this);
1020 // Inline pattern fragments into it.
1021 I->InlinePatternFragments();
1023 // Infer as many types as possible. If we cannot infer all of them, we can
1024 // never do anything with this instruction pattern: report it to the user.
1025 if (!I->InferAllTypes())
1026 I->error("Could not infer all types in pattern!");
1028 // InstInputs - Keep track of all of the inputs of the instruction, along
1029 // with the record they are declared as.
1030 std::map<std::string, TreePatternNode*> InstInputs;
1032 // InstResults - Keep track of all the virtual registers that are 'set'
1033 // in the instruction, including what reg class they are.
1034 std::map<std::string, Record*> InstResults;
1036 // Verify that the top-level forms in the instruction are of void type, and
1037 // fill in the InstResults map.
1038 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
1039 TreePatternNode *Pat = I->getTree(j);
1040 if (Pat->getExtType() != MVT::isVoid) {
1042 I->error("Top-level forms in instruction pattern should have"
1046 // Find inputs and outputs, and verify the structure of the uses/defs.
1047 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults);
1050 // Now that we have inputs and outputs of the pattern, inspect the operands
1051 // list for the instruction. This determines the order that operands are
1052 // added to the machine instruction the node corresponds to.
1053 unsigned NumResults = InstResults.size();
1055 // Parse the operands list from the (ops) list, validating it.
1056 std::vector<std::string> &Args = I->getArgList();
1057 assert(Args.empty() && "Args list should still be empty here!");
1058 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
1060 // Check that all of the results occur first in the list.
1061 std::vector<MVT::ValueType> ResultTypes;
1062 for (unsigned i = 0; i != NumResults; ++i) {
1063 if (i == CGI.OperandList.size())
1064 I->error("'" + InstResults.begin()->first +
1065 "' set but does not appear in operand list!");
1066 const std::string &OpName = CGI.OperandList[i].Name;
1068 // Check that it exists in InstResults.
1069 Record *R = InstResults[OpName];
1071 I->error("Operand $" + OpName + " should be a set destination: all "
1072 "outputs must occur before inputs in operand list!");
1074 if (CGI.OperandList[i].Rec != R)
1075 I->error("Operand $" + OpName + " class mismatch!");
1077 // Remember the return type.
1078 ResultTypes.push_back(CGI.OperandList[i].Ty);
1080 // Okay, this one checks out.
1081 InstResults.erase(OpName);
1084 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
1085 // the copy while we're checking the inputs.
1086 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
1088 std::vector<TreePatternNode*> ResultNodeOperands;
1089 std::vector<MVT::ValueType> OperandTypes;
1090 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
1091 const std::string &OpName = CGI.OperandList[i].Name;
1093 I->error("Operand #" + utostr(i) + " in operands list has no name!");
1095 if (!InstInputsCheck.count(OpName))
1096 I->error("Operand $" + OpName +
1097 " does not appear in the instruction pattern");
1098 TreePatternNode *InVal = InstInputsCheck[OpName];
1099 InstInputsCheck.erase(OpName); // It occurred, remove from map.
1100 if (CGI.OperandList[i].Ty != InVal->getExtType())
1101 I->error("Operand $" + OpName +
1102 "'s type disagrees between the operand and pattern");
1103 OperandTypes.push_back(InVal->getType());
1105 // Construct the result for the dest-pattern operand list.
1106 TreePatternNode *OpNode = InVal->clone();
1108 // No predicate is useful on the result.
1109 OpNode->setPredicateFn("");
1111 // Promote the xform function to be an explicit node if set.
1112 if (Record *Xform = OpNode->getTransformFn()) {
1113 OpNode->setTransformFn(0);
1114 std::vector<TreePatternNode*> Children;
1115 Children.push_back(OpNode);
1116 OpNode = new TreePatternNode(Xform, Children);
1119 ResultNodeOperands.push_back(OpNode);
1122 if (!InstInputsCheck.empty())
1123 I->error("Input operand $" + InstInputsCheck.begin()->first +
1124 " occurs in pattern but not in operands list!");
1126 TreePatternNode *ResultPattern =
1127 new TreePatternNode(I->getRecord(), ResultNodeOperands);
1129 // Create and insert the instruction.
1130 DAGInstruction TheInst(I, ResultTypes, OperandTypes);
1131 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
1133 // Use a temporary tree pattern to infer all types and make sure that the
1134 // constructed result is correct. This depends on the instruction already
1135 // being inserted into the Instructions map.
1136 TreePattern Temp(I->getRecord(), ResultPattern, *this);
1137 Temp.InferAllTypes();
1139 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
1140 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
1145 // If we can, convert the instructions to be patterns that are matched!
1146 for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
1147 E = Instructions.end(); II != E; ++II) {
1148 TreePattern *I = II->second.getPattern();
1149 if (I == 0) continue; // No pattern.
1151 if (I->getNumTrees() != 1) {
1152 std::cerr << "CANNOT HANDLE: " << I->getRecord()->getName() << " yet!";
1155 TreePatternNode *Pattern = I->getTree(0);
1156 if (Pattern->getOperator()->getName() != "set")
1157 continue; // Not a set (store or something?)
1159 if (Pattern->getNumChildren() != 2)
1160 continue; // Not a set of a single value (not handled so far)
1162 TreePatternNode *SrcPattern = Pattern->getChild(1)->clone();
1165 if (!SrcPattern->canPatternMatch(Reason, *this))
1166 I->error("Instruction can never match: " + Reason);
1168 TreePatternNode *DstPattern = II->second.getResultPattern();
1169 PatternsToMatch.push_back(std::make_pair(SrcPattern, DstPattern));
1173 void DAGISelEmitter::ParsePatterns() {
1174 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
1176 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1177 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
1178 TreePattern *Pattern = new TreePattern(Patterns[i], Tree, *this);
1180 // Inline pattern fragments into it.
1181 Pattern->InlinePatternFragments();
1183 // Infer as many types as possible. If we cannot infer all of them, we can
1184 // never do anything with this pattern: report it to the user.
1185 if (!Pattern->InferAllTypes())
1186 Pattern->error("Could not infer all types in pattern!");
1188 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
1189 if (LI->getSize() == 0) continue; // no pattern.
1191 // Parse the instruction.
1192 TreePattern *Result = new TreePattern(Patterns[i], LI, *this);
1194 // Inline pattern fragments into it.
1195 Result->InlinePatternFragments();
1197 // Infer as many types as possible. If we cannot infer all of them, we can
1198 // never do anything with this pattern: report it to the user.
1199 if (!Result->InferAllTypes())
1200 Result->error("Could not infer all types in pattern result!");
1202 if (Result->getNumTrees() != 1)
1203 Result->error("Cannot handle instructions producing instructions "
1204 "with temporaries yet!");
1207 if (!Pattern->getOnlyTree()->canPatternMatch(Reason, *this))
1208 Pattern->error("Pattern can never match: " + Reason);
1210 PatternsToMatch.push_back(std::make_pair(Pattern->getOnlyTree(),
1211 Result->getOnlyTree()));
1215 /// CombineChildVariants - Given a bunch of permutations of each child of the
1216 /// 'operator' node, put them together in all possible ways.
1217 static void CombineChildVariants(TreePatternNode *Orig,
1218 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
1219 std::vector<TreePatternNode*> &OutVariants,
1220 DAGISelEmitter &ISE) {
1221 // Make sure that each operand has at least one variant to choose from.
1222 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1223 if (ChildVariants[i].empty())
1226 // The end result is an all-pairs construction of the resultant pattern.
1227 std::vector<unsigned> Idxs;
1228 Idxs.resize(ChildVariants.size());
1229 bool NotDone = true;
1231 // Create the variant and add it to the output list.
1232 std::vector<TreePatternNode*> NewChildren;
1233 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1234 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
1235 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
1237 // Copy over properties.
1238 R->setName(Orig->getName());
1239 R->setPredicateFn(Orig->getPredicateFn());
1240 R->setTransformFn(Orig->getTransformFn());
1241 R->setType(Orig->getExtType());
1243 // If this pattern cannot every match, do not include it as a variant.
1244 std::string ErrString;
1245 if (!R->canPatternMatch(ErrString, ISE)) {
1248 bool AlreadyExists = false;
1250 // Scan to see if this pattern has already been emitted. We can get
1251 // duplication due to things like commuting:
1252 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
1253 // which are the same pattern. Ignore the dups.
1254 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
1255 if (R->isIsomorphicTo(OutVariants[i])) {
1256 AlreadyExists = true;
1263 OutVariants.push_back(R);
1266 // Increment indices to the next permutation.
1268 // Look for something we can increment without causing a wrap-around.
1269 for (unsigned IdxsIdx = 0; IdxsIdx != Idxs.size(); ++IdxsIdx) {
1270 if (++Idxs[IdxsIdx] < ChildVariants[IdxsIdx].size()) {
1271 NotDone = true; // Found something to increment.
1279 /// CombineChildVariants - A helper function for binary operators.
1281 static void CombineChildVariants(TreePatternNode *Orig,
1282 const std::vector<TreePatternNode*> &LHS,
1283 const std::vector<TreePatternNode*> &RHS,
1284 std::vector<TreePatternNode*> &OutVariants,
1285 DAGISelEmitter &ISE) {
1286 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1287 ChildVariants.push_back(LHS);
1288 ChildVariants.push_back(RHS);
1289 CombineChildVariants(Orig, ChildVariants, OutVariants, ISE);
1293 static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
1294 std::vector<TreePatternNode *> &Children) {
1295 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
1296 Record *Operator = N->getOperator();
1298 // Only permit raw nodes.
1299 if (!N->getName().empty() || !N->getPredicateFn().empty() ||
1300 N->getTransformFn()) {
1301 Children.push_back(N);
1305 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
1306 Children.push_back(N->getChild(0));
1308 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
1310 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
1311 Children.push_back(N->getChild(1));
1313 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
1316 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
1317 /// the (potentially recursive) pattern by using algebraic laws.
1319 static void GenerateVariantsOf(TreePatternNode *N,
1320 std::vector<TreePatternNode*> &OutVariants,
1321 DAGISelEmitter &ISE) {
1322 // We cannot permute leaves.
1324 OutVariants.push_back(N);
1328 // Look up interesting info about the node.
1329 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(N->getOperator());
1331 // If this node is associative, reassociate.
1332 if (NodeInfo.hasProperty(SDNodeInfo::SDNPAssociative)) {
1333 // Reassociate by pulling together all of the linked operators
1334 std::vector<TreePatternNode*> MaximalChildren;
1335 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
1337 // Only handle child sizes of 3. Otherwise we'll end up trying too many
1339 if (MaximalChildren.size() == 3) {
1340 // Find the variants of all of our maximal children.
1341 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
1342 GenerateVariantsOf(MaximalChildren[0], AVariants, ISE);
1343 GenerateVariantsOf(MaximalChildren[1], BVariants, ISE);
1344 GenerateVariantsOf(MaximalChildren[2], CVariants, ISE);
1346 // There are only two ways we can permute the tree:
1347 // (A op B) op C and A op (B op C)
1348 // Within these forms, we can also permute A/B/C.
1350 // Generate legal pair permutations of A/B/C.
1351 std::vector<TreePatternNode*> ABVariants;
1352 std::vector<TreePatternNode*> BAVariants;
1353 std::vector<TreePatternNode*> ACVariants;
1354 std::vector<TreePatternNode*> CAVariants;
1355 std::vector<TreePatternNode*> BCVariants;
1356 std::vector<TreePatternNode*> CBVariants;
1357 CombineChildVariants(N, AVariants, BVariants, ABVariants, ISE);
1358 CombineChildVariants(N, BVariants, AVariants, BAVariants, ISE);
1359 CombineChildVariants(N, AVariants, CVariants, ACVariants, ISE);
1360 CombineChildVariants(N, CVariants, AVariants, CAVariants, ISE);
1361 CombineChildVariants(N, BVariants, CVariants, BCVariants, ISE);
1362 CombineChildVariants(N, CVariants, BVariants, CBVariants, ISE);
1364 // Combine those into the result: (x op x) op x
1365 CombineChildVariants(N, ABVariants, CVariants, OutVariants, ISE);
1366 CombineChildVariants(N, BAVariants, CVariants, OutVariants, ISE);
1367 CombineChildVariants(N, ACVariants, BVariants, OutVariants, ISE);
1368 CombineChildVariants(N, CAVariants, BVariants, OutVariants, ISE);
1369 CombineChildVariants(N, BCVariants, AVariants, OutVariants, ISE);
1370 CombineChildVariants(N, CBVariants, AVariants, OutVariants, ISE);
1372 // Combine those into the result: x op (x op x)
1373 CombineChildVariants(N, CVariants, ABVariants, OutVariants, ISE);
1374 CombineChildVariants(N, CVariants, BAVariants, OutVariants, ISE);
1375 CombineChildVariants(N, BVariants, ACVariants, OutVariants, ISE);
1376 CombineChildVariants(N, BVariants, CAVariants, OutVariants, ISE);
1377 CombineChildVariants(N, AVariants, BCVariants, OutVariants, ISE);
1378 CombineChildVariants(N, AVariants, CBVariants, OutVariants, ISE);
1383 // Compute permutations of all children.
1384 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1385 ChildVariants.resize(N->getNumChildren());
1386 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1387 GenerateVariantsOf(N->getChild(i), ChildVariants[i], ISE);
1389 // Build all permutations based on how the children were formed.
1390 CombineChildVariants(N, ChildVariants, OutVariants, ISE);
1392 // If this node is commutative, consider the commuted order.
1393 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
1394 assert(N->getNumChildren()==2 &&"Commutative but doesn't have 2 children!");
1395 // Consider the commuted order.
1396 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
1402 // GenerateVariants - Generate variants. For example, commutative patterns can
1403 // match multiple ways. Add them to PatternsToMatch as well.
1404 void DAGISelEmitter::GenerateVariants() {
1406 DEBUG(std::cerr << "Generating instruction variants.\n");
1408 // Loop over all of the patterns we've collected, checking to see if we can
1409 // generate variants of the instruction, through the exploitation of
1410 // identities. This permits the target to provide agressive matching without
1411 // the .td file having to contain tons of variants of instructions.
1413 // Note that this loop adds new patterns to the PatternsToMatch list, but we
1414 // intentionally do not reconsider these. Any variants of added patterns have
1415 // already been added.
1417 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
1418 std::vector<TreePatternNode*> Variants;
1419 GenerateVariantsOf(PatternsToMatch[i].first, Variants, *this);
1421 assert(!Variants.empty() && "Must create at least original variant!");
1422 Variants.erase(Variants.begin()); // Remove the original pattern.
1424 if (Variants.empty()) // No variants for this pattern.
1427 DEBUG(std::cerr << "FOUND VARIANTS OF: ";
1428 PatternsToMatch[i].first->dump();
1431 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
1432 TreePatternNode *Variant = Variants[v];
1434 DEBUG(std::cerr << " VAR#" << v << ": ";
1438 // Scan to see if an instruction or explicit pattern already matches this.
1439 bool AlreadyExists = false;
1440 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
1441 // Check to see if this variant already exists.
1442 if (Variant->isIsomorphicTo(PatternsToMatch[p].first)) {
1443 DEBUG(std::cerr << " *** ALREADY EXISTS, ignoring variant.\n");
1444 AlreadyExists = true;
1448 // If we already have it, ignore the variant.
1449 if (AlreadyExists) continue;
1451 // Otherwise, add it to the list of patterns we have.
1452 PatternsToMatch.push_back(std::make_pair(Variant,
1453 PatternsToMatch[i].second));
1456 DEBUG(std::cerr << "\n");
1461 /// getPatternSize - Return the 'size' of this pattern. We want to match large
1462 /// patterns before small ones. This is used to determine the size of a
1464 static unsigned getPatternSize(TreePatternNode *P) {
1465 assert(isExtIntegerVT(P->getExtType()) ||
1466 isExtFloatingPointVT(P->getExtType()) &&
1467 "Not a valid pattern node to size!");
1468 unsigned Size = 1; // The node itself.
1470 // Count children in the count if they are also nodes.
1471 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
1472 TreePatternNode *Child = P->getChild(i);
1473 if (!Child->isLeaf() && Child->getExtType() != MVT::Other)
1474 Size += getPatternSize(Child);
1480 /// getResultPatternCost - Compute the number of instructions for this pattern.
1481 /// This is a temporary hack. We should really include the instruction
1482 /// latencies in this calculation.
1483 static unsigned getResultPatternCost(TreePatternNode *P) {
1484 if (P->isLeaf()) return 0;
1486 unsigned Cost = P->getOperator()->isSubClassOf("Instruction");
1487 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
1488 Cost += getResultPatternCost(P->getChild(i));
1492 // PatternSortingPredicate - return true if we prefer to match LHS before RHS.
1493 // In particular, we want to match maximal patterns first and lowest cost within
1494 // a particular complexity first.
1495 struct PatternSortingPredicate {
1496 bool operator()(DAGISelEmitter::PatternToMatch *LHS,
1497 DAGISelEmitter::PatternToMatch *RHS) {
1498 unsigned LHSSize = getPatternSize(LHS->first);
1499 unsigned RHSSize = getPatternSize(RHS->first);
1500 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
1501 if (LHSSize < RHSSize) return false;
1503 // If the patterns have equal complexity, compare generated instruction cost
1504 return getResultPatternCost(LHS->second) <getResultPatternCost(RHS->second);
1508 /// EmitMatchForPattern - Emit a matcher for N, going to the label for PatternNo
1509 /// if the match fails. At this point, we already know that the opcode for N
1510 /// matches, and the SDNode for the result has the RootName specified name.
1511 void DAGISelEmitter::EmitMatchForPattern(TreePatternNode *N,
1512 const std::string &RootName,
1513 std::map<std::string,std::string> &VarMap,
1514 unsigned PatternNo, std::ostream &OS) {
1515 assert(!N->isLeaf() && "Cannot match against a leaf!");
1517 // If this node has a name associated with it, capture it in VarMap. If
1518 // we already saw this in the pattern, emit code to verify dagness.
1519 if (!N->getName().empty()) {
1520 std::string &VarMapEntry = VarMap[N->getName()];
1521 if (VarMapEntry.empty()) {
1522 VarMapEntry = RootName;
1524 // If we get here, this is a second reference to a specific name. Since
1525 // we already have checked that the first reference is valid, we don't
1526 // have to recursively match it, just check that it's the same as the
1527 // previously named thing.
1528 OS << " if (" << VarMapEntry << " != " << RootName
1529 << ") goto P" << PatternNo << "Fail;\n";
1534 // Emit code to load the child nodes and match their contents recursively.
1535 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
1536 OS << " SDOperand " << RootName << i <<" = " << RootName
1537 << ".getOperand(" << i << ");\n";
1538 TreePatternNode *Child = N->getChild(i);
1540 if (!Child->isLeaf()) {
1541 // If it's not a leaf, recursively match.
1542 const SDNodeInfo &CInfo = getSDNodeInfo(Child->getOperator());
1543 OS << " if (" << RootName << i << ".getOpcode() != "
1544 << CInfo.getEnumName() << ") goto P" << PatternNo << "Fail;\n";
1545 EmitMatchForPattern(Child, RootName + utostr(i), VarMap, PatternNo, OS);
1547 // If this child has a name associated with it, capture it in VarMap. If
1548 // we already saw this in the pattern, emit code to verify dagness.
1549 if (!Child->getName().empty()) {
1550 std::string &VarMapEntry = VarMap[Child->getName()];
1551 if (VarMapEntry.empty()) {
1552 VarMapEntry = RootName + utostr(i);
1554 // If we get here, this is a second reference to a specific name. Since
1555 // we already have checked that the first reference is valid, we don't
1556 // have to recursively match it, just check that it's the same as the
1557 // previously named thing.
1558 OS << " if (" << VarMapEntry << " != " << RootName << i
1559 << ") goto P" << PatternNo << "Fail;\n";
1564 // Handle leaves of various types.
1565 Init *LeafVal = Child->getLeafValue();
1566 Record *LeafRec = dynamic_cast<DefInit*>(LeafVal)->getDef();
1567 if (LeafRec->isSubClassOf("RegisterClass")) {
1568 // Handle register references. Nothing to do here.
1569 } else if (LeafRec->isSubClassOf("ValueType")) {
1570 // Make sure this is the specified value type.
1571 OS << " if (cast<VTSDNode>(" << RootName << i << ")->getVT() != "
1572 << "MVT::" << LeafRec->getName() << ") goto P" << PatternNo
1576 assert(0 && "Unknown leaf type!");
1581 // If there is a node predicate for this, emit the call.
1582 if (!N->getPredicateFn().empty())
1583 OS << " if (!" << N->getPredicateFn() << "(" << RootName
1584 << ".Val)) goto P" << PatternNo << "Fail;\n";
1587 /// CodeGenPatternResult - Emit the action for a pattern. Now that it has
1588 /// matched, we actually have to build a DAG!
1589 unsigned DAGISelEmitter::
1590 CodeGenPatternResult(TreePatternNode *N, unsigned &Ctr,
1591 std::map<std::string,std::string> &VariableMap,
1592 std::ostream &OS, bool isRoot) {
1593 // This is something selected from the pattern we matched.
1594 if (!N->getName().empty()) {
1595 assert(!isRoot && "Root of pattern cannot be a leaf!");
1596 std::string &Val = VariableMap[N->getName()];
1597 assert(!Val.empty() &&
1598 "Variable referenced but not defined and not caught earlier!");
1599 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
1600 // Already selected this operand, just return the tmpval.
1601 return atoi(Val.c_str()+3);
1604 unsigned ResNo = Ctr++;
1605 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
1606 switch (N->getType()) {
1607 default: assert(0 && "Unknown type for constant node!");
1608 case MVT::i1: OS << " bool Tmp"; break;
1609 case MVT::i8: OS << " unsigned char Tmp"; break;
1610 case MVT::i16: OS << " unsigned short Tmp"; break;
1611 case MVT::i32: OS << " unsigned Tmp"; break;
1612 case MVT::i64: OS << " uint64_t Tmp"; break;
1614 OS << ResNo << "C = cast<ConstantSDNode>(" << Val << ")->getValue();\n";
1615 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getTargetConstant(Tmp"
1616 << ResNo << "C, MVT::" << getEnumName(N->getType()) << ");\n";
1618 OS << " SDOperand Tmp" << ResNo << " = Select(" << Val << ");\n";
1620 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
1621 // value if used multiple times by this pattern result.
1622 Val = "Tmp"+utostr(ResNo);
1627 // If this is an explicit register reference, handle it.
1628 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
1629 unsigned ResNo = Ctr++;
1630 if (DI->getDef()->isSubClassOf("Register")) {
1631 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getRegister("
1632 << getQualifiedName(DI->getDef()) << ", MVT::"
1633 << getEnumName(N->getType())
1637 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
1638 unsigned ResNo = Ctr++;
1639 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getTargetConstant("
1640 << II->getValue() << ", MVT::"
1641 << getEnumName(N->getType())
1647 assert(0 && "Unknown leaf type!");
1651 Record *Op = N->getOperator();
1652 if (Op->isSubClassOf("Instruction")) {
1653 // Emit all of the operands.
1654 std::vector<unsigned> Ops;
1655 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1656 Ops.push_back(CodeGenPatternResult(N->getChild(i), Ctr, VariableMap, OS));
1658 CodeGenInstruction &II = Target.getInstruction(Op->getName());
1659 unsigned ResNo = Ctr++;
1662 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getTargetNode("
1663 << II.Namespace << "::" << II.TheDef->getName() << ", MVT::"
1664 << getEnumName(N->getType());
1665 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1666 OS << ", Tmp" << Ops[i];
1669 // If this instruction is the root, and if there is only one use of it,
1670 // use SelectNodeTo instead of getTargetNode to avoid an allocation.
1671 OS << " if (N.Val->hasOneUse()) {\n";
1672 OS << " CurDAG->SelectNodeTo(N.Val, "
1673 << II.Namespace << "::" << II.TheDef->getName() << ", MVT::"
1674 << getEnumName(N->getType());
1675 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1676 OS << ", Tmp" << Ops[i];
1678 OS << " return N;\n";
1679 OS << " } else {\n";
1680 OS << " return CodeGenMap[N] = CurDAG->getTargetNode("
1681 << II.Namespace << "::" << II.TheDef->getName() << ", MVT::"
1682 << getEnumName(N->getType());
1683 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1684 OS << ", Tmp" << Ops[i];
1689 } else if (Op->isSubClassOf("SDNodeXForm")) {
1690 assert(N->getNumChildren() == 1 && "node xform should have one child!");
1691 unsigned OpVal = CodeGenPatternResult(N->getChild(0), Ctr, VariableMap, OS);
1693 unsigned ResNo = Ctr++;
1694 OS << " SDOperand Tmp" << ResNo << " = Transform_" << Op->getName()
1695 << "(Tmp" << OpVal << ".Val);\n";
1697 OS << " CodeGenMap[N] = Tmp" << ResNo << ";\n";
1698 OS << " return Tmp" << ResNo << ";\n";
1703 assert(0 && "Unknown node in result pattern!");
1708 /// RemoveAllTypes - A quick recursive walk over a pattern which removes all
1709 /// type information from it.
1710 static void RemoveAllTypes(TreePatternNode *N) {
1711 N->setType(MVT::isUnknown);
1713 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1714 RemoveAllTypes(N->getChild(i));
1717 /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat' and
1718 /// add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
1719 /// 'Pat' may be missing types. If we find an unresolved type to add a check
1720 /// for, this returns true otherwise false if Pat has all types.
1721 static bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
1722 const std::string &Prefix, unsigned PatternNo,
1725 if (!Pat->hasTypeSet()) {
1726 // Move a type over from 'other' to 'pat'.
1727 Pat->setType(Other->getType());
1728 OS << " if (" << Prefix << ".getValueType() != MVT::"
1729 << getName(Pat->getType()) << ") goto P" << PatternNo << "Fail;\n";
1731 } else if (Pat->isLeaf()) {
1735 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i)
1736 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
1737 Prefix + utostr(i), PatternNo, OS))
1742 /// EmitCodeForPattern - Given a pattern to match, emit code to the specified
1743 /// stream to match the pattern, and generate the code for the match if it
1745 void DAGISelEmitter::EmitCodeForPattern(PatternToMatch &Pattern,
1747 static unsigned PatternCount = 0;
1748 unsigned PatternNo = PatternCount++;
1749 OS << " { // Pattern #" << PatternNo << ": ";
1750 Pattern.first->print(OS);
1751 OS << "\n // Emits: ";
1752 Pattern.second->print(OS);
1754 OS << " // Pattern complexity = " << getPatternSize(Pattern.first)
1755 << " cost = " << getResultPatternCost(Pattern.second) << "\n";
1757 // Emit the matcher, capturing named arguments in VariableMap.
1758 std::map<std::string,std::string> VariableMap;
1759 EmitMatchForPattern(Pattern.first, "N", VariableMap, PatternNo, OS);
1761 // TP - Get *SOME* tree pattern, we don't care which.
1762 TreePattern &TP = *PatternFragments.begin()->second;
1764 // At this point, we know that we structurally match the pattern, but the
1765 // types of the nodes may not match. Figure out the fewest number of type
1766 // comparisons we need to emit. For example, if there is only one integer
1767 // type supported by a target, there should be no type comparisons at all for
1768 // integer patterns!
1770 // To figure out the fewest number of type checks needed, clone the pattern,
1771 // remove the types, then perform type inference on the pattern as a whole.
1772 // If there are unresolved types, emit an explicit check for those types,
1773 // apply the type to the tree, then rerun type inference. Iterate until all
1774 // types are resolved.
1776 TreePatternNode *Pat = Pattern.first->clone();
1777 RemoveAllTypes(Pat);
1780 // Resolve/propagate as many types as possible.
1782 bool MadeChange = true;
1784 MadeChange = Pat->ApplyTypeConstraints(TP,true/*Ignore reg constraints*/);
1786 assert(0 && "Error: could not find consistent types for something we"
1787 " already decided was ok!");
1791 // Insert a check for an unresolved type and add it to the tree. If we find
1792 // an unresolved type to add a check for, this returns true and we iterate,
1793 // otherwise we are done.
1794 } while (InsertOneTypeCheck(Pat, Pattern.first, "N", PatternNo, OS));
1797 CodeGenPatternResult(Pattern.second, TmpNo,
1798 VariableMap, OS, true /*the root*/);
1801 OS << " }\n P" << PatternNo << "Fail:\n";
1806 /// CompareByRecordName - An ordering predicate that implements less-than by
1807 /// comparing the names records.
1808 struct CompareByRecordName {
1809 bool operator()(const Record *LHS, const Record *RHS) const {
1810 // Sort by name first.
1811 if (LHS->getName() < RHS->getName()) return true;
1812 // If both names are equal, sort by pointer.
1813 return LHS->getName() == RHS->getName() && LHS < RHS;
1818 void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
1819 std::string InstNS = Target.inst_begin()->second.Namespace;
1820 if (!InstNS.empty()) InstNS += "::";
1822 // Emit boilerplate.
1823 OS << "// The main instruction selector code.\n"
1824 << "SDOperand SelectCode(SDOperand N) {\n"
1825 << " if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
1826 << " N.getOpcode() < (ISD::BUILTIN_OP_END+" << InstNS
1827 << "INSTRUCTION_LIST_END))\n"
1828 << " return N; // Already selected.\n\n"
1829 << " if (!N.Val->hasOneUse()) {\n"
1830 << " std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(N);\n"
1831 << " if (CGMI != CodeGenMap.end()) return CGMI->second;\n"
1833 << " switch (N.getOpcode()) {\n"
1834 << " default: break;\n"
1835 << " case ISD::EntryToken: // These leaves remain the same.\n"
1837 << " case ISD::AssertSext:\n"
1838 << " case ISD::AssertZext: {\n"
1839 << " SDOperand Tmp0 = Select(N.getOperand(0));\n"
1840 << " if (!N.Val->hasOneUse()) CodeGenMap[N] = Tmp0;\n"
1841 << " return Tmp0;\n"
1844 // Group the patterns by their top-level opcodes.
1845 std::map<Record*, std::vector<PatternToMatch*>,
1846 CompareByRecordName> PatternsByOpcode;
1847 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i)
1848 PatternsByOpcode[PatternsToMatch[i].first->getOperator()]
1849 .push_back(&PatternsToMatch[i]);
1851 // Loop over all of the case statements.
1852 for (std::map<Record*, std::vector<PatternToMatch*>,
1853 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
1854 E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
1855 const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
1856 std::vector<PatternToMatch*> &Patterns = PBOI->second;
1858 OS << " case " << OpcodeInfo.getEnumName() << ":\n";
1860 // We want to emit all of the matching code now. However, we want to emit
1861 // the matches in order of minimal cost. Sort the patterns so the least
1862 // cost one is at the start.
1863 std::stable_sort(Patterns.begin(), Patterns.end(),
1864 PatternSortingPredicate());
1866 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
1867 EmitCodeForPattern(*Patterns[i], OS);
1868 OS << " break;\n\n";
1872 OS << " } // end of big switch.\n\n"
1873 << " std::cerr << \"Cannot yet select: \";\n"
1874 << " N.Val->dump();\n"
1875 << " std::cerr << '\\n';\n"
1880 void DAGISelEmitter::run(std::ostream &OS) {
1881 EmitSourceFileHeader("DAG Instruction Selector for the " + Target.getName() +
1884 OS << "// *** NOTE: This file is #included into the middle of the target\n"
1885 << "// *** instruction selector class. These functions are really "
1888 OS << "// Instance var to keep track of multiply used nodes that have \n"
1889 << "// already been selected.\n"
1890 << "std::map<SDOperand, SDOperand> CodeGenMap;\n";
1893 ParseNodeTransforms(OS);
1894 ParsePatternFragments(OS);
1895 ParseInstructions();
1898 // Generate variants. For example, commutative patterns can match
1899 // multiple ways. Add them to PatternsToMatch as well.
1903 DEBUG(std::cerr << "\n\nALL PATTERNS TO MATCH:\n\n";
1904 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
1905 std::cerr << "PATTERN: "; PatternsToMatch[i].first->dump();
1906 std::cerr << "\nRESULT: ";PatternsToMatch[i].second->dump();
1910 // At this point, we have full information about the 'Patterns' we need to
1911 // parse, both implicitly from instructions as well as from explicit pattern
1912 // definitions. Emit the resultant instruction selector.
1913 EmitInstructionSelector(OS);
1915 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
1916 E = PatternFragments.end(); I != E; ++I)
1918 PatternFragments.clear();
1920 Instructions.clear();