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 // SDTypeConstraint implementation
26 SDTypeConstraint::SDTypeConstraint(Record *R) {
27 OperandNo = R->getValueAsInt("OperandNum");
29 if (R->isSubClassOf("SDTCisVT")) {
30 ConstraintType = SDTCisVT;
31 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
32 } else if (R->isSubClassOf("SDTCisInt")) {
33 ConstraintType = SDTCisInt;
34 } else if (R->isSubClassOf("SDTCisFP")) {
35 ConstraintType = SDTCisFP;
36 } else if (R->isSubClassOf("SDTCisSameAs")) {
37 ConstraintType = SDTCisSameAs;
38 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
39 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
40 ConstraintType = SDTCisVTSmallerThanOp;
41 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
42 R->getValueAsInt("OtherOperandNum");
43 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
44 ConstraintType = SDTCisOpSmallerThanOp;
45 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
46 R->getValueAsInt("BigOperandNum");
48 std::cerr << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
53 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
54 /// N, which has NumResults results.
55 TreePatternNode *SDTypeConstraint::getOperandNum(unsigned OpNo,
57 unsigned NumResults) const {
58 assert(NumResults == 1 && "We only work with single result nodes so far!");
60 if (OpNo < NumResults)
61 return N; // FIXME: need value #
63 return N->getChild(OpNo-NumResults);
67 static std::vector<MVT::ValueType>
68 FilterVTs(const std::vector<MVT::ValueType> &InVTs, T Filter) {
69 std::vector<MVT::ValueType> Result;
70 for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
72 Result.push_back(InVTs[i]);
76 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
77 /// constraint to the nodes operands. This returns true if it makes a
78 /// change, false otherwise. If a type contradiction is found, throw an
80 bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
81 const SDNodeInfo &NodeInfo,
82 TreePattern &TP) const {
83 unsigned NumResults = NodeInfo.getNumResults();
84 assert(NumResults == 1 && "We only work with single result nodes so far!");
86 // Check that the number of operands is sane.
87 if (NodeInfo.getNumOperands() >= 0) {
88 if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands())
89 TP.error(N->getOperator()->getName() + " node requires exactly " +
90 itostr(NodeInfo.getNumOperands()) + " operands!");
93 const CodeGenTarget &CGT = TP.getDAGISelEmitter().getTargetInfo();
95 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NumResults);
97 switch (ConstraintType) {
98 default: assert(0 && "Unknown constraint type!");
100 // Operand must be a particular type.
101 return NodeToApply->UpdateNodeType(x.SDTCisVT_Info.VT, TP);
103 if (NodeToApply->hasTypeSet() && !MVT::isInteger(NodeToApply->getType()))
104 NodeToApply->UpdateNodeType(MVT::i1, TP); // throw an error.
106 // If there is only one integer type supported, this must be it.
107 std::vector<MVT::ValueType> IntVTs =
108 FilterVTs(CGT.getLegalValueTypes(), MVT::isInteger);
110 // If we found exactly one supported integer type, apply it.
111 if (IntVTs.size() == 1)
112 return NodeToApply->UpdateNodeType(IntVTs[0], TP);
116 if (NodeToApply->hasTypeSet() &&
117 !MVT::isFloatingPoint(NodeToApply->getType()))
118 NodeToApply->UpdateNodeType(MVT::f32, TP); // throw an error.
120 // If there is only one FP type supported, this must be it.
121 std::vector<MVT::ValueType> FPVTs =
122 FilterVTs(CGT.getLegalValueTypes(), MVT::isFloatingPoint);
124 // If we found exactly one supported FP type, apply it.
125 if (FPVTs.size() == 1)
126 return NodeToApply->UpdateNodeType(FPVTs[0], TP);
130 TreePatternNode *OtherNode =
131 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NumResults);
132 return NodeToApply->UpdateNodeType(OtherNode->getType(), TP) |
133 OtherNode->UpdateNodeType(NodeToApply->getType(), TP);
135 case SDTCisVTSmallerThanOp: {
136 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
137 // have an integer type that is smaller than the VT.
138 if (!NodeToApply->isLeaf() ||
139 !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
140 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
141 ->isSubClassOf("ValueType"))
142 TP.error(N->getOperator()->getName() + " expects a VT operand!");
144 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
145 if (!MVT::isInteger(VT))
146 TP.error(N->getOperator()->getName() + " VT operand must be integer!");
148 TreePatternNode *OtherNode =
149 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N,NumResults);
150 if (OtherNode->hasTypeSet() &&
151 (!MVT::isInteger(OtherNode->getType()) ||
152 OtherNode->getType() <= VT))
153 OtherNode->UpdateNodeType(MVT::Other, TP); // Throw an error.
156 case SDTCisOpSmallerThanOp: {
165 //===----------------------------------------------------------------------===//
166 // SDNodeInfo implementation
168 SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
169 EnumName = R->getValueAsString("Opcode");
170 SDClassName = R->getValueAsString("SDClass");
171 Record *TypeProfile = R->getValueAsDef("TypeProfile");
172 NumResults = TypeProfile->getValueAsInt("NumResults");
173 NumOperands = TypeProfile->getValueAsInt("NumOperands");
175 // Parse the properties.
177 ListInit *LI = R->getValueAsListInit("Properties");
178 for (unsigned i = 0, e = LI->getSize(); i != e; ++i) {
179 DefInit *DI = dynamic_cast<DefInit*>(LI->getElement(i));
180 assert(DI && "Properties list must be list of defs!");
181 if (DI->getDef()->getName() == "SDNPCommutative") {
182 Properties |= 1 << SDNPCommutative;
183 } else if (DI->getDef()->getName() == "SDNPAssociative") {
184 Properties |= 1 << SDNPAssociative;
186 std::cerr << "Unknown SD Node property '" << DI->getDef()->getName()
187 << "' on node '" << R->getName() << "'!\n";
193 // Parse the type constraints.
194 ListInit *Constraints = TypeProfile->getValueAsListInit("Constraints");
195 for (unsigned i = 0, e = Constraints->getSize(); i != e; ++i) {
196 assert(dynamic_cast<DefInit*>(Constraints->getElement(i)) &&
197 "Constraints list should contain constraint definitions!");
199 static_cast<DefInit*>(Constraints->getElement(i))->getDef();
200 TypeConstraints.push_back(Constraint);
204 //===----------------------------------------------------------------------===//
205 // TreePatternNode implementation
208 TreePatternNode::~TreePatternNode() {
209 #if 0 // FIXME: implement refcounted tree nodes!
210 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
215 /// UpdateNodeType - Set the node type of N to VT if VT contains
216 /// information. If N already contains a conflicting type, then throw an
217 /// exception. This returns true if any information was updated.
219 bool TreePatternNode::UpdateNodeType(MVT::ValueType VT, TreePattern &TP) {
220 if (VT == MVT::LAST_VALUETYPE || getType() == VT) return false;
221 if (getType() == MVT::LAST_VALUETYPE) {
226 TP.error("Type inference contradiction found in node " +
227 getOperator()->getName() + "!");
228 return true; // unreachable
232 void TreePatternNode::print(std::ostream &OS) const {
234 OS << *getLeafValue();
236 OS << "(" << getOperator()->getName();
239 if (getType() == MVT::Other)
241 else if (getType() == MVT::LAST_VALUETYPE)
244 OS << ":" << getType();
247 if (getNumChildren() != 0) {
249 getChild(0)->print(OS);
250 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
252 getChild(i)->print(OS);
258 if (!PredicateFn.empty())
259 OS << "<<P:" << PredicateFn << ">>";
261 OS << "<<X:" << TransformFn->getName() << ">>";
262 if (!getName().empty())
263 OS << ":$" << getName();
266 void TreePatternNode::dump() const {
270 /// isIsomorphicTo - Return true if this node is recursively isomorphic to
271 /// the specified node. For this comparison, all of the state of the node
272 /// is considered, except for the assigned name. Nodes with differing names
273 /// that are otherwise identical are considered isomorphic.
274 bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N) const {
275 if (N == this) return true;
276 if (N->isLeaf() != isLeaf() || getType() != N->getType() ||
277 getPredicateFn() != N->getPredicateFn() ||
278 getTransformFn() != N->getTransformFn())
282 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue()))
283 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue()))
284 return DI->getDef() == NDI->getDef();
285 return getLeafValue() == N->getLeafValue();
288 if (N->getOperator() != getOperator() ||
289 N->getNumChildren() != getNumChildren()) return false;
290 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
291 if (!getChild(i)->isIsomorphicTo(N->getChild(i)))
296 /// clone - Make a copy of this tree and all of its children.
298 TreePatternNode *TreePatternNode::clone() const {
299 TreePatternNode *New;
301 New = new TreePatternNode(getLeafValue());
303 std::vector<TreePatternNode*> CChildren;
304 CChildren.reserve(Children.size());
305 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
306 CChildren.push_back(getChild(i)->clone());
307 New = new TreePatternNode(getOperator(), CChildren);
309 New->setName(getName());
310 New->setType(getType());
311 New->setPredicateFn(getPredicateFn());
312 New->setTransformFn(getTransformFn());
316 /// SubstituteFormalArguments - Replace the formal arguments in this tree
317 /// with actual values specified by ArgMap.
318 void TreePatternNode::
319 SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
320 if (isLeaf()) return;
322 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
323 TreePatternNode *Child = getChild(i);
324 if (Child->isLeaf()) {
325 Init *Val = Child->getLeafValue();
326 if (dynamic_cast<DefInit*>(Val) &&
327 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
328 // We found a use of a formal argument, replace it with its value.
329 Child = ArgMap[Child->getName()];
330 assert(Child && "Couldn't find formal argument!");
334 getChild(i)->SubstituteFormalArguments(ArgMap);
340 /// InlinePatternFragments - If this pattern refers to any pattern
341 /// fragments, inline them into place, giving us a pattern without any
342 /// PatFrag references.
343 TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
344 if (isLeaf()) return this; // nothing to do.
345 Record *Op = getOperator();
347 if (!Op->isSubClassOf("PatFrag")) {
348 // Just recursively inline children nodes.
349 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
350 setChild(i, getChild(i)->InlinePatternFragments(TP));
354 // Otherwise, we found a reference to a fragment. First, look up its
355 // TreePattern record.
356 TreePattern *Frag = TP.getDAGISelEmitter().getPatternFragment(Op);
358 // Verify that we are passing the right number of operands.
359 if (Frag->getNumArgs() != Children.size())
360 TP.error("'" + Op->getName() + "' fragment requires " +
361 utostr(Frag->getNumArgs()) + " operands!");
363 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
365 // Resolve formal arguments to their actual value.
366 if (Frag->getNumArgs()) {
367 // Compute the map of formal to actual arguments.
368 std::map<std::string, TreePatternNode*> ArgMap;
369 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
370 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
372 FragTree->SubstituteFormalArguments(ArgMap);
375 FragTree->setName(getName());
377 // Get a new copy of this fragment to stitch into here.
378 //delete this; // FIXME: implement refcounting!
382 /// getIntrinsicType - Check to see if the specified record has an intrinsic
383 /// type which should be applied to it. This infer the type of register
384 /// references from the register file information, for example.
386 static MVT::ValueType getIntrinsicType(Record *R, bool NotRegisters, TreePattern &TP) {
387 // Check to see if this is a register or a register class...
388 if (R->isSubClassOf("RegisterClass")) {
389 if (NotRegisters) return MVT::LAST_VALUETYPE;
390 return getValueType(R->getValueAsDef("RegType"));
391 } else if (R->isSubClassOf("PatFrag")) {
392 // Pattern fragment types will be resolved when they are inlined.
393 return MVT::LAST_VALUETYPE;
394 } else if (R->isSubClassOf("Register")) {
395 assert(0 && "Explicit registers not handled here yet!\n");
396 return MVT::LAST_VALUETYPE;
397 } else if (R->isSubClassOf("ValueType")) {
400 } else if (R->getName() == "node") {
402 return MVT::LAST_VALUETYPE;
405 TP.error("Unknown node flavor used in pattern: " + R->getName());
409 /// ApplyTypeConstraints - Apply all of the type constraints relevent to
410 /// this node and its children in the tree. This returns true if it makes a
411 /// change, false otherwise. If a type contradiction is found, throw an
413 bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
415 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue()))
416 // If it's a regclass or something else known, include the type.
417 return UpdateNodeType(getIntrinsicType(DI->getDef(), NotRegisters, TP),
422 // special handling for set, which isn't really an SDNode.
423 if (getOperator()->getName() == "set") {
424 assert (getNumChildren() == 2 && "Only handle 2 operand set's for now!");
425 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
426 MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
428 // Types of operands must match.
429 MadeChange |= getChild(0)->UpdateNodeType(getChild(1)->getType(), TP);
430 MadeChange |= getChild(1)->UpdateNodeType(getChild(0)->getType(), TP);
431 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
433 } else if (getOperator()->isSubClassOf("SDNode")) {
434 const SDNodeInfo &NI = TP.getDAGISelEmitter().getSDNodeInfo(getOperator());
436 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
437 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
438 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
440 } else if (getOperator()->isSubClassOf("Instruction")) {
441 const DAGInstruction &Inst =
442 TP.getDAGISelEmitter().getInstruction(getOperator());
444 assert(Inst.getNumResults() == 1 && "Only supports one result instrs!");
445 // Apply the result type to the node
446 bool MadeChange = UpdateNodeType(Inst.getResultType(0), TP);
448 if (getNumChildren() != Inst.getNumOperands())
449 TP.error("Instruction '" + getOperator()->getName() + " expects " +
450 utostr(Inst.getNumOperands()) + " operands, not " +
451 utostr(getNumChildren()) + " operands!");
452 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
453 MadeChange |= getChild(i)->UpdateNodeType(Inst.getOperandType(i), TP);
454 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
458 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
460 // Node transforms always take one operand, and take and return the same
462 if (getNumChildren() != 1)
463 TP.error("Node transform '" + getOperator()->getName() +
464 "' requires one operand!");
465 bool MadeChange = UpdateNodeType(getChild(0)->getType(), TP);
466 MadeChange |= getChild(0)->UpdateNodeType(getType(), TP);
471 /// canPatternMatch - If it is impossible for this pattern to match on this
472 /// target, fill in Reason and return false. Otherwise, return true. This is
473 /// used as a santity check for .td files (to prevent people from writing stuff
474 /// that can never possibly work), and to prevent the pattern permuter from
475 /// generating stuff that is useless.
476 bool TreePatternNode::canPatternMatch(std::string &Reason, DAGISelEmitter &ISE){
477 if (isLeaf()) return true;
479 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
480 if (!getChild(i)->canPatternMatch(Reason, ISE))
483 // If this node is a commutative operator, check that the LHS isn't an
485 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(getOperator());
486 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
487 // Scan all of the operands of the node and make sure that only the last one
488 // is a constant node.
489 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i)
490 if (!getChild(i)->isLeaf() &&
491 getChild(i)->getOperator()->getName() == "imm") {
492 Reason = "Immediate value must be on the RHS of commutative operators!";
500 //===----------------------------------------------------------------------===//
501 // TreePattern implementation
504 TreePattern::TreePattern(Record *TheRec, ListInit *RawPat,
505 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
506 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
507 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
510 TreePattern::TreePattern(Record *TheRec, DagInit *Pat,
511 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
512 Trees.push_back(ParseTreePattern(Pat));
515 TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat,
516 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
517 Trees.push_back(Pat);
522 void TreePattern::error(const std::string &Msg) const {
524 throw "In " + TheRecord->getName() + ": " + Msg;
527 TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
528 Record *Operator = Dag->getNodeType();
530 if (Operator->isSubClassOf("ValueType")) {
531 // If the operator is a ValueType, then this must be "type cast" of a leaf
533 if (Dag->getNumArgs() != 1)
534 error("Type cast only takes one operand!");
536 Init *Arg = Dag->getArg(0);
537 TreePatternNode *New;
538 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
539 Record *R = DI->getDef();
540 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
541 Dag->setArg(0, new DagInit(R,
542 std::vector<std::pair<Init*, std::string> >()));
543 TreePatternNode *TPN = ParseTreePattern(Dag);
544 TPN->setName(Dag->getArgName(0));
548 New = new TreePatternNode(DI);
549 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
550 New = ParseTreePattern(DI);
553 error("Unknown leaf value for tree pattern!");
557 // Apply the type cast.
558 New->UpdateNodeType(getValueType(Operator), *this);
562 // Verify that this is something that makes sense for an operator.
563 if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
564 !Operator->isSubClassOf("Instruction") &&
565 !Operator->isSubClassOf("SDNodeXForm") &&
566 Operator->getName() != "set")
567 error("Unrecognized node '" + Operator->getName() + "'!");
569 std::vector<TreePatternNode*> Children;
571 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
572 Init *Arg = Dag->getArg(i);
573 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
574 Children.push_back(ParseTreePattern(DI));
575 Children.back()->setName(Dag->getArgName(i));
576 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
577 Record *R = DefI->getDef();
578 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
579 // TreePatternNode if its own.
580 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
581 Dag->setArg(i, new DagInit(R,
582 std::vector<std::pair<Init*, std::string> >()));
583 --i; // Revisit this node...
585 TreePatternNode *Node = new TreePatternNode(DefI);
586 Node->setName(Dag->getArgName(i));
587 Children.push_back(Node);
590 if (R->getName() == "node") {
591 if (Dag->getArgName(i).empty())
592 error("'node' argument requires a name to match with operand list");
593 Args.push_back(Dag->getArgName(i));
598 error("Unknown leaf value for tree pattern!");
602 return new TreePatternNode(Operator, Children);
605 /// InferAllTypes - Infer/propagate as many types throughout the expression
606 /// patterns as possible. Return true if all types are infered, false
607 /// otherwise. Throw an exception if a type contradiction is found.
608 bool TreePattern::InferAllTypes() {
609 bool MadeChange = true;
612 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
613 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
616 bool HasUnresolvedTypes = false;
617 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
618 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
619 return !HasUnresolvedTypes;
622 void TreePattern::print(std::ostream &OS) const {
623 OS << getRecord()->getName();
625 OS << "(" << Args[0];
626 for (unsigned i = 1, e = Args.size(); i != e; ++i)
627 OS << ", " << Args[i];
632 if (Trees.size() > 1)
634 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
640 if (Trees.size() > 1)
644 void TreePattern::dump() const { print(std::cerr); }
648 //===----------------------------------------------------------------------===//
649 // DAGISelEmitter implementation
652 // Parse all of the SDNode definitions for the target, populating SDNodes.
653 void DAGISelEmitter::ParseNodeInfo() {
654 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
655 while (!Nodes.empty()) {
656 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
661 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
662 /// map, and emit them to the file as functions.
663 void DAGISelEmitter::ParseNodeTransforms(std::ostream &OS) {
664 OS << "\n// Node transformations.\n";
665 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
666 while (!Xforms.empty()) {
667 Record *XFormNode = Xforms.back();
668 Record *SDNode = XFormNode->getValueAsDef("Opcode");
669 std::string Code = XFormNode->getValueAsCode("XFormFunction");
670 SDNodeXForms.insert(std::make_pair(XFormNode,
671 std::make_pair(SDNode, Code)));
674 std::string ClassName = getSDNodeInfo(SDNode).getSDClassName();
675 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
677 OS << "inline SDOperand Transform_" << XFormNode->getName()
678 << "(SDNode *" << C2 << ") {\n";
679 if (ClassName != "SDNode")
680 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
681 OS << Code << "\n}\n";
690 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
691 /// file, building up the PatternFragments map. After we've collected them all,
692 /// inline fragments together as necessary, so that there are no references left
693 /// inside a pattern fragment to a pattern fragment.
695 /// This also emits all of the predicate functions to the output file.
697 void DAGISelEmitter::ParsePatternFragments(std::ostream &OS) {
698 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
700 // First step, parse all of the fragments and emit predicate functions.
701 OS << "\n// Predicate functions.\n";
702 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
703 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
704 TreePattern *P = new TreePattern(Fragments[i], Tree, *this);
705 PatternFragments[Fragments[i]] = P;
707 // Validate the argument list, converting it to map, to discard duplicates.
708 std::vector<std::string> &Args = P->getArgList();
709 std::set<std::string> OperandsMap(Args.begin(), Args.end());
711 if (OperandsMap.count(""))
712 P->error("Cannot have unnamed 'node' values in pattern fragment!");
714 // Parse the operands list.
715 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
716 if (OpsList->getNodeType()->getName() != "ops")
717 P->error("Operands list should start with '(ops ... '!");
719 // Copy over the arguments.
721 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
722 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
723 static_cast<DefInit*>(OpsList->getArg(j))->
724 getDef()->getName() != "node")
725 P->error("Operands list should all be 'node' values.");
726 if (OpsList->getArgName(j).empty())
727 P->error("Operands list should have names for each operand!");
728 if (!OperandsMap.count(OpsList->getArgName(j)))
729 P->error("'" + OpsList->getArgName(j) +
730 "' does not occur in pattern or was multiply specified!");
731 OperandsMap.erase(OpsList->getArgName(j));
732 Args.push_back(OpsList->getArgName(j));
735 if (!OperandsMap.empty())
736 P->error("Operands list does not contain an entry for operand '" +
737 *OperandsMap.begin() + "'!");
739 // If there is a code init for this fragment, emit the predicate code and
740 // keep track of the fact that this fragment uses it.
741 std::string Code = Fragments[i]->getValueAsCode("Predicate");
743 assert(!P->getOnlyTree()->isLeaf() && "Can't be a leaf!");
744 std::string ClassName =
745 getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
746 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
748 OS << "inline bool Predicate_" << Fragments[i]->getName()
749 << "(SDNode *" << C2 << ") {\n";
750 if (ClassName != "SDNode")
751 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
752 OS << Code << "\n}\n";
753 P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
756 // If there is a node transformation corresponding to this, keep track of
758 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
759 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
760 P->getOnlyTree()->setTransformFn(Transform);
765 // Now that we've parsed all of the tree fragments, do a closure on them so
766 // that there are not references to PatFrags left inside of them.
767 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
768 E = PatternFragments.end(); I != E; ++I) {
769 TreePattern *ThePat = I->second;
770 ThePat->InlinePatternFragments();
772 // Infer as many types as possible. Don't worry about it if we don't infer
773 // all of them, some may depend on the inputs of the pattern.
775 ThePat->InferAllTypes();
777 // If this pattern fragment is not supported by this target (no types can
778 // satisfy its constraints), just ignore it. If the bogus pattern is
779 // actually used by instructions, the type consistency error will be
783 // If debugging, print out the pattern fragment result.
784 DEBUG(ThePat->dump());
788 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
789 /// instruction input. Return true if this is a real use.
790 static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
791 std::map<std::string, TreePatternNode*> &InstInputs) {
792 // No name -> not interesting.
793 if (Pat->getName().empty()) {
795 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
796 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
797 I->error("Input " + DI->getDef()->getName() + " must be named!");
805 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
806 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
809 assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
810 Rec = Pat->getOperator();
813 TreePatternNode *&Slot = InstInputs[Pat->getName()];
818 if (Slot->isLeaf()) {
819 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
821 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
822 SlotRec = Slot->getOperator();
825 // Ensure that the inputs agree if we've already seen this input.
827 I->error("All $" + Pat->getName() + " inputs must agree with each other");
828 if (Slot->getType() != Pat->getType())
829 I->error("All $" + Pat->getName() + " inputs must agree with each other");
834 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
835 /// part of "I", the instruction), computing the set of inputs and outputs of
836 /// the pattern. Report errors if we see anything naughty.
837 void DAGISelEmitter::
838 FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
839 std::map<std::string, TreePatternNode*> &InstInputs,
840 std::map<std::string, Record*> &InstResults) {
842 bool isUse = HandleUse(I, Pat, InstInputs);
843 if (!isUse && Pat->getTransformFn())
844 I->error("Cannot specify a transform function for a non-input value!");
846 } else if (Pat->getOperator()->getName() != "set") {
847 // If this is not a set, verify that the children nodes are not void typed,
849 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
850 if (Pat->getChild(i)->getType() == MVT::isVoid)
851 I->error("Cannot have void nodes inside of patterns!");
852 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults);
855 // If this is a non-leaf node with no children, treat it basically as if
856 // it were a leaf. This handles nodes like (imm).
858 if (Pat->getNumChildren() == 0)
859 isUse = HandleUse(I, Pat, InstInputs);
861 if (!isUse && Pat->getTransformFn())
862 I->error("Cannot specify a transform function for a non-input value!");
866 // Otherwise, this is a set, validate and collect instruction results.
867 if (Pat->getNumChildren() == 0)
868 I->error("set requires operands!");
869 else if (Pat->getNumChildren() & 1)
870 I->error("set requires an even number of operands");
872 if (Pat->getTransformFn())
873 I->error("Cannot specify a transform function on a set node!");
875 // Check the set destinations.
876 unsigned NumValues = Pat->getNumChildren()/2;
877 for (unsigned i = 0; i != NumValues; ++i) {
878 TreePatternNode *Dest = Pat->getChild(i);
880 I->error("set destination should be a virtual register!");
882 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
884 I->error("set destination should be a virtual register!");
886 if (!Val->getDef()->isSubClassOf("RegisterClass"))
887 I->error("set destination should be a virtual register!");
888 if (Dest->getName().empty())
889 I->error("set destination must have a name!");
890 if (InstResults.count(Dest->getName()))
891 I->error("cannot set '" + Dest->getName() +"' multiple times");
892 InstResults[Dest->getName()] = Val->getDef();
894 // Verify and collect info from the computation.
895 FindPatternInputsAndOutputs(I, Pat->getChild(i+NumValues),
896 InstInputs, InstResults);
901 /// ParseInstructions - Parse all of the instructions, inlining and resolving
902 /// any fragments involved. This populates the Instructions list with fully
903 /// resolved instructions.
904 void DAGISelEmitter::ParseInstructions() {
905 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
907 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
908 if (!dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
909 continue; // no pattern yet, ignore it.
911 ListInit *LI = Instrs[i]->getValueAsListInit("Pattern");
912 if (LI->getSize() == 0) continue; // no pattern.
914 // Parse the instruction.
915 TreePattern *I = new TreePattern(Instrs[i], LI, *this);
916 // Inline pattern fragments into it.
917 I->InlinePatternFragments();
919 // Infer as many types as possible. If we cannot infer all of them, we can
920 // never do anything with this instruction pattern: report it to the user.
921 if (!I->InferAllTypes())
922 I->error("Could not infer all types in pattern!");
924 // InstInputs - Keep track of all of the inputs of the instruction, along
925 // with the record they are declared as.
926 std::map<std::string, TreePatternNode*> InstInputs;
928 // InstResults - Keep track of all the virtual registers that are 'set'
929 // in the instruction, including what reg class they are.
930 std::map<std::string, Record*> InstResults;
932 // Verify that the top-level forms in the instruction are of void type, and
933 // fill in the InstResults map.
934 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
935 TreePatternNode *Pat = I->getTree(j);
936 if (Pat->getType() != MVT::isVoid) {
938 I->error("Top-level forms in instruction pattern should have"
942 // Find inputs and outputs, and verify the structure of the uses/defs.
943 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults);
946 // Now that we have inputs and outputs of the pattern, inspect the operands
947 // list for the instruction. This determines the order that operands are
948 // added to the machine instruction the node corresponds to.
949 unsigned NumResults = InstResults.size();
951 // Parse the operands list from the (ops) list, validating it.
952 std::vector<std::string> &Args = I->getArgList();
953 assert(Args.empty() && "Args list should still be empty here!");
954 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
956 // Check that all of the results occur first in the list.
957 std::vector<MVT::ValueType> ResultTypes;
958 for (unsigned i = 0; i != NumResults; ++i) {
959 if (i == CGI.OperandList.size())
960 I->error("'" + InstResults.begin()->first +
961 "' set but does not appear in operand list!");
962 const std::string &OpName = CGI.OperandList[i].Name;
964 // Check that it exists in InstResults.
965 Record *R = InstResults[OpName];
967 I->error("Operand $" + OpName + " should be a set destination: all "
968 "outputs must occur before inputs in operand list!");
970 if (CGI.OperandList[i].Rec != R)
971 I->error("Operand $" + OpName + " class mismatch!");
973 // Remember the return type.
974 ResultTypes.push_back(CGI.OperandList[i].Ty);
976 // Okay, this one checks out.
977 InstResults.erase(OpName);
980 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
981 // the copy while we're checking the inputs.
982 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
984 std::vector<TreePatternNode*> ResultNodeOperands;
985 std::vector<MVT::ValueType> OperandTypes;
986 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
987 const std::string &OpName = CGI.OperandList[i].Name;
989 I->error("Operand #" + utostr(i) + " in operands list has no name!");
991 if (!InstInputsCheck.count(OpName))
992 I->error("Operand $" + OpName +
993 " does not appear in the instruction pattern");
994 TreePatternNode *InVal = InstInputsCheck[OpName];
995 InstInputsCheck.erase(OpName); // It occurred, remove from map.
996 if (CGI.OperandList[i].Ty != InVal->getType())
997 I->error("Operand $" + OpName +
998 "'s type disagrees between the operand and pattern");
999 OperandTypes.push_back(InVal->getType());
1001 // Construct the result for the dest-pattern operand list.
1002 TreePatternNode *OpNode = InVal->clone();
1004 // No predicate is useful on the result.
1005 OpNode->setPredicateFn("");
1007 // Promote the xform function to be an explicit node if set.
1008 if (Record *Xform = OpNode->getTransformFn()) {
1009 OpNode->setTransformFn(0);
1010 std::vector<TreePatternNode*> Children;
1011 Children.push_back(OpNode);
1012 OpNode = new TreePatternNode(Xform, Children);
1015 ResultNodeOperands.push_back(OpNode);
1018 if (!InstInputsCheck.empty())
1019 I->error("Input operand $" + InstInputsCheck.begin()->first +
1020 " occurs in pattern but not in operands list!");
1022 TreePatternNode *ResultPattern =
1023 new TreePatternNode(I->getRecord(), ResultNodeOperands);
1025 // Create and insert the instruction.
1026 DAGInstruction TheInst(I, ResultTypes, OperandTypes);
1027 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
1029 // Use a temporary tree pattern to infer all types and make sure that the
1030 // constructed result is correct. This depends on the instruction already
1031 // being inserted into the Instructions map.
1032 TreePattern Temp(I->getRecord(), ResultPattern, *this);
1033 Temp.InferAllTypes();
1035 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
1036 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
1041 // If we can, convert the instructions to be patterns that are matched!
1042 for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
1043 E = Instructions.end(); II != E; ++II) {
1044 TreePattern *I = II->second.getPattern();
1046 if (I->getNumTrees() != 1) {
1047 std::cerr << "CANNOT HANDLE: " << I->getRecord()->getName() << " yet!";
1050 TreePatternNode *Pattern = I->getTree(0);
1051 if (Pattern->getOperator()->getName() != "set")
1052 continue; // Not a set (store or something?)
1054 if (Pattern->getNumChildren() != 2)
1055 continue; // Not a set of a single value (not handled so far)
1057 TreePatternNode *SrcPattern = Pattern->getChild(1)->clone();
1060 if (!SrcPattern->canPatternMatch(Reason, *this))
1061 I->error("Instruction can never match: " + Reason);
1063 TreePatternNode *DstPattern = II->second.getResultPattern();
1064 PatternsToMatch.push_back(std::make_pair(SrcPattern, DstPattern));
1068 void DAGISelEmitter::ParsePatterns() {
1069 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
1071 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1072 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
1073 TreePattern *Pattern = new TreePattern(Patterns[i], Tree, *this);
1075 // Inline pattern fragments into it.
1076 Pattern->InlinePatternFragments();
1078 // Infer as many types as possible. If we cannot infer all of them, we can
1079 // never do anything with this pattern: report it to the user.
1080 if (!Pattern->InferAllTypes())
1081 Pattern->error("Could not infer all types in pattern!");
1083 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
1084 if (LI->getSize() == 0) continue; // no pattern.
1086 // Parse the instruction.
1087 TreePattern *Result = new TreePattern(Patterns[i], LI, *this);
1089 // Inline pattern fragments into it.
1090 Result->InlinePatternFragments();
1092 // Infer as many types as possible. If we cannot infer all of them, we can
1093 // never do anything with this pattern: report it to the user.
1094 if (!Result->InferAllTypes())
1095 Result->error("Could not infer all types in pattern result!");
1097 if (Result->getNumTrees() != 1)
1098 Result->error("Cannot handle instructions producing instructions "
1099 "with temporaries yet!");
1102 if (!Pattern->getOnlyTree()->canPatternMatch(Reason, *this))
1103 Pattern->error("Pattern can never match: " + Reason);
1105 PatternsToMatch.push_back(std::make_pair(Pattern->getOnlyTree(),
1106 Result->getOnlyTree()));
1110 /// CombineChildVariants - Given a bunch of permutations of each child of the
1111 /// 'operator' node, put them together in all possible ways.
1112 static void CombineChildVariants(TreePatternNode *Orig,
1113 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
1114 std::vector<TreePatternNode*> &OutVariants,
1115 DAGISelEmitter &ISE) {
1116 // Make sure that each operand has at least one variant to choose from.
1117 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1118 if (ChildVariants[i].empty())
1121 // The end result is an all-pairs construction of the resultant pattern.
1122 std::vector<unsigned> Idxs;
1123 Idxs.resize(ChildVariants.size());
1124 bool NotDone = true;
1126 // Create the variant and add it to the output list.
1127 std::vector<TreePatternNode*> NewChildren;
1128 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1129 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
1130 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
1132 // Copy over properties.
1133 R->setName(Orig->getName());
1134 R->setPredicateFn(Orig->getPredicateFn());
1135 R->setTransformFn(Orig->getTransformFn());
1136 R->setType(Orig->getType());
1138 // If this pattern cannot every match, do not include it as a variant.
1139 std::string ErrString;
1140 if (!R->canPatternMatch(ErrString, ISE)) {
1143 bool AlreadyExists = false;
1145 // Scan to see if this pattern has already been emitted. We can get
1146 // duplication due to things like commuting:
1147 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
1148 // which are the same pattern. Ignore the dups.
1149 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
1150 if (R->isIsomorphicTo(OutVariants[i])) {
1151 AlreadyExists = true;
1158 OutVariants.push_back(R);
1161 // Increment indices to the next permutation.
1163 // Look for something we can increment without causing a wrap-around.
1164 for (unsigned IdxsIdx = 0; IdxsIdx != Idxs.size(); ++IdxsIdx) {
1165 if (++Idxs[IdxsIdx] < ChildVariants[IdxsIdx].size()) {
1166 NotDone = true; // Found something to increment.
1174 /// CombineChildVariants - A helper function for binary operators.
1176 static void CombineChildVariants(TreePatternNode *Orig,
1177 const std::vector<TreePatternNode*> &LHS,
1178 const std::vector<TreePatternNode*> &RHS,
1179 std::vector<TreePatternNode*> &OutVariants,
1180 DAGISelEmitter &ISE) {
1181 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1182 ChildVariants.push_back(LHS);
1183 ChildVariants.push_back(RHS);
1184 CombineChildVariants(Orig, ChildVariants, OutVariants, ISE);
1188 static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
1189 std::vector<TreePatternNode *> &Children) {
1190 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
1191 Record *Operator = N->getOperator();
1193 // Only permit raw nodes.
1194 if (!N->getName().empty() || !N->getPredicateFn().empty() ||
1195 N->getTransformFn()) {
1196 Children.push_back(N);
1200 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
1201 Children.push_back(N->getChild(0));
1203 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
1205 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
1206 Children.push_back(N->getChild(1));
1208 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
1211 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
1212 /// the (potentially recursive) pattern by using algebraic laws.
1214 static void GenerateVariantsOf(TreePatternNode *N,
1215 std::vector<TreePatternNode*> &OutVariants,
1216 DAGISelEmitter &ISE) {
1217 // We cannot permute leaves.
1219 OutVariants.push_back(N);
1223 // Look up interesting info about the node.
1224 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(N->getOperator());
1226 // If this node is associative, reassociate.
1227 if (NodeInfo.hasProperty(SDNodeInfo::SDNPAssociative)) {
1228 // Reassociate by pulling together all of the linked operators
1229 std::vector<TreePatternNode*> MaximalChildren;
1230 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
1232 // Only handle child sizes of 3. Otherwise we'll end up trying too many
1234 if (MaximalChildren.size() == 3) {
1235 // Find the variants of all of our maximal children.
1236 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
1237 GenerateVariantsOf(MaximalChildren[0], AVariants, ISE);
1238 GenerateVariantsOf(MaximalChildren[1], BVariants, ISE);
1239 GenerateVariantsOf(MaximalChildren[2], CVariants, ISE);
1241 // There are only two ways we can permute the tree:
1242 // (A op B) op C and A op (B op C)
1243 // Within these forms, we can also permute A/B/C.
1245 // Generate legal pair permutations of A/B/C.
1246 std::vector<TreePatternNode*> ABVariants;
1247 std::vector<TreePatternNode*> BAVariants;
1248 std::vector<TreePatternNode*> ACVariants;
1249 std::vector<TreePatternNode*> CAVariants;
1250 std::vector<TreePatternNode*> BCVariants;
1251 std::vector<TreePatternNode*> CBVariants;
1252 CombineChildVariants(N, AVariants, BVariants, ABVariants, ISE);
1253 CombineChildVariants(N, BVariants, AVariants, BAVariants, ISE);
1254 CombineChildVariants(N, AVariants, CVariants, ACVariants, ISE);
1255 CombineChildVariants(N, CVariants, AVariants, CAVariants, ISE);
1256 CombineChildVariants(N, BVariants, CVariants, BCVariants, ISE);
1257 CombineChildVariants(N, CVariants, BVariants, CBVariants, ISE);
1259 // Combine those into the result: (x op x) op x
1260 CombineChildVariants(N, ABVariants, CVariants, OutVariants, ISE);
1261 CombineChildVariants(N, BAVariants, CVariants, OutVariants, ISE);
1262 CombineChildVariants(N, ACVariants, BVariants, OutVariants, ISE);
1263 CombineChildVariants(N, CAVariants, BVariants, OutVariants, ISE);
1264 CombineChildVariants(N, BCVariants, AVariants, OutVariants, ISE);
1265 CombineChildVariants(N, CBVariants, AVariants, OutVariants, ISE);
1267 // Combine those into the result: x op (x op x)
1268 CombineChildVariants(N, CVariants, ABVariants, OutVariants, ISE);
1269 CombineChildVariants(N, CVariants, BAVariants, OutVariants, ISE);
1270 CombineChildVariants(N, BVariants, ACVariants, OutVariants, ISE);
1271 CombineChildVariants(N, BVariants, CAVariants, OutVariants, ISE);
1272 CombineChildVariants(N, AVariants, BCVariants, OutVariants, ISE);
1273 CombineChildVariants(N, AVariants, CBVariants, OutVariants, ISE);
1278 // Compute permutations of all children.
1279 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1280 ChildVariants.resize(N->getNumChildren());
1281 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1282 GenerateVariantsOf(N->getChild(i), ChildVariants[i], ISE);
1284 // Build all permutations based on how the children were formed.
1285 CombineChildVariants(N, ChildVariants, OutVariants, ISE);
1287 // If this node is commutative, consider the commuted order.
1288 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
1289 assert(N->getNumChildren()==2 &&"Commutative but doesn't have 2 children!");
1290 // Consider the commuted order.
1291 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
1297 // GenerateVariants - Generate variants. For example, commutative patterns can
1298 // match multiple ways. Add them to PatternsToMatch as well.
1299 void DAGISelEmitter::GenerateVariants() {
1301 DEBUG(std::cerr << "Generating instruction variants.\n");
1303 // Loop over all of the patterns we've collected, checking to see if we can
1304 // generate variants of the instruction, through the exploitation of
1305 // identities. This permits the target to provide agressive matching without
1306 // the .td file having to contain tons of variants of instructions.
1308 // Note that this loop adds new patterns to the PatternsToMatch list, but we
1309 // intentionally do not reconsider these. Any variants of added patterns have
1310 // already been added.
1312 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
1313 std::vector<TreePatternNode*> Variants;
1314 GenerateVariantsOf(PatternsToMatch[i].first, Variants, *this);
1316 assert(!Variants.empty() && "Must create at least original variant!");
1317 Variants.erase(Variants.begin()); // Remove the original pattern.
1319 if (Variants.empty()) // No variants for this pattern.
1322 DEBUG(std::cerr << "FOUND VARIANTS OF: ";
1323 PatternsToMatch[i].first->dump();
1326 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
1327 TreePatternNode *Variant = Variants[v];
1329 DEBUG(std::cerr << " VAR#" << v << ": ";
1333 // Scan to see if an instruction or explicit pattern already matches this.
1334 bool AlreadyExists = false;
1335 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
1336 // Check to see if this variant already exists.
1337 if (Variant->isIsomorphicTo(PatternsToMatch[p].first)) {
1338 DEBUG(std::cerr << " *** ALREADY EXISTS, ignoring variant.\n");
1339 AlreadyExists = true;
1343 // If we already have it, ignore the variant.
1344 if (AlreadyExists) continue;
1346 // Otherwise, add it to the list of patterns we have.
1347 PatternsToMatch.push_back(std::make_pair(Variant,
1348 PatternsToMatch[i].second));
1351 DEBUG(std::cerr << "\n");
1356 /// getPatternSize - Return the 'size' of this pattern. We want to match large
1357 /// patterns before small ones. This is used to determine the size of a
1359 static unsigned getPatternSize(TreePatternNode *P) {
1360 assert(MVT::isInteger(P->getType()) || MVT::isFloatingPoint(P->getType()) &&
1361 "Not a valid pattern node to size!");
1362 unsigned Size = 1; // The node itself.
1364 // Count children in the count if they are also nodes.
1365 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
1366 TreePatternNode *Child = P->getChild(i);
1367 if (!Child->isLeaf() && Child->getType() != MVT::Other)
1368 Size += getPatternSize(Child);
1374 /// getResultPatternCost - Compute the number of instructions for this pattern.
1375 /// This is a temporary hack. We should really include the instruction
1376 /// latencies in this calculation.
1377 static unsigned getResultPatternCost(TreePatternNode *P) {
1378 if (P->isLeaf()) return 0;
1380 unsigned Cost = P->getOperator()->isSubClassOf("Instruction");
1381 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
1382 Cost += getResultPatternCost(P->getChild(i));
1386 // PatternSortingPredicate - return true if we prefer to match LHS before RHS.
1387 // In particular, we want to match maximal patterns first and lowest cost within
1388 // a particular complexity first.
1389 struct PatternSortingPredicate {
1390 bool operator()(DAGISelEmitter::PatternToMatch *LHS,
1391 DAGISelEmitter::PatternToMatch *RHS) {
1392 unsigned LHSSize = getPatternSize(LHS->first);
1393 unsigned RHSSize = getPatternSize(RHS->first);
1394 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
1395 if (LHSSize < RHSSize) return false;
1397 // If the patterns have equal complexity, compare generated instruction cost
1398 return getResultPatternCost(LHS->second) <getResultPatternCost(RHS->second);
1402 /// EmitMatchForPattern - Emit a matcher for N, going to the label for PatternNo
1403 /// if the match fails. At this point, we already know that the opcode for N
1404 /// matches, and the SDNode for the result has the RootName specified name.
1405 void DAGISelEmitter::EmitMatchForPattern(TreePatternNode *N,
1406 const std::string &RootName,
1407 std::map<std::string,std::string> &VarMap,
1408 unsigned PatternNo, std::ostream &OS) {
1409 assert(!N->isLeaf() && "Cannot match against a leaf!");
1411 // If this node has a name associated with it, capture it in VarMap. If
1412 // we already saw this in the pattern, emit code to verify dagness.
1413 if (!N->getName().empty()) {
1414 std::string &VarMapEntry = VarMap[N->getName()];
1415 if (VarMapEntry.empty()) {
1416 VarMapEntry = RootName;
1418 // If we get here, this is a second reference to a specific name. Since
1419 // we already have checked that the first reference is valid, we don't
1420 // have to recursively match it, just check that it's the same as the
1421 // previously named thing.
1422 OS << " if (" << VarMapEntry << " != " << RootName
1423 << ") goto P" << PatternNo << "Fail;\n";
1428 // Emit code to load the child nodes and match their contents recursively.
1429 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
1430 OS << " SDOperand " << RootName << i <<" = " << RootName
1431 << ".getOperand(" << i << ");\n";
1432 TreePatternNode *Child = N->getChild(i);
1434 if (!Child->isLeaf()) {
1435 // If it's not a leaf, recursively match.
1436 const SDNodeInfo &CInfo = getSDNodeInfo(Child->getOperator());
1437 OS << " if (" << RootName << i << ".getOpcode() != "
1438 << CInfo.getEnumName() << ") goto P" << PatternNo << "Fail;\n";
1439 EmitMatchForPattern(Child, RootName + utostr(i), VarMap, PatternNo, OS);
1441 // If this child has a name associated with it, capture it in VarMap. If
1442 // we already saw this in the pattern, emit code to verify dagness.
1443 if (!Child->getName().empty()) {
1444 std::string &VarMapEntry = VarMap[Child->getName()];
1445 if (VarMapEntry.empty()) {
1446 VarMapEntry = RootName + utostr(i);
1448 // If we get here, this is a second reference to a specific name. Since
1449 // we already have checked that the first reference is valid, we don't
1450 // have to recursively match it, just check that it's the same as the
1451 // previously named thing.
1452 OS << " if (" << VarMapEntry << " != " << RootName << i
1453 << ") goto P" << PatternNo << "Fail;\n";
1458 // Handle leaves of various types.
1459 Init *LeafVal = Child->getLeafValue();
1460 Record *LeafRec = dynamic_cast<DefInit*>(LeafVal)->getDef();
1461 if (LeafRec->isSubClassOf("RegisterClass")) {
1462 // Handle register references. Nothing to do here.
1463 } else if (LeafRec->isSubClassOf("ValueType")) {
1464 // Make sure this is the specified value type.
1465 OS << " if (cast<VTSDNode>(" << RootName << i << ")->getVT() != "
1466 << "MVT::" << LeafRec->getName() << ") goto P" << PatternNo
1470 assert(0 && "Unknown leaf type!");
1475 // If there is a node predicate for this, emit the call.
1476 if (!N->getPredicateFn().empty())
1477 OS << " if (!" << N->getPredicateFn() << "(" << RootName
1478 << ".Val)) goto P" << PatternNo << "Fail;\n";
1481 /// CodeGenPatternResult - Emit the action for a pattern. Now that it has
1482 /// matched, we actually have to build a DAG!
1483 unsigned DAGISelEmitter::
1484 CodeGenPatternResult(TreePatternNode *N, unsigned &Ctr,
1485 std::map<std::string,std::string> &VariableMap,
1487 // This is something selected from the pattern we matched.
1488 if (!N->getName().empty()) {
1489 std::string &Val = VariableMap[N->getName()];
1490 assert(!Val.empty() &&
1491 "Variable referenced but not defined and not caught earlier!");
1492 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
1493 // Already selected this operand, just return the tmpval.
1494 return atoi(Val.c_str()+3);
1497 unsigned ResNo = Ctr++;
1498 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
1499 switch (N->getType()) {
1500 default: assert(0 && "Unknown type for constant node!");
1501 case MVT::i1: OS << " bool Tmp"; break;
1502 case MVT::i8: OS << " unsigned char Tmp"; break;
1503 case MVT::i16: OS << " unsigned short Tmp"; break;
1504 case MVT::i32: OS << " unsigned Tmp"; break;
1505 case MVT::i64: OS << " uint64_t Tmp"; break;
1507 OS << ResNo << "C = cast<ConstantSDNode>(" << Val << ")->getValue();\n";
1508 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getTargetConstant(Tmp"
1509 << ResNo << "C, MVT::" << getEnumName(N->getType()) << ");\n";
1511 OS << " SDOperand Tmp" << ResNo << " = Select(" << Val << ");\n";
1513 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
1514 // value if used multiple times by this pattern result.
1515 Val = "Tmp"+utostr(ResNo);
1521 assert(0 && "Unknown leaf type!");
1525 Record *Op = N->getOperator();
1526 if (Op->isSubClassOf("Instruction")) {
1527 // Emit all of the operands.
1528 std::vector<unsigned> Ops;
1529 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1530 Ops.push_back(CodeGenPatternResult(N->getChild(i), Ctr, VariableMap, OS));
1532 CodeGenInstruction &II = Target.getInstruction(Op->getName());
1533 unsigned ResNo = Ctr++;
1535 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getTargetNode("
1536 << II.Namespace << "::" << II.TheDef->getName() << ", MVT::"
1537 << getEnumName(N->getType());
1538 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1539 OS << ", Tmp" << Ops[i];
1542 } else if (Op->isSubClassOf("SDNodeXForm")) {
1543 assert(N->getNumChildren() == 1 && "node xform should have one child!");
1544 unsigned OpVal = CodeGenPatternResult(N->getChild(0), Ctr, VariableMap, OS);
1546 unsigned ResNo = Ctr++;
1547 OS << " SDOperand Tmp" << ResNo << " = Transform_" << Op->getName()
1548 << "(Tmp" << OpVal << ".Val);\n";
1552 assert(0 && "Unknown node in result pattern!");
1557 /// RemoveAllTypes - A quick recursive walk over a pattern which removes all
1558 /// type information from it.
1559 static void RemoveAllTypes(TreePatternNode *N) {
1560 N->setType(MVT::LAST_VALUETYPE);
1562 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1563 RemoveAllTypes(N->getChild(i));
1566 /// EmitCodeForPattern - Given a pattern to match, emit code to the specified
1567 /// stream to match the pattern, and generate the code for the match if it
1569 void DAGISelEmitter::EmitCodeForPattern(PatternToMatch &Pattern,
1571 static unsigned PatternCount = 0;
1572 unsigned PatternNo = PatternCount++;
1573 OS << " { // Pattern #" << PatternNo << ": ";
1574 Pattern.first->print(OS);
1575 OS << "\n // Emits: ";
1576 Pattern.second->print(OS);
1578 OS << " // Pattern complexity = " << getPatternSize(Pattern.first)
1579 << " cost = " << getResultPatternCost(Pattern.second) << "\n";
1581 // Emit the matcher, capturing named arguments in VariableMap.
1582 std::map<std::string,std::string> VariableMap;
1583 EmitMatchForPattern(Pattern.first, "N", VariableMap, PatternNo, OS);
1585 // TP - Get *SOME* tree pattern, we don't care which.
1586 TreePattern &TP = *PatternFragments.begin()->second;
1588 // At this point, we know that we structurally match the pattern, but the
1589 // types of the nodes may not match. Figure out the fewest number of type
1590 // comparisons we need to emit. For example, if there is only one integer
1591 // type supported by a target, there should be no type comparisons at all for
1592 // integer patterns!
1594 // To figure out the fewest number of type checks needed, clone the pattern,
1595 // remove the types, then perform type inference on the pattern as a whole.
1596 // If there are unresolved types, emit an explicit check for those types,
1597 // apply the type to the tree, then rerun type inference. Iterate until all
1598 // types are resolved.
1600 TreePatternNode *Pat = Pattern.first->clone();
1601 RemoveAllTypes(Pat);
1602 bool MadeChange = true;
1605 MadeChange = Pat->ApplyTypeConstraints(TP,true/*Ignore reg constraints*/);
1607 assert(0 && "Error: could not find consistent types for something we"
1608 " already decided was ok!");
1612 if (!Pat->ContainsUnresolvedType()) {
1614 unsigned Res = CodeGenPatternResult(Pattern.second, TmpNo, VariableMap, OS);
1616 // Add the result to the map if it has multiple uses.
1617 OS << " if (!N.Val->hasOneUse()) CodeGenMap[N] = Tmp" << Res << ";\n";
1618 OS << " return Tmp" << Res << ";\n";
1623 OS << " }\n P" << PatternNo << "Fail:\n";
1628 /// CompareByRecordName - An ordering predicate that implements less-than by
1629 /// comparing the names records.
1630 struct CompareByRecordName {
1631 bool operator()(const Record *LHS, const Record *RHS) const {
1632 // Sort by name first.
1633 if (LHS->getName() < RHS->getName()) return true;
1634 // If both names are equal, sort by pointer.
1635 return LHS->getName() == RHS->getName() && LHS < RHS;
1640 void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
1641 // Emit boilerplate.
1642 OS << "// The main instruction selector code.\n"
1643 << "SDOperand SelectCode(SDOperand N) {\n"
1644 << " if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
1645 << " N.getOpcode() < PPCISD::FIRST_NUMBER)\n"
1646 << " return N; // Already selected.\n\n"
1647 << " if (!N.Val->hasOneUse()) {\n"
1648 << " std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(N);\n"
1649 << " if (CGMI != CodeGenMap.end()) return CGMI->second;\n"
1651 << " switch (N.getOpcode()) {\n"
1652 << " default: break;\n"
1653 << " case ISD::EntryToken: // These leaves remain the same.\n"
1655 << " case ISD::AssertSext:\n"
1656 << " case ISD::AssertZext: {\n"
1657 << " SDOperand Tmp0 = Select(N.getOperand(0));\n"
1658 << " if (!N.Val->hasOneUse()) CodeGenMap[N] = Tmp0;\n"
1659 << " return Tmp0;\n"
1662 // Group the patterns by their top-level opcodes.
1663 std::map<Record*, std::vector<PatternToMatch*>,
1664 CompareByRecordName> PatternsByOpcode;
1665 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i)
1666 PatternsByOpcode[PatternsToMatch[i].first->getOperator()]
1667 .push_back(&PatternsToMatch[i]);
1669 // Loop over all of the case statements.
1670 for (std::map<Record*, std::vector<PatternToMatch*>,
1671 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
1672 E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
1673 const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
1674 std::vector<PatternToMatch*> &Patterns = PBOI->second;
1676 OS << " case " << OpcodeInfo.getEnumName() << ":\n";
1678 // We want to emit all of the matching code now. However, we want to emit
1679 // the matches in order of minimal cost. Sort the patterns so the least
1680 // cost one is at the start.
1681 std::stable_sort(Patterns.begin(), Patterns.end(),
1682 PatternSortingPredicate());
1684 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
1685 EmitCodeForPattern(*Patterns[i], OS);
1686 OS << " break;\n\n";
1690 OS << " } // end of big switch.\n\n"
1691 << " std::cerr << \"Cannot yet select: \";\n"
1692 << " N.Val->dump();\n"
1693 << " std::cerr << '\\n';\n"
1698 void DAGISelEmitter::run(std::ostream &OS) {
1699 EmitSourceFileHeader("DAG Instruction Selector for the " + Target.getName() +
1702 OS << "// *** NOTE: This file is #included into the middle of the target\n"
1703 << "// *** instruction selector class. These functions are really "
1706 OS << "// Instance var to keep track of multiply used nodes that have \n"
1707 << "// already been selected.\n"
1708 << "std::map<SDOperand, SDOperand> CodeGenMap;\n";
1711 ParseNodeTransforms(OS);
1712 ParsePatternFragments(OS);
1713 ParseInstructions();
1716 // Generate variants. For example, commutative patterns can match
1717 // multiple ways. Add them to PatternsToMatch as well.
1721 DEBUG(std::cerr << "\n\nALL PATTERNS TO MATCH:\n\n";
1722 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
1723 std::cerr << "PATTERN: "; PatternsToMatch[i].first->dump();
1724 std::cerr << "\nRESULT: ";PatternsToMatch[i].second->dump();
1728 // At this point, we have full information about the 'Patterns' we need to
1729 // parse, both implicitly from instructions as well as from explicit pattern
1730 // definitions. Emit the resultant instruction selector.
1731 EmitInstructionSelector(OS);
1733 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
1734 E = PatternFragments.end(); I != E; ++I)
1736 PatternFragments.clear();
1738 Instructions.clear();