1 //===- DAGISelEmitter.cpp - Generate an instruction selector --------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Chris Lattner and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This tablegen backend emits a DAG instruction selector.
12 //===----------------------------------------------------------------------===//
14 #include "DAGISelEmitter.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/Support/Debug.h"
22 //===----------------------------------------------------------------------===//
23 // Helpers for working with extended types.
25 /// FilterVTs - Filter a list of VT's according to a predicate.
28 static std::vector<MVT::ValueType>
29 FilterVTs(const std::vector<MVT::ValueType> &InVTs, T Filter) {
30 std::vector<MVT::ValueType> Result;
31 for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
33 Result.push_back(InVTs[i]);
38 static std::vector<unsigned char>
39 FilterEVTs(const std::vector<unsigned char> &InVTs, T Filter) {
40 std::vector<unsigned char> Result;
41 for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
42 if (Filter((MVT::ValueType)InVTs[i]))
43 Result.push_back(InVTs[i]);
47 static std::vector<unsigned char>
48 ConvertVTs(const std::vector<MVT::ValueType> &InVTs) {
49 std::vector<unsigned char> Result;
50 for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
51 Result.push_back(InVTs[i]);
55 static bool LHSIsSubsetOfRHS(const std::vector<unsigned char> &LHS,
56 const std::vector<unsigned char> &RHS) {
57 if (LHS.size() > RHS.size()) return false;
58 for (unsigned i = 0, e = LHS.size(); i != e; ++i)
59 if (std::find(RHS.begin(), RHS.end(), LHS[i]) == RHS.end())
64 /// isExtIntegerVT - Return true if the specified extended value type vector
65 /// contains isInt or an integer value type.
66 static bool isExtIntegerInVTs(std::vector<unsigned char> EVTs) {
67 assert(!EVTs.empty() && "Cannot check for integer in empty ExtVT list!");
68 return EVTs[0] == MVT::isInt || !(FilterEVTs(EVTs, MVT::isInteger).empty());
71 /// isExtFloatingPointVT - Return true if the specified extended value type
72 /// vector contains isFP or a FP value type.
73 static bool isExtFloatingPointInVTs(std::vector<unsigned char> EVTs) {
74 assert(!EVTs.empty() && "Cannot check for integer in empty ExtVT list!");
75 return EVTs[0] == MVT::isFP || !(FilterEVTs(EVTs, MVT::isFloatingPoint).empty());
78 //===----------------------------------------------------------------------===//
79 // SDTypeConstraint implementation
82 SDTypeConstraint::SDTypeConstraint(Record *R) {
83 OperandNo = R->getValueAsInt("OperandNum");
85 if (R->isSubClassOf("SDTCisVT")) {
86 ConstraintType = SDTCisVT;
87 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
88 } else if (R->isSubClassOf("SDTCisPtrTy")) {
89 ConstraintType = SDTCisPtrTy;
90 } else if (R->isSubClassOf("SDTCisInt")) {
91 ConstraintType = SDTCisInt;
92 } else if (R->isSubClassOf("SDTCisFP")) {
93 ConstraintType = SDTCisFP;
94 } else if (R->isSubClassOf("SDTCisSameAs")) {
95 ConstraintType = SDTCisSameAs;
96 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
97 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
98 ConstraintType = SDTCisVTSmallerThanOp;
99 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
100 R->getValueAsInt("OtherOperandNum");
101 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
102 ConstraintType = SDTCisOpSmallerThanOp;
103 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
104 R->getValueAsInt("BigOperandNum");
106 std::cerr << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
111 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
112 /// N, which has NumResults results.
113 TreePatternNode *SDTypeConstraint::getOperandNum(unsigned OpNo,
115 unsigned NumResults) const {
116 assert(NumResults <= 1 &&
117 "We only work with nodes with zero or one result so far!");
119 if (OpNo < NumResults)
120 return N; // FIXME: need value #
122 return N->getChild(OpNo-NumResults);
125 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
126 /// constraint to the nodes operands. This returns true if it makes a
127 /// change, false otherwise. If a type contradiction is found, throw an
129 bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
130 const SDNodeInfo &NodeInfo,
131 TreePattern &TP) const {
132 unsigned NumResults = NodeInfo.getNumResults();
133 assert(NumResults <= 1 &&
134 "We only work with nodes with zero or one result so far!");
136 // Check that the number of operands is sane.
137 if (NodeInfo.getNumOperands() >= 0) {
138 if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands())
139 TP.error(N->getOperator()->getName() + " node requires exactly " +
140 itostr(NodeInfo.getNumOperands()) + " operands!");
143 const CodeGenTarget &CGT = TP.getDAGISelEmitter().getTargetInfo();
145 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NumResults);
147 switch (ConstraintType) {
148 default: assert(0 && "Unknown constraint type!");
150 // Operand must be a particular type.
151 return NodeToApply->UpdateNodeType(x.SDTCisVT_Info.VT, TP);
153 // Operand must be same as target pointer type.
154 return NodeToApply->UpdateNodeType(CGT.getPointerType(), TP);
157 // If there is only one integer type supported, this must be it.
158 std::vector<MVT::ValueType> IntVTs =
159 FilterVTs(CGT.getLegalValueTypes(), MVT::isInteger);
161 // If we found exactly one supported integer type, apply it.
162 if (IntVTs.size() == 1)
163 return NodeToApply->UpdateNodeType(IntVTs[0], TP);
164 return NodeToApply->UpdateNodeType(MVT::isInt, TP);
167 // If there is only one FP type supported, this must be it.
168 std::vector<MVT::ValueType> FPVTs =
169 FilterVTs(CGT.getLegalValueTypes(), MVT::isFloatingPoint);
171 // If we found exactly one supported FP type, apply it.
172 if (FPVTs.size() == 1)
173 return NodeToApply->UpdateNodeType(FPVTs[0], TP);
174 return NodeToApply->UpdateNodeType(MVT::isFP, TP);
177 TreePatternNode *OtherNode =
178 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NumResults);
179 return NodeToApply->UpdateNodeType(OtherNode->getExtTypes(), TP) |
180 OtherNode->UpdateNodeType(NodeToApply->getExtTypes(), TP);
182 case SDTCisVTSmallerThanOp: {
183 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
184 // have an integer type that is smaller than the VT.
185 if (!NodeToApply->isLeaf() ||
186 !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
187 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
188 ->isSubClassOf("ValueType"))
189 TP.error(N->getOperator()->getName() + " expects a VT operand!");
191 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
192 if (!MVT::isInteger(VT))
193 TP.error(N->getOperator()->getName() + " VT operand must be integer!");
195 TreePatternNode *OtherNode =
196 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N,NumResults);
198 // It must be integer.
199 bool MadeChange = false;
200 MadeChange |= OtherNode->UpdateNodeType(MVT::isInt, TP);
202 // This code only handles nodes that have one type set. Assert here so
203 // that we can change this if we ever need to deal with multiple value
204 // types at this point.
205 assert(OtherNode->getExtTypes().size() == 1 && "Node has too many types!");
206 if (OtherNode->hasTypeSet() && OtherNode->getTypeNum(0) <= VT)
207 OtherNode->UpdateNodeType(MVT::Other, TP); // Throw an error.
210 case SDTCisOpSmallerThanOp: {
211 TreePatternNode *BigOperand =
212 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NumResults);
214 // Both operands must be integer or FP, but we don't care which.
215 bool MadeChange = false;
217 // This code does not currently handle nodes which have multiple types,
218 // where some types are integer, and some are fp. Assert that this is not
220 assert(!(isExtIntegerInVTs(NodeToApply->getExtTypes()) &&
221 isExtFloatingPointInVTs(NodeToApply->getExtTypes())) &&
222 !(isExtIntegerInVTs(BigOperand->getExtTypes()) &&
223 isExtFloatingPointInVTs(BigOperand->getExtTypes())) &&
224 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
225 if (isExtIntegerInVTs(NodeToApply->getExtTypes()))
226 MadeChange |= BigOperand->UpdateNodeType(MVT::isInt, TP);
227 else if (isExtFloatingPointInVTs(NodeToApply->getExtTypes()))
228 MadeChange |= BigOperand->UpdateNodeType(MVT::isFP, TP);
229 if (isExtIntegerInVTs(BigOperand->getExtTypes()))
230 MadeChange |= NodeToApply->UpdateNodeType(MVT::isInt, TP);
231 else if (isExtFloatingPointInVTs(BigOperand->getExtTypes()))
232 MadeChange |= NodeToApply->UpdateNodeType(MVT::isFP, TP);
234 std::vector<MVT::ValueType> VTs = CGT.getLegalValueTypes();
236 if (isExtIntegerInVTs(NodeToApply->getExtTypes())) {
237 VTs = FilterVTs(VTs, MVT::isInteger);
238 } else if (isExtFloatingPointInVTs(NodeToApply->getExtTypes())) {
239 VTs = FilterVTs(VTs, MVT::isFloatingPoint);
244 switch (VTs.size()) {
245 default: // Too many VT's to pick from.
246 case 0: break; // No info yet.
248 // Only one VT of this flavor. Cannot ever satisify the constraints.
249 return NodeToApply->UpdateNodeType(MVT::Other, TP); // throw
251 // If we have exactly two possible types, the little operand must be the
252 // small one, the big operand should be the big one. Common with
253 // float/double for example.
254 assert(VTs[0] < VTs[1] && "Should be sorted!");
255 MadeChange |= NodeToApply->UpdateNodeType(VTs[0], TP);
256 MadeChange |= BigOperand->UpdateNodeType(VTs[1], TP);
266 //===----------------------------------------------------------------------===//
267 // SDNodeInfo implementation
269 SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
270 EnumName = R->getValueAsString("Opcode");
271 SDClassName = R->getValueAsString("SDClass");
272 Record *TypeProfile = R->getValueAsDef("TypeProfile");
273 NumResults = TypeProfile->getValueAsInt("NumResults");
274 NumOperands = TypeProfile->getValueAsInt("NumOperands");
276 // Parse the properties.
278 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
279 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
280 if (PropList[i]->getName() == "SDNPCommutative") {
281 Properties |= 1 << SDNPCommutative;
282 } else if (PropList[i]->getName() == "SDNPAssociative") {
283 Properties |= 1 << SDNPAssociative;
284 } else if (PropList[i]->getName() == "SDNPHasChain") {
285 Properties |= 1 << SDNPHasChain;
287 std::cerr << "Unknown SD Node property '" << PropList[i]->getName()
288 << "' on node '" << R->getName() << "'!\n";
294 // Parse the type constraints.
295 std::vector<Record*> ConstraintList =
296 TypeProfile->getValueAsListOfDefs("Constraints");
297 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
300 //===----------------------------------------------------------------------===//
301 // TreePatternNode implementation
304 TreePatternNode::~TreePatternNode() {
305 #if 0 // FIXME: implement refcounted tree nodes!
306 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
311 /// UpdateNodeType - Set the node type of N to VT if VT contains
312 /// information. If N already contains a conflicting type, then throw an
313 /// exception. This returns true if any information was updated.
315 bool TreePatternNode::UpdateNodeType(const std::vector<unsigned char> &ExtVTs,
317 assert(!ExtVTs.empty() && "Cannot update node type with empty type vector!");
319 if (ExtVTs[0] == MVT::isUnknown || LHSIsSubsetOfRHS(getExtTypes(), ExtVTs))
321 if (isTypeCompletelyUnknown() || LHSIsSubsetOfRHS(ExtVTs, getExtTypes())) {
326 if (ExtVTs[0] == MVT::isInt && isExtIntegerInVTs(getExtTypes())) {
327 assert(hasTypeSet() && "should be handled above!");
328 std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), MVT::isInteger);
329 if (getExtTypes() == FVTs)
334 if (ExtVTs[0] == MVT::isFP && isExtFloatingPointInVTs(getExtTypes())) {
335 assert(hasTypeSet() && "should be handled above!");
336 std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), MVT::isFloatingPoint);
337 if (getExtTypes() == FVTs)
343 // If we know this is an int or fp type, and we are told it is a specific one,
346 // Similarly, we should probably set the type here to the intersection of
347 // {isInt|isFP} and ExtVTs
348 if ((getExtTypeNum(0) == MVT::isInt && isExtIntegerInVTs(ExtVTs)) ||
349 (getExtTypeNum(0) == MVT::isFP && isExtFloatingPointInVTs(ExtVTs))) {
357 TP.error("Type inference contradiction found in node!");
359 TP.error("Type inference contradiction found in node " +
360 getOperator()->getName() + "!");
362 return true; // unreachable
366 void TreePatternNode::print(std::ostream &OS) const {
368 OS << *getLeafValue();
370 OS << "(" << getOperator()->getName();
373 // FIXME: At some point we should handle printing all the value types for
374 // nodes that are multiply typed.
375 switch (getExtTypeNum(0)) {
376 case MVT::Other: OS << ":Other"; break;
377 case MVT::isInt: OS << ":isInt"; break;
378 case MVT::isFP : OS << ":isFP"; break;
379 case MVT::isUnknown: ; /*OS << ":?";*/ break;
380 default: OS << ":" << getTypeNum(0); break;
384 if (getNumChildren() != 0) {
386 getChild(0)->print(OS);
387 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
389 getChild(i)->print(OS);
395 if (!PredicateFn.empty())
396 OS << "<<P:" << PredicateFn << ">>";
398 OS << "<<X:" << TransformFn->getName() << ">>";
399 if (!getName().empty())
400 OS << ":$" << getName();
403 void TreePatternNode::dump() const {
407 /// isIsomorphicTo - Return true if this node is recursively isomorphic to
408 /// the specified node. For this comparison, all of the state of the node
409 /// is considered, except for the assigned name. Nodes with differing names
410 /// that are otherwise identical are considered isomorphic.
411 bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N) const {
412 if (N == this) return true;
413 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
414 getPredicateFn() != N->getPredicateFn() ||
415 getTransformFn() != N->getTransformFn())
419 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue()))
420 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue()))
421 return DI->getDef() == NDI->getDef();
422 return getLeafValue() == N->getLeafValue();
425 if (N->getOperator() != getOperator() ||
426 N->getNumChildren() != getNumChildren()) return false;
427 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
428 if (!getChild(i)->isIsomorphicTo(N->getChild(i)))
433 /// clone - Make a copy of this tree and all of its children.
435 TreePatternNode *TreePatternNode::clone() const {
436 TreePatternNode *New;
438 New = new TreePatternNode(getLeafValue());
440 std::vector<TreePatternNode*> CChildren;
441 CChildren.reserve(Children.size());
442 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
443 CChildren.push_back(getChild(i)->clone());
444 New = new TreePatternNode(getOperator(), CChildren);
446 New->setName(getName());
447 New->setTypes(getExtTypes());
448 New->setPredicateFn(getPredicateFn());
449 New->setTransformFn(getTransformFn());
453 /// SubstituteFormalArguments - Replace the formal arguments in this tree
454 /// with actual values specified by ArgMap.
455 void TreePatternNode::
456 SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
457 if (isLeaf()) return;
459 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
460 TreePatternNode *Child = getChild(i);
461 if (Child->isLeaf()) {
462 Init *Val = Child->getLeafValue();
463 if (dynamic_cast<DefInit*>(Val) &&
464 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
465 // We found a use of a formal argument, replace it with its value.
466 Child = ArgMap[Child->getName()];
467 assert(Child && "Couldn't find formal argument!");
471 getChild(i)->SubstituteFormalArguments(ArgMap);
477 /// InlinePatternFragments - If this pattern refers to any pattern
478 /// fragments, inline them into place, giving us a pattern without any
479 /// PatFrag references.
480 TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
481 if (isLeaf()) return this; // nothing to do.
482 Record *Op = getOperator();
484 if (!Op->isSubClassOf("PatFrag")) {
485 // Just recursively inline children nodes.
486 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
487 setChild(i, getChild(i)->InlinePatternFragments(TP));
491 // Otherwise, we found a reference to a fragment. First, look up its
492 // TreePattern record.
493 TreePattern *Frag = TP.getDAGISelEmitter().getPatternFragment(Op);
495 // Verify that we are passing the right number of operands.
496 if (Frag->getNumArgs() != Children.size())
497 TP.error("'" + Op->getName() + "' fragment requires " +
498 utostr(Frag->getNumArgs()) + " operands!");
500 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
502 // Resolve formal arguments to their actual value.
503 if (Frag->getNumArgs()) {
504 // Compute the map of formal to actual arguments.
505 std::map<std::string, TreePatternNode*> ArgMap;
506 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
507 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
509 FragTree->SubstituteFormalArguments(ArgMap);
512 FragTree->setName(getName());
513 FragTree->UpdateNodeType(getExtTypes(), TP);
515 // Get a new copy of this fragment to stitch into here.
516 //delete this; // FIXME: implement refcounting!
520 /// getIntrinsicType - Check to see if the specified record has an intrinsic
521 /// type which should be applied to it. This infer the type of register
522 /// references from the register file information, for example.
524 static std::vector<unsigned char> getIntrinsicType(Record *R, bool NotRegisters,
526 // Some common return values
527 std::vector<unsigned char> Unknown(1, MVT::isUnknown);
528 std::vector<unsigned char> Other(1, MVT::Other);
530 // Check to see if this is a register or a register class...
531 if (R->isSubClassOf("RegisterClass")) {
534 const CodeGenRegisterClass &RC =
535 TP.getDAGISelEmitter().getTargetInfo().getRegisterClass(R);
536 return ConvertVTs(RC.getValueTypes());
537 } else if (R->isSubClassOf("PatFrag")) {
538 // Pattern fragment types will be resolved when they are inlined.
540 } else if (R->isSubClassOf("Register")) {
541 // If the register appears in exactly one regclass, and the regclass has one
542 // value type, use it as the known type.
543 const CodeGenTarget &T = TP.getDAGISelEmitter().getTargetInfo();
544 if (const CodeGenRegisterClass *RC = T.getRegisterClassForRegister(R))
545 return ConvertVTs(RC->getValueTypes());
547 } else if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
548 // Using a VTSDNode or CondCodeSDNode.
550 } else if (R->isSubClassOf("ComplexPattern")) {
551 std::vector<unsigned char>
552 ComplexPat(1, TP.getDAGISelEmitter().getComplexPattern(R).getValueType());
554 } else if (R->getName() == "node" || R->getName() == "srcvalue") {
559 TP.error("Unknown node flavor used in pattern: " + R->getName());
563 /// ApplyTypeConstraints - Apply all of the type constraints relevent to
564 /// this node and its children in the tree. This returns true if it makes a
565 /// change, false otherwise. If a type contradiction is found, throw an
567 bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
569 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
570 // If it's a regclass or something else known, include the type.
571 return UpdateNodeType(getIntrinsicType(DI->getDef(), NotRegisters, TP),
573 } else if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
574 // Int inits are always integers. :)
575 bool MadeChange = UpdateNodeType(MVT::isInt, TP);
578 // At some point, it may make sense for this tree pattern to have
579 // multiple types. Assert here that it does not, so we revisit this
580 // code when appropriate.
581 assert(getExtTypes().size() == 1 && "TreePattern has too many types!");
583 unsigned Size = MVT::getSizeInBits(getTypeNum(0));
584 // Make sure that the value is representable for this type.
586 int Val = (II->getValue() << (32-Size)) >> (32-Size);
587 if (Val != II->getValue())
588 TP.error("Sign-extended integer value '" + itostr(II->getValue()) +
589 "' is out of range for type 'MVT::" +
590 getEnumName(getTypeNum(0)) + "'!");
599 // special handling for set, which isn't really an SDNode.
600 if (getOperator()->getName() == "set") {
601 assert (getNumChildren() == 2 && "Only handle 2 operand set's for now!");
602 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
603 MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
605 // Types of operands must match.
606 MadeChange |= getChild(0)->UpdateNodeType(getChild(1)->getExtTypes(), TP);
607 MadeChange |= getChild(1)->UpdateNodeType(getChild(0)->getExtTypes(), TP);
608 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
610 } else if (getOperator()->isSubClassOf("SDNode")) {
611 const SDNodeInfo &NI = TP.getDAGISelEmitter().getSDNodeInfo(getOperator());
613 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
614 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
615 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
616 // Branch, etc. do not produce results and top-level forms in instr pattern
617 // must have void types.
618 if (NI.getNumResults() == 0)
619 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
621 } else if (getOperator()->isSubClassOf("Instruction")) {
622 const DAGInstruction &Inst =
623 TP.getDAGISelEmitter().getInstruction(getOperator());
624 bool MadeChange = false;
625 unsigned NumResults = Inst.getNumResults();
627 assert(NumResults <= 1 &&
628 "Only supports zero or one result instrs!");
629 // Apply the result type to the node
630 if (NumResults == 0) {
631 MadeChange = UpdateNodeType(MVT::isVoid, TP);
633 Record *ResultNode = Inst.getResult(0);
634 assert(ResultNode->isSubClassOf("RegisterClass") &&
635 "Operands should be register classes!");
637 const CodeGenRegisterClass &RC =
638 TP.getDAGISelEmitter().getTargetInfo().getRegisterClass(ResultNode);
639 MadeChange = UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
642 if (getNumChildren() != Inst.getNumOperands())
643 TP.error("Instruction '" + getOperator()->getName() + " expects " +
644 utostr(Inst.getNumOperands()) + " operands, not " +
645 utostr(getNumChildren()) + " operands!");
646 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
647 Record *OperandNode = Inst.getOperand(i);
649 if (OperandNode->isSubClassOf("RegisterClass")) {
650 const CodeGenRegisterClass &RC =
651 TP.getDAGISelEmitter().getTargetInfo().getRegisterClass(OperandNode);
652 //VT = RC.getValueTypeNum(0);
653 MadeChange |=getChild(i)->UpdateNodeType(ConvertVTs(RC.getValueTypes()),
655 } else if (OperandNode->isSubClassOf("Operand")) {
656 VT = getValueType(OperandNode->getValueAsDef("Type"));
657 MadeChange |= getChild(i)->UpdateNodeType(VT, TP);
659 assert(0 && "Unknown operand type!");
662 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
666 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
668 // Node transforms always take one operand, and take and return the same
670 if (getNumChildren() != 1)
671 TP.error("Node transform '" + getOperator()->getName() +
672 "' requires one operand!");
673 bool MadeChange = UpdateNodeType(getChild(0)->getExtTypes(), TP);
674 MadeChange |= getChild(0)->UpdateNodeType(getExtTypes(), TP);
679 /// canPatternMatch - If it is impossible for this pattern to match on this
680 /// target, fill in Reason and return false. Otherwise, return true. This is
681 /// used as a santity check for .td files (to prevent people from writing stuff
682 /// that can never possibly work), and to prevent the pattern permuter from
683 /// generating stuff that is useless.
684 bool TreePatternNode::canPatternMatch(std::string &Reason, DAGISelEmitter &ISE){
685 if (isLeaf()) return true;
687 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
688 if (!getChild(i)->canPatternMatch(Reason, ISE))
691 // If this node is a commutative operator, check that the LHS isn't an
693 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(getOperator());
694 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
695 // Scan all of the operands of the node and make sure that only the last one
696 // is a constant node.
697 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i)
698 if (!getChild(i)->isLeaf() &&
699 getChild(i)->getOperator()->getName() == "imm") {
700 Reason = "Immediate value must be on the RHS of commutative operators!";
708 //===----------------------------------------------------------------------===//
709 // TreePattern implementation
712 TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
713 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
714 isInputPattern = isInput;
715 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
716 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
719 TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
720 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
721 isInputPattern = isInput;
722 Trees.push_back(ParseTreePattern(Pat));
725 TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
726 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
727 isInputPattern = isInput;
728 Trees.push_back(Pat);
733 void TreePattern::error(const std::string &Msg) const {
735 throw "In " + TheRecord->getName() + ": " + Msg;
738 TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
739 Record *Operator = Dag->getNodeType();
741 if (Operator->isSubClassOf("ValueType")) {
742 // If the operator is a ValueType, then this must be "type cast" of a leaf
744 if (Dag->getNumArgs() != 1)
745 error("Type cast only takes one operand!");
747 Init *Arg = Dag->getArg(0);
748 TreePatternNode *New;
749 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
750 Record *R = DI->getDef();
751 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
752 Dag->setArg(0, new DagInit(R,
753 std::vector<std::pair<Init*, std::string> >()));
754 return ParseTreePattern(Dag);
756 New = new TreePatternNode(DI);
757 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
758 New = ParseTreePattern(DI);
759 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
760 New = new TreePatternNode(II);
761 if (!Dag->getArgName(0).empty())
762 error("Constant int argument should not have a name!");
765 error("Unknown leaf value for tree pattern!");
769 // Apply the type cast.
770 New->UpdateNodeType(getValueType(Operator), *this);
771 New->setName(Dag->getArgName(0));
775 // Verify that this is something that makes sense for an operator.
776 if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
777 !Operator->isSubClassOf("Instruction") &&
778 !Operator->isSubClassOf("SDNodeXForm") &&
779 Operator->getName() != "set")
780 error("Unrecognized node '" + Operator->getName() + "'!");
782 // Check to see if this is something that is illegal in an input pattern.
783 if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
784 Operator->isSubClassOf("SDNodeXForm")))
785 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
787 std::vector<TreePatternNode*> Children;
789 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
790 Init *Arg = Dag->getArg(i);
791 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
792 Children.push_back(ParseTreePattern(DI));
793 if (Children.back()->getName().empty())
794 Children.back()->setName(Dag->getArgName(i));
795 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
796 Record *R = DefI->getDef();
797 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
798 // TreePatternNode if its own.
799 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
800 Dag->setArg(i, new DagInit(R,
801 std::vector<std::pair<Init*, std::string> >()));
802 --i; // Revisit this node...
804 TreePatternNode *Node = new TreePatternNode(DefI);
805 Node->setName(Dag->getArgName(i));
806 Children.push_back(Node);
809 if (R->getName() == "node") {
810 if (Dag->getArgName(i).empty())
811 error("'node' argument requires a name to match with operand list");
812 Args.push_back(Dag->getArgName(i));
815 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
816 TreePatternNode *Node = new TreePatternNode(II);
817 if (!Dag->getArgName(i).empty())
818 error("Constant int argument should not have a name!");
819 Children.push_back(Node);
824 error("Unknown leaf value for tree pattern!");
828 return new TreePatternNode(Operator, Children);
831 /// InferAllTypes - Infer/propagate as many types throughout the expression
832 /// patterns as possible. Return true if all types are infered, false
833 /// otherwise. Throw an exception if a type contradiction is found.
834 bool TreePattern::InferAllTypes() {
835 bool MadeChange = true;
838 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
839 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
842 bool HasUnresolvedTypes = false;
843 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
844 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
845 return !HasUnresolvedTypes;
848 void TreePattern::print(std::ostream &OS) const {
849 OS << getRecord()->getName();
851 OS << "(" << Args[0];
852 for (unsigned i = 1, e = Args.size(); i != e; ++i)
853 OS << ", " << Args[i];
858 if (Trees.size() > 1)
860 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
866 if (Trees.size() > 1)
870 void TreePattern::dump() const { print(std::cerr); }
874 //===----------------------------------------------------------------------===//
875 // DAGISelEmitter implementation
878 // Parse all of the SDNode definitions for the target, populating SDNodes.
879 void DAGISelEmitter::ParseNodeInfo() {
880 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
881 while (!Nodes.empty()) {
882 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
887 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
888 /// map, and emit them to the file as functions.
889 void DAGISelEmitter::ParseNodeTransforms(std::ostream &OS) {
890 OS << "\n// Node transformations.\n";
891 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
892 while (!Xforms.empty()) {
893 Record *XFormNode = Xforms.back();
894 Record *SDNode = XFormNode->getValueAsDef("Opcode");
895 std::string Code = XFormNode->getValueAsCode("XFormFunction");
896 SDNodeXForms.insert(std::make_pair(XFormNode,
897 std::make_pair(SDNode, Code)));
900 std::string ClassName = getSDNodeInfo(SDNode).getSDClassName();
901 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
903 OS << "inline SDOperand Transform_" << XFormNode->getName()
904 << "(SDNode *" << C2 << ") {\n";
905 if (ClassName != "SDNode")
906 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
907 OS << Code << "\n}\n";
914 void DAGISelEmitter::ParseComplexPatterns() {
915 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
916 while (!AMs.empty()) {
917 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
923 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
924 /// file, building up the PatternFragments map. After we've collected them all,
925 /// inline fragments together as necessary, so that there are no references left
926 /// inside a pattern fragment to a pattern fragment.
928 /// This also emits all of the predicate functions to the output file.
930 void DAGISelEmitter::ParsePatternFragments(std::ostream &OS) {
931 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
933 // First step, parse all of the fragments and emit predicate functions.
934 OS << "\n// Predicate functions.\n";
935 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
936 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
937 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
938 PatternFragments[Fragments[i]] = P;
940 // Validate the argument list, converting it to map, to discard duplicates.
941 std::vector<std::string> &Args = P->getArgList();
942 std::set<std::string> OperandsMap(Args.begin(), Args.end());
944 if (OperandsMap.count(""))
945 P->error("Cannot have unnamed 'node' values in pattern fragment!");
947 // Parse the operands list.
948 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
949 if (OpsList->getNodeType()->getName() != "ops")
950 P->error("Operands list should start with '(ops ... '!");
952 // Copy over the arguments.
954 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
955 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
956 static_cast<DefInit*>(OpsList->getArg(j))->
957 getDef()->getName() != "node")
958 P->error("Operands list should all be 'node' values.");
959 if (OpsList->getArgName(j).empty())
960 P->error("Operands list should have names for each operand!");
961 if (!OperandsMap.count(OpsList->getArgName(j)))
962 P->error("'" + OpsList->getArgName(j) +
963 "' does not occur in pattern or was multiply specified!");
964 OperandsMap.erase(OpsList->getArgName(j));
965 Args.push_back(OpsList->getArgName(j));
968 if (!OperandsMap.empty())
969 P->error("Operands list does not contain an entry for operand '" +
970 *OperandsMap.begin() + "'!");
972 // If there is a code init for this fragment, emit the predicate code and
973 // keep track of the fact that this fragment uses it.
974 std::string Code = Fragments[i]->getValueAsCode("Predicate");
976 assert(!P->getOnlyTree()->isLeaf() && "Can't be a leaf!");
977 std::string ClassName =
978 getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
979 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
981 OS << "inline bool Predicate_" << Fragments[i]->getName()
982 << "(SDNode *" << C2 << ") {\n";
983 if (ClassName != "SDNode")
984 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
985 OS << Code << "\n}\n";
986 P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
989 // If there is a node transformation corresponding to this, keep track of
991 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
992 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
993 P->getOnlyTree()->setTransformFn(Transform);
998 // Now that we've parsed all of the tree fragments, do a closure on them so
999 // that there are not references to PatFrags left inside of them.
1000 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
1001 E = PatternFragments.end(); I != E; ++I) {
1002 TreePattern *ThePat = I->second;
1003 ThePat->InlinePatternFragments();
1005 // Infer as many types as possible. Don't worry about it if we don't infer
1006 // all of them, some may depend on the inputs of the pattern.
1008 ThePat->InferAllTypes();
1010 // If this pattern fragment is not supported by this target (no types can
1011 // satisfy its constraints), just ignore it. If the bogus pattern is
1012 // actually used by instructions, the type consistency error will be
1016 // If debugging, print out the pattern fragment result.
1017 DEBUG(ThePat->dump());
1021 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
1022 /// instruction input. Return true if this is a real use.
1023 static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
1024 std::map<std::string, TreePatternNode*> &InstInputs,
1025 std::vector<Record*> &InstImpInputs) {
1026 // No name -> not interesting.
1027 if (Pat->getName().empty()) {
1028 if (Pat->isLeaf()) {
1029 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1030 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1031 I->error("Input " + DI->getDef()->getName() + " must be named!");
1032 else if (DI && DI->getDef()->isSubClassOf("Register"))
1033 InstImpInputs.push_back(DI->getDef());
1039 if (Pat->isLeaf()) {
1040 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1041 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
1044 assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
1045 Rec = Pat->getOperator();
1048 // SRCVALUE nodes are ignored.
1049 if (Rec->getName() == "srcvalue")
1052 TreePatternNode *&Slot = InstInputs[Pat->getName()];
1057 if (Slot->isLeaf()) {
1058 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
1060 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
1061 SlotRec = Slot->getOperator();
1064 // Ensure that the inputs agree if we've already seen this input.
1066 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1067 if (Slot->getExtTypes() != Pat->getExtTypes())
1068 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1073 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
1074 /// part of "I", the instruction), computing the set of inputs and outputs of
1075 /// the pattern. Report errors if we see anything naughty.
1076 void DAGISelEmitter::
1077 FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
1078 std::map<std::string, TreePatternNode*> &InstInputs,
1079 std::map<std::string, Record*> &InstResults,
1080 std::vector<Record*> &InstImpInputs,
1081 std::vector<Record*> &InstImpResults) {
1082 if (Pat->isLeaf()) {
1083 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1084 if (!isUse && Pat->getTransformFn())
1085 I->error("Cannot specify a transform function for a non-input value!");
1087 } else if (Pat->getOperator()->getName() != "set") {
1088 // If this is not a set, verify that the children nodes are not void typed,
1090 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1091 if (Pat->getChild(i)->getExtTypeNum(0) == MVT::isVoid)
1092 I->error("Cannot have void nodes inside of patterns!");
1093 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
1094 InstImpInputs, InstImpResults);
1097 // If this is a non-leaf node with no children, treat it basically as if
1098 // it were a leaf. This handles nodes like (imm).
1100 if (Pat->getNumChildren() == 0)
1101 isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1103 if (!isUse && Pat->getTransformFn())
1104 I->error("Cannot specify a transform function for a non-input value!");
1108 // Otherwise, this is a set, validate and collect instruction results.
1109 if (Pat->getNumChildren() == 0)
1110 I->error("set requires operands!");
1111 else if (Pat->getNumChildren() & 1)
1112 I->error("set requires an even number of operands");
1114 if (Pat->getTransformFn())
1115 I->error("Cannot specify a transform function on a set node!");
1117 // Check the set destinations.
1118 unsigned NumValues = Pat->getNumChildren()/2;
1119 for (unsigned i = 0; i != NumValues; ++i) {
1120 TreePatternNode *Dest = Pat->getChild(i);
1121 if (!Dest->isLeaf())
1122 I->error("set destination should be a register!");
1124 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1126 I->error("set destination should be a register!");
1128 if (Val->getDef()->isSubClassOf("RegisterClass")) {
1129 if (Dest->getName().empty())
1130 I->error("set destination must have a name!");
1131 if (InstResults.count(Dest->getName()))
1132 I->error("cannot set '" + Dest->getName() +"' multiple times");
1133 InstResults[Dest->getName()] = Val->getDef();
1134 } else if (Val->getDef()->isSubClassOf("Register")) {
1135 InstImpResults.push_back(Val->getDef());
1137 I->error("set destination should be a register!");
1140 // Verify and collect info from the computation.
1141 FindPatternInputsAndOutputs(I, Pat->getChild(i+NumValues),
1142 InstInputs, InstResults,
1143 InstImpInputs, InstImpResults);
1147 /// ParseInstructions - Parse all of the instructions, inlining and resolving
1148 /// any fragments involved. This populates the Instructions list with fully
1149 /// resolved instructions.
1150 void DAGISelEmitter::ParseInstructions() {
1151 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
1153 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
1156 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
1157 LI = Instrs[i]->getValueAsListInit("Pattern");
1159 // If there is no pattern, only collect minimal information about the
1160 // instruction for its operand list. We have to assume that there is one
1161 // result, as we have no detailed info.
1162 if (!LI || LI->getSize() == 0) {
1163 std::vector<Record*> Results;
1164 std::vector<Record*> Operands;
1166 CodeGenInstruction &InstInfo =Target.getInstruction(Instrs[i]->getName());
1168 if (InstInfo.OperandList.size() != 0) {
1169 // FIXME: temporary hack...
1170 if (InstInfo.noResults) {
1171 // These produce no results
1172 for (unsigned j = 0, e = InstInfo.OperandList.size(); j < e; ++j)
1173 Operands.push_back(InstInfo.OperandList[j].Rec);
1175 // Assume the first operand is the result.
1176 Results.push_back(InstInfo.OperandList[0].Rec);
1178 // The rest are inputs.
1179 for (unsigned j = 1, e = InstInfo.OperandList.size(); j < e; ++j)
1180 Operands.push_back(InstInfo.OperandList[j].Rec);
1184 // Create and insert the instruction.
1185 std::vector<Record*> ImpResults;
1186 std::vector<Record*> ImpOperands;
1187 Instructions.insert(std::make_pair(Instrs[i],
1188 DAGInstruction(0, Results, Operands, ImpResults,
1190 continue; // no pattern.
1193 // Parse the instruction.
1194 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
1195 // Inline pattern fragments into it.
1196 I->InlinePatternFragments();
1198 // Infer as many types as possible. If we cannot infer all of them, we can
1199 // never do anything with this instruction pattern: report it to the user.
1200 if (!I->InferAllTypes())
1201 I->error("Could not infer all types in pattern!");
1203 // InstInputs - Keep track of all of the inputs of the instruction, along
1204 // with the record they are declared as.
1205 std::map<std::string, TreePatternNode*> InstInputs;
1207 // InstResults - Keep track of all the virtual registers that are 'set'
1208 // in the instruction, including what reg class they are.
1209 std::map<std::string, Record*> InstResults;
1211 std::vector<Record*> InstImpInputs;
1212 std::vector<Record*> InstImpResults;
1214 // Verify that the top-level forms in the instruction are of void type, and
1215 // fill in the InstResults map.
1216 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
1217 TreePatternNode *Pat = I->getTree(j);
1218 if (Pat->getExtTypeNum(0) != MVT::isVoid)
1219 I->error("Top-level forms in instruction pattern should have"
1222 // Find inputs and outputs, and verify the structure of the uses/defs.
1223 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
1224 InstImpInputs, InstImpResults);
1227 // Now that we have inputs and outputs of the pattern, inspect the operands
1228 // list for the instruction. This determines the order that operands are
1229 // added to the machine instruction the node corresponds to.
1230 unsigned NumResults = InstResults.size();
1232 // Parse the operands list from the (ops) list, validating it.
1233 std::vector<std::string> &Args = I->getArgList();
1234 assert(Args.empty() && "Args list should still be empty here!");
1235 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
1237 // Check that all of the results occur first in the list.
1238 std::vector<Record*> Results;
1239 for (unsigned i = 0; i != NumResults; ++i) {
1240 if (i == CGI.OperandList.size())
1241 I->error("'" + InstResults.begin()->first +
1242 "' set but does not appear in operand list!");
1243 const std::string &OpName = CGI.OperandList[i].Name;
1245 // Check that it exists in InstResults.
1246 Record *R = InstResults[OpName];
1248 I->error("Operand $" + OpName + " should be a set destination: all "
1249 "outputs must occur before inputs in operand list!");
1251 if (CGI.OperandList[i].Rec != R)
1252 I->error("Operand $" + OpName + " class mismatch!");
1254 // Remember the return type.
1255 Results.push_back(CGI.OperandList[i].Rec);
1257 // Okay, this one checks out.
1258 InstResults.erase(OpName);
1261 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
1262 // the copy while we're checking the inputs.
1263 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
1265 std::vector<TreePatternNode*> ResultNodeOperands;
1266 std::vector<Record*> Operands;
1267 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
1268 const std::string &OpName = CGI.OperandList[i].Name;
1270 I->error("Operand #" + utostr(i) + " in operands list has no name!");
1272 if (!InstInputsCheck.count(OpName))
1273 I->error("Operand $" + OpName +
1274 " does not appear in the instruction pattern");
1275 TreePatternNode *InVal = InstInputsCheck[OpName];
1276 InstInputsCheck.erase(OpName); // It occurred, remove from map.
1278 if (InVal->isLeaf() &&
1279 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
1280 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
1281 if (CGI.OperandList[i].Rec != InRec &&
1282 !InRec->isSubClassOf("ComplexPattern"))
1283 I->error("Operand $" + OpName +
1284 "'s register class disagrees between the operand and pattern");
1286 Operands.push_back(CGI.OperandList[i].Rec);
1288 // Construct the result for the dest-pattern operand list.
1289 TreePatternNode *OpNode = InVal->clone();
1291 // No predicate is useful on the result.
1292 OpNode->setPredicateFn("");
1294 // Promote the xform function to be an explicit node if set.
1295 if (Record *Xform = OpNode->getTransformFn()) {
1296 OpNode->setTransformFn(0);
1297 std::vector<TreePatternNode*> Children;
1298 Children.push_back(OpNode);
1299 OpNode = new TreePatternNode(Xform, Children);
1302 ResultNodeOperands.push_back(OpNode);
1305 if (!InstInputsCheck.empty())
1306 I->error("Input operand $" + InstInputsCheck.begin()->first +
1307 " occurs in pattern but not in operands list!");
1309 TreePatternNode *ResultPattern =
1310 new TreePatternNode(I->getRecord(), ResultNodeOperands);
1312 // Create and insert the instruction.
1313 DAGInstruction TheInst(I, Results, Operands, InstImpResults, InstImpInputs);
1314 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
1316 // Use a temporary tree pattern to infer all types and make sure that the
1317 // constructed result is correct. This depends on the instruction already
1318 // being inserted into the Instructions map.
1319 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
1320 Temp.InferAllTypes();
1322 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
1323 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
1328 // If we can, convert the instructions to be patterns that are matched!
1329 for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
1330 E = Instructions.end(); II != E; ++II) {
1331 DAGInstruction &TheInst = II->second;
1332 TreePattern *I = TheInst.getPattern();
1333 if (I == 0) continue; // No pattern.
1335 if (I->getNumTrees() != 1) {
1336 std::cerr << "CANNOT HANDLE: " << I->getRecord()->getName() << " yet!";
1339 TreePatternNode *Pattern = I->getTree(0);
1340 TreePatternNode *SrcPattern;
1341 if (Pattern->getOperator()->getName() == "set") {
1342 if (Pattern->getNumChildren() != 2)
1343 continue; // Not a set of a single value (not handled so far)
1345 SrcPattern = Pattern->getChild(1)->clone();
1347 // Not a set (store or something?)
1348 SrcPattern = Pattern;
1352 if (!SrcPattern->canPatternMatch(Reason, *this))
1353 I->error("Instruction can never match: " + Reason);
1355 Record *Instr = II->first;
1356 TreePatternNode *DstPattern = TheInst.getResultPattern();
1358 push_back(PatternToMatch(Instr->getValueAsListInit("Predicates"),
1359 SrcPattern, DstPattern));
1363 void DAGISelEmitter::ParsePatterns() {
1364 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
1366 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1367 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
1368 TreePattern *Pattern = new TreePattern(Patterns[i], Tree, true, *this);
1370 // Inline pattern fragments into it.
1371 Pattern->InlinePatternFragments();
1373 // Infer as many types as possible. If we cannot infer all of them, we can
1374 // never do anything with this pattern: report it to the user.
1375 if (!Pattern->InferAllTypes())
1376 Pattern->error("Could not infer all types in pattern!");
1378 // Validate that the input pattern is correct.
1380 std::map<std::string, TreePatternNode*> InstInputs;
1381 std::map<std::string, Record*> InstResults;
1382 std::vector<Record*> InstImpInputs;
1383 std::vector<Record*> InstImpResults;
1384 FindPatternInputsAndOutputs(Pattern, Pattern->getOnlyTree(),
1385 InstInputs, InstResults,
1386 InstImpInputs, InstImpResults);
1389 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
1390 if (LI->getSize() == 0) continue; // no pattern.
1392 // Parse the instruction.
1393 TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
1395 // Inline pattern fragments into it.
1396 Result->InlinePatternFragments();
1398 // Infer as many types as possible. If we cannot infer all of them, we can
1399 // never do anything with this pattern: report it to the user.
1400 if (!Result->InferAllTypes())
1401 Result->error("Could not infer all types in pattern result!");
1403 if (Result->getNumTrees() != 1)
1404 Result->error("Cannot handle instructions producing instructions "
1405 "with temporaries yet!");
1408 if (!Pattern->getOnlyTree()->canPatternMatch(Reason, *this))
1409 Pattern->error("Pattern can never match: " + Reason);
1412 push_back(PatternToMatch(Patterns[i]->getValueAsListInit("Predicates"),
1413 Pattern->getOnlyTree(),
1414 Result->getOnlyTree()));
1418 /// CombineChildVariants - Given a bunch of permutations of each child of the
1419 /// 'operator' node, put them together in all possible ways.
1420 static void CombineChildVariants(TreePatternNode *Orig,
1421 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
1422 std::vector<TreePatternNode*> &OutVariants,
1423 DAGISelEmitter &ISE) {
1424 // Make sure that each operand has at least one variant to choose from.
1425 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1426 if (ChildVariants[i].empty())
1429 // The end result is an all-pairs construction of the resultant pattern.
1430 std::vector<unsigned> Idxs;
1431 Idxs.resize(ChildVariants.size());
1432 bool NotDone = true;
1434 // Create the variant and add it to the output list.
1435 std::vector<TreePatternNode*> NewChildren;
1436 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1437 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
1438 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
1440 // Copy over properties.
1441 R->setName(Orig->getName());
1442 R->setPredicateFn(Orig->getPredicateFn());
1443 R->setTransformFn(Orig->getTransformFn());
1444 R->setTypes(Orig->getExtTypes());
1446 // If this pattern cannot every match, do not include it as a variant.
1447 std::string ErrString;
1448 if (!R->canPatternMatch(ErrString, ISE)) {
1451 bool AlreadyExists = false;
1453 // Scan to see if this pattern has already been emitted. We can get
1454 // duplication due to things like commuting:
1455 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
1456 // which are the same pattern. Ignore the dups.
1457 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
1458 if (R->isIsomorphicTo(OutVariants[i])) {
1459 AlreadyExists = true;
1466 OutVariants.push_back(R);
1469 // Increment indices to the next permutation.
1471 // Look for something we can increment without causing a wrap-around.
1472 for (unsigned IdxsIdx = 0; IdxsIdx != Idxs.size(); ++IdxsIdx) {
1473 if (++Idxs[IdxsIdx] < ChildVariants[IdxsIdx].size()) {
1474 NotDone = true; // Found something to increment.
1482 /// CombineChildVariants - A helper function for binary operators.
1484 static void CombineChildVariants(TreePatternNode *Orig,
1485 const std::vector<TreePatternNode*> &LHS,
1486 const std::vector<TreePatternNode*> &RHS,
1487 std::vector<TreePatternNode*> &OutVariants,
1488 DAGISelEmitter &ISE) {
1489 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1490 ChildVariants.push_back(LHS);
1491 ChildVariants.push_back(RHS);
1492 CombineChildVariants(Orig, ChildVariants, OutVariants, ISE);
1496 static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
1497 std::vector<TreePatternNode *> &Children) {
1498 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
1499 Record *Operator = N->getOperator();
1501 // Only permit raw nodes.
1502 if (!N->getName().empty() || !N->getPredicateFn().empty() ||
1503 N->getTransformFn()) {
1504 Children.push_back(N);
1508 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
1509 Children.push_back(N->getChild(0));
1511 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
1513 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
1514 Children.push_back(N->getChild(1));
1516 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
1519 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
1520 /// the (potentially recursive) pattern by using algebraic laws.
1522 static void GenerateVariantsOf(TreePatternNode *N,
1523 std::vector<TreePatternNode*> &OutVariants,
1524 DAGISelEmitter &ISE) {
1525 // We cannot permute leaves.
1527 OutVariants.push_back(N);
1531 // Look up interesting info about the node.
1532 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(N->getOperator());
1534 // If this node is associative, reassociate.
1535 if (NodeInfo.hasProperty(SDNodeInfo::SDNPAssociative)) {
1536 // Reassociate by pulling together all of the linked operators
1537 std::vector<TreePatternNode*> MaximalChildren;
1538 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
1540 // Only handle child sizes of 3. Otherwise we'll end up trying too many
1542 if (MaximalChildren.size() == 3) {
1543 // Find the variants of all of our maximal children.
1544 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
1545 GenerateVariantsOf(MaximalChildren[0], AVariants, ISE);
1546 GenerateVariantsOf(MaximalChildren[1], BVariants, ISE);
1547 GenerateVariantsOf(MaximalChildren[2], CVariants, ISE);
1549 // There are only two ways we can permute the tree:
1550 // (A op B) op C and A op (B op C)
1551 // Within these forms, we can also permute A/B/C.
1553 // Generate legal pair permutations of A/B/C.
1554 std::vector<TreePatternNode*> ABVariants;
1555 std::vector<TreePatternNode*> BAVariants;
1556 std::vector<TreePatternNode*> ACVariants;
1557 std::vector<TreePatternNode*> CAVariants;
1558 std::vector<TreePatternNode*> BCVariants;
1559 std::vector<TreePatternNode*> CBVariants;
1560 CombineChildVariants(N, AVariants, BVariants, ABVariants, ISE);
1561 CombineChildVariants(N, BVariants, AVariants, BAVariants, ISE);
1562 CombineChildVariants(N, AVariants, CVariants, ACVariants, ISE);
1563 CombineChildVariants(N, CVariants, AVariants, CAVariants, ISE);
1564 CombineChildVariants(N, BVariants, CVariants, BCVariants, ISE);
1565 CombineChildVariants(N, CVariants, BVariants, CBVariants, ISE);
1567 // Combine those into the result: (x op x) op x
1568 CombineChildVariants(N, ABVariants, CVariants, OutVariants, ISE);
1569 CombineChildVariants(N, BAVariants, CVariants, OutVariants, ISE);
1570 CombineChildVariants(N, ACVariants, BVariants, OutVariants, ISE);
1571 CombineChildVariants(N, CAVariants, BVariants, OutVariants, ISE);
1572 CombineChildVariants(N, BCVariants, AVariants, OutVariants, ISE);
1573 CombineChildVariants(N, CBVariants, AVariants, OutVariants, ISE);
1575 // Combine those into the result: x op (x op x)
1576 CombineChildVariants(N, CVariants, ABVariants, OutVariants, ISE);
1577 CombineChildVariants(N, CVariants, BAVariants, OutVariants, ISE);
1578 CombineChildVariants(N, BVariants, ACVariants, OutVariants, ISE);
1579 CombineChildVariants(N, BVariants, CAVariants, OutVariants, ISE);
1580 CombineChildVariants(N, AVariants, BCVariants, OutVariants, ISE);
1581 CombineChildVariants(N, AVariants, CBVariants, OutVariants, ISE);
1586 // Compute permutations of all children.
1587 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1588 ChildVariants.resize(N->getNumChildren());
1589 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1590 GenerateVariantsOf(N->getChild(i), ChildVariants[i], ISE);
1592 // Build all permutations based on how the children were formed.
1593 CombineChildVariants(N, ChildVariants, OutVariants, ISE);
1595 // If this node is commutative, consider the commuted order.
1596 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
1597 assert(N->getNumChildren()==2 &&"Commutative but doesn't have 2 children!");
1598 // Consider the commuted order.
1599 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
1605 // GenerateVariants - Generate variants. For example, commutative patterns can
1606 // match multiple ways. Add them to PatternsToMatch as well.
1607 void DAGISelEmitter::GenerateVariants() {
1609 DEBUG(std::cerr << "Generating instruction variants.\n");
1611 // Loop over all of the patterns we've collected, checking to see if we can
1612 // generate variants of the instruction, through the exploitation of
1613 // identities. This permits the target to provide agressive matching without
1614 // the .td file having to contain tons of variants of instructions.
1616 // Note that this loop adds new patterns to the PatternsToMatch list, but we
1617 // intentionally do not reconsider these. Any variants of added patterns have
1618 // already been added.
1620 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
1621 std::vector<TreePatternNode*> Variants;
1622 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this);
1624 assert(!Variants.empty() && "Must create at least original variant!");
1625 Variants.erase(Variants.begin()); // Remove the original pattern.
1627 if (Variants.empty()) // No variants for this pattern.
1630 DEBUG(std::cerr << "FOUND VARIANTS OF: ";
1631 PatternsToMatch[i].getSrcPattern()->dump();
1634 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
1635 TreePatternNode *Variant = Variants[v];
1637 DEBUG(std::cerr << " VAR#" << v << ": ";
1641 // Scan to see if an instruction or explicit pattern already matches this.
1642 bool AlreadyExists = false;
1643 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
1644 // Check to see if this variant already exists.
1645 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern())) {
1646 DEBUG(std::cerr << " *** ALREADY EXISTS, ignoring variant.\n");
1647 AlreadyExists = true;
1651 // If we already have it, ignore the variant.
1652 if (AlreadyExists) continue;
1654 // Otherwise, add it to the list of patterns we have.
1656 push_back(PatternToMatch(PatternsToMatch[i].getPredicates(),
1657 Variant, PatternsToMatch[i].getDstPattern()));
1660 DEBUG(std::cerr << "\n");
1665 // NodeIsComplexPattern - return true if N is a leaf node and a subclass of
1667 static bool NodeIsComplexPattern(TreePatternNode *N)
1669 return (N->isLeaf() &&
1670 dynamic_cast<DefInit*>(N->getLeafValue()) &&
1671 static_cast<DefInit*>(N->getLeafValue())->getDef()->
1672 isSubClassOf("ComplexPattern"));
1675 // NodeGetComplexPattern - return the pointer to the ComplexPattern if N
1676 // is a leaf node and a subclass of ComplexPattern, else it returns NULL.
1677 static const ComplexPattern *NodeGetComplexPattern(TreePatternNode *N,
1678 DAGISelEmitter &ISE)
1681 dynamic_cast<DefInit*>(N->getLeafValue()) &&
1682 static_cast<DefInit*>(N->getLeafValue())->getDef()->
1683 isSubClassOf("ComplexPattern")) {
1684 return &ISE.getComplexPattern(static_cast<DefInit*>(N->getLeafValue())
1690 /// getPatternSize - Return the 'size' of this pattern. We want to match large
1691 /// patterns before small ones. This is used to determine the size of a
1693 static unsigned getPatternSize(TreePatternNode *P, DAGISelEmitter &ISE) {
1694 assert(isExtIntegerInVTs(P->getExtTypes()) ||
1695 isExtFloatingPointInVTs(P->getExtTypes()) ||
1696 P->getExtTypeNum(0) == MVT::isVoid ||
1697 P->getExtTypeNum(0) == MVT::Flag &&
1698 "Not a valid pattern node to size!");
1699 unsigned Size = 1; // The node itself.
1701 // FIXME: This is a hack to statically increase the priority of patterns
1702 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
1703 // Later we can allow complexity / cost for each pattern to be (optionally)
1704 // specified. To get best possible pattern match we'll need to dynamically
1705 // calculate the complexity of all patterns a dag can potentially map to.
1706 const ComplexPattern *AM = NodeGetComplexPattern(P, ISE);
1708 Size += AM->getNumOperands();
1710 // Count children in the count if they are also nodes.
1711 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
1712 TreePatternNode *Child = P->getChild(i);
1713 if (!Child->isLeaf() && Child->getExtTypeNum(0) != MVT::Other)
1714 Size += getPatternSize(Child, ISE);
1715 else if (Child->isLeaf()) {
1716 if (dynamic_cast<IntInit*>(Child->getLeafValue()))
1717 ++Size; // Matches a ConstantSDNode.
1718 else if (NodeIsComplexPattern(Child))
1719 Size += getPatternSize(Child, ISE);
1726 /// getResultPatternCost - Compute the number of instructions for this pattern.
1727 /// This is a temporary hack. We should really include the instruction
1728 /// latencies in this calculation.
1729 static unsigned getResultPatternCost(TreePatternNode *P) {
1730 if (P->isLeaf()) return 0;
1732 unsigned Cost = P->getOperator()->isSubClassOf("Instruction");
1733 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
1734 Cost += getResultPatternCost(P->getChild(i));
1738 // PatternSortingPredicate - return true if we prefer to match LHS before RHS.
1739 // In particular, we want to match maximal patterns first and lowest cost within
1740 // a particular complexity first.
1741 struct PatternSortingPredicate {
1742 PatternSortingPredicate(DAGISelEmitter &ise) : ISE(ise) {};
1743 DAGISelEmitter &ISE;
1745 bool operator()(PatternToMatch *LHS,
1746 PatternToMatch *RHS) {
1747 unsigned LHSSize = getPatternSize(LHS->getSrcPattern(), ISE);
1748 unsigned RHSSize = getPatternSize(RHS->getSrcPattern(), ISE);
1749 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
1750 if (LHSSize < RHSSize) return false;
1752 // If the patterns have equal complexity, compare generated instruction cost
1753 return getResultPatternCost(LHS->getDstPattern()) <
1754 getResultPatternCost(RHS->getDstPattern());
1758 /// getRegisterValueType - Look up and return the first ValueType of specified
1759 /// RegisterClass record
1760 static MVT::ValueType getRegisterValueType(Record *R, const CodeGenTarget &T) {
1761 if (const CodeGenRegisterClass *RC = T.getRegisterClassForRegister(R))
1762 return RC->getValueTypeNum(0);
1767 /// RemoveAllTypes - A quick recursive walk over a pattern which removes all
1768 /// type information from it.
1769 static void RemoveAllTypes(TreePatternNode *N) {
1772 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1773 RemoveAllTypes(N->getChild(i));
1776 Record *DAGISelEmitter::getSDNodeNamed(const std::string &Name) const {
1777 Record *N = Records.getDef(Name);
1778 assert(N && N->isSubClassOf("SDNode") && "Bad argument");
1782 /// NodeHasChain - return true if TreePatternNode has the property
1783 /// 'hasChain', meaning it reads a ctrl-flow chain operand and writes
1785 static bool NodeHasChain(TreePatternNode *N, DAGISelEmitter &ISE)
1787 if (N->isLeaf()) return false;
1788 Record *Operator = N->getOperator();
1789 if (!Operator->isSubClassOf("SDNode")) return false;
1791 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(Operator);
1792 return NodeInfo.hasProperty(SDNodeInfo::SDNPHasChain);
1795 static bool PatternHasCtrlDep(TreePatternNode *N, DAGISelEmitter &ISE)
1797 if (NodeHasChain(N, ISE))
1800 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
1801 TreePatternNode *Child = N->getChild(i);
1802 if (PatternHasCtrlDep(Child, ISE))
1810 class PatternCodeEmitter {
1812 DAGISelEmitter &ISE;
1815 ListInit *Predicates;
1816 // Instruction selector pattern.
1817 TreePatternNode *Pattern;
1818 // Matched instruction.
1819 TreePatternNode *Instruction;
1822 // Node to name mapping
1823 std::map<std::string,std::string> VariableMap;
1824 // Names of all the folded nodes which produce chains.
1825 std::vector<std::pair<std::string, unsigned> > FoldedChains;
1829 PatternCodeEmitter(DAGISelEmitter &ise, ListInit *preds,
1830 TreePatternNode *pattern, TreePatternNode *instr,
1831 unsigned PatNum, std::ostream &os) :
1832 ISE(ise), Predicates(preds), Pattern(pattern), Instruction(instr),
1833 PatternNo(PatNum), OS(os), TmpNo(0) {}
1835 /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
1836 /// if the match fails. At this point, we already know that the opcode for N
1837 /// matches, and the SDNode for the result has the RootName specified name.
1838 void EmitMatchCode(TreePatternNode *N, const std::string &RootName,
1839 bool &FoundChain, bool isRoot = false) {
1841 // Emit instruction predicates. Each predicate is just a string for now.
1843 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
1844 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
1845 Record *Def = Pred->getDef();
1846 if (Def->isSubClassOf("Predicate")) {
1851 OS << "!(" << Def->getValueAsString("CondString") << ")";
1853 OS << ") goto P" << PatternNo << "Fail;\n";
1856 assert(0 && "Unknown predicate type!");
1863 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
1864 OS << " if (cast<ConstantSDNode>(" << RootName
1865 << ")->getSignExtended() != " << II->getValue() << ")\n"
1866 << " goto P" << PatternNo << "Fail;\n";
1868 } else if (!NodeIsComplexPattern(N)) {
1869 assert(0 && "Cannot match this as a leaf value!");
1874 // If this node has a name associated with it, capture it in VariableMap. If
1875 // we already saw this in the pattern, emit code to verify dagness.
1876 if (!N->getName().empty()) {
1877 std::string &VarMapEntry = VariableMap[N->getName()];
1878 if (VarMapEntry.empty()) {
1879 VarMapEntry = RootName;
1881 // If we get here, this is a second reference to a specific name. Since
1882 // we already have checked that the first reference is valid, we don't
1883 // have to recursively match it, just check that it's the same as the
1884 // previously named thing.
1885 OS << " if (" << VarMapEntry << " != " << RootName
1886 << ") goto P" << PatternNo << "Fail;\n";
1892 // Emit code to load the child nodes and match their contents recursively.
1894 bool HasChain = NodeHasChain(N, ISE);
1898 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(N->getOperator());
1899 OS << " if (!" << RootName << ".hasOneUse()) goto P"
1900 << PatternNo << "Fail; // Multiple uses of actual result?\n";
1901 OS << " if (CodeGenMap.count(" << RootName
1902 << ".getValue(" << CInfo.getNumResults() << "))) goto P"
1903 << PatternNo << "Fail; // Already selected for a chain use?\n";
1907 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
1908 OS << " SDOperand " << RootName << OpNo << " = "
1909 << RootName << ".getOperand(" << OpNo << ");\n";
1910 TreePatternNode *Child = N->getChild(i);
1912 if (!Child->isLeaf()) {
1913 // If it's not a leaf, recursively match.
1914 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(Child->getOperator());
1915 OS << " if (" << RootName << OpNo << ".getOpcode() != "
1916 << CInfo.getEnumName() << ") goto P" << PatternNo << "Fail;\n";
1917 EmitMatchCode(Child, RootName + utostr(OpNo), FoundChain);
1918 if (NodeHasChain(Child, ISE)) {
1919 FoldedChains.push_back(std::make_pair(RootName + utostr(OpNo),
1920 CInfo.getNumResults()));
1923 // If this child has a name associated with it, capture it in VarMap. If
1924 // we already saw this in the pattern, emit code to verify dagness.
1925 if (!Child->getName().empty()) {
1926 std::string &VarMapEntry = VariableMap[Child->getName()];
1927 if (VarMapEntry.empty()) {
1928 VarMapEntry = RootName + utostr(OpNo);
1930 // If we get here, this is a second reference to a specific name. Since
1931 // we already have checked that the first reference is valid, we don't
1932 // have to recursively match it, just check that it's the same as the
1933 // previously named thing.
1934 OS << " if (" << VarMapEntry << " != " << RootName << OpNo
1935 << ") goto P" << PatternNo << "Fail;\n";
1940 // Handle leaves of various types.
1941 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
1942 Record *LeafRec = DI->getDef();
1943 if (LeafRec->isSubClassOf("RegisterClass")) {
1944 // Handle register references. Nothing to do here.
1945 } else if (LeafRec->isSubClassOf("Register")) {
1946 // Handle register references.
1947 } else if (LeafRec->isSubClassOf("ComplexPattern")) {
1948 // Handle complex pattern. Nothing to do here.
1949 } else if (LeafRec->getName() == "srcvalue") {
1950 // Place holder for SRCVALUE nodes. Nothing to do here.
1951 } else if (LeafRec->isSubClassOf("ValueType")) {
1952 // Make sure this is the specified value type.
1953 OS << " if (cast<VTSDNode>(" << RootName << OpNo << ")->getVT() != "
1954 << "MVT::" << LeafRec->getName() << ") goto P" << PatternNo
1956 } else if (LeafRec->isSubClassOf("CondCode")) {
1957 // Make sure this is the specified cond code.
1958 OS << " if (cast<CondCodeSDNode>(" << RootName << OpNo
1959 << ")->get() != " << "ISD::" << LeafRec->getName()
1960 << ") goto P" << PatternNo << "Fail;\n";
1964 assert(0 && "Unknown leaf type!");
1966 } else if (IntInit *II = dynamic_cast<IntInit*>(Child->getLeafValue())) {
1967 OS << " if (!isa<ConstantSDNode>(" << RootName << OpNo << ") ||\n"
1968 << " cast<ConstantSDNode>(" << RootName << OpNo
1969 << ")->getSignExtended() != " << II->getValue() << ")\n"
1970 << " goto P" << PatternNo << "Fail;\n";
1973 assert(0 && "Unknown leaf type!");
1980 OS << " SDOperand Chain = " << RootName << ".getOperand(0);\n";
1985 // If there is a node predicate for this, emit the call.
1986 if (!N->getPredicateFn().empty())
1987 OS << " if (!" << N->getPredicateFn() << "(" << RootName
1988 << ".Val)) goto P" << PatternNo << "Fail;\n";
1991 /// EmitResultCode - Emit the action for a pattern. Now that it has matched
1992 /// we actually have to build a DAG!
1993 std::pair<unsigned, unsigned>
1994 EmitResultCode(TreePatternNode *N, bool isRoot = false) {
1995 // This is something selected from the pattern we matched.
1996 if (!N->getName().empty()) {
1997 assert(!isRoot && "Root of pattern cannot be a leaf!");
1998 std::string &Val = VariableMap[N->getName()];
1999 assert(!Val.empty() &&
2000 "Variable referenced but not defined and not caught earlier!");
2001 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
2002 // Already selected this operand, just return the tmpval.
2003 return std::make_pair(1, atoi(Val.c_str()+3));
2006 const ComplexPattern *CP;
2007 unsigned ResNo = TmpNo++;
2008 unsigned NumRes = 1;
2009 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
2010 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
2011 switch (N->getTypeNum(0)) {
2012 default: assert(0 && "Unknown type for constant node!");
2013 case MVT::i1: OS << " bool Tmp"; break;
2014 case MVT::i8: OS << " unsigned char Tmp"; break;
2015 case MVT::i16: OS << " unsigned short Tmp"; break;
2016 case MVT::i32: OS << " unsigned Tmp"; break;
2017 case MVT::i64: OS << " uint64_t Tmp"; break;
2019 OS << ResNo << "C = cast<ConstantSDNode>(" << Val << ")->getValue();\n";
2020 OS << " SDOperand Tmp" << utostr(ResNo)
2021 << " = CurDAG->getTargetConstant(Tmp"
2022 << ResNo << "C, MVT::" << getEnumName(N->getTypeNum(0)) << ");\n";
2023 } else if (!N->isLeaf() && N->getOperator()->getName() == "tglobaladdr") {
2024 OS << " SDOperand Tmp" << ResNo << " = " << Val << ";\n";
2025 } else if (!N->isLeaf() && N->getOperator()->getName() == "tconstpool") {
2026 OS << " SDOperand Tmp" << ResNo << " = " << Val << ";\n";
2027 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
2028 OS << " SDOperand Tmp" << ResNo << " = " << Val << ";\n";
2029 } else if (N->isLeaf() && (CP = NodeGetComplexPattern(N, ISE))) {
2030 std::string Fn = CP->getSelectFunc();
2031 NumRes = CP->getNumOperands();
2032 OS << " SDOperand ";
2033 for (unsigned i = 0; i != NumRes; ++i)
2034 OS << "Tmp" << (i+ResNo) << ",";
2037 OS << " if (!" << Fn << "(" << Val;
2038 for (unsigned i = 0; i < NumRes; i++)
2039 OS << ", Tmp" << i + ResNo;
2040 OS << ")) goto P" << PatternNo << "Fail;\n";
2041 TmpNo = ResNo + NumRes;
2043 OS << " SDOperand Tmp" << ResNo << " = Select(" << Val << ");\n";
2045 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
2046 // value if used multiple times by this pattern result.
2047 Val = "Tmp"+utostr(ResNo);
2048 return std::make_pair(NumRes, ResNo);
2052 // If this is an explicit register reference, handle it.
2053 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
2054 unsigned ResNo = TmpNo++;
2055 if (DI->getDef()->isSubClassOf("Register")) {
2056 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getRegister("
2057 << ISE.getQualifiedName(DI->getDef()) << ", MVT::"
2058 << getEnumName(N->getTypeNum(0))
2060 return std::make_pair(1, ResNo);
2062 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
2063 unsigned ResNo = TmpNo++;
2064 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
2065 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getTargetConstant("
2066 << II->getValue() << ", MVT::"
2067 << getEnumName(N->getTypeNum(0))
2069 return std::make_pair(1, ResNo);
2073 assert(0 && "Unknown leaf type!");
2074 return std::make_pair(1, ~0U);
2077 Record *Op = N->getOperator();
2078 if (Op->isSubClassOf("Instruction")) {
2079 const CodeGenTarget &CGT = ISE.getTargetInfo();
2080 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
2081 const DAGInstruction &Inst = ISE.getInstruction(Op);
2082 bool HasImpInputs = Inst.getNumImpOperands() > 0;
2083 bool HasImpResults = Inst.getNumImpResults() > 0;
2084 bool HasInFlag = II.hasInFlag || HasImpInputs;
2085 bool HasOutFlag = II.hasOutFlag || HasImpResults;
2086 bool HasChain = II.hasCtrlDep;
2088 if (isRoot && PatternHasCtrlDep(Pattern, ISE))
2090 if (HasInFlag || HasOutFlag)
2091 OS << " SDOperand InFlag = SDOperand(0, 0);\n";
2093 // Determine operand emission order. Complex pattern first.
2094 std::vector<std::pair<unsigned, TreePatternNode*> > EmitOrder;
2095 std::vector<std::pair<unsigned, TreePatternNode*> >::iterator OI;
2096 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2097 TreePatternNode *Child = N->getChild(i);
2099 EmitOrder.push_back(std::make_pair(i, Child));
2100 OI = EmitOrder.begin();
2101 } else if (NodeIsComplexPattern(Child)) {
2102 OI = EmitOrder.insert(OI, std::make_pair(i, Child));
2104 EmitOrder.push_back(std::make_pair(i, Child));
2108 // Emit all of the operands.
2109 std::vector<std::pair<unsigned, unsigned> > NumTemps(EmitOrder.size());
2110 for (unsigned i = 0, e = EmitOrder.size(); i != e; ++i) {
2111 unsigned OpOrder = EmitOrder[i].first;
2112 TreePatternNode *Child = EmitOrder[i].second;
2113 std::pair<unsigned, unsigned> NumTemp = EmitResultCode(Child);
2114 NumTemps[OpOrder] = NumTemp;
2117 // List all the operands in the right order.
2118 std::vector<unsigned> Ops;
2119 for (unsigned i = 0, e = NumTemps.size(); i != e; i++) {
2120 for (unsigned j = 0; j < NumTemps[i].first; j++)
2121 Ops.push_back(NumTemps[i].second + j);
2124 // Emit all the chain and CopyToReg stuff.
2126 OS << " Chain = Select(Chain);\n";
2128 EmitInFlags(Pattern, "N", HasChain, II.hasInFlag, true);
2130 unsigned NumResults = Inst.getNumResults();
2131 unsigned ResNo = TmpNo++;
2133 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getTargetNode("
2134 << II.Namespace << "::" << II.TheDef->getName();
2135 if (N->getTypeNum(0) != MVT::isVoid)
2136 OS << ", MVT::" << getEnumName(N->getTypeNum(0));
2138 OS << ", MVT::Flag";
2140 unsigned LastOp = 0;
2141 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2143 OS << ", Tmp" << LastOp;
2147 // Must have at least one result
2148 OS << " Chain = Tmp" << LastOp << ".getValue("
2149 << NumResults << ");\n";
2151 } else if (HasChain || HasOutFlag) {
2152 OS << " SDOperand Result = CurDAG->getTargetNode("
2153 << II.Namespace << "::" << II.TheDef->getName();
2155 // Output order: results, chain, flags
2157 if (NumResults > 0) {
2158 if (N->getTypeNum(0) != MVT::isVoid)
2159 OS << ", MVT::" << getEnumName(N->getTypeNum(0));
2162 OS << ", MVT::Other";
2164 OS << ", MVT::Flag";
2167 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2168 OS << ", Tmp" << Ops[i];
2169 if (HasChain) OS << ", Chain";
2170 if (HasInFlag) OS << ", InFlag";
2174 for (unsigned i = 0; i < NumResults; i++) {
2175 OS << " CodeGenMap[N.getValue(" << ValNo << ")] = Result"
2176 << ".getValue(" << ValNo << ");\n";
2181 OS << " Chain = Result.getValue(" << ValNo << ");\n";
2184 OS << " InFlag = Result.getValue("
2185 << ValNo + (unsigned)HasChain << ");\n";
2187 if (HasImpResults) {
2188 if (EmitCopyFromRegs(N, HasChain)) {
2189 OS << " CodeGenMap[N.getValue(" << ValNo << ")] = "
2190 << "Result.getValue(" << ValNo << ");\n";
2196 // User does not expect that the instruction produces a chain!
2197 bool AddedChain = HasChain && !NodeHasChain(Pattern, ISE);
2198 if (NodeHasChain(Pattern, ISE))
2199 OS << " CodeGenMap[N.getValue(" << ValNo++ << ")] = Chain;\n";
2201 if (FoldedChains.size() > 0) {
2203 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++)
2204 OS << "CodeGenMap[" << FoldedChains[j].first << ".getValue("
2205 << FoldedChains[j].second << ")] = ";
2210 OS << " CodeGenMap[N.getValue(" << ValNo << ")] = InFlag;\n";
2212 if (AddedChain && HasOutFlag) {
2213 if (NumResults == 0) {
2214 OS << " return Result.getValue(N.ResNo+1);\n";
2216 OS << " if (N.ResNo < " << NumResults << ")\n";
2217 OS << " return Result.getValue(N.ResNo);\n";
2219 OS << " return Result.getValue(N.ResNo+1);\n";
2222 OS << " return Result.getValue(N.ResNo);\n";
2225 // If this instruction is the root, and if there is only one use of it,
2226 // use SelectNodeTo instead of getTargetNode to avoid an allocation.
2227 OS << " if (N.Val->hasOneUse()) {\n";
2228 OS << " return CurDAG->SelectNodeTo(N.Val, "
2229 << II.Namespace << "::" << II.TheDef->getName();
2230 if (N->getTypeNum(0) != MVT::isVoid)
2231 OS << ", MVT::" << getEnumName(N->getTypeNum(0));
2233 OS << ", MVT::Flag";
2234 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2235 OS << ", Tmp" << Ops[i];
2239 OS << " } else {\n";
2240 OS << " return CodeGenMap[N] = CurDAG->getTargetNode("
2241 << II.Namespace << "::" << II.TheDef->getName();
2242 if (N->getTypeNum(0) != MVT::isVoid)
2243 OS << ", MVT::" << getEnumName(N->getTypeNum(0));
2245 OS << ", MVT::Flag";
2246 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2247 OS << ", Tmp" << Ops[i];
2254 return std::make_pair(1, ResNo);
2255 } else if (Op->isSubClassOf("SDNodeXForm")) {
2256 assert(N->getNumChildren() == 1 && "node xform should have one child!");
2257 unsigned OpVal = EmitResultCode(N->getChild(0)).second;
2258 unsigned ResNo = TmpNo++;
2259 OS << " SDOperand Tmp" << ResNo << " = Transform_" << Op->getName()
2260 << "(Tmp" << OpVal << ".Val);\n";
2262 OS << " CodeGenMap[N] = Tmp" << ResNo << ";\n";
2263 OS << " return Tmp" << ResNo << ";\n";
2265 return std::make_pair(1, ResNo);
2268 assert(0 && "Unknown node in result pattern!");
2269 return std::make_pair(1, ~0U);
2273 /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat' and
2274 /// add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
2275 /// 'Pat' may be missing types. If we find an unresolved type to add a check
2276 /// for, this returns true otherwise false if Pat has all types.
2277 bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
2278 const std::string &Prefix) {
2280 if (!Pat->hasTypeSet()) {
2281 // Move a type over from 'other' to 'pat'.
2282 Pat->setTypes(Other->getExtTypes());
2283 OS << " if (" << Prefix << ".Val->getValueType(0) != MVT::"
2284 << getName(Pat->getTypeNum(0)) << ") goto P" << PatternNo << "Fail;\n";
2288 unsigned OpNo = (unsigned) NodeHasChain(Pat, ISE);
2289 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
2290 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
2291 Prefix + utostr(OpNo)))
2297 /// EmitInFlags - Emit the flag operands for the DAG that is
2299 void EmitInFlags(TreePatternNode *N, const std::string &RootName,
2300 bool HasChain, bool HasInFlag, bool isRoot = false) {
2301 const CodeGenTarget &T = ISE.getTargetInfo();
2302 unsigned OpNo = (unsigned) NodeHasChain(N, ISE);
2303 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
2304 TreePatternNode *Child = N->getChild(i);
2305 if (!Child->isLeaf()) {
2306 EmitInFlags(Child, RootName + utostr(OpNo), HasChain, HasInFlag);
2308 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2309 Record *RR = DI->getDef();
2310 if (RR->isSubClassOf("Register")) {
2311 MVT::ValueType RVT = getRegisterValueType(RR, T);
2312 if (RVT == MVT::Flag) {
2313 OS << " InFlag = Select(" << RootName << OpNo << ");\n";
2314 } else if (HasChain) {
2315 OS << " SDOperand " << RootName << "CR" << i << ";\n";
2316 OS << " " << RootName << "CR" << i
2317 << " = CurDAG->getCopyToReg(Chain, CurDAG->getRegister("
2318 << ISE.getQualifiedName(RR) << ", MVT::"
2319 << getEnumName(RVT) << ")"
2320 << ", Select(" << RootName << OpNo << "), InFlag);\n";
2321 OS << " Chain = " << RootName << "CR" << i
2322 << ".getValue(0);\n";
2323 OS << " InFlag = " << RootName << "CR" << i
2324 << ".getValue(1);\n";
2326 OS << " InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode()"
2327 << ", CurDAG->getRegister(" << ISE.getQualifiedName(RR)
2328 << ", MVT::" << getEnumName(RVT) << ")"
2329 << ", Select(" << RootName << OpNo
2330 << "), InFlag).getValue(1);\n";
2337 if (isRoot && HasInFlag) {
2338 OS << " SDOperand " << RootName << OpNo << " = " << RootName
2339 << ".getOperand(" << OpNo << ");\n";
2340 OS << " InFlag = Select(" << RootName << OpNo << ");\n";
2344 /// EmitCopyFromRegs - Emit code to copy result to physical registers
2345 /// as specified by the instruction. It returns true if any copy is
2347 bool EmitCopyFromRegs(TreePatternNode *N, bool HasChain) {
2348 bool RetVal = false;
2349 Record *Op = N->getOperator();
2350 if (Op->isSubClassOf("Instruction")) {
2351 const DAGInstruction &Inst = ISE.getInstruction(Op);
2352 const CodeGenTarget &CGT = ISE.getTargetInfo();
2353 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
2354 unsigned NumImpResults = Inst.getNumImpResults();
2355 for (unsigned i = 0; i < NumImpResults; i++) {
2356 Record *RR = Inst.getImpResult(i);
2357 if (RR->isSubClassOf("Register")) {
2358 MVT::ValueType RVT = getRegisterValueType(RR, CGT);
2359 if (RVT != MVT::Flag) {
2361 OS << " Result = CurDAG->getCopyFromReg(Chain, "
2362 << ISE.getQualifiedName(RR)
2363 << ", MVT::" << getEnumName(RVT) << ", InFlag);\n";
2364 OS << " Chain = Result.getValue(1);\n";
2365 OS << " InFlag = Result.getValue(2);\n";
2368 OS << " Result = CurDAG->getCopyFromReg("
2369 << "CurDAG->getEntryNode(), ISE.getQualifiedName(RR)"
2370 << ", MVT::" << getEnumName(RVT) << ", InFlag);\n";
2371 OS << " Chain = Result.getValue(1);\n";
2372 OS << " InFlag = Result.getValue(2);\n";
2383 /// EmitCodeForPattern - Given a pattern to match, emit code to the specified
2384 /// stream to match the pattern, and generate the code for the match if it
2386 void DAGISelEmitter::EmitCodeForPattern(PatternToMatch &Pattern,
2388 static unsigned PatternCount = 0;
2389 unsigned PatternNo = PatternCount++;
2390 OS << " { // Pattern #" << PatternNo << ": ";
2391 Pattern.getSrcPattern()->print(OS);
2392 OS << "\n // Emits: ";
2393 Pattern.getDstPattern()->print(OS);
2395 OS << " // Pattern complexity = "
2396 << getPatternSize(Pattern.getSrcPattern(), *this)
2398 << getResultPatternCost(Pattern.getDstPattern()) << "\n";
2400 PatternCodeEmitter Emitter(*this, Pattern.getPredicates(),
2401 Pattern.getSrcPattern(), Pattern.getDstPattern(),
2404 // Emit the matcher, capturing named arguments in VariableMap.
2405 bool FoundChain = false;
2406 Emitter.EmitMatchCode(Pattern.getSrcPattern(), "N", FoundChain,
2409 // TP - Get *SOME* tree pattern, we don't care which.
2410 TreePattern &TP = *PatternFragments.begin()->second;
2412 // At this point, we know that we structurally match the pattern, but the
2413 // types of the nodes may not match. Figure out the fewest number of type
2414 // comparisons we need to emit. For example, if there is only one integer
2415 // type supported by a target, there should be no type comparisons at all for
2416 // integer patterns!
2418 // To figure out the fewest number of type checks needed, clone the pattern,
2419 // remove the types, then perform type inference on the pattern as a whole.
2420 // If there are unresolved types, emit an explicit check for those types,
2421 // apply the type to the tree, then rerun type inference. Iterate until all
2422 // types are resolved.
2424 TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
2425 RemoveAllTypes(Pat);
2428 // Resolve/propagate as many types as possible.
2430 bool MadeChange = true;
2432 MadeChange = Pat->ApplyTypeConstraints(TP,true/*Ignore reg constraints*/);
2434 assert(0 && "Error: could not find consistent types for something we"
2435 " already decided was ok!");
2439 // Insert a check for an unresolved type and add it to the tree. If we find
2440 // an unresolved type to add a check for, this returns true and we iterate,
2441 // otherwise we are done.
2442 } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N"));
2444 Emitter.EmitResultCode(Pattern.getDstPattern(), true /*the root*/);
2448 OS << " }\n P" << PatternNo << "Fail:\n";
2453 /// CompareByRecordName - An ordering predicate that implements less-than by
2454 /// comparing the names records.
2455 struct CompareByRecordName {
2456 bool operator()(const Record *LHS, const Record *RHS) const {
2457 // Sort by name first.
2458 if (LHS->getName() < RHS->getName()) return true;
2459 // If both names are equal, sort by pointer.
2460 return LHS->getName() == RHS->getName() && LHS < RHS;
2465 void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
2466 std::string InstNS = Target.inst_begin()->second.Namespace;
2467 if (!InstNS.empty()) InstNS += "::";
2469 // Group the patterns by their top-level opcodes.
2470 std::map<Record*, std::vector<PatternToMatch*>,
2471 CompareByRecordName> PatternsByOpcode;
2472 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
2473 TreePatternNode *Node = PatternsToMatch[i].getSrcPattern();
2474 if (!Node->isLeaf()) {
2475 PatternsByOpcode[Node->getOperator()].push_back(&PatternsToMatch[i]);
2477 const ComplexPattern *CP;
2479 dynamic_cast<IntInit*>(Node->getLeafValue())) {
2480 PatternsByOpcode[getSDNodeNamed("imm")].push_back(&PatternsToMatch[i]);
2481 } else if ((CP = NodeGetComplexPattern(Node, *this))) {
2482 std::vector<Record*> OpNodes = CP->getRootNodes();
2483 for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
2484 PatternsByOpcode[OpNodes[j]].insert(PatternsByOpcode[OpNodes[j]].begin(),
2485 &PatternsToMatch[i]);
2488 std::cerr << "Unrecognized opcode '";
2490 std::cerr << "' on tree pattern '";
2491 std::cerr << PatternsToMatch[i].getDstPattern()->getOperator()->getName();
2492 std::cerr << "'!\n";
2498 // Emit one Select_* method for each top-level opcode. We do this instead of
2499 // emitting one giant switch statement to support compilers where this will
2500 // result in the recursive functions taking less stack space.
2501 for (std::map<Record*, std::vector<PatternToMatch*>,
2502 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
2503 E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
2504 OS << "SDOperand Select_" << PBOI->first->getName() << "(SDOperand N) {\n";
2506 const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
2507 std::vector<PatternToMatch*> &Patterns = PBOI->second;
2509 // We want to emit all of the matching code now. However, we want to emit
2510 // the matches in order of minimal cost. Sort the patterns so the least
2511 // cost one is at the start.
2512 std::stable_sort(Patterns.begin(), Patterns.end(),
2513 PatternSortingPredicate(*this));
2515 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
2516 EmitCodeForPattern(*Patterns[i], OS);
2518 OS << " std::cerr << \"Cannot yet select: \";\n"
2519 << " N.Val->dump(CurDAG);\n"
2520 << " std::cerr << '\\n';\n"
2525 // Emit boilerplate.
2526 OS << "// The main instruction selector code.\n"
2527 << "SDOperand SelectCode(SDOperand N) {\n"
2528 << " if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
2529 << " N.getOpcode() < (ISD::BUILTIN_OP_END+" << InstNS
2530 << "INSTRUCTION_LIST_END))\n"
2531 << " return N; // Already selected.\n\n"
2532 << " std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(N);\n"
2533 << " if (CGMI != CodeGenMap.end()) return CGMI->second;\n"
2534 << " // Work arounds for GCC stack overflow bugs.\n"
2535 << " switch (N.getOpcode()) {\n"
2536 << " default: break;\n"
2537 << " case ISD::EntryToken: // These leaves remain the same.\n"
2538 << " case ISD::BasicBlock:\n"
2540 << " case ISD::AssertSext:\n"
2541 << " case ISD::AssertZext: {\n"
2542 << " SDOperand Tmp0 = Select(N.getOperand(0));\n"
2543 << " if (!N.Val->hasOneUse()) CodeGenMap[N] = Tmp0;\n"
2544 << " return Tmp0;\n"
2546 << " case ISD::TokenFactor:\n"
2547 << " if (N.getNumOperands() == 2) {\n"
2548 << " SDOperand Op0 = Select(N.getOperand(0));\n"
2549 << " SDOperand Op1 = Select(N.getOperand(1));\n"
2550 << " return CodeGenMap[N] =\n"
2551 << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Op0, Op1);\n"
2553 << " std::vector<SDOperand> Ops;\n"
2554 << " for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i)\n"
2555 << " Ops.push_back(Select(N.getOperand(i)));\n"
2556 << " return CodeGenMap[N] = \n"
2557 << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Ops);\n"
2559 << " case ISD::CopyFromReg: {\n"
2560 << " SDOperand Chain = Select(N.getOperand(0));\n"
2561 << " unsigned Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();\n"
2562 << " MVT::ValueType VT = N.Val->getValueType(0);\n"
2563 << " if (N.Val->getNumValues() == 2) {\n"
2564 << " if (Chain == N.getOperand(0)) return N; // No change\n"
2565 << " SDOperand New = CurDAG->getCopyFromReg(Chain, Reg, VT);\n"
2566 << " CodeGenMap[N.getValue(0)] = New;\n"
2567 << " CodeGenMap[N.getValue(1)] = New.getValue(1);\n"
2568 << " return New.getValue(N.ResNo);\n"
2570 << " SDOperand Flag(0, 0);\n"
2571 << " if (N.getNumOperands() == 3) Flag = Select(N.getOperand(2));\n"
2572 << " if (Chain == N.getOperand(0) &&\n"
2573 << " (N.getNumOperands() == 2 || Flag == N.getOperand(2)))\n"
2574 << " return N; // No change\n"
2575 << " SDOperand New = CurDAG->getCopyFromReg(Chain, Reg, VT, Flag);\n"
2576 << " CodeGenMap[N.getValue(0)] = New;\n"
2577 << " CodeGenMap[N.getValue(1)] = New.getValue(1);\n"
2578 << " CodeGenMap[N.getValue(2)] = New.getValue(2);\n"
2579 << " return New.getValue(N.ResNo);\n"
2582 << " case ISD::CopyToReg: {\n"
2583 << " SDOperand Chain = Select(N.getOperand(0));\n"
2584 << " unsigned Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();\n"
2585 << " SDOperand Val = Select(N.getOperand(2));\n"
2586 << " SDOperand Result = N;\n"
2587 << " if (N.Val->getNumValues() == 1) {\n"
2588 << " if (Chain != N.getOperand(0) || Val != N.getOperand(2))\n"
2589 << " Result = CurDAG->getCopyToReg(Chain, Reg, Val);\n"
2590 << " return CodeGenMap[N] = Result;\n"
2592 << " SDOperand Flag(0, 0);\n"
2593 << " if (N.getNumOperands() == 4) Flag = Select(N.getOperand(3));\n"
2594 << " if (Chain != N.getOperand(0) || Val != N.getOperand(2) ||\n"
2595 << " (N.getNumOperands() == 4 && Flag != N.getOperand(3)))\n"
2596 << " Result = CurDAG->getCopyToReg(Chain, Reg, Val, Flag);\n"
2597 << " CodeGenMap[N.getValue(0)] = Result;\n"
2598 << " CodeGenMap[N.getValue(1)] = Result.getValue(1);\n"
2599 << " return Result.getValue(N.ResNo);\n"
2603 // Loop over all of the case statements, emiting a call to each method we
2605 for (std::map<Record*, std::vector<PatternToMatch*>,
2606 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
2607 E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
2608 const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
2609 OS << " case " << OpcodeInfo.getEnumName() << ": "
2610 << std::string(std::max(0, int(16-OpcodeInfo.getEnumName().size())), ' ')
2611 << "return Select_" << PBOI->first->getName() << "(N);\n";
2614 OS << " } // end of big switch.\n\n"
2615 << " std::cerr << \"Cannot yet select: \";\n"
2616 << " N.Val->dump(CurDAG);\n"
2617 << " std::cerr << '\\n';\n"
2622 void DAGISelEmitter::run(std::ostream &OS) {
2623 EmitSourceFileHeader("DAG Instruction Selector for the " + Target.getName() +
2626 OS << "// *** NOTE: This file is #included into the middle of the target\n"
2627 << "// *** instruction selector class. These functions are really "
2630 OS << "// Instance var to keep track of multiply used nodes that have \n"
2631 << "// already been selected.\n"
2632 << "std::map<SDOperand, SDOperand> CodeGenMap;\n";
2635 ParseNodeTransforms(OS);
2636 ParseComplexPatterns();
2637 ParsePatternFragments(OS);
2638 ParseInstructions();
2641 // Generate variants. For example, commutative patterns can match
2642 // multiple ways. Add them to PatternsToMatch as well.
2646 DEBUG(std::cerr << "\n\nALL PATTERNS TO MATCH:\n\n";
2647 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
2648 std::cerr << "PATTERN: "; PatternsToMatch[i].getSrcPattern()->dump();
2649 std::cerr << "\nRESULT: ";PatternsToMatch[i].getDstPattern()->dump();
2653 // At this point, we have full information about the 'Patterns' we need to
2654 // parse, both implicitly from instructions as well as from explicit pattern
2655 // definitions. Emit the resultant instruction selector.
2656 EmitInstructionSelector(OS);
2658 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
2659 E = PatternFragments.end(); I != E; ++I)
2661 PatternFragments.clear();
2663 Instructions.clear();