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"
18 #include "llvm/Support/MathExtras.h"
19 #include "llvm/Support/Streams.h"
24 //===----------------------------------------------------------------------===//
25 // Helpers for working with extended types.
27 /// FilterVTs - Filter a list of VT's according to a predicate.
30 static std::vector<MVT::ValueType>
31 FilterVTs(const std::vector<MVT::ValueType> &InVTs, T Filter) {
32 std::vector<MVT::ValueType> Result;
33 for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
35 Result.push_back(InVTs[i]);
40 static std::vector<unsigned char>
41 FilterEVTs(const std::vector<unsigned char> &InVTs, T Filter) {
42 std::vector<unsigned char> Result;
43 for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
44 if (Filter((MVT::ValueType)InVTs[i]))
45 Result.push_back(InVTs[i]);
49 static std::vector<unsigned char>
50 ConvertVTs(const std::vector<MVT::ValueType> &InVTs) {
51 std::vector<unsigned char> Result;
52 for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
53 Result.push_back(InVTs[i]);
57 static bool LHSIsSubsetOfRHS(const std::vector<unsigned char> &LHS,
58 const std::vector<unsigned char> &RHS) {
59 if (LHS.size() > RHS.size()) return false;
60 for (unsigned i = 0, e = LHS.size(); i != e; ++i)
61 if (std::find(RHS.begin(), RHS.end(), LHS[i]) == RHS.end())
66 /// isExtIntegerVT - Return true if the specified extended value type vector
67 /// contains isInt or an integer value type.
68 static bool isExtIntegerInVTs(const std::vector<unsigned char> &EVTs) {
69 assert(!EVTs.empty() && "Cannot check for integer in empty ExtVT list!");
70 return EVTs[0] == MVT::isInt || !(FilterEVTs(EVTs, MVT::isInteger).empty());
73 /// isExtFloatingPointVT - Return true if the specified extended value type
74 /// vector contains isFP or a FP value type.
75 static bool isExtFloatingPointInVTs(const std::vector<unsigned char> &EVTs) {
76 assert(!EVTs.empty() && "Cannot check for integer in empty ExtVT list!");
77 return EVTs[0] == MVT::isFP ||
78 !(FilterEVTs(EVTs, MVT::isFloatingPoint).empty());
81 //===----------------------------------------------------------------------===//
82 // SDTypeConstraint implementation
85 SDTypeConstraint::SDTypeConstraint(Record *R) {
86 OperandNo = R->getValueAsInt("OperandNum");
88 if (R->isSubClassOf("SDTCisVT")) {
89 ConstraintType = SDTCisVT;
90 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
91 } else if (R->isSubClassOf("SDTCisPtrTy")) {
92 ConstraintType = SDTCisPtrTy;
93 } else if (R->isSubClassOf("SDTCisInt")) {
94 ConstraintType = SDTCisInt;
95 } else if (R->isSubClassOf("SDTCisFP")) {
96 ConstraintType = SDTCisFP;
97 } else if (R->isSubClassOf("SDTCisSameAs")) {
98 ConstraintType = SDTCisSameAs;
99 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
100 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
101 ConstraintType = SDTCisVTSmallerThanOp;
102 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
103 R->getValueAsInt("OtherOperandNum");
104 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
105 ConstraintType = SDTCisOpSmallerThanOp;
106 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
107 R->getValueAsInt("BigOperandNum");
108 } else if (R->isSubClassOf("SDTCisIntVectorOfSameSize")) {
109 ConstraintType = SDTCisIntVectorOfSameSize;
110 x.SDTCisIntVectorOfSameSize_Info.OtherOperandNum =
111 R->getValueAsInt("OtherOpNum");
113 cerr << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
118 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
119 /// N, which has NumResults results.
120 TreePatternNode *SDTypeConstraint::getOperandNum(unsigned OpNo,
122 unsigned NumResults) const {
123 assert(NumResults <= 1 &&
124 "We only work with nodes with zero or one result so far!");
126 if (OpNo >= (NumResults + N->getNumChildren())) {
127 cerr << "Invalid operand number " << OpNo << " ";
133 if (OpNo < NumResults)
134 return N; // FIXME: need value #
136 return N->getChild(OpNo-NumResults);
139 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
140 /// constraint to the nodes operands. This returns true if it makes a
141 /// change, false otherwise. If a type contradiction is found, throw an
143 bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
144 const SDNodeInfo &NodeInfo,
145 TreePattern &TP) const {
146 unsigned NumResults = NodeInfo.getNumResults();
147 assert(NumResults <= 1 &&
148 "We only work with nodes with zero or one result so far!");
150 // Check that the number of operands is sane. Negative operands -> varargs.
151 if (NodeInfo.getNumOperands() >= 0) {
152 if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands())
153 TP.error(N->getOperator()->getName() + " node requires exactly " +
154 itostr(NodeInfo.getNumOperands()) + " operands!");
157 const CodeGenTarget &CGT = TP.getDAGISelEmitter().getTargetInfo();
159 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NumResults);
161 switch (ConstraintType) {
162 default: assert(0 && "Unknown constraint type!");
164 // Operand must be a particular type.
165 return NodeToApply->UpdateNodeType(x.SDTCisVT_Info.VT, TP);
167 // Operand must be same as target pointer type.
168 return NodeToApply->UpdateNodeType(MVT::iPTR, TP);
171 // If there is only one integer type supported, this must be it.
172 std::vector<MVT::ValueType> IntVTs =
173 FilterVTs(CGT.getLegalValueTypes(), MVT::isInteger);
175 // If we found exactly one supported integer type, apply it.
176 if (IntVTs.size() == 1)
177 return NodeToApply->UpdateNodeType(IntVTs[0], TP);
178 return NodeToApply->UpdateNodeType(MVT::isInt, TP);
181 // If there is only one FP type supported, this must be it.
182 std::vector<MVT::ValueType> FPVTs =
183 FilterVTs(CGT.getLegalValueTypes(), MVT::isFloatingPoint);
185 // If we found exactly one supported FP type, apply it.
186 if (FPVTs.size() == 1)
187 return NodeToApply->UpdateNodeType(FPVTs[0], TP);
188 return NodeToApply->UpdateNodeType(MVT::isFP, TP);
191 TreePatternNode *OtherNode =
192 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NumResults);
193 return NodeToApply->UpdateNodeType(OtherNode->getExtTypes(), TP) |
194 OtherNode->UpdateNodeType(NodeToApply->getExtTypes(), TP);
196 case SDTCisVTSmallerThanOp: {
197 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
198 // have an integer type that is smaller than the VT.
199 if (!NodeToApply->isLeaf() ||
200 !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
201 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
202 ->isSubClassOf("ValueType"))
203 TP.error(N->getOperator()->getName() + " expects a VT operand!");
205 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
206 if (!MVT::isInteger(VT))
207 TP.error(N->getOperator()->getName() + " VT operand must be integer!");
209 TreePatternNode *OtherNode =
210 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N,NumResults);
212 // It must be integer.
213 bool MadeChange = false;
214 MadeChange |= OtherNode->UpdateNodeType(MVT::isInt, TP);
216 // This code only handles nodes that have one type set. Assert here so
217 // that we can change this if we ever need to deal with multiple value
218 // types at this point.
219 assert(OtherNode->getExtTypes().size() == 1 && "Node has too many types!");
220 if (OtherNode->hasTypeSet() && OtherNode->getTypeNum(0) <= VT)
221 OtherNode->UpdateNodeType(MVT::Other, TP); // Throw an error.
224 case SDTCisOpSmallerThanOp: {
225 TreePatternNode *BigOperand =
226 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NumResults);
228 // Both operands must be integer or FP, but we don't care which.
229 bool MadeChange = false;
231 // This code does not currently handle nodes which have multiple types,
232 // where some types are integer, and some are fp. Assert that this is not
234 assert(!(isExtIntegerInVTs(NodeToApply->getExtTypes()) &&
235 isExtFloatingPointInVTs(NodeToApply->getExtTypes())) &&
236 !(isExtIntegerInVTs(BigOperand->getExtTypes()) &&
237 isExtFloatingPointInVTs(BigOperand->getExtTypes())) &&
238 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
239 if (isExtIntegerInVTs(NodeToApply->getExtTypes()))
240 MadeChange |= BigOperand->UpdateNodeType(MVT::isInt, TP);
241 else if (isExtFloatingPointInVTs(NodeToApply->getExtTypes()))
242 MadeChange |= BigOperand->UpdateNodeType(MVT::isFP, TP);
243 if (isExtIntegerInVTs(BigOperand->getExtTypes()))
244 MadeChange |= NodeToApply->UpdateNodeType(MVT::isInt, TP);
245 else if (isExtFloatingPointInVTs(BigOperand->getExtTypes()))
246 MadeChange |= NodeToApply->UpdateNodeType(MVT::isFP, TP);
248 std::vector<MVT::ValueType> VTs = CGT.getLegalValueTypes();
250 if (isExtIntegerInVTs(NodeToApply->getExtTypes())) {
251 VTs = FilterVTs(VTs, MVT::isInteger);
252 } else if (isExtFloatingPointInVTs(NodeToApply->getExtTypes())) {
253 VTs = FilterVTs(VTs, MVT::isFloatingPoint);
258 switch (VTs.size()) {
259 default: // Too many VT's to pick from.
260 case 0: break; // No info yet.
262 // Only one VT of this flavor. Cannot ever satisify the constraints.
263 return NodeToApply->UpdateNodeType(MVT::Other, TP); // throw
265 // If we have exactly two possible types, the little operand must be the
266 // small one, the big operand should be the big one. Common with
267 // float/double for example.
268 assert(VTs[0] < VTs[1] && "Should be sorted!");
269 MadeChange |= NodeToApply->UpdateNodeType(VTs[0], TP);
270 MadeChange |= BigOperand->UpdateNodeType(VTs[1], TP);
275 case SDTCisIntVectorOfSameSize: {
276 TreePatternNode *OtherOperand =
277 getOperandNum(x.SDTCisIntVectorOfSameSize_Info.OtherOperandNum,
279 if (OtherOperand->hasTypeSet()) {
280 if (!MVT::isVector(OtherOperand->getTypeNum(0)))
281 TP.error(N->getOperator()->getName() + " VT operand must be a vector!");
282 MVT::ValueType IVT = OtherOperand->getTypeNum(0);
283 IVT = MVT::getIntVectorWithNumElements(MVT::getVectorNumElements(IVT));
284 return NodeToApply->UpdateNodeType(IVT, TP);
293 //===----------------------------------------------------------------------===//
294 // SDNodeInfo implementation
296 SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
297 EnumName = R->getValueAsString("Opcode");
298 SDClassName = R->getValueAsString("SDClass");
299 Record *TypeProfile = R->getValueAsDef("TypeProfile");
300 NumResults = TypeProfile->getValueAsInt("NumResults");
301 NumOperands = TypeProfile->getValueAsInt("NumOperands");
303 // Parse the properties.
305 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
306 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
307 if (PropList[i]->getName() == "SDNPCommutative") {
308 Properties |= 1 << SDNPCommutative;
309 } else if (PropList[i]->getName() == "SDNPAssociative") {
310 Properties |= 1 << SDNPAssociative;
311 } else if (PropList[i]->getName() == "SDNPHasChain") {
312 Properties |= 1 << SDNPHasChain;
313 } else if (PropList[i]->getName() == "SDNPOutFlag") {
314 Properties |= 1 << SDNPOutFlag;
315 } else if (PropList[i]->getName() == "SDNPInFlag") {
316 Properties |= 1 << SDNPInFlag;
317 } else if (PropList[i]->getName() == "SDNPOptInFlag") {
318 Properties |= 1 << SDNPOptInFlag;
320 cerr << "Unknown SD Node property '" << PropList[i]->getName()
321 << "' on node '" << R->getName() << "'!\n";
327 // Parse the type constraints.
328 std::vector<Record*> ConstraintList =
329 TypeProfile->getValueAsListOfDefs("Constraints");
330 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
333 //===----------------------------------------------------------------------===//
334 // TreePatternNode implementation
337 TreePatternNode::~TreePatternNode() {
338 #if 0 // FIXME: implement refcounted tree nodes!
339 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
344 /// UpdateNodeType - Set the node type of N to VT if VT contains
345 /// information. If N already contains a conflicting type, then throw an
346 /// exception. This returns true if any information was updated.
348 bool TreePatternNode::UpdateNodeType(const std::vector<unsigned char> &ExtVTs,
350 assert(!ExtVTs.empty() && "Cannot update node type with empty type vector!");
352 if (ExtVTs[0] == MVT::isUnknown || LHSIsSubsetOfRHS(getExtTypes(), ExtVTs))
354 if (isTypeCompletelyUnknown() || LHSIsSubsetOfRHS(ExtVTs, getExtTypes())) {
359 if (getExtTypeNum(0) == MVT::iPTR) {
360 if (ExtVTs[0] == MVT::iPTR || ExtVTs[0] == MVT::isInt)
362 if (isExtIntegerInVTs(ExtVTs)) {
363 std::vector<unsigned char> FVTs = FilterEVTs(ExtVTs, MVT::isInteger);
371 if (ExtVTs[0] == MVT::isInt && isExtIntegerInVTs(getExtTypes())) {
372 assert(hasTypeSet() && "should be handled above!");
373 std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), MVT::isInteger);
374 if (getExtTypes() == FVTs)
379 if (ExtVTs[0] == MVT::iPTR && isExtIntegerInVTs(getExtTypes())) {
380 //assert(hasTypeSet() && "should be handled above!");
381 std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), MVT::isInteger);
382 if (getExtTypes() == FVTs)
389 if (ExtVTs[0] == MVT::isFP && isExtFloatingPointInVTs(getExtTypes())) {
390 assert(hasTypeSet() && "should be handled above!");
391 std::vector<unsigned char> FVTs =
392 FilterEVTs(getExtTypes(), MVT::isFloatingPoint);
393 if (getExtTypes() == FVTs)
399 // If we know this is an int or fp type, and we are told it is a specific one,
402 // Similarly, we should probably set the type here to the intersection of
403 // {isInt|isFP} and ExtVTs
404 if ((getExtTypeNum(0) == MVT::isInt && isExtIntegerInVTs(ExtVTs)) ||
405 (getExtTypeNum(0) == MVT::isFP && isExtFloatingPointInVTs(ExtVTs))) {
409 if (getExtTypeNum(0) == MVT::isInt && ExtVTs[0] == MVT::iPTR) {
417 TP.error("Type inference contradiction found in node!");
419 TP.error("Type inference contradiction found in node " +
420 getOperator()->getName() + "!");
422 return true; // unreachable
426 void TreePatternNode::print(std::ostream &OS) const {
428 OS << *getLeafValue();
430 OS << "(" << getOperator()->getName();
433 // FIXME: At some point we should handle printing all the value types for
434 // nodes that are multiply typed.
435 switch (getExtTypeNum(0)) {
436 case MVT::Other: OS << ":Other"; break;
437 case MVT::isInt: OS << ":isInt"; break;
438 case MVT::isFP : OS << ":isFP"; break;
439 case MVT::isUnknown: ; /*OS << ":?";*/ break;
440 case MVT::iPTR: OS << ":iPTR"; break;
442 std::string VTName = llvm::getName(getTypeNum(0));
443 // Strip off MVT:: prefix if present.
444 if (VTName.substr(0,5) == "MVT::")
445 VTName = VTName.substr(5);
452 if (getNumChildren() != 0) {
454 getChild(0)->print(OS);
455 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
457 getChild(i)->print(OS);
463 if (!PredicateFn.empty())
464 OS << "<<P:" << PredicateFn << ">>";
466 OS << "<<X:" << TransformFn->getName() << ">>";
467 if (!getName().empty())
468 OS << ":$" << getName();
471 void TreePatternNode::dump() const {
472 print(*cerr.stream());
475 /// isIsomorphicTo - Return true if this node is recursively isomorphic to
476 /// the specified node. For this comparison, all of the state of the node
477 /// is considered, except for the assigned name. Nodes with differing names
478 /// that are otherwise identical are considered isomorphic.
479 bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N) const {
480 if (N == this) return true;
481 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
482 getPredicateFn() != N->getPredicateFn() ||
483 getTransformFn() != N->getTransformFn())
487 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue()))
488 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue()))
489 return DI->getDef() == NDI->getDef();
490 return getLeafValue() == N->getLeafValue();
493 if (N->getOperator() != getOperator() ||
494 N->getNumChildren() != getNumChildren()) return false;
495 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
496 if (!getChild(i)->isIsomorphicTo(N->getChild(i)))
501 /// clone - Make a copy of this tree and all of its children.
503 TreePatternNode *TreePatternNode::clone() const {
504 TreePatternNode *New;
506 New = new TreePatternNode(getLeafValue());
508 std::vector<TreePatternNode*> CChildren;
509 CChildren.reserve(Children.size());
510 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
511 CChildren.push_back(getChild(i)->clone());
512 New = new TreePatternNode(getOperator(), CChildren);
514 New->setName(getName());
515 New->setTypes(getExtTypes());
516 New->setPredicateFn(getPredicateFn());
517 New->setTransformFn(getTransformFn());
521 /// SubstituteFormalArguments - Replace the formal arguments in this tree
522 /// with actual values specified by ArgMap.
523 void TreePatternNode::
524 SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
525 if (isLeaf()) return;
527 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
528 TreePatternNode *Child = getChild(i);
529 if (Child->isLeaf()) {
530 Init *Val = Child->getLeafValue();
531 if (dynamic_cast<DefInit*>(Val) &&
532 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
533 // We found a use of a formal argument, replace it with its value.
534 Child = ArgMap[Child->getName()];
535 assert(Child && "Couldn't find formal argument!");
539 getChild(i)->SubstituteFormalArguments(ArgMap);
545 /// InlinePatternFragments - If this pattern refers to any pattern
546 /// fragments, inline them into place, giving us a pattern without any
547 /// PatFrag references.
548 TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
549 if (isLeaf()) return this; // nothing to do.
550 Record *Op = getOperator();
552 if (!Op->isSubClassOf("PatFrag")) {
553 // Just recursively inline children nodes.
554 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
555 setChild(i, getChild(i)->InlinePatternFragments(TP));
559 // Otherwise, we found a reference to a fragment. First, look up its
560 // TreePattern record.
561 TreePattern *Frag = TP.getDAGISelEmitter().getPatternFragment(Op);
563 // Verify that we are passing the right number of operands.
564 if (Frag->getNumArgs() != Children.size())
565 TP.error("'" + Op->getName() + "' fragment requires " +
566 utostr(Frag->getNumArgs()) + " operands!");
568 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
570 // Resolve formal arguments to their actual value.
571 if (Frag->getNumArgs()) {
572 // Compute the map of formal to actual arguments.
573 std::map<std::string, TreePatternNode*> ArgMap;
574 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
575 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
577 FragTree->SubstituteFormalArguments(ArgMap);
580 FragTree->setName(getName());
581 FragTree->UpdateNodeType(getExtTypes(), TP);
583 // Get a new copy of this fragment to stitch into here.
584 //delete this; // FIXME: implement refcounting!
588 /// getImplicitType - Check to see if the specified record has an implicit
589 /// type which should be applied to it. This infer the type of register
590 /// references from the register file information, for example.
592 static std::vector<unsigned char> getImplicitType(Record *R, bool NotRegisters,
594 // Some common return values
595 std::vector<unsigned char> Unknown(1, MVT::isUnknown);
596 std::vector<unsigned char> Other(1, MVT::Other);
598 // Check to see if this is a register or a register class...
599 if (R->isSubClassOf("RegisterClass")) {
602 const CodeGenRegisterClass &RC =
603 TP.getDAGISelEmitter().getTargetInfo().getRegisterClass(R);
604 return ConvertVTs(RC.getValueTypes());
605 } else if (R->isSubClassOf("PatFrag")) {
606 // Pattern fragment types will be resolved when they are inlined.
608 } else if (R->isSubClassOf("Register")) {
611 const CodeGenTarget &T = TP.getDAGISelEmitter().getTargetInfo();
612 return T.getRegisterVTs(R);
613 } else if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
614 // Using a VTSDNode or CondCodeSDNode.
616 } else if (R->isSubClassOf("ComplexPattern")) {
619 std::vector<unsigned char>
620 ComplexPat(1, TP.getDAGISelEmitter().getComplexPattern(R).getValueType());
622 } else if (R->getName() == "ptr_rc") {
623 Other[0] = MVT::iPTR;
625 } else if (R->getName() == "node" || R->getName() == "srcvalue") {
630 TP.error("Unknown node flavor used in pattern: " + R->getName());
634 /// ApplyTypeConstraints - Apply all of the type constraints relevent to
635 /// this node and its children in the tree. This returns true if it makes a
636 /// change, false otherwise. If a type contradiction is found, throw an
638 bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
639 DAGISelEmitter &ISE = TP.getDAGISelEmitter();
641 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
642 // If it's a regclass or something else known, include the type.
643 return UpdateNodeType(getImplicitType(DI->getDef(), NotRegisters, TP),TP);
644 } else if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
645 // Int inits are always integers. :)
646 bool MadeChange = UpdateNodeType(MVT::isInt, TP);
649 // At some point, it may make sense for this tree pattern to have
650 // multiple types. Assert here that it does not, so we revisit this
651 // code when appropriate.
652 assert(getExtTypes().size() >= 1 && "TreePattern doesn't have a type!");
653 MVT::ValueType VT = getTypeNum(0);
654 for (unsigned i = 1, e = getExtTypes().size(); i != e; ++i)
655 assert(getTypeNum(i) == VT && "TreePattern has too many types!");
658 if (VT != MVT::iPTR) {
659 unsigned Size = MVT::getSizeInBits(VT);
660 // Make sure that the value is representable for this type.
662 int Val = (II->getValue() << (32-Size)) >> (32-Size);
663 if (Val != II->getValue())
664 TP.error("Sign-extended integer value '" + itostr(II->getValue())+
665 "' is out of range for type '" +
666 getEnumName(getTypeNum(0)) + "'!");
676 // special handling for set, which isn't really an SDNode.
677 if (getOperator()->getName() == "set") {
678 assert (getNumChildren() == 2 && "Only handle 2 operand set's for now!");
679 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
680 MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
682 // Types of operands must match.
683 MadeChange |= getChild(0)->UpdateNodeType(getChild(1)->getExtTypes(), TP);
684 MadeChange |= getChild(1)->UpdateNodeType(getChild(0)->getExtTypes(), TP);
685 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
687 } else if (getOperator() == ISE.get_intrinsic_void_sdnode() ||
688 getOperator() == ISE.get_intrinsic_w_chain_sdnode() ||
689 getOperator() == ISE.get_intrinsic_wo_chain_sdnode()) {
691 dynamic_cast<IntInit*>(getChild(0)->getLeafValue())->getValue();
692 const CodeGenIntrinsic &Int = ISE.getIntrinsicInfo(IID);
693 bool MadeChange = false;
695 // Apply the result type to the node.
696 MadeChange = UpdateNodeType(Int.ArgVTs[0], TP);
698 if (getNumChildren() != Int.ArgVTs.size())
699 TP.error("Intrinsic '" + Int.Name + "' expects " +
700 utostr(Int.ArgVTs.size()-1) + " operands, not " +
701 utostr(getNumChildren()-1) + " operands!");
703 // Apply type info to the intrinsic ID.
704 MadeChange |= getChild(0)->UpdateNodeType(MVT::iPTR, TP);
706 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
707 MVT::ValueType OpVT = Int.ArgVTs[i];
708 MadeChange |= getChild(i)->UpdateNodeType(OpVT, TP);
709 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
712 } else if (getOperator()->isSubClassOf("SDNode")) {
713 const SDNodeInfo &NI = ISE.getSDNodeInfo(getOperator());
715 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
716 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
717 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
718 // Branch, etc. do not produce results and top-level forms in instr pattern
719 // must have void types.
720 if (NI.getNumResults() == 0)
721 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
723 // If this is a vector_shuffle operation, apply types to the build_vector
724 // operation. The types of the integers don't matter, but this ensures they
725 // won't get checked.
726 if (getOperator()->getName() == "vector_shuffle" &&
727 getChild(2)->getOperator()->getName() == "build_vector") {
728 TreePatternNode *BV = getChild(2);
729 const std::vector<MVT::ValueType> &LegalVTs
730 = ISE.getTargetInfo().getLegalValueTypes();
731 MVT::ValueType LegalIntVT = MVT::Other;
732 for (unsigned i = 0, e = LegalVTs.size(); i != e; ++i)
733 if (MVT::isInteger(LegalVTs[i]) && !MVT::isVector(LegalVTs[i])) {
734 LegalIntVT = LegalVTs[i];
737 assert(LegalIntVT != MVT::Other && "No legal integer VT?");
739 for (unsigned i = 0, e = BV->getNumChildren(); i != e; ++i)
740 MadeChange |= BV->getChild(i)->UpdateNodeType(LegalIntVT, TP);
743 } else if (getOperator()->isSubClassOf("Instruction")) {
744 const DAGInstruction &Inst = ISE.getInstruction(getOperator());
745 bool MadeChange = false;
746 unsigned NumResults = Inst.getNumResults();
748 assert(NumResults <= 1 &&
749 "Only supports zero or one result instrs!");
751 CodeGenInstruction &InstInfo =
752 ISE.getTargetInfo().getInstruction(getOperator()->getName());
753 // Apply the result type to the node
754 if (NumResults == 0 || InstInfo.noResults) { // FIXME: temporary hack.
755 MadeChange = UpdateNodeType(MVT::isVoid, TP);
757 Record *ResultNode = Inst.getResult(0);
759 if (ResultNode->getName() == "ptr_rc") {
760 std::vector<unsigned char> VT;
761 VT.push_back(MVT::iPTR);
762 MadeChange = UpdateNodeType(VT, TP);
764 assert(ResultNode->isSubClassOf("RegisterClass") &&
765 "Operands should be register classes!");
767 const CodeGenRegisterClass &RC =
768 ISE.getTargetInfo().getRegisterClass(ResultNode);
769 MadeChange = UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
773 unsigned ChildNo = 0;
774 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
775 Record *OperandNode = Inst.getOperand(i);
777 // If the instruction expects a predicate operand, we codegen this by
778 // setting the predicate to it's "execute always" value.
779 if (OperandNode->isSubClassOf("PredicateOperand"))
782 // Verify that we didn't run out of provided operands.
783 if (ChildNo >= getNumChildren())
784 TP.error("Instruction '" + getOperator()->getName() +
785 "' expects more operands than were provided.");
788 TreePatternNode *Child = getChild(ChildNo++);
789 if (OperandNode->isSubClassOf("RegisterClass")) {
790 const CodeGenRegisterClass &RC =
791 ISE.getTargetInfo().getRegisterClass(OperandNode);
792 MadeChange |= Child->UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
793 } else if (OperandNode->isSubClassOf("Operand")) {
794 VT = getValueType(OperandNode->getValueAsDef("Type"));
795 MadeChange |= Child->UpdateNodeType(VT, TP);
796 } else if (OperandNode->getName() == "ptr_rc") {
797 MadeChange |= Child->UpdateNodeType(MVT::iPTR, TP);
799 assert(0 && "Unknown operand type!");
802 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
805 if (ChildNo != getNumChildren())
806 TP.error("Instruction '" + getOperator()->getName() +
807 "' was provided too many operands!");
811 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
813 // Node transforms always take one operand.
814 if (getNumChildren() != 1)
815 TP.error("Node transform '" + getOperator()->getName() +
816 "' requires one operand!");
818 // If either the output or input of the xform does not have exact
819 // type info. We assume they must be the same. Otherwise, it is perfectly
820 // legal to transform from one type to a completely different type.
821 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
822 bool MadeChange = UpdateNodeType(getChild(0)->getExtTypes(), TP);
823 MadeChange |= getChild(0)->UpdateNodeType(getExtTypes(), TP);
830 /// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
831 /// RHS of a commutative operation, not the on LHS.
832 static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
833 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
835 if (N->isLeaf() && dynamic_cast<IntInit*>(N->getLeafValue()))
841 /// canPatternMatch - If it is impossible for this pattern to match on this
842 /// target, fill in Reason and return false. Otherwise, return true. This is
843 /// used as a santity check for .td files (to prevent people from writing stuff
844 /// that can never possibly work), and to prevent the pattern permuter from
845 /// generating stuff that is useless.
846 bool TreePatternNode::canPatternMatch(std::string &Reason, DAGISelEmitter &ISE){
847 if (isLeaf()) return true;
849 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
850 if (!getChild(i)->canPatternMatch(Reason, ISE))
853 // If this is an intrinsic, handle cases that would make it not match. For
854 // example, if an operand is required to be an immediate.
855 if (getOperator()->isSubClassOf("Intrinsic")) {
860 // If this node is a commutative operator, check that the LHS isn't an
862 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(getOperator());
863 if (NodeInfo.hasProperty(SDNPCommutative)) {
864 // Scan all of the operands of the node and make sure that only the last one
865 // is a constant node, unless the RHS also is.
866 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
867 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i)
868 if (OnlyOnRHSOfCommutative(getChild(i))) {
869 Reason="Immediate value must be on the RHS of commutative operators!";
878 //===----------------------------------------------------------------------===//
879 // TreePattern implementation
882 TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
883 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
884 isInputPattern = isInput;
885 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
886 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
889 TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
890 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
891 isInputPattern = isInput;
892 Trees.push_back(ParseTreePattern(Pat));
895 TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
896 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
897 isInputPattern = isInput;
898 Trees.push_back(Pat);
903 void TreePattern::error(const std::string &Msg) const {
905 throw "In " + TheRecord->getName() + ": " + Msg;
908 TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
909 DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
910 if (!OpDef) error("Pattern has unexpected operator type!");
911 Record *Operator = OpDef->getDef();
913 if (Operator->isSubClassOf("ValueType")) {
914 // If the operator is a ValueType, then this must be "type cast" of a leaf
916 if (Dag->getNumArgs() != 1)
917 error("Type cast only takes one operand!");
919 Init *Arg = Dag->getArg(0);
920 TreePatternNode *New;
921 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
922 Record *R = DI->getDef();
923 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
924 Dag->setArg(0, new DagInit(DI,
925 std::vector<std::pair<Init*, std::string> >()));
926 return ParseTreePattern(Dag);
928 New = new TreePatternNode(DI);
929 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
930 New = ParseTreePattern(DI);
931 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
932 New = new TreePatternNode(II);
933 if (!Dag->getArgName(0).empty())
934 error("Constant int argument should not have a name!");
935 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
936 // Turn this into an IntInit.
937 Init *II = BI->convertInitializerTo(new IntRecTy());
938 if (II == 0 || !dynamic_cast<IntInit*>(II))
939 error("Bits value must be constants!");
941 New = new TreePatternNode(dynamic_cast<IntInit*>(II));
942 if (!Dag->getArgName(0).empty())
943 error("Constant int argument should not have a name!");
946 error("Unknown leaf value for tree pattern!");
950 // Apply the type cast.
951 New->UpdateNodeType(getValueType(Operator), *this);
952 New->setName(Dag->getArgName(0));
956 // Verify that this is something that makes sense for an operator.
957 if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
958 !Operator->isSubClassOf("Instruction") &&
959 !Operator->isSubClassOf("SDNodeXForm") &&
960 !Operator->isSubClassOf("Intrinsic") &&
961 Operator->getName() != "set")
962 error("Unrecognized node '" + Operator->getName() + "'!");
964 // Check to see if this is something that is illegal in an input pattern.
965 if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
966 Operator->isSubClassOf("SDNodeXForm")))
967 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
969 std::vector<TreePatternNode*> Children;
971 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
972 Init *Arg = Dag->getArg(i);
973 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
974 Children.push_back(ParseTreePattern(DI));
975 if (Children.back()->getName().empty())
976 Children.back()->setName(Dag->getArgName(i));
977 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
978 Record *R = DefI->getDef();
979 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
980 // TreePatternNode if its own.
981 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
982 Dag->setArg(i, new DagInit(DefI,
983 std::vector<std::pair<Init*, std::string> >()));
984 --i; // Revisit this node...
986 TreePatternNode *Node = new TreePatternNode(DefI);
987 Node->setName(Dag->getArgName(i));
988 Children.push_back(Node);
991 if (R->getName() == "node") {
992 if (Dag->getArgName(i).empty())
993 error("'node' argument requires a name to match with operand list");
994 Args.push_back(Dag->getArgName(i));
997 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
998 TreePatternNode *Node = new TreePatternNode(II);
999 if (!Dag->getArgName(i).empty())
1000 error("Constant int argument should not have a name!");
1001 Children.push_back(Node);
1002 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
1003 // Turn this into an IntInit.
1004 Init *II = BI->convertInitializerTo(new IntRecTy());
1005 if (II == 0 || !dynamic_cast<IntInit*>(II))
1006 error("Bits value must be constants!");
1008 TreePatternNode *Node = new TreePatternNode(dynamic_cast<IntInit*>(II));
1009 if (!Dag->getArgName(i).empty())
1010 error("Constant int argument should not have a name!");
1011 Children.push_back(Node);
1016 error("Unknown leaf value for tree pattern!");
1020 // If the operator is an intrinsic, then this is just syntactic sugar for for
1021 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
1022 // convert the intrinsic name to a number.
1023 if (Operator->isSubClassOf("Intrinsic")) {
1024 const CodeGenIntrinsic &Int = getDAGISelEmitter().getIntrinsic(Operator);
1025 unsigned IID = getDAGISelEmitter().getIntrinsicID(Operator)+1;
1027 // If this intrinsic returns void, it must have side-effects and thus a
1029 if (Int.ArgVTs[0] == MVT::isVoid) {
1030 Operator = getDAGISelEmitter().get_intrinsic_void_sdnode();
1031 } else if (Int.ModRef != CodeGenIntrinsic::NoMem) {
1032 // Has side-effects, requires chain.
1033 Operator = getDAGISelEmitter().get_intrinsic_w_chain_sdnode();
1035 // Otherwise, no chain.
1036 Operator = getDAGISelEmitter().get_intrinsic_wo_chain_sdnode();
1039 TreePatternNode *IIDNode = new TreePatternNode(new IntInit(IID));
1040 Children.insert(Children.begin(), IIDNode);
1043 return new TreePatternNode(Operator, Children);
1046 /// InferAllTypes - Infer/propagate as many types throughout the expression
1047 /// patterns as possible. Return true if all types are infered, false
1048 /// otherwise. Throw an exception if a type contradiction is found.
1049 bool TreePattern::InferAllTypes() {
1050 bool MadeChange = true;
1051 while (MadeChange) {
1053 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1054 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
1057 bool HasUnresolvedTypes = false;
1058 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1059 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
1060 return !HasUnresolvedTypes;
1063 void TreePattern::print(std::ostream &OS) const {
1064 OS << getRecord()->getName();
1065 if (!Args.empty()) {
1066 OS << "(" << Args[0];
1067 for (unsigned i = 1, e = Args.size(); i != e; ++i)
1068 OS << ", " << Args[i];
1073 if (Trees.size() > 1)
1075 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
1077 Trees[i]->print(OS);
1081 if (Trees.size() > 1)
1085 void TreePattern::dump() const { print(*cerr.stream()); }
1089 //===----------------------------------------------------------------------===//
1090 // DAGISelEmitter implementation
1093 // Parse all of the SDNode definitions for the target, populating SDNodes.
1094 void DAGISelEmitter::ParseNodeInfo() {
1095 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
1096 while (!Nodes.empty()) {
1097 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
1101 // Get the buildin intrinsic nodes.
1102 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
1103 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
1104 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
1107 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
1108 /// map, and emit them to the file as functions.
1109 void DAGISelEmitter::ParseNodeTransforms(std::ostream &OS) {
1110 OS << "\n// Node transformations.\n";
1111 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
1112 while (!Xforms.empty()) {
1113 Record *XFormNode = Xforms.back();
1114 Record *SDNode = XFormNode->getValueAsDef("Opcode");
1115 std::string Code = XFormNode->getValueAsCode("XFormFunction");
1116 SDNodeXForms.insert(std::make_pair(XFormNode,
1117 std::make_pair(SDNode, Code)));
1119 if (!Code.empty()) {
1120 std::string ClassName = getSDNodeInfo(SDNode).getSDClassName();
1121 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
1123 OS << "inline SDOperand Transform_" << XFormNode->getName()
1124 << "(SDNode *" << C2 << ") {\n";
1125 if (ClassName != "SDNode")
1126 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
1127 OS << Code << "\n}\n";
1134 void DAGISelEmitter::ParseComplexPatterns() {
1135 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
1136 while (!AMs.empty()) {
1137 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
1143 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
1144 /// file, building up the PatternFragments map. After we've collected them all,
1145 /// inline fragments together as necessary, so that there are no references left
1146 /// inside a pattern fragment to a pattern fragment.
1148 /// This also emits all of the predicate functions to the output file.
1150 void DAGISelEmitter::ParsePatternFragments(std::ostream &OS) {
1151 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
1153 // First step, parse all of the fragments and emit predicate functions.
1154 OS << "\n// Predicate functions.\n";
1155 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1156 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
1157 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
1158 PatternFragments[Fragments[i]] = P;
1160 // Validate the argument list, converting it to map, to discard duplicates.
1161 std::vector<std::string> &Args = P->getArgList();
1162 std::set<std::string> OperandsMap(Args.begin(), Args.end());
1164 if (OperandsMap.count(""))
1165 P->error("Cannot have unnamed 'node' values in pattern fragment!");
1167 // Parse the operands list.
1168 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
1169 DefInit *OpsOp = dynamic_cast<DefInit*>(OpsList->getOperator());
1170 if (!OpsOp || OpsOp->getDef()->getName() != "ops")
1171 P->error("Operands list should start with '(ops ... '!");
1173 // Copy over the arguments.
1175 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
1176 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
1177 static_cast<DefInit*>(OpsList->getArg(j))->
1178 getDef()->getName() != "node")
1179 P->error("Operands list should all be 'node' values.");
1180 if (OpsList->getArgName(j).empty())
1181 P->error("Operands list should have names for each operand!");
1182 if (!OperandsMap.count(OpsList->getArgName(j)))
1183 P->error("'" + OpsList->getArgName(j) +
1184 "' does not occur in pattern or was multiply specified!");
1185 OperandsMap.erase(OpsList->getArgName(j));
1186 Args.push_back(OpsList->getArgName(j));
1189 if (!OperandsMap.empty())
1190 P->error("Operands list does not contain an entry for operand '" +
1191 *OperandsMap.begin() + "'!");
1193 // If there is a code init for this fragment, emit the predicate code and
1194 // keep track of the fact that this fragment uses it.
1195 std::string Code = Fragments[i]->getValueAsCode("Predicate");
1196 if (!Code.empty()) {
1197 if (P->getOnlyTree()->isLeaf())
1198 OS << "inline bool Predicate_" << Fragments[i]->getName()
1199 << "(SDNode *N) {\n";
1201 std::string ClassName =
1202 getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
1203 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
1205 OS << "inline bool Predicate_" << Fragments[i]->getName()
1206 << "(SDNode *" << C2 << ") {\n";
1207 if (ClassName != "SDNode")
1208 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
1210 OS << Code << "\n}\n";
1211 P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
1214 // If there is a node transformation corresponding to this, keep track of
1216 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
1217 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
1218 P->getOnlyTree()->setTransformFn(Transform);
1223 // Now that we've parsed all of the tree fragments, do a closure on them so
1224 // that there are not references to PatFrags left inside of them.
1225 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
1226 E = PatternFragments.end(); I != E; ++I) {
1227 TreePattern *ThePat = I->second;
1228 ThePat->InlinePatternFragments();
1230 // Infer as many types as possible. Don't worry about it if we don't infer
1231 // all of them, some may depend on the inputs of the pattern.
1233 ThePat->InferAllTypes();
1235 // If this pattern fragment is not supported by this target (no types can
1236 // satisfy its constraints), just ignore it. If the bogus pattern is
1237 // actually used by instructions, the type consistency error will be
1241 // If debugging, print out the pattern fragment result.
1242 DEBUG(ThePat->dump());
1246 void DAGISelEmitter::ParsePredicateOperands() {
1247 std::vector<Record*> PredOps =
1248 Records.getAllDerivedDefinitions("PredicateOperand");
1250 // Find some SDNode.
1251 assert(!SDNodes.empty() && "No SDNodes parsed?");
1252 Init *SomeSDNode = new DefInit(SDNodes.begin()->first);
1254 for (unsigned i = 0, e = PredOps.size(); i != e; ++i) {
1255 DagInit *AlwaysInfo = PredOps[i]->getValueAsDag("ExecuteAlways");
1257 // Clone the AlwaysInfo dag node, changing the operator from 'ops' to
1258 // SomeSDnode so that we can parse this.
1259 std::vector<std::pair<Init*, std::string> > Ops;
1260 for (unsigned op = 0, e = AlwaysInfo->getNumArgs(); op != e; ++op)
1261 Ops.push_back(std::make_pair(AlwaysInfo->getArg(op),
1262 AlwaysInfo->getArgName(op)));
1263 DagInit *DI = new DagInit(SomeSDNode, Ops);
1265 // Create a TreePattern to parse this.
1266 TreePattern P(PredOps[i], DI, false, *this);
1267 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
1269 // Copy the operands over into a DAGPredicateOperand.
1270 DAGPredicateOperand PredOpInfo;
1272 TreePatternNode *T = P.getTree(0);
1273 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
1274 TreePatternNode *TPN = T->getChild(op);
1275 while (TPN->ApplyTypeConstraints(P, false))
1276 /* Resolve all types */;
1278 if (TPN->ContainsUnresolvedType())
1279 throw "Value #" + utostr(i) + " of PredicateOperand '" +
1280 PredOps[i]->getName() + "' doesn't have a concrete type!";
1282 PredOpInfo.AlwaysOps.push_back(TPN);
1285 // Insert it into the PredicateOperands map so we can find it later.
1286 PredicateOperands[PredOps[i]] = PredOpInfo;
1290 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
1291 /// instruction input. Return true if this is a real use.
1292 static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
1293 std::map<std::string, TreePatternNode*> &InstInputs,
1294 std::vector<Record*> &InstImpInputs) {
1295 // No name -> not interesting.
1296 if (Pat->getName().empty()) {
1297 if (Pat->isLeaf()) {
1298 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1299 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1300 I->error("Input " + DI->getDef()->getName() + " must be named!");
1301 else if (DI && DI->getDef()->isSubClassOf("Register"))
1302 InstImpInputs.push_back(DI->getDef());
1308 if (Pat->isLeaf()) {
1309 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1310 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
1313 assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
1314 Rec = Pat->getOperator();
1317 // SRCVALUE nodes are ignored.
1318 if (Rec->getName() == "srcvalue")
1321 TreePatternNode *&Slot = InstInputs[Pat->getName()];
1326 if (Slot->isLeaf()) {
1327 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
1329 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
1330 SlotRec = Slot->getOperator();
1333 // Ensure that the inputs agree if we've already seen this input.
1335 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1336 if (Slot->getExtTypes() != Pat->getExtTypes())
1337 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1342 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
1343 /// part of "I", the instruction), computing the set of inputs and outputs of
1344 /// the pattern. Report errors if we see anything naughty.
1345 void DAGISelEmitter::
1346 FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
1347 std::map<std::string, TreePatternNode*> &InstInputs,
1348 std::map<std::string, TreePatternNode*>&InstResults,
1349 std::vector<Record*> &InstImpInputs,
1350 std::vector<Record*> &InstImpResults) {
1351 if (Pat->isLeaf()) {
1352 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1353 if (!isUse && Pat->getTransformFn())
1354 I->error("Cannot specify a transform function for a non-input value!");
1356 } else if (Pat->getOperator()->getName() != "set") {
1357 // If this is not a set, verify that the children nodes are not void typed,
1359 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1360 if (Pat->getChild(i)->getExtTypeNum(0) == MVT::isVoid)
1361 I->error("Cannot have void nodes inside of patterns!");
1362 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
1363 InstImpInputs, InstImpResults);
1366 // If this is a non-leaf node with no children, treat it basically as if
1367 // it were a leaf. This handles nodes like (imm).
1369 if (Pat->getNumChildren() == 0)
1370 isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1372 if (!isUse && Pat->getTransformFn())
1373 I->error("Cannot specify a transform function for a non-input value!");
1377 // Otherwise, this is a set, validate and collect instruction results.
1378 if (Pat->getNumChildren() == 0)
1379 I->error("set requires operands!");
1380 else if (Pat->getNumChildren() & 1)
1381 I->error("set requires an even number of operands");
1383 if (Pat->getTransformFn())
1384 I->error("Cannot specify a transform function on a set node!");
1386 // Check the set destinations.
1387 unsigned NumValues = Pat->getNumChildren()/2;
1388 for (unsigned i = 0; i != NumValues; ++i) {
1389 TreePatternNode *Dest = Pat->getChild(i);
1390 if (!Dest->isLeaf())
1391 I->error("set destination should be a register!");
1393 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1395 I->error("set destination should be a register!");
1397 if (Val->getDef()->isSubClassOf("RegisterClass") ||
1398 Val->getDef()->getName() == "ptr_rc") {
1399 if (Dest->getName().empty())
1400 I->error("set destination must have a name!");
1401 if (InstResults.count(Dest->getName()))
1402 I->error("cannot set '" + Dest->getName() +"' multiple times");
1403 InstResults[Dest->getName()] = Dest;
1404 } else if (Val->getDef()->isSubClassOf("Register")) {
1405 InstImpResults.push_back(Val->getDef());
1407 I->error("set destination should be a register!");
1410 // Verify and collect info from the computation.
1411 FindPatternInputsAndOutputs(I, Pat->getChild(i+NumValues),
1412 InstInputs, InstResults,
1413 InstImpInputs, InstImpResults);
1417 /// ParseInstructions - Parse all of the instructions, inlining and resolving
1418 /// any fragments involved. This populates the Instructions list with fully
1419 /// resolved instructions.
1420 void DAGISelEmitter::ParseInstructions() {
1421 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
1423 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
1426 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
1427 LI = Instrs[i]->getValueAsListInit("Pattern");
1429 // If there is no pattern, only collect minimal information about the
1430 // instruction for its operand list. We have to assume that there is one
1431 // result, as we have no detailed info.
1432 if (!LI || LI->getSize() == 0) {
1433 std::vector<Record*> Results;
1434 std::vector<Record*> Operands;
1436 CodeGenInstruction &InstInfo =Target.getInstruction(Instrs[i]->getName());
1438 if (InstInfo.OperandList.size() != 0) {
1439 // FIXME: temporary hack...
1440 if (InstInfo.noResults) {
1441 // These produce no results
1442 for (unsigned j = 0, e = InstInfo.OperandList.size(); j < e; ++j)
1443 Operands.push_back(InstInfo.OperandList[j].Rec);
1445 // Assume the first operand is the result.
1446 Results.push_back(InstInfo.OperandList[0].Rec);
1448 // The rest are inputs.
1449 for (unsigned j = 1, e = InstInfo.OperandList.size(); j < e; ++j)
1450 Operands.push_back(InstInfo.OperandList[j].Rec);
1454 // Create and insert the instruction.
1455 std::vector<Record*> ImpResults;
1456 std::vector<Record*> ImpOperands;
1457 Instructions.insert(std::make_pair(Instrs[i],
1458 DAGInstruction(0, Results, Operands, ImpResults,
1460 continue; // no pattern.
1463 // Parse the instruction.
1464 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
1465 // Inline pattern fragments into it.
1466 I->InlinePatternFragments();
1468 // Infer as many types as possible. If we cannot infer all of them, we can
1469 // never do anything with this instruction pattern: report it to the user.
1470 if (!I->InferAllTypes())
1471 I->error("Could not infer all types in pattern!");
1473 // InstInputs - Keep track of all of the inputs of the instruction, along
1474 // with the record they are declared as.
1475 std::map<std::string, TreePatternNode*> InstInputs;
1477 // InstResults - Keep track of all the virtual registers that are 'set'
1478 // in the instruction, including what reg class they are.
1479 std::map<std::string, TreePatternNode*> InstResults;
1481 std::vector<Record*> InstImpInputs;
1482 std::vector<Record*> InstImpResults;
1484 // Verify that the top-level forms in the instruction are of void type, and
1485 // fill in the InstResults map.
1486 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
1487 TreePatternNode *Pat = I->getTree(j);
1488 if (Pat->getExtTypeNum(0) != MVT::isVoid)
1489 I->error("Top-level forms in instruction pattern should have"
1492 // Find inputs and outputs, and verify the structure of the uses/defs.
1493 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
1494 InstImpInputs, InstImpResults);
1497 // Now that we have inputs and outputs of the pattern, inspect the operands
1498 // list for the instruction. This determines the order that operands are
1499 // added to the machine instruction the node corresponds to.
1500 unsigned NumResults = InstResults.size();
1502 // Parse the operands list from the (ops) list, validating it.
1503 std::vector<std::string> &Args = I->getArgList();
1504 assert(Args.empty() && "Args list should still be empty here!");
1505 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
1507 // Check that all of the results occur first in the list.
1508 std::vector<Record*> Results;
1509 TreePatternNode *Res0Node = NULL;
1510 for (unsigned i = 0; i != NumResults; ++i) {
1511 if (i == CGI.OperandList.size())
1512 I->error("'" + InstResults.begin()->first +
1513 "' set but does not appear in operand list!");
1514 const std::string &OpName = CGI.OperandList[i].Name;
1516 // Check that it exists in InstResults.
1517 TreePatternNode *RNode = InstResults[OpName];
1519 I->error("Operand $" + OpName + " does not exist in operand list!");
1523 Record *R = dynamic_cast<DefInit*>(RNode->getLeafValue())->getDef();
1525 I->error("Operand $" + OpName + " should be a set destination: all "
1526 "outputs must occur before inputs in operand list!");
1528 if (CGI.OperandList[i].Rec != R)
1529 I->error("Operand $" + OpName + " class mismatch!");
1531 // Remember the return type.
1532 Results.push_back(CGI.OperandList[i].Rec);
1534 // Okay, this one checks out.
1535 InstResults.erase(OpName);
1538 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
1539 // the copy while we're checking the inputs.
1540 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
1542 std::vector<TreePatternNode*> ResultNodeOperands;
1543 std::vector<Record*> Operands;
1544 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
1545 CodeGenInstruction::OperandInfo &Op = CGI.OperandList[i];
1546 const std::string &OpName = Op.Name;
1548 I->error("Operand #" + utostr(i) + " in operands list has no name!");
1550 if (!InstInputsCheck.count(OpName)) {
1551 // If this is an predicate operand with an ExecuteAlways set filled in,
1552 // we can ignore this. When we codegen it, we will do so as always
1554 if (Op.Rec->isSubClassOf("PredicateOperand")) {
1555 // Does it have a non-empty ExecuteAlways field? If so, ignore this
1557 if (!getPredicateOperand(Op.Rec).AlwaysOps.empty())
1560 I->error("Operand $" + OpName +
1561 " does not appear in the instruction pattern");
1563 TreePatternNode *InVal = InstInputsCheck[OpName];
1564 InstInputsCheck.erase(OpName); // It occurred, remove from map.
1566 if (InVal->isLeaf() &&
1567 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
1568 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
1569 if (Op.Rec != InRec && !InRec->isSubClassOf("ComplexPattern"))
1570 I->error("Operand $" + OpName + "'s register class disagrees"
1571 " between the operand and pattern");
1573 Operands.push_back(Op.Rec);
1575 // Construct the result for the dest-pattern operand list.
1576 TreePatternNode *OpNode = InVal->clone();
1578 // No predicate is useful on the result.
1579 OpNode->setPredicateFn("");
1581 // Promote the xform function to be an explicit node if set.
1582 if (Record *Xform = OpNode->getTransformFn()) {
1583 OpNode->setTransformFn(0);
1584 std::vector<TreePatternNode*> Children;
1585 Children.push_back(OpNode);
1586 OpNode = new TreePatternNode(Xform, Children);
1589 ResultNodeOperands.push_back(OpNode);
1592 if (!InstInputsCheck.empty())
1593 I->error("Input operand $" + InstInputsCheck.begin()->first +
1594 " occurs in pattern but not in operands list!");
1596 TreePatternNode *ResultPattern =
1597 new TreePatternNode(I->getRecord(), ResultNodeOperands);
1598 // Copy fully inferred output node type to instruction result pattern.
1600 ResultPattern->setTypes(Res0Node->getExtTypes());
1602 // Create and insert the instruction.
1603 DAGInstruction TheInst(I, Results, Operands, InstImpResults, InstImpInputs);
1604 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
1606 // Use a temporary tree pattern to infer all types and make sure that the
1607 // constructed result is correct. This depends on the instruction already
1608 // being inserted into the Instructions map.
1609 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
1610 Temp.InferAllTypes();
1612 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
1613 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
1618 // If we can, convert the instructions to be patterns that are matched!
1619 for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
1620 E = Instructions.end(); II != E; ++II) {
1621 DAGInstruction &TheInst = II->second;
1622 TreePattern *I = TheInst.getPattern();
1623 if (I == 0) continue; // No pattern.
1625 if (I->getNumTrees() != 1) {
1626 cerr << "CANNOT HANDLE: " << I->getRecord()->getName() << " yet!";
1629 TreePatternNode *Pattern = I->getTree(0);
1630 TreePatternNode *SrcPattern;
1631 if (Pattern->getOperator()->getName() == "set") {
1632 if (Pattern->getNumChildren() != 2)
1633 continue; // Not a set of a single value (not handled so far)
1635 SrcPattern = Pattern->getChild(1)->clone();
1637 // Not a set (store or something?)
1638 SrcPattern = Pattern;
1642 if (!SrcPattern->canPatternMatch(Reason, *this))
1643 I->error("Instruction can never match: " + Reason);
1645 Record *Instr = II->first;
1646 TreePatternNode *DstPattern = TheInst.getResultPattern();
1648 push_back(PatternToMatch(Instr->getValueAsListInit("Predicates"),
1649 SrcPattern, DstPattern,
1650 Instr->getValueAsInt("AddedComplexity")));
1654 void DAGISelEmitter::ParsePatterns() {
1655 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
1657 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1658 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
1659 TreePattern *Pattern = new TreePattern(Patterns[i], Tree, true, *this);
1661 // Inline pattern fragments into it.
1662 Pattern->InlinePatternFragments();
1664 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
1665 if (LI->getSize() == 0) continue; // no pattern.
1667 // Parse the instruction.
1668 TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
1670 // Inline pattern fragments into it.
1671 Result->InlinePatternFragments();
1673 if (Result->getNumTrees() != 1)
1674 Result->error("Cannot handle instructions producing instructions "
1675 "with temporaries yet!");
1677 bool IterateInference;
1678 bool InferredAllPatternTypes, InferredAllResultTypes;
1680 // Infer as many types as possible. If we cannot infer all of them, we
1681 // can never do anything with this pattern: report it to the user.
1682 InferredAllPatternTypes = Pattern->InferAllTypes();
1684 // Infer as many types as possible. If we cannot infer all of them, we
1685 // can never do anything with this pattern: report it to the user.
1686 InferredAllResultTypes = Result->InferAllTypes();
1688 // Apply the type of the result to the source pattern. This helps us
1689 // resolve cases where the input type is known to be a pointer type (which
1690 // is considered resolved), but the result knows it needs to be 32- or
1691 // 64-bits. Infer the other way for good measure.
1692 IterateInference = Pattern->getOnlyTree()->
1693 UpdateNodeType(Result->getOnlyTree()->getExtTypes(), *Result);
1694 IterateInference |= Result->getOnlyTree()->
1695 UpdateNodeType(Pattern->getOnlyTree()->getExtTypes(), *Result);
1696 } while (IterateInference);
1698 // Verify that we inferred enough types that we can do something with the
1699 // pattern and result. If these fire the user has to add type casts.
1700 if (!InferredAllPatternTypes)
1701 Pattern->error("Could not infer all types in pattern!");
1702 if (!InferredAllResultTypes)
1703 Result->error("Could not infer all types in pattern result!");
1705 // Validate that the input pattern is correct.
1707 std::map<std::string, TreePatternNode*> InstInputs;
1708 std::map<std::string, TreePatternNode*> InstResults;
1709 std::vector<Record*> InstImpInputs;
1710 std::vector<Record*> InstImpResults;
1711 FindPatternInputsAndOutputs(Pattern, Pattern->getOnlyTree(),
1712 InstInputs, InstResults,
1713 InstImpInputs, InstImpResults);
1716 // Promote the xform function to be an explicit node if set.
1717 std::vector<TreePatternNode*> ResultNodeOperands;
1718 TreePatternNode *DstPattern = Result->getOnlyTree();
1719 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
1720 TreePatternNode *OpNode = DstPattern->getChild(ii);
1721 if (Record *Xform = OpNode->getTransformFn()) {
1722 OpNode->setTransformFn(0);
1723 std::vector<TreePatternNode*> Children;
1724 Children.push_back(OpNode);
1725 OpNode = new TreePatternNode(Xform, Children);
1727 ResultNodeOperands.push_back(OpNode);
1729 DstPattern = Result->getOnlyTree();
1730 if (!DstPattern->isLeaf())
1731 DstPattern = new TreePatternNode(DstPattern->getOperator(),
1732 ResultNodeOperands);
1733 DstPattern->setTypes(Result->getOnlyTree()->getExtTypes());
1734 TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
1735 Temp.InferAllTypes();
1738 if (!Pattern->getOnlyTree()->canPatternMatch(Reason, *this))
1739 Pattern->error("Pattern can never match: " + Reason);
1742 push_back(PatternToMatch(Patterns[i]->getValueAsListInit("Predicates"),
1743 Pattern->getOnlyTree(),
1745 Patterns[i]->getValueAsInt("AddedComplexity")));
1749 /// CombineChildVariants - Given a bunch of permutations of each child of the
1750 /// 'operator' node, put them together in all possible ways.
1751 static void CombineChildVariants(TreePatternNode *Orig,
1752 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
1753 std::vector<TreePatternNode*> &OutVariants,
1754 DAGISelEmitter &ISE) {
1755 // Make sure that each operand has at least one variant to choose from.
1756 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1757 if (ChildVariants[i].empty())
1760 // The end result is an all-pairs construction of the resultant pattern.
1761 std::vector<unsigned> Idxs;
1762 Idxs.resize(ChildVariants.size());
1763 bool NotDone = true;
1765 // Create the variant and add it to the output list.
1766 std::vector<TreePatternNode*> NewChildren;
1767 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1768 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
1769 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
1771 // Copy over properties.
1772 R->setName(Orig->getName());
1773 R->setPredicateFn(Orig->getPredicateFn());
1774 R->setTransformFn(Orig->getTransformFn());
1775 R->setTypes(Orig->getExtTypes());
1777 // If this pattern cannot every match, do not include it as a variant.
1778 std::string ErrString;
1779 if (!R->canPatternMatch(ErrString, ISE)) {
1782 bool AlreadyExists = false;
1784 // Scan to see if this pattern has already been emitted. We can get
1785 // duplication due to things like commuting:
1786 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
1787 // which are the same pattern. Ignore the dups.
1788 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
1789 if (R->isIsomorphicTo(OutVariants[i])) {
1790 AlreadyExists = true;
1797 OutVariants.push_back(R);
1800 // Increment indices to the next permutation.
1802 // Look for something we can increment without causing a wrap-around.
1803 for (unsigned IdxsIdx = 0; IdxsIdx != Idxs.size(); ++IdxsIdx) {
1804 if (++Idxs[IdxsIdx] < ChildVariants[IdxsIdx].size()) {
1805 NotDone = true; // Found something to increment.
1813 /// CombineChildVariants - A helper function for binary operators.
1815 static void CombineChildVariants(TreePatternNode *Orig,
1816 const std::vector<TreePatternNode*> &LHS,
1817 const std::vector<TreePatternNode*> &RHS,
1818 std::vector<TreePatternNode*> &OutVariants,
1819 DAGISelEmitter &ISE) {
1820 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1821 ChildVariants.push_back(LHS);
1822 ChildVariants.push_back(RHS);
1823 CombineChildVariants(Orig, ChildVariants, OutVariants, ISE);
1827 static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
1828 std::vector<TreePatternNode *> &Children) {
1829 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
1830 Record *Operator = N->getOperator();
1832 // Only permit raw nodes.
1833 if (!N->getName().empty() || !N->getPredicateFn().empty() ||
1834 N->getTransformFn()) {
1835 Children.push_back(N);
1839 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
1840 Children.push_back(N->getChild(0));
1842 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
1844 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
1845 Children.push_back(N->getChild(1));
1847 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
1850 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
1851 /// the (potentially recursive) pattern by using algebraic laws.
1853 static void GenerateVariantsOf(TreePatternNode *N,
1854 std::vector<TreePatternNode*> &OutVariants,
1855 DAGISelEmitter &ISE) {
1856 // We cannot permute leaves.
1858 OutVariants.push_back(N);
1862 // Look up interesting info about the node.
1863 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(N->getOperator());
1865 // If this node is associative, reassociate.
1866 if (NodeInfo.hasProperty(SDNPAssociative)) {
1867 // Reassociate by pulling together all of the linked operators
1868 std::vector<TreePatternNode*> MaximalChildren;
1869 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
1871 // Only handle child sizes of 3. Otherwise we'll end up trying too many
1873 if (MaximalChildren.size() == 3) {
1874 // Find the variants of all of our maximal children.
1875 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
1876 GenerateVariantsOf(MaximalChildren[0], AVariants, ISE);
1877 GenerateVariantsOf(MaximalChildren[1], BVariants, ISE);
1878 GenerateVariantsOf(MaximalChildren[2], CVariants, ISE);
1880 // There are only two ways we can permute the tree:
1881 // (A op B) op C and A op (B op C)
1882 // Within these forms, we can also permute A/B/C.
1884 // Generate legal pair permutations of A/B/C.
1885 std::vector<TreePatternNode*> ABVariants;
1886 std::vector<TreePatternNode*> BAVariants;
1887 std::vector<TreePatternNode*> ACVariants;
1888 std::vector<TreePatternNode*> CAVariants;
1889 std::vector<TreePatternNode*> BCVariants;
1890 std::vector<TreePatternNode*> CBVariants;
1891 CombineChildVariants(N, AVariants, BVariants, ABVariants, ISE);
1892 CombineChildVariants(N, BVariants, AVariants, BAVariants, ISE);
1893 CombineChildVariants(N, AVariants, CVariants, ACVariants, ISE);
1894 CombineChildVariants(N, CVariants, AVariants, CAVariants, ISE);
1895 CombineChildVariants(N, BVariants, CVariants, BCVariants, ISE);
1896 CombineChildVariants(N, CVariants, BVariants, CBVariants, ISE);
1898 // Combine those into the result: (x op x) op x
1899 CombineChildVariants(N, ABVariants, CVariants, OutVariants, ISE);
1900 CombineChildVariants(N, BAVariants, CVariants, OutVariants, ISE);
1901 CombineChildVariants(N, ACVariants, BVariants, OutVariants, ISE);
1902 CombineChildVariants(N, CAVariants, BVariants, OutVariants, ISE);
1903 CombineChildVariants(N, BCVariants, AVariants, OutVariants, ISE);
1904 CombineChildVariants(N, CBVariants, AVariants, OutVariants, ISE);
1906 // Combine those into the result: x op (x op x)
1907 CombineChildVariants(N, CVariants, ABVariants, OutVariants, ISE);
1908 CombineChildVariants(N, CVariants, BAVariants, OutVariants, ISE);
1909 CombineChildVariants(N, BVariants, ACVariants, OutVariants, ISE);
1910 CombineChildVariants(N, BVariants, CAVariants, OutVariants, ISE);
1911 CombineChildVariants(N, AVariants, BCVariants, OutVariants, ISE);
1912 CombineChildVariants(N, AVariants, CBVariants, OutVariants, ISE);
1917 // Compute permutations of all children.
1918 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1919 ChildVariants.resize(N->getNumChildren());
1920 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1921 GenerateVariantsOf(N->getChild(i), ChildVariants[i], ISE);
1923 // Build all permutations based on how the children were formed.
1924 CombineChildVariants(N, ChildVariants, OutVariants, ISE);
1926 // If this node is commutative, consider the commuted order.
1927 if (NodeInfo.hasProperty(SDNPCommutative)) {
1928 assert(N->getNumChildren()==2 &&"Commutative but doesn't have 2 children!");
1929 // Don't count children which are actually register references.
1931 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
1932 TreePatternNode *Child = N->getChild(i);
1933 if (Child->isLeaf())
1934 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
1935 Record *RR = DI->getDef();
1936 if (RR->isSubClassOf("Register"))
1941 // Consider the commuted order.
1943 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
1949 // GenerateVariants - Generate variants. For example, commutative patterns can
1950 // match multiple ways. Add them to PatternsToMatch as well.
1951 void DAGISelEmitter::GenerateVariants() {
1953 DOUT << "Generating instruction variants.\n";
1955 // Loop over all of the patterns we've collected, checking to see if we can
1956 // generate variants of the instruction, through the exploitation of
1957 // identities. This permits the target to provide agressive matching without
1958 // the .td file having to contain tons of variants of instructions.
1960 // Note that this loop adds new patterns to the PatternsToMatch list, but we
1961 // intentionally do not reconsider these. Any variants of added patterns have
1962 // already been added.
1964 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
1965 std::vector<TreePatternNode*> Variants;
1966 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this);
1968 assert(!Variants.empty() && "Must create at least original variant!");
1969 Variants.erase(Variants.begin()); // Remove the original pattern.
1971 if (Variants.empty()) // No variants for this pattern.
1974 DOUT << "FOUND VARIANTS OF: ";
1975 DEBUG(PatternsToMatch[i].getSrcPattern()->dump());
1978 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
1979 TreePatternNode *Variant = Variants[v];
1981 DOUT << " VAR#" << v << ": ";
1982 DEBUG(Variant->dump());
1985 // Scan to see if an instruction or explicit pattern already matches this.
1986 bool AlreadyExists = false;
1987 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
1988 // Check to see if this variant already exists.
1989 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern())) {
1990 DOUT << " *** ALREADY EXISTS, ignoring variant.\n";
1991 AlreadyExists = true;
1995 // If we already have it, ignore the variant.
1996 if (AlreadyExists) continue;
1998 // Otherwise, add it to the list of patterns we have.
2000 push_back(PatternToMatch(PatternsToMatch[i].getPredicates(),
2001 Variant, PatternsToMatch[i].getDstPattern(),
2002 PatternsToMatch[i].getAddedComplexity()));
2009 // NodeIsComplexPattern - return true if N is a leaf node and a subclass of
2011 static bool NodeIsComplexPattern(TreePatternNode *N)
2013 return (N->isLeaf() &&
2014 dynamic_cast<DefInit*>(N->getLeafValue()) &&
2015 static_cast<DefInit*>(N->getLeafValue())->getDef()->
2016 isSubClassOf("ComplexPattern"));
2019 // NodeGetComplexPattern - return the pointer to the ComplexPattern if N
2020 // is a leaf node and a subclass of ComplexPattern, else it returns NULL.
2021 static const ComplexPattern *NodeGetComplexPattern(TreePatternNode *N,
2022 DAGISelEmitter &ISE)
2025 dynamic_cast<DefInit*>(N->getLeafValue()) &&
2026 static_cast<DefInit*>(N->getLeafValue())->getDef()->
2027 isSubClassOf("ComplexPattern")) {
2028 return &ISE.getComplexPattern(static_cast<DefInit*>(N->getLeafValue())
2034 /// getPatternSize - Return the 'size' of this pattern. We want to match large
2035 /// patterns before small ones. This is used to determine the size of a
2037 static unsigned getPatternSize(TreePatternNode *P, DAGISelEmitter &ISE) {
2038 assert((isExtIntegerInVTs(P->getExtTypes()) ||
2039 isExtFloatingPointInVTs(P->getExtTypes()) ||
2040 P->getExtTypeNum(0) == MVT::isVoid ||
2041 P->getExtTypeNum(0) == MVT::Flag ||
2042 P->getExtTypeNum(0) == MVT::iPTR) &&
2043 "Not a valid pattern node to size!");
2044 unsigned Size = 3; // The node itself.
2045 // If the root node is a ConstantSDNode, increases its size.
2046 // e.g. (set R32:$dst, 0).
2047 if (P->isLeaf() && dynamic_cast<IntInit*>(P->getLeafValue()))
2050 // FIXME: This is a hack to statically increase the priority of patterns
2051 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
2052 // Later we can allow complexity / cost for each pattern to be (optionally)
2053 // specified. To get best possible pattern match we'll need to dynamically
2054 // calculate the complexity of all patterns a dag can potentially map to.
2055 const ComplexPattern *AM = NodeGetComplexPattern(P, ISE);
2057 Size += AM->getNumOperands() * 3;
2059 // If this node has some predicate function that must match, it adds to the
2060 // complexity of this node.
2061 if (!P->getPredicateFn().empty())
2064 // Count children in the count if they are also nodes.
2065 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
2066 TreePatternNode *Child = P->getChild(i);
2067 if (!Child->isLeaf() && Child->getExtTypeNum(0) != MVT::Other)
2068 Size += getPatternSize(Child, ISE);
2069 else if (Child->isLeaf()) {
2070 if (dynamic_cast<IntInit*>(Child->getLeafValue()))
2071 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
2072 else if (NodeIsComplexPattern(Child))
2073 Size += getPatternSize(Child, ISE);
2074 else if (!Child->getPredicateFn().empty())
2082 /// getResultPatternCost - Compute the number of instructions for this pattern.
2083 /// This is a temporary hack. We should really include the instruction
2084 /// latencies in this calculation.
2085 static unsigned getResultPatternCost(TreePatternNode *P, DAGISelEmitter &ISE) {
2086 if (P->isLeaf()) return 0;
2089 Record *Op = P->getOperator();
2090 if (Op->isSubClassOf("Instruction")) {
2092 CodeGenInstruction &II = ISE.getTargetInfo().getInstruction(Op->getName());
2093 if (II.usesCustomDAGSchedInserter)
2096 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
2097 Cost += getResultPatternCost(P->getChild(i), ISE);
2101 /// getResultPatternCodeSize - Compute the code size of instructions for this
2103 static unsigned getResultPatternSize(TreePatternNode *P, DAGISelEmitter &ISE) {
2104 if (P->isLeaf()) return 0;
2107 Record *Op = P->getOperator();
2108 if (Op->isSubClassOf("Instruction")) {
2109 Cost += Op->getValueAsInt("CodeSize");
2111 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
2112 Cost += getResultPatternSize(P->getChild(i), ISE);
2116 // PatternSortingPredicate - return true if we prefer to match LHS before RHS.
2117 // In particular, we want to match maximal patterns first and lowest cost within
2118 // a particular complexity first.
2119 struct PatternSortingPredicate {
2120 PatternSortingPredicate(DAGISelEmitter &ise) : ISE(ise) {};
2121 DAGISelEmitter &ISE;
2123 bool operator()(PatternToMatch *LHS,
2124 PatternToMatch *RHS) {
2125 unsigned LHSSize = getPatternSize(LHS->getSrcPattern(), ISE);
2126 unsigned RHSSize = getPatternSize(RHS->getSrcPattern(), ISE);
2127 LHSSize += LHS->getAddedComplexity();
2128 RHSSize += RHS->getAddedComplexity();
2129 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
2130 if (LHSSize < RHSSize) return false;
2132 // If the patterns have equal complexity, compare generated instruction cost
2133 unsigned LHSCost = getResultPatternCost(LHS->getDstPattern(), ISE);
2134 unsigned RHSCost = getResultPatternCost(RHS->getDstPattern(), ISE);
2135 if (LHSCost < RHSCost) return true;
2136 if (LHSCost > RHSCost) return false;
2138 return getResultPatternSize(LHS->getDstPattern(), ISE) <
2139 getResultPatternSize(RHS->getDstPattern(), ISE);
2143 /// getRegisterValueType - Look up and return the first ValueType of specified
2144 /// RegisterClass record
2145 static MVT::ValueType getRegisterValueType(Record *R, const CodeGenTarget &T) {
2146 if (const CodeGenRegisterClass *RC = T.getRegisterClassForRegister(R))
2147 return RC->getValueTypeNum(0);
2152 /// RemoveAllTypes - A quick recursive walk over a pattern which removes all
2153 /// type information from it.
2154 static void RemoveAllTypes(TreePatternNode *N) {
2157 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2158 RemoveAllTypes(N->getChild(i));
2161 Record *DAGISelEmitter::getSDNodeNamed(const std::string &Name) const {
2162 Record *N = Records.getDef(Name);
2163 if (!N || !N->isSubClassOf("SDNode")) {
2164 cerr << "Error getting SDNode '" << Name << "'!\n";
2170 /// NodeHasProperty - return true if TreePatternNode has the specified
2172 static bool NodeHasProperty(TreePatternNode *N, SDNP Property,
2173 DAGISelEmitter &ISE)
2176 const ComplexPattern *CP = NodeGetComplexPattern(N, ISE);
2178 return CP->hasProperty(Property);
2181 Record *Operator = N->getOperator();
2182 if (!Operator->isSubClassOf("SDNode")) return false;
2184 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(Operator);
2185 return NodeInfo.hasProperty(Property);
2188 static bool PatternHasProperty(TreePatternNode *N, SDNP Property,
2189 DAGISelEmitter &ISE)
2191 if (NodeHasProperty(N, Property, ISE))
2194 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2195 TreePatternNode *Child = N->getChild(i);
2196 if (PatternHasProperty(Child, Property, ISE))
2203 class PatternCodeEmitter {
2205 DAGISelEmitter &ISE;
2208 ListInit *Predicates;
2211 // Instruction selector pattern.
2212 TreePatternNode *Pattern;
2213 // Matched instruction.
2214 TreePatternNode *Instruction;
2216 // Node to name mapping
2217 std::map<std::string, std::string> VariableMap;
2218 // Node to operator mapping
2219 std::map<std::string, Record*> OperatorMap;
2220 // Names of all the folded nodes which produce chains.
2221 std::vector<std::pair<std::string, unsigned> > FoldedChains;
2222 // Original input chain(s).
2223 std::vector<std::pair<std::string, std::string> > OrigChains;
2224 std::set<std::string> Duplicates;
2226 /// GeneratedCode - This is the buffer that we emit code to. The first int
2227 /// indicates whether this is an exit predicate (something that should be
2228 /// tested, and if true, the match fails) [when 1], or normal code to emit
2229 /// [when 0], or initialization code to emit [when 2].
2230 std::vector<std::pair<unsigned, std::string> > &GeneratedCode;
2231 /// GeneratedDecl - This is the set of all SDOperand declarations needed for
2232 /// the set of patterns for each top-level opcode.
2233 std::set<std::string> &GeneratedDecl;
2234 /// TargetOpcodes - The target specific opcodes used by the resulting
2236 std::vector<std::string> &TargetOpcodes;
2237 std::vector<std::string> &TargetVTs;
2239 std::string ChainName;
2244 void emitCheck(const std::string &S) {
2246 GeneratedCode.push_back(std::make_pair(1, S));
2248 void emitCode(const std::string &S) {
2250 GeneratedCode.push_back(std::make_pair(0, S));
2252 void emitInit(const std::string &S) {
2254 GeneratedCode.push_back(std::make_pair(2, S));
2256 void emitDecl(const std::string &S) {
2257 assert(!S.empty() && "Invalid declaration");
2258 GeneratedDecl.insert(S);
2260 void emitOpcode(const std::string &Opc) {
2261 TargetOpcodes.push_back(Opc);
2264 void emitVT(const std::string &VT) {
2265 TargetVTs.push_back(VT);
2269 PatternCodeEmitter(DAGISelEmitter &ise, ListInit *preds,
2270 TreePatternNode *pattern, TreePatternNode *instr,
2271 std::vector<std::pair<unsigned, std::string> > &gc,
2272 std::set<std::string> &gd,
2273 std::vector<std::string> &to,
2274 std::vector<std::string> &tv)
2275 : ISE(ise), Predicates(preds), Pattern(pattern), Instruction(instr),
2276 GeneratedCode(gc), GeneratedDecl(gd),
2277 TargetOpcodes(to), TargetVTs(tv),
2278 TmpNo(0), OpcNo(0), VTNo(0) {}
2280 /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
2281 /// if the match fails. At this point, we already know that the opcode for N
2282 /// matches, and the SDNode for the result has the RootName specified name.
2283 void EmitMatchCode(TreePatternNode *N, TreePatternNode *P,
2284 const std::string &RootName, const std::string &ChainSuffix,
2286 bool isRoot = (P == NULL);
2287 // Emit instruction predicates. Each predicate is just a string for now.
2289 std::string PredicateCheck;
2290 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
2291 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
2292 Record *Def = Pred->getDef();
2293 if (!Def->isSubClassOf("Predicate")) {
2297 assert(0 && "Unknown predicate type!");
2299 if (!PredicateCheck.empty())
2300 PredicateCheck += " && ";
2301 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
2305 emitCheck(PredicateCheck);
2309 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
2310 emitCheck("cast<ConstantSDNode>(" + RootName +
2311 ")->getSignExtended() == " + itostr(II->getValue()));
2313 } else if (!NodeIsComplexPattern(N)) {
2314 assert(0 && "Cannot match this as a leaf value!");
2319 // If this node has a name associated with it, capture it in VariableMap. If
2320 // we already saw this in the pattern, emit code to verify dagness.
2321 if (!N->getName().empty()) {
2322 std::string &VarMapEntry = VariableMap[N->getName()];
2323 if (VarMapEntry.empty()) {
2324 VarMapEntry = RootName;
2326 // If we get here, this is a second reference to a specific name. Since
2327 // we already have checked that the first reference is valid, we don't
2328 // have to recursively match it, just check that it's the same as the
2329 // previously named thing.
2330 emitCheck(VarMapEntry + " == " + RootName);
2335 OperatorMap[N->getName()] = N->getOperator();
2339 // Emit code to load the child nodes and match their contents recursively.
2341 bool NodeHasChain = NodeHasProperty (N, SDNPHasChain, ISE);
2342 bool HasChain = PatternHasProperty(N, SDNPHasChain, ISE);
2343 bool EmittedUseCheck = false;
2348 // Multiple uses of actual result?
2349 emitCheck(RootName + ".hasOneUse()");
2350 EmittedUseCheck = true;
2352 // If the immediate use can somehow reach this node through another
2353 // path, then can't fold it either or it will create a cycle.
2354 // e.g. In the following diagram, XX can reach ld through YY. If
2355 // ld is folded into XX, then YY is both a predecessor and a successor
2365 bool NeedCheck = false;
2369 const SDNodeInfo &PInfo = ISE.getSDNodeInfo(P->getOperator());
2371 P->getOperator() == ISE.get_intrinsic_void_sdnode() ||
2372 P->getOperator() == ISE.get_intrinsic_w_chain_sdnode() ||
2373 P->getOperator() == ISE.get_intrinsic_wo_chain_sdnode() ||
2374 PInfo.getNumOperands() > 1 ||
2375 PInfo.hasProperty(SDNPHasChain) ||
2376 PInfo.hasProperty(SDNPInFlag) ||
2377 PInfo.hasProperty(SDNPOptInFlag);
2381 std::string ParentName(RootName.begin(), RootName.end()-1);
2382 emitCheck("CanBeFoldedBy(" + RootName + ".Val, " + ParentName +
2390 emitCheck("(" + ChainName + ".Val == " + RootName + ".Val || "
2391 "IsChainCompatible(" + ChainName + ".Val, " +
2392 RootName + ".Val))");
2393 OrigChains.push_back(std::make_pair(ChainName, RootName));
2396 ChainName = "Chain" + ChainSuffix;
2397 emitInit("SDOperand " + ChainName + " = " + RootName +
2402 // Don't fold any node which reads or writes a flag and has multiple uses.
2403 // FIXME: We really need to separate the concepts of flag and "glue". Those
2404 // real flag results, e.g. X86CMP output, can have multiple uses.
2405 // FIXME: If the optional incoming flag does not exist. Then it is ok to
2408 (PatternHasProperty(N, SDNPInFlag, ISE) ||
2409 PatternHasProperty(N, SDNPOptInFlag, ISE) ||
2410 PatternHasProperty(N, SDNPOutFlag, ISE))) {
2411 if (!EmittedUseCheck) {
2412 // Multiple uses of actual result?
2413 emitCheck(RootName + ".hasOneUse()");
2417 // If there is a node predicate for this, emit the call.
2418 if (!N->getPredicateFn().empty())
2419 emitCheck(N->getPredicateFn() + "(" + RootName + ".Val)");
2422 // If this is an 'and R, 1234' where the operation is AND/OR and the RHS is
2423 // a constant without a predicate fn that has more that one bit set, handle
2424 // this as a special case. This is usually for targets that have special
2425 // handling of certain large constants (e.g. alpha with it's 8/16/32-bit
2426 // handling stuff). Using these instructions is often far more efficient
2427 // than materializing the constant. Unfortunately, both the instcombiner
2428 // and the dag combiner can often infer that bits are dead, and thus drop
2429 // them from the mask in the dag. For example, it might turn 'AND X, 255'
2430 // into 'AND X, 254' if it knows the low bit is set. Emit code that checks
2433 (N->getOperator()->getName() == "and" ||
2434 N->getOperator()->getName() == "or") &&
2435 N->getChild(1)->isLeaf() &&
2436 N->getChild(1)->getPredicateFn().empty()) {
2437 if (IntInit *II = dynamic_cast<IntInit*>(N->getChild(1)->getLeafValue())) {
2438 if (!isPowerOf2_32(II->getValue())) { // Don't bother with single bits.
2439 emitInit("SDOperand " + RootName + "0" + " = " +
2440 RootName + ".getOperand(" + utostr(0) + ");");
2441 emitInit("SDOperand " + RootName + "1" + " = " +
2442 RootName + ".getOperand(" + utostr(1) + ");");
2444 emitCheck("isa<ConstantSDNode>(" + RootName + "1)");
2445 const char *MaskPredicate = N->getOperator()->getName() == "or"
2446 ? "CheckOrMask(" : "CheckAndMask(";
2447 emitCheck(MaskPredicate + RootName + "0, cast<ConstantSDNode>(" +
2448 RootName + "1), " + itostr(II->getValue()) + ")");
2450 EmitChildMatchCode(N->getChild(0), N, RootName + utostr(0),
2451 ChainSuffix + utostr(0), FoundChain);
2457 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
2458 emitInit("SDOperand " + RootName + utostr(OpNo) + " = " +
2459 RootName + ".getOperand(" +utostr(OpNo) + ");");
2461 EmitChildMatchCode(N->getChild(i), N, RootName + utostr(OpNo),
2462 ChainSuffix + utostr(OpNo), FoundChain);
2465 // Handle cases when root is a complex pattern.
2466 const ComplexPattern *CP;
2467 if (isRoot && N->isLeaf() && (CP = NodeGetComplexPattern(N, ISE))) {
2468 std::string Fn = CP->getSelectFunc();
2469 unsigned NumOps = CP->getNumOperands();
2470 for (unsigned i = 0; i < NumOps; ++i) {
2471 emitDecl("CPTmp" + utostr(i));
2472 emitCode("SDOperand CPTmp" + utostr(i) + ";");
2474 if (CP->hasProperty(SDNPHasChain)) {
2475 emitDecl("CPInChain");
2476 emitDecl("Chain" + ChainSuffix);
2477 emitCode("SDOperand CPInChain;");
2478 emitCode("SDOperand Chain" + ChainSuffix + ";");
2481 std::string Code = Fn + "(" + RootName + ", " + RootName;
2482 for (unsigned i = 0; i < NumOps; i++)
2483 Code += ", CPTmp" + utostr(i);
2484 if (CP->hasProperty(SDNPHasChain)) {
2485 ChainName = "Chain" + ChainSuffix;
2486 Code += ", CPInChain, Chain" + ChainSuffix;
2488 emitCheck(Code + ")");
2492 void EmitChildMatchCode(TreePatternNode *Child, TreePatternNode *Parent,
2493 const std::string &RootName,
2494 const std::string &ChainSuffix, bool &FoundChain) {
2495 if (!Child->isLeaf()) {
2496 // If it's not a leaf, recursively match.
2497 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(Child->getOperator());
2498 emitCheck(RootName + ".getOpcode() == " +
2499 CInfo.getEnumName());
2500 EmitMatchCode(Child, Parent, RootName, ChainSuffix, FoundChain);
2501 if (NodeHasProperty(Child, SDNPHasChain, ISE))
2502 FoldedChains.push_back(std::make_pair(RootName, CInfo.getNumResults()));
2504 // If this child has a name associated with it, capture it in VarMap. If
2505 // we already saw this in the pattern, emit code to verify dagness.
2506 if (!Child->getName().empty()) {
2507 std::string &VarMapEntry = VariableMap[Child->getName()];
2508 if (VarMapEntry.empty()) {
2509 VarMapEntry = RootName;
2511 // If we get here, this is a second reference to a specific name.
2512 // Since we already have checked that the first reference is valid,
2513 // we don't have to recursively match it, just check that it's the
2514 // same as the previously named thing.
2515 emitCheck(VarMapEntry + " == " + RootName);
2516 Duplicates.insert(RootName);
2521 // Handle leaves of various types.
2522 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2523 Record *LeafRec = DI->getDef();
2524 if (LeafRec->isSubClassOf("RegisterClass") ||
2525 LeafRec->getName() == "ptr_rc") {
2526 // Handle register references. Nothing to do here.
2527 } else if (LeafRec->isSubClassOf("Register")) {
2528 // Handle register references.
2529 } else if (LeafRec->isSubClassOf("ComplexPattern")) {
2530 // Handle complex pattern.
2531 const ComplexPattern *CP = NodeGetComplexPattern(Child, ISE);
2532 std::string Fn = CP->getSelectFunc();
2533 unsigned NumOps = CP->getNumOperands();
2534 for (unsigned i = 0; i < NumOps; ++i) {
2535 emitDecl("CPTmp" + utostr(i));
2536 emitCode("SDOperand CPTmp" + utostr(i) + ";");
2538 if (CP->hasProperty(SDNPHasChain)) {
2539 const SDNodeInfo &PInfo = ISE.getSDNodeInfo(Parent->getOperator());
2540 FoldedChains.push_back(std::make_pair("CPInChain",
2541 PInfo.getNumResults()));
2542 ChainName = "Chain" + ChainSuffix;
2543 emitDecl("CPInChain");
2544 emitDecl(ChainName);
2545 emitCode("SDOperand CPInChain;");
2546 emitCode("SDOperand " + ChainName + ";");
2549 std::string Code = Fn + "(N, ";
2550 if (CP->hasProperty(SDNPHasChain)) {
2551 std::string ParentName(RootName.begin(), RootName.end()-1);
2552 Code += ParentName + ", ";
2555 for (unsigned i = 0; i < NumOps; i++)
2556 Code += ", CPTmp" + utostr(i);
2557 if (CP->hasProperty(SDNPHasChain))
2558 Code += ", CPInChain, Chain" + ChainSuffix;
2559 emitCheck(Code + ")");
2560 } else if (LeafRec->getName() == "srcvalue") {
2561 // Place holder for SRCVALUE nodes. Nothing to do here.
2562 } else if (LeafRec->isSubClassOf("ValueType")) {
2563 // Make sure this is the specified value type.
2564 emitCheck("cast<VTSDNode>(" + RootName +
2565 ")->getVT() == MVT::" + LeafRec->getName());
2566 } else if (LeafRec->isSubClassOf("CondCode")) {
2567 // Make sure this is the specified cond code.
2568 emitCheck("cast<CondCodeSDNode>(" + RootName +
2569 ")->get() == ISD::" + LeafRec->getName());
2575 assert(0 && "Unknown leaf type!");
2578 // If there is a node predicate for this, emit the call.
2579 if (!Child->getPredicateFn().empty())
2580 emitCheck(Child->getPredicateFn() + "(" + RootName +
2582 } else if (IntInit *II =
2583 dynamic_cast<IntInit*>(Child->getLeafValue())) {
2584 emitCheck("isa<ConstantSDNode>(" + RootName + ")");
2585 unsigned CTmp = TmpNo++;
2586 emitCode("int64_t CN"+utostr(CTmp)+" = cast<ConstantSDNode>("+
2587 RootName + ")->getSignExtended();");
2589 emitCheck("CN" + utostr(CTmp) + " == " +itostr(II->getValue()));
2594 assert(0 && "Unknown leaf type!");
2599 /// EmitResultCode - Emit the action for a pattern. Now that it has matched
2600 /// we actually have to build a DAG!
2601 std::vector<std::string>
2602 EmitResultCode(TreePatternNode *N, bool RetSelected,
2603 bool InFlagDecled, bool ResNodeDecled,
2604 bool LikeLeaf = false, bool isRoot = false) {
2605 // List of arguments of getTargetNode() or SelectNodeTo().
2606 std::vector<std::string> NodeOps;
2607 // This is something selected from the pattern we matched.
2608 if (!N->getName().empty()) {
2609 std::string &Val = VariableMap[N->getName()];
2610 assert(!Val.empty() &&
2611 "Variable referenced but not defined and not caught earlier!");
2612 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
2613 // Already selected this operand, just return the tmpval.
2614 NodeOps.push_back(Val);
2618 const ComplexPattern *CP;
2619 unsigned ResNo = TmpNo++;
2620 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
2621 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
2622 std::string CastType;
2623 switch (N->getTypeNum(0)) {
2624 default: assert(0 && "Unknown type for constant node!");
2625 case MVT::i1: CastType = "bool"; break;
2626 case MVT::i8: CastType = "unsigned char"; break;
2627 case MVT::i16: CastType = "unsigned short"; break;
2628 case MVT::i32: CastType = "unsigned"; break;
2629 case MVT::i64: CastType = "uint64_t"; break;
2631 emitCode("SDOperand Tmp" + utostr(ResNo) +
2632 " = CurDAG->getTargetConstant(((" + CastType +
2633 ") cast<ConstantSDNode>(" + Val + ")->getValue()), " +
2634 getEnumName(N->getTypeNum(0)) + ");");
2635 NodeOps.push_back("Tmp" + utostr(ResNo));
2636 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
2637 // value if used multiple times by this pattern result.
2638 Val = "Tmp"+utostr(ResNo);
2639 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
2640 Record *Op = OperatorMap[N->getName()];
2641 // Transform ExternalSymbol to TargetExternalSymbol
2642 if (Op && Op->getName() == "externalsym") {
2643 emitCode("SDOperand Tmp" + utostr(ResNo) + " = CurDAG->getTarget"
2644 "ExternalSymbol(cast<ExternalSymbolSDNode>(" +
2645 Val + ")->getSymbol(), " +
2646 getEnumName(N->getTypeNum(0)) + ");");
2647 NodeOps.push_back("Tmp" + utostr(ResNo));
2648 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
2649 // this value if used multiple times by this pattern result.
2650 Val = "Tmp"+utostr(ResNo);
2652 NodeOps.push_back(Val);
2654 } else if (!N->isLeaf() && N->getOperator()->getName() == "tglobaladdr") {
2655 Record *Op = OperatorMap[N->getName()];
2656 // Transform GlobalAddress to TargetGlobalAddress
2657 if (Op && Op->getName() == "globaladdr") {
2658 emitCode("SDOperand Tmp" + utostr(ResNo) + " = CurDAG->getTarget"
2659 "GlobalAddress(cast<GlobalAddressSDNode>(" + Val +
2660 ")->getGlobal(), " + getEnumName(N->getTypeNum(0)) +
2662 NodeOps.push_back("Tmp" + utostr(ResNo));
2663 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
2664 // this value if used multiple times by this pattern result.
2665 Val = "Tmp"+utostr(ResNo);
2667 NodeOps.push_back(Val);
2669 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
2670 NodeOps.push_back(Val);
2671 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
2672 // value if used multiple times by this pattern result.
2673 Val = "Tmp"+utostr(ResNo);
2674 } else if (!N->isLeaf() && N->getOperator()->getName() == "tconstpool") {
2675 NodeOps.push_back(Val);
2676 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
2677 // value if used multiple times by this pattern result.
2678 Val = "Tmp"+utostr(ResNo);
2679 } else if (N->isLeaf() && (CP = NodeGetComplexPattern(N, ISE))) {
2680 for (unsigned i = 0; i < CP->getNumOperands(); ++i) {
2681 emitCode("AddToISelQueue(CPTmp" + utostr(i) + ");");
2682 NodeOps.push_back("CPTmp" + utostr(i));
2685 // This node, probably wrapped in a SDNodeXForm, behaves like a leaf
2686 // node even if it isn't one. Don't select it.
2688 emitCode("AddToISelQueue(" + Val + ");");
2689 if (isRoot && N->isLeaf()) {
2690 emitCode("ReplaceUses(N, " + Val + ");");
2691 emitCode("return NULL;");
2694 NodeOps.push_back(Val);
2699 // If this is an explicit register reference, handle it.
2700 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
2701 unsigned ResNo = TmpNo++;
2702 if (DI->getDef()->isSubClassOf("Register")) {
2703 emitCode("SDOperand Tmp" + utostr(ResNo) + " = CurDAG->getRegister(" +
2704 ISE.getQualifiedName(DI->getDef()) + ", " +
2705 getEnumName(N->getTypeNum(0)) + ");");
2706 NodeOps.push_back("Tmp" + utostr(ResNo));
2709 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
2710 unsigned ResNo = TmpNo++;
2711 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
2712 emitCode("SDOperand Tmp" + utostr(ResNo) +
2713 " = CurDAG->getTargetConstant(" + itostr(II->getValue()) +
2714 ", " + getEnumName(N->getTypeNum(0)) + ");");
2715 NodeOps.push_back("Tmp" + utostr(ResNo));
2722 assert(0 && "Unknown leaf type!");
2726 Record *Op = N->getOperator();
2727 if (Op->isSubClassOf("Instruction")) {
2728 const CodeGenTarget &CGT = ISE.getTargetInfo();
2729 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
2730 const DAGInstruction &Inst = ISE.getInstruction(Op);
2731 TreePattern *InstPat = Inst.getPattern();
2732 TreePatternNode *InstPatNode =
2733 isRoot ? (InstPat ? InstPat->getOnlyTree() : Pattern)
2734 : (InstPat ? InstPat->getOnlyTree() : NULL);
2735 if (InstPatNode && InstPatNode->getOperator()->getName() == "set") {
2736 InstPatNode = InstPatNode->getChild(1);
2738 bool HasVarOps = isRoot && II.hasVariableNumberOfOperands;
2739 bool HasImpInputs = isRoot && Inst.getNumImpOperands() > 0;
2740 bool HasImpResults = isRoot && Inst.getNumImpResults() > 0;
2741 bool NodeHasOptInFlag = isRoot &&
2742 PatternHasProperty(Pattern, SDNPOptInFlag, ISE);
2743 bool NodeHasInFlag = isRoot &&
2744 PatternHasProperty(Pattern, SDNPInFlag, ISE);
2745 bool NodeHasOutFlag = HasImpResults || (isRoot &&
2746 PatternHasProperty(Pattern, SDNPOutFlag, ISE));
2747 bool NodeHasChain = InstPatNode &&
2748 PatternHasProperty(InstPatNode, SDNPHasChain, ISE);
2749 bool InputHasChain = isRoot &&
2750 NodeHasProperty(Pattern, SDNPHasChain, ISE);
2751 unsigned NumResults = Inst.getNumResults();
2753 if (NodeHasOptInFlag) {
2754 emitCode("bool HasInFlag = "
2755 "(N.getOperand(N.getNumOperands()-1).getValueType() == MVT::Flag);");
2758 emitCode("SmallVector<SDOperand, 8> Ops" + utostr(OpcNo) + ";");
2760 // How many results is this pattern expected to produce?
2761 unsigned PatResults = 0;
2762 for (unsigned i = 0, e = Pattern->getExtTypes().size(); i != e; i++) {
2763 MVT::ValueType VT = Pattern->getTypeNum(i);
2764 if (VT != MVT::isVoid && VT != MVT::Flag)
2768 if (OrigChains.size() > 0) {
2769 // The original input chain is being ignored. If it is not just
2770 // pointing to the op that's being folded, we should create a
2771 // TokenFactor with it and the chain of the folded op as the new chain.
2772 // We could potentially be doing multiple levels of folding, in that
2773 // case, the TokenFactor can have more operands.
2774 emitCode("SmallVector<SDOperand, 8> InChains;");
2775 for (unsigned i = 0, e = OrigChains.size(); i < e; ++i) {
2776 emitCode("if (" + OrigChains[i].first + ".Val != " +
2777 OrigChains[i].second + ".Val) {");
2778 emitCode(" AddToISelQueue(" + OrigChains[i].first + ");");
2779 emitCode(" InChains.push_back(" + OrigChains[i].first + ");");
2782 emitCode("AddToISelQueue(" + ChainName + ");");
2783 emitCode("InChains.push_back(" + ChainName + ");");
2784 emitCode(ChainName + " = CurDAG->getNode(ISD::TokenFactor, MVT::Other, "
2785 "&InChains[0], InChains.size());");
2788 // Loop over all of the operands of the instruction pattern, emitting code
2789 // to fill them all in. The node 'N' usually has number children equal to
2790 // the number of input operands of the instruction. However, in cases
2791 // where there are predicate operands for an instruction, we need to fill
2792 // in the 'execute always' values. Match up the node operands to the
2793 // instruction operands to do this.
2794 std::vector<std::string> AllOps;
2795 for (unsigned ChildNo = 0, InstOpNo = NumResults;
2796 InstOpNo != II.OperandList.size(); ++InstOpNo) {
2797 std::vector<std::string> Ops;
2799 // If this is a normal operand, emit it.
2800 if (!II.OperandList[InstOpNo].Rec->isSubClassOf("PredicateOperand")) {
2801 Ops = EmitResultCode(N->getChild(ChildNo), RetSelected,
2802 InFlagDecled, ResNodeDecled);
2803 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
2806 // Otherwise, this is a predicate operand, emit the 'execute always'
2808 const DAGPredicateOperand &Pred =
2809 ISE.getPredicateOperand(II.OperandList[InstOpNo].Rec);
2810 for (unsigned i = 0, e = Pred.AlwaysOps.size(); i != e; ++i) {
2811 Ops = EmitResultCode(Pred.AlwaysOps[i], RetSelected,
2812 InFlagDecled, ResNodeDecled);
2813 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
2818 // Emit all the chain and CopyToReg stuff.
2819 bool ChainEmitted = NodeHasChain;
2821 emitCode("AddToISelQueue(" + ChainName + ");");
2822 if (NodeHasInFlag || HasImpInputs)
2823 EmitInFlagSelectCode(Pattern, "N", ChainEmitted,
2824 InFlagDecled, ResNodeDecled, true);
2825 if (NodeHasOptInFlag || NodeHasInFlag || HasImpInputs) {
2826 if (!InFlagDecled) {
2827 emitCode("SDOperand InFlag(0, 0);");
2828 InFlagDecled = true;
2830 if (NodeHasOptInFlag) {
2831 emitCode("if (HasInFlag) {");
2832 emitCode(" InFlag = N.getOperand(N.getNumOperands()-1);");
2833 emitCode(" AddToISelQueue(InFlag);");
2838 unsigned ResNo = TmpNo++;
2839 if (!isRoot || InputHasChain || NodeHasChain || NodeHasOutFlag ||
2843 std::string NodeName;
2845 NodeName = "Tmp" + utostr(ResNo);
2846 Code2 = "SDOperand " + NodeName + " = SDOperand(";
2848 NodeName = "ResNode";
2850 Code2 = "SDNode *" + NodeName + " = ";
2852 Code2 = NodeName + " = ";
2855 Code = "CurDAG->getTargetNode(Opc" + utostr(OpcNo);
2856 unsigned OpsNo = OpcNo;
2857 emitOpcode(II.Namespace + "::" + II.TheDef->getName());
2859 // Output order: results, chain, flags
2861 if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid) {
2862 Code += ", VT" + utostr(VTNo);
2863 emitVT(getEnumName(N->getTypeNum(0)));
2866 Code += ", MVT::Other";
2868 Code += ", MVT::Flag";
2870 // Figure out how many fixed inputs the node has. This is important to
2871 // know which inputs are the variable ones if present.
2872 unsigned NumInputs = AllOps.size();
2873 NumInputs += NodeHasChain;
2877 for (unsigned i = 0, e = AllOps.size(); i != e; ++i)
2878 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + AllOps[i] + ");");
2883 // Figure out whether any operands at the end of the op list are not
2884 // part of the variable section.
2885 std::string EndAdjust;
2886 if (NodeHasInFlag || HasImpInputs)
2887 EndAdjust = "-1"; // Always has one flag.
2888 else if (NodeHasOptInFlag)
2889 EndAdjust = "-(HasInFlag?1:0)"; // May have a flag.
2891 emitCode("for (unsigned i = " + utostr(NumInputs) +
2892 ", e = N.getNumOperands()" + EndAdjust + "; i != e; ++i) {");
2894 emitCode(" AddToISelQueue(N.getOperand(i));");
2895 emitCode(" Ops" + utostr(OpsNo) + ".push_back(N.getOperand(i));");
2901 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + ChainName + ");");
2903 AllOps.push_back(ChainName);
2907 if (NodeHasInFlag || HasImpInputs)
2908 emitCode("Ops" + utostr(OpsNo) + ".push_back(InFlag);");
2909 else if (NodeHasOptInFlag) {
2910 emitCode("if (HasInFlag)");
2911 emitCode(" Ops" + utostr(OpsNo) + ".push_back(InFlag);");
2913 Code += ", &Ops" + utostr(OpsNo) + "[0], Ops" + utostr(OpsNo) +
2915 } else if (NodeHasInFlag || NodeHasOptInFlag || HasImpInputs)
2916 AllOps.push_back("InFlag");
2918 unsigned NumOps = AllOps.size();
2920 if (!NodeHasOptInFlag && NumOps < 4) {
2921 for (unsigned i = 0; i != NumOps; ++i)
2922 Code += ", " + AllOps[i];
2924 std::string OpsCode = "SDOperand Ops" + utostr(OpsNo) + "[] = { ";
2925 for (unsigned i = 0; i != NumOps; ++i) {
2926 OpsCode += AllOps[i];
2930 emitCode(OpsCode + " };");
2931 Code += ", Ops" + utostr(OpsNo) + ", ";
2932 if (NodeHasOptInFlag) {
2933 Code += "HasInFlag ? ";
2934 Code += utostr(NumOps) + " : " + utostr(NumOps-1);
2936 Code += utostr(NumOps);
2942 emitCode(Code2 + Code + ");");
2945 // Remember which op produces the chain.
2947 emitCode(ChainName + " = SDOperand(" + NodeName +
2948 ".Val, " + utostr(PatResults) + ");");
2950 emitCode(ChainName + " = SDOperand(" + NodeName +
2951 ", " + utostr(PatResults) + ");");
2954 NodeOps.push_back("Tmp" + utostr(ResNo));
2958 bool NeedReplace = false;
2959 if (NodeHasOutFlag) {
2960 if (!InFlagDecled) {
2961 emitCode("SDOperand InFlag = SDOperand(ResNode, " +
2962 utostr(NumResults + (unsigned)NodeHasChain) + ");");
2963 InFlagDecled = true;
2965 emitCode("InFlag = SDOperand(ResNode, " +
2966 utostr(NumResults + (unsigned)NodeHasChain) + ");");
2969 if (HasImpResults && EmitCopyFromRegs(N, ResNodeDecled, ChainEmitted)) {
2970 emitCode("ReplaceUses(SDOperand(N.Val, 0), SDOperand(ResNode, 0));");
2974 if (FoldedChains.size() > 0) {
2976 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++)
2977 emitCode("ReplaceUses(SDOperand(" +
2978 FoldedChains[j].first + ".Val, " +
2979 utostr(FoldedChains[j].second) + "), SDOperand(ResNode, " +
2980 utostr(NumResults) + "));");
2984 if (NodeHasOutFlag) {
2985 emitCode("ReplaceUses(SDOperand(N.Val, " +
2986 utostr(PatResults + (unsigned)InputHasChain) +"), InFlag);");
2991 for (unsigned i = 0; i < NumResults; i++)
2992 emitCode("ReplaceUses(SDOperand(N.Val, " +
2993 utostr(i) + "), SDOperand(ResNode, " + utostr(i) + "));");
2995 emitCode("ReplaceUses(SDOperand(N.Val, " +
2996 utostr(PatResults) + "), SDOperand(" + ChainName + ".Val, "
2997 + ChainName + ".ResNo" + "));");
3001 // User does not expect the instruction would produce a chain!
3002 if ((!InputHasChain && NodeHasChain) && NodeHasOutFlag) {
3004 } else if (InputHasChain && !NodeHasChain) {
3005 // One of the inner node produces a chain.
3007 emitCode("ReplaceUses(SDOperand(N.Val, " + utostr(PatResults+1) +
3008 "), SDOperand(ResNode, N.ResNo-1));");
3009 for (unsigned i = 0; i < PatResults; ++i)
3010 emitCode("ReplaceUses(SDOperand(N.Val, " + utostr(i) +
3011 "), SDOperand(ResNode, " + utostr(i) + "));");
3012 emitCode("ReplaceUses(SDOperand(N.Val, " + utostr(PatResults) +
3013 "), " + ChainName + ");");
3014 RetSelected = false;
3018 emitCode("return ResNode;");
3020 emitCode("return NULL;");
3022 std::string Code = "return CurDAG->SelectNodeTo(N.Val, Opc" +
3024 if (N->getTypeNum(0) != MVT::isVoid)
3025 Code += ", VT" + utostr(VTNo);
3027 Code += ", MVT::Flag";
3029 if (NodeHasInFlag || NodeHasOptInFlag || HasImpInputs)
3030 AllOps.push_back("InFlag");
3032 unsigned NumOps = AllOps.size();
3034 if (!NodeHasOptInFlag && NumOps < 4) {
3035 for (unsigned i = 0; i != NumOps; ++i)
3036 Code += ", " + AllOps[i];
3038 std::string OpsCode = "SDOperand Ops" + utostr(OpcNo) + "[] = { ";
3039 for (unsigned i = 0; i != NumOps; ++i) {
3040 OpsCode += AllOps[i];
3044 emitCode(OpsCode + " };");
3045 Code += ", Ops" + utostr(OpcNo) + ", ";
3046 Code += utostr(NumOps);
3049 emitCode(Code + ");");
3050 emitOpcode(II.Namespace + "::" + II.TheDef->getName());
3051 if (N->getTypeNum(0) != MVT::isVoid)
3052 emitVT(getEnumName(N->getTypeNum(0)));
3056 } else if (Op->isSubClassOf("SDNodeXForm")) {
3057 assert(N->getNumChildren() == 1 && "node xform should have one child!");
3058 // PatLeaf node - the operand may or may not be a leaf node. But it should
3060 std::vector<std::string> Ops =
3061 EmitResultCode(N->getChild(0), RetSelected, InFlagDecled,
3062 ResNodeDecled, true);
3063 unsigned ResNo = TmpNo++;
3064 emitCode("SDOperand Tmp" + utostr(ResNo) + " = Transform_" + Op->getName()
3065 + "(" + Ops.back() + ".Val);");
3066 NodeOps.push_back("Tmp" + utostr(ResNo));
3068 emitCode("return Tmp" + utostr(ResNo) + ".Val;");
3073 throw std::string("Unknown node in result pattern!");
3077 /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat'
3078 /// and add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
3079 /// 'Pat' may be missing types. If we find an unresolved type to add a check
3080 /// for, this returns true otherwise false if Pat has all types.
3081 bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
3082 const std::string &Prefix, bool isRoot = false) {
3084 if (Pat->getExtTypes() != Other->getExtTypes()) {
3085 // Move a type over from 'other' to 'pat'.
3086 Pat->setTypes(Other->getExtTypes());
3087 // The top level node type is checked outside of the select function.
3089 emitCheck(Prefix + ".Val->getValueType(0) == " +
3090 getName(Pat->getTypeNum(0)));
3095 (unsigned) NodeHasProperty(Pat, SDNPHasChain, ISE);
3096 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
3097 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
3098 Prefix + utostr(OpNo)))
3104 /// EmitInFlagSelectCode - Emit the flag operands for the DAG that is
3106 void EmitInFlagSelectCode(TreePatternNode *N, const std::string &RootName,
3107 bool &ChainEmitted, bool &InFlagDecled,
3108 bool &ResNodeDecled, bool isRoot = false) {
3109 const CodeGenTarget &T = ISE.getTargetInfo();
3111 (unsigned) NodeHasProperty(N, SDNPHasChain, ISE);
3112 bool HasInFlag = NodeHasProperty(N, SDNPInFlag, ISE);
3113 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
3114 TreePatternNode *Child = N->getChild(i);
3115 if (!Child->isLeaf()) {
3116 EmitInFlagSelectCode(Child, RootName + utostr(OpNo), ChainEmitted,
3117 InFlagDecled, ResNodeDecled);
3119 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
3120 if (!Child->getName().empty()) {
3121 std::string Name = RootName + utostr(OpNo);
3122 if (Duplicates.find(Name) != Duplicates.end())
3123 // A duplicate! Do not emit a copy for this node.
3127 Record *RR = DI->getDef();
3128 if (RR->isSubClassOf("Register")) {
3129 MVT::ValueType RVT = getRegisterValueType(RR, T);
3130 if (RVT == MVT::Flag) {
3131 if (!InFlagDecled) {
3132 emitCode("SDOperand InFlag = " + RootName + utostr(OpNo) + ";");
3133 InFlagDecled = true;
3135 emitCode("InFlag = " + RootName + utostr(OpNo) + ";");
3136 emitCode("AddToISelQueue(InFlag);");
3138 if (!ChainEmitted) {
3139 emitCode("SDOperand Chain = CurDAG->getEntryNode();");
3140 ChainName = "Chain";
3141 ChainEmitted = true;
3143 emitCode("AddToISelQueue(" + RootName + utostr(OpNo) + ");");
3144 if (!InFlagDecled) {
3145 emitCode("SDOperand InFlag(0, 0);");
3146 InFlagDecled = true;
3148 std::string Decl = (!ResNodeDecled) ? "SDNode *" : "";
3149 emitCode(Decl + "ResNode = CurDAG->getCopyToReg(" + ChainName +
3150 ", " + ISE.getQualifiedName(RR) +
3151 ", " + RootName + utostr(OpNo) + ", InFlag).Val;");
3152 ResNodeDecled = true;
3153 emitCode(ChainName + " = SDOperand(ResNode, 0);");
3154 emitCode("InFlag = SDOperand(ResNode, 1);");
3162 if (!InFlagDecled) {
3163 emitCode("SDOperand InFlag = " + RootName +
3164 ".getOperand(" + utostr(OpNo) + ");");
3165 InFlagDecled = true;
3167 emitCode("InFlag = " + RootName +
3168 ".getOperand(" + utostr(OpNo) + ");");
3169 emitCode("AddToISelQueue(InFlag);");
3173 /// EmitCopyFromRegs - Emit code to copy result to physical registers
3174 /// as specified by the instruction. It returns true if any copy is
3176 bool EmitCopyFromRegs(TreePatternNode *N, bool &ResNodeDecled,
3177 bool &ChainEmitted) {
3178 bool RetVal = false;
3179 Record *Op = N->getOperator();
3180 if (Op->isSubClassOf("Instruction")) {
3181 const DAGInstruction &Inst = ISE.getInstruction(Op);
3182 const CodeGenTarget &CGT = ISE.getTargetInfo();
3183 unsigned NumImpResults = Inst.getNumImpResults();
3184 for (unsigned i = 0; i < NumImpResults; i++) {
3185 Record *RR = Inst.getImpResult(i);
3186 if (RR->isSubClassOf("Register")) {
3187 MVT::ValueType RVT = getRegisterValueType(RR, CGT);
3188 if (RVT != MVT::Flag) {
3189 if (!ChainEmitted) {
3190 emitCode("SDOperand Chain = CurDAG->getEntryNode();");
3191 ChainEmitted = true;
3192 ChainName = "Chain";
3194 std::string Decl = (!ResNodeDecled) ? "SDNode *" : "";
3195 emitCode(Decl + "ResNode = CurDAG->getCopyFromReg(" + ChainName +
3196 ", " + ISE.getQualifiedName(RR) + ", " + getEnumName(RVT) +
3198 ResNodeDecled = true;
3199 emitCode(ChainName + " = SDOperand(ResNode, 1);");
3200 emitCode("InFlag = SDOperand(ResNode, 2);");
3210 /// EmitCodeForPattern - Given a pattern to match, emit code to the specified
3211 /// stream to match the pattern, and generate the code for the match if it
3212 /// succeeds. Returns true if the pattern is not guaranteed to match.
3213 void DAGISelEmitter::GenerateCodeForPattern(PatternToMatch &Pattern,
3214 std::vector<std::pair<unsigned, std::string> > &GeneratedCode,
3215 std::set<std::string> &GeneratedDecl,
3216 std::vector<std::string> &TargetOpcodes,
3217 std::vector<std::string> &TargetVTs) {
3218 PatternCodeEmitter Emitter(*this, Pattern.getPredicates(),
3219 Pattern.getSrcPattern(), Pattern.getDstPattern(),
3220 GeneratedCode, GeneratedDecl,
3221 TargetOpcodes, TargetVTs);
3223 // Emit the matcher, capturing named arguments in VariableMap.
3224 bool FoundChain = false;
3225 Emitter.EmitMatchCode(Pattern.getSrcPattern(), NULL, "N", "", FoundChain);
3227 // TP - Get *SOME* tree pattern, we don't care which.
3228 TreePattern &TP = *PatternFragments.begin()->second;
3230 // At this point, we know that we structurally match the pattern, but the
3231 // types of the nodes may not match. Figure out the fewest number of type
3232 // comparisons we need to emit. For example, if there is only one integer
3233 // type supported by a target, there should be no type comparisons at all for
3234 // integer patterns!
3236 // To figure out the fewest number of type checks needed, clone the pattern,
3237 // remove the types, then perform type inference on the pattern as a whole.
3238 // If there are unresolved types, emit an explicit check for those types,
3239 // apply the type to the tree, then rerun type inference. Iterate until all
3240 // types are resolved.
3242 TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
3243 RemoveAllTypes(Pat);
3246 // Resolve/propagate as many types as possible.
3248 bool MadeChange = true;
3250 MadeChange = Pat->ApplyTypeConstraints(TP,
3251 true/*Ignore reg constraints*/);
3253 assert(0 && "Error: could not find consistent types for something we"
3254 " already decided was ok!");
3258 // Insert a check for an unresolved type and add it to the tree. If we find
3259 // an unresolved type to add a check for, this returns true and we iterate,
3260 // otherwise we are done.
3261 } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N", true));
3263 Emitter.EmitResultCode(Pattern.getDstPattern(),
3264 false, false, false, false, true);
3268 /// EraseCodeLine - Erase one code line from all of the patterns. If removing
3269 /// a line causes any of them to be empty, remove them and return true when
3271 static bool EraseCodeLine(std::vector<std::pair<PatternToMatch*,
3272 std::vector<std::pair<unsigned, std::string> > > >
3274 bool ErasedPatterns = false;
3275 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
3276 Patterns[i].second.pop_back();
3277 if (Patterns[i].second.empty()) {
3278 Patterns.erase(Patterns.begin()+i);
3280 ErasedPatterns = true;
3283 return ErasedPatterns;
3286 /// EmitPatterns - Emit code for at least one pattern, but try to group common
3287 /// code together between the patterns.
3288 void DAGISelEmitter::EmitPatterns(std::vector<std::pair<PatternToMatch*,
3289 std::vector<std::pair<unsigned, std::string> > > >
3290 &Patterns, unsigned Indent,
3292 typedef std::pair<unsigned, std::string> CodeLine;
3293 typedef std::vector<CodeLine> CodeList;
3294 typedef std::vector<std::pair<PatternToMatch*, CodeList> > PatternList;
3296 if (Patterns.empty()) return;
3298 // Figure out how many patterns share the next code line. Explicitly copy
3299 // FirstCodeLine so that we don't invalidate a reference when changing
3301 const CodeLine FirstCodeLine = Patterns.back().second.back();
3302 unsigned LastMatch = Patterns.size()-1;
3303 while (LastMatch != 0 && Patterns[LastMatch-1].second.back() == FirstCodeLine)
3306 // If not all patterns share this line, split the list into two pieces. The
3307 // first chunk will use this line, the second chunk won't.
3308 if (LastMatch != 0) {
3309 PatternList Shared(Patterns.begin()+LastMatch, Patterns.end());
3310 PatternList Other(Patterns.begin(), Patterns.begin()+LastMatch);
3312 // FIXME: Emit braces?
3313 if (Shared.size() == 1) {
3314 PatternToMatch &Pattern = *Shared.back().first;
3315 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
3316 Pattern.getSrcPattern()->print(OS);
3317 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
3318 Pattern.getDstPattern()->print(OS);
3320 unsigned AddedComplexity = Pattern.getAddedComplexity();
3321 OS << std::string(Indent, ' ') << "// Pattern complexity = "
3322 << getPatternSize(Pattern.getSrcPattern(), *this) + AddedComplexity
3324 << getResultPatternCost(Pattern.getDstPattern(), *this)
3326 << getResultPatternSize(Pattern.getDstPattern(), *this) << "\n";
3328 if (FirstCodeLine.first != 1) {
3329 OS << std::string(Indent, ' ') << "{\n";
3332 EmitPatterns(Shared, Indent, OS);
3333 if (FirstCodeLine.first != 1) {
3335 OS << std::string(Indent, ' ') << "}\n";
3338 if (Other.size() == 1) {
3339 PatternToMatch &Pattern = *Other.back().first;
3340 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
3341 Pattern.getSrcPattern()->print(OS);
3342 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
3343 Pattern.getDstPattern()->print(OS);
3345 unsigned AddedComplexity = Pattern.getAddedComplexity();
3346 OS << std::string(Indent, ' ') << "// Pattern complexity = "
3347 << getPatternSize(Pattern.getSrcPattern(), *this) + AddedComplexity
3349 << getResultPatternCost(Pattern.getDstPattern(), *this)
3351 << getResultPatternSize(Pattern.getDstPattern(), *this) << "\n";
3353 EmitPatterns(Other, Indent, OS);
3357 // Remove this code from all of the patterns that share it.
3358 bool ErasedPatterns = EraseCodeLine(Patterns);
3360 bool isPredicate = FirstCodeLine.first == 1;
3362 // Otherwise, every pattern in the list has this line. Emit it.
3365 OS << std::string(Indent, ' ') << FirstCodeLine.second << "\n";
3367 OS << std::string(Indent, ' ') << "if (" << FirstCodeLine.second;
3369 // If the next code line is another predicate, and if all of the pattern
3370 // in this group share the same next line, emit it inline now. Do this
3371 // until we run out of common predicates.
3372 while (!ErasedPatterns && Patterns.back().second.back().first == 1) {
3373 // Check that all of fhe patterns in Patterns end with the same predicate.
3374 bool AllEndWithSamePredicate = true;
3375 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
3376 if (Patterns[i].second.back() != Patterns.back().second.back()) {
3377 AllEndWithSamePredicate = false;
3380 // If all of the predicates aren't the same, we can't share them.
3381 if (!AllEndWithSamePredicate) break;
3383 // Otherwise we can. Emit it shared now.
3384 OS << " &&\n" << std::string(Indent+4, ' ')
3385 << Patterns.back().second.back().second;
3386 ErasedPatterns = EraseCodeLine(Patterns);
3393 EmitPatterns(Patterns, Indent, OS);
3396 OS << std::string(Indent-2, ' ') << "}\n";
3399 static std::string getOpcodeName(Record *Op, DAGISelEmitter &ISE) {
3400 const SDNodeInfo &OpcodeInfo = ISE.getSDNodeInfo(Op);
3401 return OpcodeInfo.getEnumName();
3404 static std::string getLegalCName(std::string OpName) {
3405 std::string::size_type pos = OpName.find("::");
3406 if (pos != std::string::npos)
3407 OpName.replace(pos, 2, "_");
3411 void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
3412 // Get the namespace to insert instructions into. Make sure not to pick up
3413 // "TargetInstrInfo" by accidentally getting the namespace off the PHI
3414 // instruction or something.
3416 for (CodeGenTarget::inst_iterator i = Target.inst_begin(),
3417 e = Target.inst_end(); i != e; ++i) {
3418 InstNS = i->second.Namespace;
3419 if (InstNS != "TargetInstrInfo")
3423 if (!InstNS.empty()) InstNS += "::";
3425 // Group the patterns by their top-level opcodes.
3426 std::map<std::string, std::vector<PatternToMatch*> > PatternsByOpcode;
3427 // All unique target node emission functions.
3428 std::map<std::string, unsigned> EmitFunctions;
3429 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
3430 TreePatternNode *Node = PatternsToMatch[i].getSrcPattern();
3431 if (!Node->isLeaf()) {
3432 PatternsByOpcode[getOpcodeName(Node->getOperator(), *this)].
3433 push_back(&PatternsToMatch[i]);
3435 const ComplexPattern *CP;
3436 if (dynamic_cast<IntInit*>(Node->getLeafValue())) {
3437 PatternsByOpcode[getOpcodeName(getSDNodeNamed("imm"), *this)].
3438 push_back(&PatternsToMatch[i]);
3439 } else if ((CP = NodeGetComplexPattern(Node, *this))) {
3440 std::vector<Record*> OpNodes = CP->getRootNodes();
3441 for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
3442 PatternsByOpcode[getOpcodeName(OpNodes[j], *this)]
3443 .insert(PatternsByOpcode[getOpcodeName(OpNodes[j], *this)].begin(),
3444 &PatternsToMatch[i]);
3447 cerr << "Unrecognized opcode '";
3449 cerr << "' on tree pattern '";
3450 cerr << PatternsToMatch[i].getDstPattern()->getOperator()->getName();
3457 // For each opcode, there might be multiple select functions, one per
3458 // ValueType of the node (or its first operand if it doesn't produce a
3459 // non-chain result.
3460 std::map<std::string, std::vector<std::string> > OpcodeVTMap;
3462 // Emit one Select_* method for each top-level opcode. We do this instead of
3463 // emitting one giant switch statement to support compilers where this will
3464 // result in the recursive functions taking less stack space.
3465 for (std::map<std::string, std::vector<PatternToMatch*> >::iterator
3466 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
3467 PBOI != E; ++PBOI) {
3468 const std::string &OpName = PBOI->first;
3469 std::vector<PatternToMatch*> &PatternsOfOp = PBOI->second;
3470 assert(!PatternsOfOp.empty() && "No patterns but map has entry?");
3472 // We want to emit all of the matching code now. However, we want to emit
3473 // the matches in order of minimal cost. Sort the patterns so the least
3474 // cost one is at the start.
3475 std::stable_sort(PatternsOfOp.begin(), PatternsOfOp.end(),
3476 PatternSortingPredicate(*this));
3478 // Split them into groups by type.
3479 std::map<MVT::ValueType, std::vector<PatternToMatch*> > PatternsByType;
3480 for (unsigned i = 0, e = PatternsOfOp.size(); i != e; ++i) {
3481 PatternToMatch *Pat = PatternsOfOp[i];
3482 TreePatternNode *SrcPat = Pat->getSrcPattern();
3483 MVT::ValueType VT = SrcPat->getTypeNum(0);
3484 std::map<MVT::ValueType, std::vector<PatternToMatch*> >::iterator TI =
3485 PatternsByType.find(VT);
3486 if (TI != PatternsByType.end())
3487 TI->second.push_back(Pat);
3489 std::vector<PatternToMatch*> PVec;
3490 PVec.push_back(Pat);
3491 PatternsByType.insert(std::make_pair(VT, PVec));
3495 for (std::map<MVT::ValueType, std::vector<PatternToMatch*> >::iterator
3496 II = PatternsByType.begin(), EE = PatternsByType.end(); II != EE;
3498 MVT::ValueType OpVT = II->first;
3499 std::vector<PatternToMatch*> &Patterns = II->second;
3500 typedef std::vector<std::pair<unsigned,std::string> > CodeList;
3501 typedef std::vector<std::pair<unsigned,std::string> >::iterator CodeListI;
3503 std::vector<std::pair<PatternToMatch*, CodeList> > CodeForPatterns;
3504 std::vector<std::vector<std::string> > PatternOpcodes;
3505 std::vector<std::vector<std::string> > PatternVTs;
3506 std::vector<std::set<std::string> > PatternDecls;
3507 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
3508 CodeList GeneratedCode;
3509 std::set<std::string> GeneratedDecl;
3510 std::vector<std::string> TargetOpcodes;
3511 std::vector<std::string> TargetVTs;
3512 GenerateCodeForPattern(*Patterns[i], GeneratedCode, GeneratedDecl,
3513 TargetOpcodes, TargetVTs);
3514 CodeForPatterns.push_back(std::make_pair(Patterns[i], GeneratedCode));
3515 PatternDecls.push_back(GeneratedDecl);
3516 PatternOpcodes.push_back(TargetOpcodes);
3517 PatternVTs.push_back(TargetVTs);
3520 // Scan the code to see if all of the patterns are reachable and if it is
3521 // possible that the last one might not match.
3522 bool mightNotMatch = true;
3523 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
3524 CodeList &GeneratedCode = CodeForPatterns[i].second;
3525 mightNotMatch = false;
3527 for (unsigned j = 0, e = GeneratedCode.size(); j != e; ++j) {
3528 if (GeneratedCode[j].first == 1) { // predicate.
3529 mightNotMatch = true;
3534 // If this pattern definitely matches, and if it isn't the last one, the
3535 // patterns after it CANNOT ever match. Error out.
3536 if (mightNotMatch == false && i != CodeForPatterns.size()-1) {
3537 cerr << "Pattern '";
3538 CodeForPatterns[i].first->getSrcPattern()->print(*cerr.stream());
3539 cerr << "' is impossible to select!\n";
3544 // Factor target node emission code (emitted by EmitResultCode) into
3545 // separate functions. Uniquing and share them among all instruction
3546 // selection routines.
3547 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
3548 CodeList &GeneratedCode = CodeForPatterns[i].second;
3549 std::vector<std::string> &TargetOpcodes = PatternOpcodes[i];
3550 std::vector<std::string> &TargetVTs = PatternVTs[i];
3551 std::set<std::string> Decls = PatternDecls[i];
3552 std::vector<std::string> AddedInits;
3553 int CodeSize = (int)GeneratedCode.size();
3555 for (int j = CodeSize-1; j >= 0; --j) {
3556 if (LastPred == -1 && GeneratedCode[j].first == 1)
3558 else if (LastPred != -1 && GeneratedCode[j].first == 2)
3559 AddedInits.push_back(GeneratedCode[j].second);
3562 std::string CalleeCode = "(const SDOperand &N";
3563 std::string CallerCode = "(N";
3564 for (unsigned j = 0, e = TargetOpcodes.size(); j != e; ++j) {
3565 CalleeCode += ", unsigned Opc" + utostr(j);
3566 CallerCode += ", " + TargetOpcodes[j];
3568 for (unsigned j = 0, e = TargetVTs.size(); j != e; ++j) {
3569 CalleeCode += ", MVT::ValueType VT" + utostr(j);
3570 CallerCode += ", " + TargetVTs[j];
3572 for (std::set<std::string>::iterator
3573 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
3574 std::string Name = *I;
3575 CalleeCode += ", SDOperand &" + Name;
3576 CallerCode += ", " + Name;
3580 // Prevent emission routines from being inlined to reduce selection
3581 // routines stack frame sizes.
3582 CalleeCode += "DISABLE_INLINE ";
3583 CalleeCode += "{\n";
3585 for (std::vector<std::string>::const_reverse_iterator
3586 I = AddedInits.rbegin(), E = AddedInits.rend(); I != E; ++I)
3587 CalleeCode += " " + *I + "\n";
3589 for (int j = LastPred+1; j < CodeSize; ++j)
3590 CalleeCode += " " + GeneratedCode[j].second + "\n";
3591 for (int j = LastPred+1; j < CodeSize; ++j)
3592 GeneratedCode.pop_back();
3593 CalleeCode += "}\n";
3595 // Uniquing the emission routines.
3596 unsigned EmitFuncNum;
3597 std::map<std::string, unsigned>::iterator EFI =
3598 EmitFunctions.find(CalleeCode);
3599 if (EFI != EmitFunctions.end()) {
3600 EmitFuncNum = EFI->second;
3602 EmitFuncNum = EmitFunctions.size();
3603 EmitFunctions.insert(std::make_pair(CalleeCode, EmitFuncNum));
3604 OS << "SDNode *Emit_" << utostr(EmitFuncNum) << CalleeCode;
3607 // Replace the emission code within selection routines with calls to the
3608 // emission functions.
3609 CallerCode = "return Emit_" + utostr(EmitFuncNum) + CallerCode;
3610 GeneratedCode.push_back(std::make_pair(false, CallerCode));
3614 std::string OpVTStr;
3615 if (OpVT == MVT::iPTR) {
3617 } else if (OpVT == MVT::isVoid) {
3618 // Nodes with a void result actually have a first result type of either
3619 // Other (a chain) or Flag. Since there is no one-to-one mapping from
3620 // void to this case, we handle it specially here.
3622 OpVTStr = "_" + getEnumName(OpVT).substr(5); // Skip 'MVT::'
3624 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
3625 OpcodeVTMap.find(OpName);
3626 if (OpVTI == OpcodeVTMap.end()) {
3627 std::vector<std::string> VTSet;
3628 VTSet.push_back(OpVTStr);
3629 OpcodeVTMap.insert(std::make_pair(OpName, VTSet));
3631 OpVTI->second.push_back(OpVTStr);
3633 OS << "SDNode *Select_" << getLegalCName(OpName)
3634 << OpVTStr << "(const SDOperand &N) {\n";
3636 // Loop through and reverse all of the CodeList vectors, as we will be
3637 // accessing them from their logical front, but accessing the end of a
3638 // vector is more efficient.
3639 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
3640 CodeList &GeneratedCode = CodeForPatterns[i].second;
3641 std::reverse(GeneratedCode.begin(), GeneratedCode.end());
3644 // Next, reverse the list of patterns itself for the same reason.
3645 std::reverse(CodeForPatterns.begin(), CodeForPatterns.end());
3647 // Emit all of the patterns now, grouped together to share code.
3648 EmitPatterns(CodeForPatterns, 2, OS);
3650 // If the last pattern has predicates (which could fail) emit code to
3651 // catch the case where nothing handles a pattern.
3652 if (mightNotMatch) {
3653 OS << " cerr << \"Cannot yet select: \";\n";
3654 if (OpName != "ISD::INTRINSIC_W_CHAIN" &&
3655 OpName != "ISD::INTRINSIC_WO_CHAIN" &&
3656 OpName != "ISD::INTRINSIC_VOID") {
3657 OS << " N.Val->dump(CurDAG);\n";
3659 OS << " unsigned iid = cast<ConstantSDNode>(N.getOperand("
3660 "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
3661 << " cerr << \"intrinsic %\"<< "
3662 "Intrinsic::getName((Intrinsic::ID)iid);\n";
3664 OS << " cerr << '\\n';\n"
3666 << " return NULL;\n";
3672 // Emit boilerplate.
3673 OS << "SDNode *Select_INLINEASM(SDOperand N) {\n"
3674 << " std::vector<SDOperand> Ops(N.Val->op_begin(), N.Val->op_end());\n"
3675 << " AddToISelQueue(N.getOperand(0)); // Select the chain.\n\n"
3676 << " // Select the flag operand.\n"
3677 << " if (Ops.back().getValueType() == MVT::Flag)\n"
3678 << " AddToISelQueue(Ops.back());\n"
3679 << " SelectInlineAsmMemoryOperands(Ops, *CurDAG);\n"
3680 << " std::vector<MVT::ValueType> VTs;\n"
3681 << " VTs.push_back(MVT::Other);\n"
3682 << " VTs.push_back(MVT::Flag);\n"
3683 << " SDOperand New = CurDAG->getNode(ISD::INLINEASM, VTs, &Ops[0], "
3685 << " return New.Val;\n"
3688 OS << "// The main instruction selector code.\n"
3689 << "SDNode *SelectCode(SDOperand N) {\n"
3690 << " if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
3691 << " N.getOpcode() < (ISD::BUILTIN_OP_END+" << InstNS
3692 << "INSTRUCTION_LIST_END)) {\n"
3693 << " return NULL; // Already selected.\n"
3695 << " MVT::ValueType NVT = N.Val->getValueType(0);\n"
3696 << " switch (N.getOpcode()) {\n"
3697 << " default: break;\n"
3698 << " case ISD::EntryToken: // These leaves remain the same.\n"
3699 << " case ISD::BasicBlock:\n"
3700 << " case ISD::Register:\n"
3701 << " case ISD::HANDLENODE:\n"
3702 << " case ISD::TargetConstant:\n"
3703 << " case ISD::TargetConstantPool:\n"
3704 << " case ISD::TargetFrameIndex:\n"
3705 << " case ISD::TargetJumpTable:\n"
3706 << " case ISD::TargetGlobalAddress: {\n"
3707 << " return NULL;\n"
3709 << " case ISD::AssertSext:\n"
3710 << " case ISD::AssertZext: {\n"
3711 << " AddToISelQueue(N.getOperand(0));\n"
3712 << " ReplaceUses(N, N.getOperand(0));\n"
3713 << " return NULL;\n"
3715 << " case ISD::TokenFactor:\n"
3716 << " case ISD::CopyFromReg:\n"
3717 << " case ISD::CopyToReg: {\n"
3718 << " for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i)\n"
3719 << " AddToISelQueue(N.getOperand(i));\n"
3720 << " return NULL;\n"
3722 << " case ISD::INLINEASM: return Select_INLINEASM(N);\n";
3725 // Loop over all of the case statements, emiting a call to each method we
3727 for (std::map<std::string, std::vector<PatternToMatch*> >::iterator
3728 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
3729 PBOI != E; ++PBOI) {
3730 const std::string &OpName = PBOI->first;
3731 // Potentially multiple versions of select for this opcode. One for each
3732 // ValueType of the node (or its first true operand if it doesn't produce a
3734 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
3735 OpcodeVTMap.find(OpName);
3736 std::vector<std::string> &OpVTs = OpVTI->second;
3737 OS << " case " << OpName << ": {\n";
3738 if (OpVTs.size() == 1) {
3739 std::string &VTStr = OpVTs[0];
3740 OS << " return Select_" << getLegalCName(OpName)
3741 << VTStr << "(N);\n";
3743 // Keep track of whether we see a pattern that has an iPtr result.
3744 bool HasPtrPattern = false;
3745 bool HasDefaultPattern = false;
3747 OS << " switch (NVT) {\n";
3748 for (unsigned i = 0, e = OpVTs.size(); i < e; ++i) {
3749 std::string &VTStr = OpVTs[i];
3750 if (VTStr.empty()) {
3751 HasDefaultPattern = true;
3755 // If this is a match on iPTR: don't emit it directly, we need special
3757 if (VTStr == "_iPTR") {
3758 HasPtrPattern = true;
3761 OS << " case MVT::" << VTStr.substr(1) << ":\n"
3762 << " return Select_" << getLegalCName(OpName)
3763 << VTStr << "(N);\n";
3765 OS << " default:\n";
3767 // If there is an iPTR result version of this pattern, emit it here.
3768 if (HasPtrPattern) {
3769 OS << " if (NVT == TLI.getPointerTy())\n";
3770 OS << " return Select_" << getLegalCName(OpName) <<"_iPTR(N);\n";
3772 if (HasDefaultPattern) {
3773 OS << " return Select_" << getLegalCName(OpName) << "(N);\n";
3782 OS << " } // end of big switch.\n\n"
3783 << " cerr << \"Cannot yet select: \";\n"
3784 << " if (N.getOpcode() != ISD::INTRINSIC_W_CHAIN &&\n"
3785 << " N.getOpcode() != ISD::INTRINSIC_WO_CHAIN &&\n"
3786 << " N.getOpcode() != ISD::INTRINSIC_VOID) {\n"
3787 << " N.Val->dump(CurDAG);\n"
3789 << " unsigned iid = cast<ConstantSDNode>(N.getOperand("
3790 "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
3791 << " cerr << \"intrinsic %\"<< "
3792 "Intrinsic::getName((Intrinsic::ID)iid);\n"
3794 << " cerr << '\\n';\n"
3796 << " return NULL;\n"
3800 void DAGISelEmitter::run(std::ostream &OS) {
3801 EmitSourceFileHeader("DAG Instruction Selector for the " + Target.getName() +
3804 OS << "// *** NOTE: This file is #included into the middle of the target\n"
3805 << "// *** instruction selector class. These functions are really "
3808 OS << "#include \"llvm/Support/Compiler.h\"\n";
3810 OS << "// Instruction selector priority queue:\n"
3811 << "std::vector<SDNode*> ISelQueue;\n";
3812 OS << "/// Keep track of nodes which have already been added to queue.\n"
3813 << "unsigned char *ISelQueued;\n";
3814 OS << "/// Keep track of nodes which have already been selected.\n"
3815 << "unsigned char *ISelSelected;\n";
3816 OS << "/// Dummy parameter to ReplaceAllUsesOfValueWith().\n"
3817 << "std::vector<SDNode*> ISelKilled;\n\n";
3819 OS << "/// IsChainCompatible - Returns true if Chain is Op or Chain does\n";
3820 OS << "/// not reach Op.\n";
3821 OS << "static bool IsChainCompatible(SDNode *Chain, SDNode *Op) {\n";
3822 OS << " if (Chain->getOpcode() == ISD::EntryToken)\n";
3823 OS << " return true;\n";
3824 OS << " else if (Chain->getOpcode() == ISD::TokenFactor)\n";
3825 OS << " return false;\n";
3826 OS << " else if (Chain->getNumOperands() > 0) {\n";
3827 OS << " SDOperand C0 = Chain->getOperand(0);\n";
3828 OS << " if (C0.getValueType() == MVT::Other)\n";
3829 OS << " return C0.Val != Op && IsChainCompatible(C0.Val, Op);\n";
3831 OS << " return true;\n";
3834 OS << "/// Sorting functions for the selection queue.\n"
3835 << "struct isel_sort : public std::binary_function"
3836 << "<SDNode*, SDNode*, bool> {\n"
3837 << " bool operator()(const SDNode* left, const SDNode* right) "
3839 << " return (left->getNodeId() > right->getNodeId());\n"
3843 OS << "inline void setQueued(int Id) {\n";
3844 OS << " ISelQueued[Id / 8] |= 1 << (Id % 8);\n";
3846 OS << "inline bool isQueued(int Id) {\n";
3847 OS << " return ISelQueued[Id / 8] & (1 << (Id % 8));\n";
3849 OS << "inline void setSelected(int Id) {\n";
3850 OS << " ISelSelected[Id / 8] |= 1 << (Id % 8);\n";
3852 OS << "inline bool isSelected(int Id) {\n";
3853 OS << " return ISelSelected[Id / 8] & (1 << (Id % 8));\n";
3856 OS << "void AddToISelQueue(SDOperand N) DISABLE_INLINE {\n";
3857 OS << " int Id = N.Val->getNodeId();\n";
3858 OS << " if (Id != -1 && !isQueued(Id)) {\n";
3859 OS << " ISelQueue.push_back(N.Val);\n";
3860 OS << " std::push_heap(ISelQueue.begin(), ISelQueue.end(), isel_sort());\n";
3861 OS << " setQueued(Id);\n";
3865 OS << "inline void RemoveKilled() {\n";
3866 OS << " unsigned NumKilled = ISelKilled.size();\n";
3867 OS << " if (NumKilled) {\n";
3868 OS << " for (unsigned i = 0; i != NumKilled; ++i) {\n";
3869 OS << " SDNode *Temp = ISelKilled[i];\n";
3870 OS << " ISelQueue.erase(std::remove(ISelQueue.begin(), ISelQueue.end(), "
3871 << "Temp), ISelQueue.end());\n";
3873 OS << " std::make_heap(ISelQueue.begin(), ISelQueue.end(), isel_sort());\n";
3874 OS << " ISelKilled.clear();\n";
3878 OS << "void ReplaceUses(SDOperand F, SDOperand T) DISABLE_INLINE {\n";
3879 OS << " CurDAG->ReplaceAllUsesOfValueWith(F, T, ISelKilled);\n";
3880 OS << " setSelected(F.Val->getNodeId());\n";
3881 OS << " RemoveKilled();\n";
3883 OS << "inline void ReplaceUses(SDNode *F, SDNode *T) {\n";
3884 OS << " CurDAG->ReplaceAllUsesWith(F, T, &ISelKilled);\n";
3885 OS << " setSelected(F->getNodeId());\n";
3886 OS << " RemoveKilled();\n";
3889 OS << "// SelectRoot - Top level entry to DAG isel.\n";
3890 OS << "SDOperand SelectRoot(SDOperand Root) {\n";
3891 OS << " SelectRootInit();\n";
3892 OS << " unsigned NumBytes = (DAGSize + 7) / 8;\n";
3893 OS << " ISelQueued = new unsigned char[NumBytes];\n";
3894 OS << " ISelSelected = new unsigned char[NumBytes];\n";
3895 OS << " memset(ISelQueued, 0, NumBytes);\n";
3896 OS << " memset(ISelSelected, 0, NumBytes);\n";
3898 OS << " // Create a dummy node (which is not added to allnodes), that adds\n"
3899 << " // a reference to the root node, preventing it from being deleted,\n"
3900 << " // and tracking any changes of the root.\n"
3901 << " HandleSDNode Dummy(CurDAG->getRoot());\n"
3902 << " ISelQueue.push_back(CurDAG->getRoot().Val);\n";
3903 OS << " while (!ISelQueue.empty()) {\n";
3904 OS << " SDNode *Node = ISelQueue.front();\n";
3905 OS << " std::pop_heap(ISelQueue.begin(), ISelQueue.end(), isel_sort());\n";
3906 OS << " ISelQueue.pop_back();\n";
3907 OS << " if (!isSelected(Node->getNodeId())) {\n";
3908 OS << " SDNode *ResNode = Select(SDOperand(Node, 0));\n";
3909 OS << " if (ResNode != Node) {\n";
3910 OS << " if (ResNode)\n";
3911 OS << " ReplaceUses(Node, ResNode);\n";
3912 OS << " if (Node->use_empty()) { // Don't delete EntryToken, etc.\n";
3913 OS << " CurDAG->RemoveDeadNode(Node, ISelKilled);\n";
3914 OS << " RemoveKilled();\n";
3920 OS << " delete[] ISelQueued;\n";
3921 OS << " ISelQueued = NULL;\n";
3922 OS << " delete[] ISelSelected;\n";
3923 OS << " ISelSelected = NULL;\n";
3924 OS << " return Dummy.getValue();\n";
3927 Intrinsics = LoadIntrinsics(Records);
3929 ParseNodeTransforms(OS);
3930 ParseComplexPatterns();
3931 ParsePatternFragments(OS);
3932 ParsePredicateOperands();
3933 ParseInstructions();
3936 // Generate variants. For example, commutative patterns can match
3937 // multiple ways. Add them to PatternsToMatch as well.
3940 DOUT << "\n\nALL PATTERNS TO MATCH:\n\n";
3941 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
3942 DOUT << "PATTERN: "; DEBUG(PatternsToMatch[i].getSrcPattern()->dump());
3943 DOUT << "\nRESULT: "; DEBUG(PatternsToMatch[i].getDstPattern()->dump());
3947 // At this point, we have full information about the 'Patterns' we need to
3948 // parse, both implicitly from instructions as well as from explicit pattern
3949 // definitions. Emit the resultant instruction selector.
3950 EmitInstructionSelector(OS);
3952 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
3953 E = PatternFragments.end(); I != E; ++I)
3955 PatternFragments.clear();
3957 Instructions.clear();