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"
21 //===----------------------------------------------------------------------===//
22 // SDTypeConstraint implementation
25 SDTypeConstraint::SDTypeConstraint(Record *R) {
26 OperandNo = R->getValueAsInt("OperandNum");
28 if (R->isSubClassOf("SDTCisVT")) {
29 ConstraintType = SDTCisVT;
30 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
31 } else if (R->isSubClassOf("SDTCisInt")) {
32 ConstraintType = SDTCisInt;
33 } else if (R->isSubClassOf("SDTCisFP")) {
34 ConstraintType = SDTCisFP;
35 } else if (R->isSubClassOf("SDTCisSameAs")) {
36 ConstraintType = SDTCisSameAs;
37 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
38 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
39 ConstraintType = SDTCisVTSmallerThanOp;
40 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
41 R->getValueAsInt("OtherOperandNum");
43 std::cerr << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
48 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
49 /// N, which has NumResults results.
50 TreePatternNode *SDTypeConstraint::getOperandNum(unsigned OpNo,
52 unsigned NumResults) const {
53 assert(NumResults == 1 && "We only work with single result nodes so far!");
55 if (OpNo < NumResults)
56 return N; // FIXME: need value #
58 return N->getChild(OpNo-NumResults);
61 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
62 /// constraint to the nodes operands. This returns true if it makes a
63 /// change, false otherwise. If a type contradiction is found, throw an
65 bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
66 const SDNodeInfo &NodeInfo,
67 TreePattern &TP) const {
68 unsigned NumResults = NodeInfo.getNumResults();
69 assert(NumResults == 1 && "We only work with single result nodes so far!");
71 // Check that the number of operands is sane.
72 if (NodeInfo.getNumOperands() >= 0) {
73 if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands())
74 TP.error(N->getOperator()->getName() + " node requires exactly " +
75 itostr(NodeInfo.getNumOperands()) + " operands!");
78 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NumResults);
80 switch (ConstraintType) {
81 default: assert(0 && "Unknown constraint type!");
83 // Operand must be a particular type.
84 return NodeToApply->UpdateNodeType(x.SDTCisVT_Info.VT, TP);
86 if (NodeToApply->hasTypeSet() && !MVT::isInteger(NodeToApply->getType()))
87 NodeToApply->UpdateNodeType(MVT::i1, TP); // throw an error.
89 // FIXME: can tell from the target if there is only one Int type supported.
92 if (NodeToApply->hasTypeSet() &&
93 !MVT::isFloatingPoint(NodeToApply->getType()))
94 NodeToApply->UpdateNodeType(MVT::f32, TP); // throw an error.
95 // FIXME: can tell from the target if there is only one FP type supported.
98 TreePatternNode *OtherNode =
99 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NumResults);
100 return NodeToApply->UpdateNodeType(OtherNode->getType(), TP) |
101 OtherNode->UpdateNodeType(NodeToApply->getType(), TP);
103 case SDTCisVTSmallerThanOp: {
104 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
105 // have an integer type that is smaller than the VT.
106 if (!NodeToApply->isLeaf() ||
107 !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
108 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
109 ->isSubClassOf("ValueType"))
110 TP.error(N->getOperator()->getName() + " expects a VT operand!");
112 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
113 if (!MVT::isInteger(VT))
114 TP.error(N->getOperator()->getName() + " VT operand must be integer!");
116 TreePatternNode *OtherNode =
117 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N,NumResults);
118 if (OtherNode->hasTypeSet() &&
119 (!MVT::isInteger(OtherNode->getType()) ||
120 OtherNode->getType() <= VT))
121 OtherNode->UpdateNodeType(MVT::Other, TP); // Throw an error.
129 //===----------------------------------------------------------------------===//
130 // SDNodeInfo implementation
132 SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
133 EnumName = R->getValueAsString("Opcode");
134 SDClassName = R->getValueAsString("SDClass");
135 Record *TypeProfile = R->getValueAsDef("TypeProfile");
136 NumResults = TypeProfile->getValueAsInt("NumResults");
137 NumOperands = TypeProfile->getValueAsInt("NumOperands");
139 // Parse the type constraints.
140 ListInit *Constraints = TypeProfile->getValueAsListInit("Constraints");
141 for (unsigned i = 0, e = Constraints->getSize(); i != e; ++i) {
142 assert(dynamic_cast<DefInit*>(Constraints->getElement(i)) &&
143 "Constraints list should contain constraint definitions!");
145 static_cast<DefInit*>(Constraints->getElement(i))->getDef();
146 TypeConstraints.push_back(Constraint);
150 //===----------------------------------------------------------------------===//
151 // TreePatternNode implementation
154 TreePatternNode::~TreePatternNode() {
155 #if 0 // FIXME: implement refcounted tree nodes!
156 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
161 /// UpdateNodeType - Set the node type of N to VT if VT contains
162 /// information. If N already contains a conflicting type, then throw an
163 /// exception. This returns true if any information was updated.
165 bool TreePatternNode::UpdateNodeType(MVT::ValueType VT, TreePattern &TP) {
166 if (VT == MVT::LAST_VALUETYPE || getType() == VT) return false;
167 if (getType() == MVT::LAST_VALUETYPE) {
172 TP.error("Type inference contradiction found in node " +
173 getOperator()->getName() + "!");
174 return true; // unreachable
178 void TreePatternNode::print(std::ostream &OS) const {
180 OS << *getLeafValue();
182 OS << "(" << getOperator()->getName();
185 if (getType() == MVT::Other)
187 else if (getType() == MVT::LAST_VALUETYPE)
190 OS << ":" << getType();
193 if (getNumChildren() != 0) {
195 getChild(0)->print(OS);
196 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
198 getChild(i)->print(OS);
204 if (!PredicateFn.empty())
205 OS << "<<P:" << PredicateFn << ">>";
207 OS << "<<X:" << TransformFn->getName() << ">>";
208 if (!getName().empty())
209 OS << ":$" << getName();
212 void TreePatternNode::dump() const {
216 /// clone - Make a copy of this tree and all of its children.
218 TreePatternNode *TreePatternNode::clone() const {
219 TreePatternNode *New;
221 New = new TreePatternNode(getLeafValue());
223 std::vector<TreePatternNode*> CChildren;
224 CChildren.reserve(Children.size());
225 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
226 CChildren.push_back(getChild(i)->clone());
227 New = new TreePatternNode(getOperator(), CChildren);
229 New->setName(getName());
230 New->setType(getType());
231 New->setPredicateFn(getPredicateFn());
232 New->setTransformFn(getTransformFn());
236 /// SubstituteFormalArguments - Replace the formal arguments in this tree
237 /// with actual values specified by ArgMap.
238 void TreePatternNode::
239 SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
240 if (isLeaf()) return;
242 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
243 TreePatternNode *Child = getChild(i);
244 if (Child->isLeaf()) {
245 Init *Val = Child->getLeafValue();
246 if (dynamic_cast<DefInit*>(Val) &&
247 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
248 // We found a use of a formal argument, replace it with its value.
249 Child = ArgMap[Child->getName()];
250 assert(Child && "Couldn't find formal argument!");
254 getChild(i)->SubstituteFormalArguments(ArgMap);
260 /// InlinePatternFragments - If this pattern refers to any pattern
261 /// fragments, inline them into place, giving us a pattern without any
262 /// PatFrag references.
263 TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
264 if (isLeaf()) return this; // nothing to do.
265 Record *Op = getOperator();
267 if (!Op->isSubClassOf("PatFrag")) {
268 // Just recursively inline children nodes.
269 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
270 setChild(i, getChild(i)->InlinePatternFragments(TP));
274 // Otherwise, we found a reference to a fragment. First, look up its
275 // TreePattern record.
276 TreePattern *Frag = TP.getDAGISelEmitter().getPatternFragment(Op);
278 // Verify that we are passing the right number of operands.
279 if (Frag->getNumArgs() != Children.size())
280 TP.error("'" + Op->getName() + "' fragment requires " +
281 utostr(Frag->getNumArgs()) + " operands!");
283 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
285 // Resolve formal arguments to their actual value.
286 if (Frag->getNumArgs()) {
287 // Compute the map of formal to actual arguments.
288 std::map<std::string, TreePatternNode*> ArgMap;
289 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
290 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
292 FragTree->SubstituteFormalArguments(ArgMap);
295 FragTree->setName(getName());
297 // Get a new copy of this fragment to stitch into here.
298 //delete this; // FIXME: implement refcounting!
302 /// ApplyTypeConstraints - Apply all of the type constraints relevent to
303 /// this node and its children in the tree. This returns true if it makes a
304 /// change, false otherwise. If a type contradiction is found, throw an
306 bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP) {
307 if (isLeaf()) return false;
309 // special handling for set, which isn't really an SDNode.
310 if (getOperator()->getName() == "set") {
311 assert (getNumChildren() == 2 && "Only handle 2 operand set's for now!");
312 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP);
313 MadeChange |= getChild(1)->ApplyTypeConstraints(TP);
315 // Types of operands must match.
316 MadeChange |= getChild(0)->UpdateNodeType(getChild(1)->getType(), TP);
317 MadeChange |= getChild(1)->UpdateNodeType(getChild(0)->getType(), TP);
318 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
320 } else if (getOperator()->isSubClassOf("SDNode")) {
321 const SDNodeInfo &NI = TP.getDAGISelEmitter().getSDNodeInfo(getOperator());
323 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
324 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
325 MadeChange |= getChild(i)->ApplyTypeConstraints(TP);
327 } else if (getOperator()->isSubClassOf("Instruction")) {
328 const DAGInstruction &Inst =
329 TP.getDAGISelEmitter().getInstruction(getOperator());
331 assert(Inst.getNumResults() == 1 && "Only supports one result instrs!");
332 // Apply the result type to the node
333 bool MadeChange = UpdateNodeType(Inst.getResultType(0), TP);
335 if (getNumChildren() != Inst.getNumOperands())
336 TP.error("Instruction '" + getOperator()->getName() + " expects " +
337 utostr(Inst.getNumOperands()) + " operands, not " +
338 utostr(getNumChildren()) + " operands!");
339 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
340 MadeChange |= getChild(i)->UpdateNodeType(Inst.getOperandType(i), TP);
341 MadeChange |= getChild(i)->ApplyTypeConstraints(TP);
345 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
347 // Node transforms always take one operand, and take and return the same
349 if (getNumChildren() != 1)
350 TP.error("Node transform '" + getOperator()->getName() +
351 "' requires one operand!");
352 bool MadeChange = UpdateNodeType(getChild(0)->getType(), TP);
353 MadeChange |= getChild(0)->UpdateNodeType(getType(), TP);
359 //===----------------------------------------------------------------------===//
360 // TreePattern implementation
363 TreePattern::TreePattern(Record *TheRec, ListInit *RawPat,
364 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
365 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
366 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
369 TreePattern::TreePattern(Record *TheRec, DagInit *Pat,
370 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
371 Trees.push_back(ParseTreePattern(Pat));
374 TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat,
375 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
376 Trees.push_back(Pat);
381 void TreePattern::error(const std::string &Msg) const {
383 throw "In " + TheRecord->getName() + ": " + Msg;
386 /// getIntrinsicType - Check to see if the specified record has an intrinsic
387 /// type which should be applied to it. This infer the type of register
388 /// references from the register file information, for example.
390 MVT::ValueType TreePattern::getIntrinsicType(Record *R) const {
391 // Check to see if this is a register or a register class...
392 if (R->isSubClassOf("RegisterClass"))
393 return getValueType(R->getValueAsDef("RegType"));
394 else if (R->isSubClassOf("PatFrag")) {
395 // Pattern fragment types will be resolved when they are inlined.
396 return MVT::LAST_VALUETYPE;
397 } else if (R->isSubClassOf("Register")) {
398 assert(0 && "Explicit registers not handled here yet!\n");
399 return MVT::LAST_VALUETYPE;
400 } else if (R->isSubClassOf("ValueType")) {
403 } else if (R->getName() == "node") {
405 return MVT::LAST_VALUETYPE;
408 error("Unknown value used: " + R->getName());
412 TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
413 Record *Operator = Dag->getNodeType();
415 if (Operator->isSubClassOf("ValueType")) {
416 // If the operator is a ValueType, then this must be "type cast" of a leaf
418 if (Dag->getNumArgs() != 1)
419 error("Type cast only valid for a leaf node!");
421 Init *Arg = Dag->getArg(0);
422 TreePatternNode *New;
423 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
424 New = new TreePatternNode(DI);
425 // If it's a regclass or something else known, set the type.
426 New->setType(getIntrinsicType(DI->getDef()));
427 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
428 New = ParseTreePattern(DI);
431 error("Unknown leaf value for tree pattern!");
435 // Apply the type cast.
436 New->UpdateNodeType(getValueType(Operator), *this);
440 // Verify that this is something that makes sense for an operator.
441 if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
442 !Operator->isSubClassOf("Instruction") &&
443 !Operator->isSubClassOf("SDNodeXForm") &&
444 Operator->getName() != "set")
445 error("Unrecognized node '" + Operator->getName() + "'!");
447 std::vector<TreePatternNode*> Children;
449 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
450 Init *Arg = Dag->getArg(i);
451 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
452 Children.push_back(ParseTreePattern(DI));
453 Children.back()->setName(Dag->getArgName(i));
454 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
455 Record *R = DefI->getDef();
456 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
457 // TreePatternNode if its own.
458 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
459 Dag->setArg(i, new DagInit(R,
460 std::vector<std::pair<Init*, std::string> >()));
461 --i; // Revisit this node...
463 TreePatternNode *Node = new TreePatternNode(DefI);
464 Node->setName(Dag->getArgName(i));
465 Children.push_back(Node);
467 // If it's a regclass or something else known, set the type.
468 Node->setType(getIntrinsicType(R));
471 if (R->getName() == "node") {
472 if (Dag->getArgName(i).empty())
473 error("'node' argument requires a name to match with operand list");
474 Args.push_back(Dag->getArgName(i));
479 error("Unknown leaf value for tree pattern!");
483 return new TreePatternNode(Operator, Children);
486 /// InferAllTypes - Infer/propagate as many types throughout the expression
487 /// patterns as possible. Return true if all types are infered, false
488 /// otherwise. Throw an exception if a type contradiction is found.
489 bool TreePattern::InferAllTypes() {
490 bool MadeChange = true;
493 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
494 MadeChange |= Trees[i]->ApplyTypeConstraints(*this);
497 bool HasUnresolvedTypes = false;
498 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
499 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
500 return !HasUnresolvedTypes;
503 void TreePattern::print(std::ostream &OS) const {
504 OS << getRecord()->getName();
506 OS << "(" << Args[0];
507 for (unsigned i = 1, e = Args.size(); i != e; ++i)
508 OS << ", " << Args[i];
513 if (Trees.size() > 1)
515 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
521 if (Trees.size() > 1)
525 void TreePattern::dump() const { print(std::cerr); }
529 //===----------------------------------------------------------------------===//
530 // DAGISelEmitter implementation
533 // Parse all of the SDNode definitions for the target, populating SDNodes.
534 void DAGISelEmitter::ParseNodeInfo() {
535 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
536 while (!Nodes.empty()) {
537 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
542 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
543 /// map, and emit them to the file as functions.
544 void DAGISelEmitter::ParseNodeTransforms(std::ostream &OS) {
545 OS << "\n// Node transformations.\n";
546 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
547 while (!Xforms.empty()) {
548 Record *XFormNode = Xforms.back();
549 Record *SDNode = XFormNode->getValueAsDef("Opcode");
550 std::string Code = XFormNode->getValueAsCode("XFormFunction");
551 SDNodeXForms.insert(std::make_pair(XFormNode,
552 std::make_pair(SDNode, Code)));
555 std::string ClassName = getSDNodeInfo(SDNode).getSDClassName();
556 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
558 OS << "inline SDOperand Transform_" << XFormNode->getName()
559 << "(SDNode *" << C2 << ") {\n";
560 if (ClassName != "SDNode")
561 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
562 OS << Code << "\n}\n";
571 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
572 /// file, building up the PatternFragments map. After we've collected them all,
573 /// inline fragments together as necessary, so that there are no references left
574 /// inside a pattern fragment to a pattern fragment.
576 /// This also emits all of the predicate functions to the output file.
578 void DAGISelEmitter::ParsePatternFragments(std::ostream &OS) {
579 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
581 // First step, parse all of the fragments and emit predicate functions.
582 OS << "\n// Predicate functions.\n";
583 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
584 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
585 TreePattern *P = new TreePattern(Fragments[i], Tree, *this);
586 PatternFragments[Fragments[i]] = P;
588 // Validate the argument list, converting it to map, to discard duplicates.
589 std::vector<std::string> &Args = P->getArgList();
590 std::set<std::string> OperandsMap(Args.begin(), Args.end());
592 if (OperandsMap.count(""))
593 P->error("Cannot have unnamed 'node' values in pattern fragment!");
595 // Parse the operands list.
596 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
597 if (OpsList->getNodeType()->getName() != "ops")
598 P->error("Operands list should start with '(ops ... '!");
600 // Copy over the arguments.
602 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
603 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
604 static_cast<DefInit*>(OpsList->getArg(j))->
605 getDef()->getName() != "node")
606 P->error("Operands list should all be 'node' values.");
607 if (OpsList->getArgName(j).empty())
608 P->error("Operands list should have names for each operand!");
609 if (!OperandsMap.count(OpsList->getArgName(j)))
610 P->error("'" + OpsList->getArgName(j) +
611 "' does not occur in pattern or was multiply specified!");
612 OperandsMap.erase(OpsList->getArgName(j));
613 Args.push_back(OpsList->getArgName(j));
616 if (!OperandsMap.empty())
617 P->error("Operands list does not contain an entry for operand '" +
618 *OperandsMap.begin() + "'!");
620 // If there is a code init for this fragment, emit the predicate code and
621 // keep track of the fact that this fragment uses it.
622 std::string Code = Fragments[i]->getValueAsCode("Predicate");
624 assert(!P->getOnlyTree()->isLeaf() && "Can't be a leaf!");
625 std::string ClassName =
626 getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
627 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
629 OS << "inline bool Predicate_" << Fragments[i]->getName()
630 << "(SDNode *" << C2 << ") {\n";
631 if (ClassName != "SDNode")
632 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
633 OS << Code << "\n}\n";
634 P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
637 // If there is a node transformation corresponding to this, keep track of
639 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
640 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
641 P->getOnlyTree()->setTransformFn(Transform);
646 // Now that we've parsed all of the tree fragments, do a closure on them so
647 // that there are not references to PatFrags left inside of them.
648 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
649 E = PatternFragments.end(); I != E; ++I) {
650 TreePattern *ThePat = I->second;
651 ThePat->InlinePatternFragments();
653 // Infer as many types as possible. Don't worry about it if we don't infer
654 // all of them, some may depend on the inputs of the pattern.
656 ThePat->InferAllTypes();
658 // If this pattern fragment is not supported by this target (no types can
659 // satisfy its constraints), just ignore it. If the bogus pattern is
660 // actually used by instructions, the type consistency error will be
664 // If debugging, print out the pattern fragment result.
665 DEBUG(ThePat->dump());
669 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
670 /// instruction input. Return true if this is a real use.
671 static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
672 std::map<std::string, TreePatternNode*> &InstInputs) {
673 // No name -> not interesting.
674 if (Pat->getName().empty()) {
676 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
677 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
678 I->error("Input " + DI->getDef()->getName() + " must be named!");
686 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
687 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
690 assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
691 Rec = Pat->getOperator();
694 TreePatternNode *&Slot = InstInputs[Pat->getName()];
699 if (Slot->isLeaf()) {
700 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
702 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
703 SlotRec = Slot->getOperator();
706 // Ensure that the inputs agree if we've already seen this input.
708 I->error("All $" + Pat->getName() + " inputs must agree with each other");
709 if (Slot->getType() != Pat->getType())
710 I->error("All $" + Pat->getName() + " inputs must agree with each other");
715 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
716 /// part of "I", the instruction), computing the set of inputs and outputs of
717 /// the pattern. Report errors if we see anything naughty.
718 void DAGISelEmitter::
719 FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
720 std::map<std::string, TreePatternNode*> &InstInputs,
721 std::map<std::string, Record*> &InstResults) {
723 bool isUse = HandleUse(I, Pat, InstInputs);
724 if (!isUse && Pat->getTransformFn())
725 I->error("Cannot specify a transform function for a non-input value!");
727 } else if (Pat->getOperator()->getName() != "set") {
728 // If this is not a set, verify that the children nodes are not void typed,
730 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
731 if (Pat->getChild(i)->getType() == MVT::isVoid)
732 I->error("Cannot have void nodes inside of patterns!");
733 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults);
736 // If this is a non-leaf node with no children, treat it basically as if
737 // it were a leaf. This handles nodes like (imm).
739 if (Pat->getNumChildren() == 0)
740 isUse = HandleUse(I, Pat, InstInputs);
742 if (!isUse && Pat->getTransformFn())
743 I->error("Cannot specify a transform function for a non-input value!");
747 // Otherwise, this is a set, validate and collect instruction results.
748 if (Pat->getNumChildren() == 0)
749 I->error("set requires operands!");
750 else if (Pat->getNumChildren() & 1)
751 I->error("set requires an even number of operands");
753 if (Pat->getTransformFn())
754 I->error("Cannot specify a transform function on a set node!");
756 // Check the set destinations.
757 unsigned NumValues = Pat->getNumChildren()/2;
758 for (unsigned i = 0; i != NumValues; ++i) {
759 TreePatternNode *Dest = Pat->getChild(i);
761 I->error("set destination should be a virtual register!");
763 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
765 I->error("set destination should be a virtual register!");
767 if (!Val->getDef()->isSubClassOf("RegisterClass"))
768 I->error("set destination should be a virtual register!");
769 if (Dest->getName().empty())
770 I->error("set destination must have a name!");
771 if (InstResults.count(Dest->getName()))
772 I->error("cannot set '" + Dest->getName() +"' multiple times");
773 InstResults[Dest->getName()] = Val->getDef();
775 // Verify and collect info from the computation.
776 FindPatternInputsAndOutputs(I, Pat->getChild(i+NumValues),
777 InstInputs, InstResults);
782 /// ParseInstructions - Parse all of the instructions, inlining and resolving
783 /// any fragments involved. This populates the Instructions list with fully
784 /// resolved instructions.
785 void DAGISelEmitter::ParseInstructions() {
786 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
788 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
789 if (!dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
790 continue; // no pattern yet, ignore it.
792 ListInit *LI = Instrs[i]->getValueAsListInit("Pattern");
793 if (LI->getSize() == 0) continue; // no pattern.
795 // Parse the instruction.
796 TreePattern *I = new TreePattern(Instrs[i], LI, *this);
797 // Inline pattern fragments into it.
798 I->InlinePatternFragments();
800 // Infer as many types as possible. If we cannot infer all of them, we can
801 // never do anything with this instruction pattern: report it to the user.
802 if (!I->InferAllTypes())
803 I->error("Could not infer all types in pattern!");
805 // InstInputs - Keep track of all of the inputs of the instruction, along
806 // with the record they are declared as.
807 std::map<std::string, TreePatternNode*> InstInputs;
809 // InstResults - Keep track of all the virtual registers that are 'set'
810 // in the instruction, including what reg class they are.
811 std::map<std::string, Record*> InstResults;
813 // Verify that the top-level forms in the instruction are of void type, and
814 // fill in the InstResults map.
815 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
816 TreePatternNode *Pat = I->getTree(j);
817 if (Pat->getType() != MVT::isVoid) {
819 I->error("Top-level forms in instruction pattern should have"
823 // Find inputs and outputs, and verify the structure of the uses/defs.
824 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults);
827 // Now that we have inputs and outputs of the pattern, inspect the operands
828 // list for the instruction. This determines the order that operands are
829 // added to the machine instruction the node corresponds to.
830 unsigned NumResults = InstResults.size();
832 // Parse the operands list from the (ops) list, validating it.
833 std::vector<std::string> &Args = I->getArgList();
834 assert(Args.empty() && "Args list should still be empty here!");
835 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
837 // Check that all of the results occur first in the list.
838 std::vector<MVT::ValueType> ResultTypes;
839 for (unsigned i = 0; i != NumResults; ++i) {
840 if (i == CGI.OperandList.size())
841 I->error("'" + InstResults.begin()->first +
842 "' set but does not appear in operand list!");
843 const std::string &OpName = CGI.OperandList[i].Name;
845 // Check that it exists in InstResults.
846 Record *R = InstResults[OpName];
848 I->error("Operand $" + OpName + " should be a set destination: all "
849 "outputs must occur before inputs in operand list!");
851 if (CGI.OperandList[i].Rec != R)
852 I->error("Operand $" + OpName + " class mismatch!");
854 // Remember the return type.
855 ResultTypes.push_back(CGI.OperandList[i].Ty);
857 // Okay, this one checks out.
858 InstResults.erase(OpName);
861 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
862 // the copy while we're checking the inputs.
863 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
865 std::vector<TreePatternNode*> ResultNodeOperands;
866 std::vector<MVT::ValueType> OperandTypes;
867 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
868 const std::string &OpName = CGI.OperandList[i].Name;
870 I->error("Operand #" + utostr(i) + " in operands list has no name!");
872 if (!InstInputsCheck.count(OpName))
873 I->error("Operand $" + OpName +
874 " does not appear in the instruction pattern");
875 TreePatternNode *InVal = InstInputsCheck[OpName];
876 InstInputsCheck.erase(OpName); // It occurred, remove from map.
877 if (CGI.OperandList[i].Ty != InVal->getType())
878 I->error("Operand $" + OpName +
879 "'s type disagrees between the operand and pattern");
880 OperandTypes.push_back(InVal->getType());
882 // Construct the result for the dest-pattern operand list.
883 TreePatternNode *OpNode = InVal->clone();
885 // No predicate is useful on the result.
886 OpNode->setPredicateFn("");
888 // Promote the xform function to be an explicit node if set.
889 if (Record *Xform = OpNode->getTransformFn()) {
890 OpNode->setTransformFn(0);
891 std::vector<TreePatternNode*> Children;
892 Children.push_back(OpNode);
893 OpNode = new TreePatternNode(Xform, Children);
896 ResultNodeOperands.push_back(OpNode);
899 if (!InstInputsCheck.empty())
900 I->error("Input operand $" + InstInputsCheck.begin()->first +
901 " occurs in pattern but not in operands list!");
903 TreePatternNode *ResultPattern =
904 new TreePatternNode(I->getRecord(), ResultNodeOperands);
906 // Create and insert the instruction.
907 DAGInstruction TheInst(I, ResultTypes, OperandTypes);
908 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
910 // Use a temporary tree pattern to infer all types and make sure that the
911 // constructed result is correct. This depends on the instruction already
912 // being inserted into the Instructions map.
913 TreePattern Temp(I->getRecord(), ResultPattern, *this);
914 Temp.InferAllTypes();
916 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
917 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
922 // If we can, convert the instructions to be patterns that are matched!
923 for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
924 E = Instructions.end(); II != E; ++II) {
925 TreePattern *I = II->second.getPattern();
927 if (I->getNumTrees() != 1) {
928 std::cerr << "CANNOT HANDLE: " << I->getRecord()->getName() << " yet!";
931 TreePatternNode *Pattern = I->getTree(0);
932 if (Pattern->getOperator()->getName() != "set")
933 continue; // Not a set (store or something?)
935 if (Pattern->getNumChildren() != 2)
936 continue; // Not a set of a single value (not handled so far)
938 TreePatternNode *SrcPattern = Pattern->getChild(1)->clone();
939 TreePatternNode *DstPattern = II->second.getResultPattern();
940 PatternsToMatch.push_back(std::make_pair(SrcPattern, DstPattern));
944 void DAGISelEmitter::ParsePatterns() {
945 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
947 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
948 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
949 TreePattern *Pattern = new TreePattern(Patterns[i], Tree, *this);
951 // Inline pattern fragments into it.
952 Pattern->InlinePatternFragments();
954 // Infer as many types as possible. If we cannot infer all of them, we can
955 // never do anything with this pattern: report it to the user.
956 if (!Pattern->InferAllTypes())
957 Pattern->error("Could not infer all types in pattern!");
959 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
960 if (LI->getSize() == 0) continue; // no pattern.
962 // Parse the instruction.
963 TreePattern *Result = new TreePattern(Patterns[i], LI, *this);
965 // Inline pattern fragments into it.
966 Result->InlinePatternFragments();
968 // Infer as many types as possible. If we cannot infer all of them, we can
969 // never do anything with this pattern: report it to the user.
970 if (!Result->InferAllTypes())
971 Result->error("Could not infer all types in pattern result!");
973 if (Result->getNumTrees() != 1)
974 Result->error("Cannot handle instructions producing instructions "
975 "with temporaries yet!");
976 PatternsToMatch.push_back(std::make_pair(Pattern->getOnlyTree(),
977 Result->getOnlyTree()));
980 DEBUG(std::cerr << "\n\nPARSED PATTERNS TO MATCH:\n\n";
981 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
982 std::cerr << "PATTERN: "; PatternsToMatch[i].first->dump();
983 std::cerr << "\nRESULT: ";PatternsToMatch[i].second->dump();
988 /// EmitMatchForPattern - Emit a matcher for N, going to the label for PatternNo
989 /// if the match fails. At this point, we already know that the opcode for N
990 /// matches, and the SDNode for the result has the RootName specified name.
991 void DAGISelEmitter::EmitMatchForPattern(TreePatternNode *N,
992 const std::string &RootName,
993 unsigned PatternNo, std::ostream &OS) {
994 assert(!N->isLeaf() && "Cannot match against a leaf!");
995 // Emit code to load the child nodes and match their contents recursively.
996 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
997 OS << " SDOperand " << RootName << i <<" = " << RootName
998 << ".getOperand(" << i << ");\n";
999 TreePatternNode *Child = N->getChild(i);
1000 if (!Child->isLeaf()) {
1001 // If it's not a leaf, recursively match.
1002 const SDNodeInfo &CInfo = getSDNodeInfo(Child->getOperator());
1003 OS << " if (" << RootName << i << ".getOpcode() != "
1004 << CInfo.getEnumName() << ") goto P" << PatternNo << "Fail;\n";
1005 EmitMatchForPattern(Child, RootName + utostr(i), PatternNo, OS);
1007 // Handle leaves of various types.
1008 Init *LeafVal = Child->getLeafValue();
1009 Record *LeafRec = dynamic_cast<DefInit*>(LeafVal)->getDef();
1010 if (LeafRec->isSubClassOf("RegisterClass")) {
1011 // Handle register references. Nothing to do here.
1012 } else if (LeafRec->isSubClassOf("ValueType")) {
1013 // Make sure this is the specified value type.
1014 OS << " if (cast<VTSDNode>(" << RootName << i << ")->getVT() != "
1015 << "MVT::" << LeafRec->getName() << ") goto P" << PatternNo
1019 assert(0 && "Unknown leaf type!");
1023 // If this child has a name associated with it, capture it as a variable.
1024 if (!Child->getName().empty())
1025 OS << " SDOperand op" << Child->getName() << " = " << RootName
1029 // If there is a node predicate for this, emit the call.
1030 if (!N->getPredicateFn().empty())
1031 OS << " if (!" << N->getPredicateFn() << "(" << RootName
1032 << ".Val)) goto P" << PatternNo << "Fail;\n";
1035 /// EmitCodeForPattern - Given a pattern to match, emit code to the specified
1036 /// stream to match the pattern, and generate the code for the match if it
1038 void DAGISelEmitter::EmitCodeForPattern(PatternToMatch &Pattern,
1040 static unsigned PatternCount = 0;
1041 unsigned PatternNo = PatternCount++;
1042 OS << " { // Pattern #" << PatternNo << ": ";
1043 Pattern.first->print(OS);
1046 EmitMatchForPattern(Pattern.first, "N", PatternNo, OS);
1049 Pattern.second->print(OS);
1052 OS << " }\n P" << PatternNo << "Fail:\n";
1055 /// getPatternSize - Return the 'size' of this pattern. We want to match large
1056 /// patterns before small ones. This is used to determine the size of a
1058 static unsigned getPatternSize(TreePatternNode *P) {
1059 assert(MVT::isInteger(P->getType()) || MVT::isFloatingPoint(P->getType()) &&
1060 "Not a valid pattern node to size!");
1061 unsigned Size = 1; // The node itself.
1063 // Count children in the count if they are also nodes.
1064 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
1065 TreePatternNode *Child = P->getChild(i);
1066 if (!Child->isLeaf() && Child->getType() != MVT::Other)
1067 Size += getPatternSize(Child);
1073 // PatternSortingPredicate - return true if we prefer to match LHS before RHS.
1074 // In particular, we want to match maximal patterns first and lowest cost within
1075 // a particular complexity first.
1076 struct PatternSortingPredicate {
1077 bool operator()(DAGISelEmitter::PatternToMatch *LHS,
1078 DAGISelEmitter::PatternToMatch *RHS) {
1079 unsigned LHSSize = getPatternSize(LHS->first);
1080 unsigned RHSSize = getPatternSize(RHS->first);
1081 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
1082 if (LHSSize < RHSSize) return false;
1084 // If they are equal, compare cost.
1085 // FIXME: Compute cost!
1090 void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
1091 // Emit boilerplate.
1092 OS << "// The main instruction selector code.\n"
1093 << "SDOperand SelectCode(SDOperand N) {\n"
1094 << " if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
1095 << " N.getOpcode() < PPCISD::FIRST_NUMBER)\n"
1096 << " return N; // Already selected.\n\n"
1097 << " switch (N.getOpcode()) {\n"
1098 << " default: break;\n"
1099 << " case ISD::EntryToken: // These leaves remain the same.\n"
1101 << " case ISD::AssertSext:\n"
1102 << " case ISD::AssertZext:\n"
1103 << " return Select(N.getOperand(0));\n";
1105 // Group the patterns by their top-level opcodes.
1106 std::map<Record*, std::vector<PatternToMatch*> > PatternsByOpcode;
1107 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i)
1108 PatternsByOpcode[PatternsToMatch[i].first->getOperator()]
1109 .push_back(&PatternsToMatch[i]);
1111 // Loop over all of the case statements.
1112 for (std::map<Record*, std::vector<PatternToMatch*> >::iterator
1113 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end(); PBOI != E;
1115 const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
1116 std::vector<PatternToMatch*> &Patterns = PBOI->second;
1118 OS << " case " << OpcodeInfo.getEnumName() << ":\n";
1120 // We want to emit all of the matching code now. However, we want to emit
1121 // the matches in order of minimal cost. Sort the patterns so the least
1122 // cost one is at the start.
1123 std::stable_sort(Patterns.begin(), Patterns.end(),
1124 PatternSortingPredicate());
1126 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
1127 EmitCodeForPattern(*Patterns[i], OS);
1128 OS << " break;\n\n";
1132 OS << " } // end of big switch.\n\n"
1133 << " std::cerr << \"Cannot yet select: \";\n"
1134 << " N.Val->dump();\n"
1135 << " std::cerr << '\\n';\n"
1140 void DAGISelEmitter::run(std::ostream &OS) {
1141 EmitSourceFileHeader("DAG Instruction Selector for the " + Target.getName() +
1144 OS << "// *** NOTE: This file is #included into the middle of the target\n"
1145 << "// *** instruction selector class. These functions are really "
1149 ParseNodeTransforms(OS);
1150 ParsePatternFragments(OS);
1151 ParseInstructions();
1154 // FIXME: Generate variants. For example, commutative patterns can match
1155 // multiple ways. Add them to PatternsToMatch as well.
1157 // At this point, we have full information about the 'Patterns' we need to
1158 // parse, both implicitly from instructions as well as from explicit pattern
1161 EmitInstructionSelector(OS);
1163 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
1164 E = PatternFragments.end(); I != E; ++I)
1166 PatternFragments.clear();
1168 Instructions.clear();