1 //===- CodeGenDAGPatterns.cpp - Read DAG patterns from .td file -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the CodeGenDAGPatterns class, which is used to read and
11 // represent the patterns present in a .td file for instructions.
13 //===----------------------------------------------------------------------===//
15 #include "CodeGenDAGPatterns.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/Support/Debug.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.
70 bool isExtIntegerInVTs(const std::vector<unsigned char> &EVTs) {
71 assert(!EVTs.empty() && "Cannot check for integer in empty ExtVT list!");
72 return EVTs[0] == isInt || !(FilterEVTs(EVTs, isInteger).empty());
75 /// isExtFloatingPointVT - Return true if the specified extended value type
76 /// vector contains isFP or a FP value type.
77 bool isExtFloatingPointInVTs(const std::vector<unsigned char> &EVTs) {
78 assert(!EVTs.empty() && "Cannot check for integer in empty ExtVT list!");
79 return EVTs[0] == isFP || !(FilterEVTs(EVTs, isFloatingPoint).empty());
81 } // end namespace MVT.
82 } // end namespace llvm.
85 /// Dependent variable map for CodeGenDAGPattern variant generation
86 typedef std::map<std::string, int> DepVarMap;
88 /// Const iterator shorthand for DepVarMap
89 typedef DepVarMap::const_iterator DepVarMap_citer;
92 void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
94 if (dynamic_cast<DefInit*>(N->getLeafValue()) != NULL) {
95 DepMap[N->getName()]++;
98 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
99 FindDepVarsOf(N->getChild(i), DepMap);
103 //! Find dependent variables within child patterns
106 void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
108 FindDepVarsOf(N, depcounts);
109 for (DepVarMap_citer i = depcounts.begin(); i != depcounts.end(); ++i) {
110 if (i->second > 1) { // std::pair<std::string, int>
111 DepVars.insert(i->first);
116 //! Dump the dependent variable set:
117 void DumpDepVars(MultipleUseVarSet &DepVars) {
118 if (DepVars.empty()) {
119 DOUT << "<empty set>";
122 for (MultipleUseVarSet::const_iterator i = DepVars.begin(), e = DepVars.end();
131 //===----------------------------------------------------------------------===//
132 // SDTypeConstraint implementation
135 SDTypeConstraint::SDTypeConstraint(Record *R) {
136 OperandNo = R->getValueAsInt("OperandNum");
138 if (R->isSubClassOf("SDTCisVT")) {
139 ConstraintType = SDTCisVT;
140 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
141 } else if (R->isSubClassOf("SDTCisPtrTy")) {
142 ConstraintType = SDTCisPtrTy;
143 } else if (R->isSubClassOf("SDTCisInt")) {
144 ConstraintType = SDTCisInt;
145 } else if (R->isSubClassOf("SDTCisFP")) {
146 ConstraintType = SDTCisFP;
147 } else if (R->isSubClassOf("SDTCisSameAs")) {
148 ConstraintType = SDTCisSameAs;
149 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
150 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
151 ConstraintType = SDTCisVTSmallerThanOp;
152 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
153 R->getValueAsInt("OtherOperandNum");
154 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
155 ConstraintType = SDTCisOpSmallerThanOp;
156 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
157 R->getValueAsInt("BigOperandNum");
158 } else if (R->isSubClassOf("SDTCisIntVectorOfSameSize")) {
159 ConstraintType = SDTCisIntVectorOfSameSize;
160 x.SDTCisIntVectorOfSameSize_Info.OtherOperandNum =
161 R->getValueAsInt("OtherOpNum");
162 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
163 ConstraintType = SDTCisEltOfVec;
164 x.SDTCisEltOfVec_Info.OtherOperandNum =
165 R->getValueAsInt("OtherOpNum");
167 cerr << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
172 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
173 /// N, which has NumResults results.
174 TreePatternNode *SDTypeConstraint::getOperandNum(unsigned OpNo,
176 unsigned NumResults) const {
177 assert(NumResults <= 1 &&
178 "We only work with nodes with zero or one result so far!");
180 if (OpNo >= (NumResults + N->getNumChildren())) {
181 cerr << "Invalid operand number " << OpNo << " ";
187 if (OpNo < NumResults)
188 return N; // FIXME: need value #
190 return N->getChild(OpNo-NumResults);
193 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
194 /// constraint to the nodes operands. This returns true if it makes a
195 /// change, false otherwise. If a type contradiction is found, throw an
197 bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
198 const SDNodeInfo &NodeInfo,
199 TreePattern &TP) const {
200 unsigned NumResults = NodeInfo.getNumResults();
201 assert(NumResults <= 1 &&
202 "We only work with nodes with zero or one result so far!");
204 // Check that the number of operands is sane. Negative operands -> varargs.
205 if (NodeInfo.getNumOperands() >= 0) {
206 if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands())
207 TP.error(N->getOperator()->getName() + " node requires exactly " +
208 itostr(NodeInfo.getNumOperands()) + " operands!");
211 const CodeGenTarget &CGT = TP.getDAGPatterns().getTargetInfo();
213 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NumResults);
215 switch (ConstraintType) {
216 default: assert(0 && "Unknown constraint type!");
218 // Operand must be a particular type.
219 return NodeToApply->UpdateNodeType(x.SDTCisVT_Info.VT, TP);
221 // Operand must be same as target pointer type.
222 return NodeToApply->UpdateNodeType(MVT::iPTR, TP);
225 // If there is only one integer type supported, this must be it.
226 std::vector<MVT::ValueType> IntVTs =
227 FilterVTs(CGT.getLegalValueTypes(), MVT::isInteger);
229 // If we found exactly one supported integer type, apply it.
230 if (IntVTs.size() == 1)
231 return NodeToApply->UpdateNodeType(IntVTs[0], TP);
232 return NodeToApply->UpdateNodeType(MVT::isInt, TP);
235 // If there is only one FP type supported, this must be it.
236 std::vector<MVT::ValueType> FPVTs =
237 FilterVTs(CGT.getLegalValueTypes(), MVT::isFloatingPoint);
239 // If we found exactly one supported FP type, apply it.
240 if (FPVTs.size() == 1)
241 return NodeToApply->UpdateNodeType(FPVTs[0], TP);
242 return NodeToApply->UpdateNodeType(MVT::isFP, TP);
245 TreePatternNode *OtherNode =
246 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NumResults);
247 return NodeToApply->UpdateNodeType(OtherNode->getExtTypes(), TP) |
248 OtherNode->UpdateNodeType(NodeToApply->getExtTypes(), TP);
250 case SDTCisVTSmallerThanOp: {
251 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
252 // have an integer type that is smaller than the VT.
253 if (!NodeToApply->isLeaf() ||
254 !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
255 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
256 ->isSubClassOf("ValueType"))
257 TP.error(N->getOperator()->getName() + " expects a VT operand!");
259 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
260 if (!MVT::isInteger(VT))
261 TP.error(N->getOperator()->getName() + " VT operand must be integer!");
263 TreePatternNode *OtherNode =
264 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N,NumResults);
266 // It must be integer.
267 bool MadeChange = false;
268 MadeChange |= OtherNode->UpdateNodeType(MVT::isInt, TP);
270 // This code only handles nodes that have one type set. Assert here so
271 // that we can change this if we ever need to deal with multiple value
272 // types at this point.
273 assert(OtherNode->getExtTypes().size() == 1 && "Node has too many types!");
274 if (OtherNode->hasTypeSet() && OtherNode->getTypeNum(0) <= VT)
275 OtherNode->UpdateNodeType(MVT::Other, TP); // Throw an error.
278 case SDTCisOpSmallerThanOp: {
279 TreePatternNode *BigOperand =
280 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NumResults);
282 // Both operands must be integer or FP, but we don't care which.
283 bool MadeChange = false;
285 // This code does not currently handle nodes which have multiple types,
286 // where some types are integer, and some are fp. Assert that this is not
288 assert(!(MVT::isExtIntegerInVTs(NodeToApply->getExtTypes()) &&
289 MVT::isExtFloatingPointInVTs(NodeToApply->getExtTypes())) &&
290 !(MVT::isExtIntegerInVTs(BigOperand->getExtTypes()) &&
291 MVT::isExtFloatingPointInVTs(BigOperand->getExtTypes())) &&
292 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
293 if (MVT::isExtIntegerInVTs(NodeToApply->getExtTypes()))
294 MadeChange |= BigOperand->UpdateNodeType(MVT::isInt, TP);
295 else if (MVT::isExtFloatingPointInVTs(NodeToApply->getExtTypes()))
296 MadeChange |= BigOperand->UpdateNodeType(MVT::isFP, TP);
297 if (MVT::isExtIntegerInVTs(BigOperand->getExtTypes()))
298 MadeChange |= NodeToApply->UpdateNodeType(MVT::isInt, TP);
299 else if (MVT::isExtFloatingPointInVTs(BigOperand->getExtTypes()))
300 MadeChange |= NodeToApply->UpdateNodeType(MVT::isFP, TP);
302 std::vector<MVT::ValueType> VTs = CGT.getLegalValueTypes();
304 if (MVT::isExtIntegerInVTs(NodeToApply->getExtTypes())) {
305 VTs = FilterVTs(VTs, MVT::isInteger);
306 } else if (MVT::isExtFloatingPointInVTs(NodeToApply->getExtTypes())) {
307 VTs = FilterVTs(VTs, MVT::isFloatingPoint);
312 switch (VTs.size()) {
313 default: // Too many VT's to pick from.
314 case 0: break; // No info yet.
316 // Only one VT of this flavor. Cannot ever satisify the constraints.
317 return NodeToApply->UpdateNodeType(MVT::Other, TP); // throw
319 // If we have exactly two possible types, the little operand must be the
320 // small one, the big operand should be the big one. Common with
321 // float/double for example.
322 assert(VTs[0] < VTs[1] && "Should be sorted!");
323 MadeChange |= NodeToApply->UpdateNodeType(VTs[0], TP);
324 MadeChange |= BigOperand->UpdateNodeType(VTs[1], TP);
329 case SDTCisIntVectorOfSameSize: {
330 TreePatternNode *OtherOperand =
331 getOperandNum(x.SDTCisIntVectorOfSameSize_Info.OtherOperandNum,
333 if (OtherOperand->hasTypeSet()) {
334 if (!MVT::isVector(OtherOperand->getTypeNum(0)))
335 TP.error(N->getOperator()->getName() + " VT operand must be a vector!");
336 MVT::ValueType IVT = OtherOperand->getTypeNum(0);
337 IVT = MVT::getIntVectorWithNumElements(MVT::getVectorNumElements(IVT));
338 return NodeToApply->UpdateNodeType(IVT, TP);
342 case SDTCisEltOfVec: {
343 TreePatternNode *OtherOperand =
344 getOperandNum(x.SDTCisIntVectorOfSameSize_Info.OtherOperandNum,
346 if (OtherOperand->hasTypeSet()) {
347 if (!MVT::isVector(OtherOperand->getTypeNum(0)))
348 TP.error(N->getOperator()->getName() + " VT operand must be a vector!");
349 MVT::ValueType IVT = OtherOperand->getTypeNum(0);
350 IVT = MVT::getVectorElementType(IVT);
351 return NodeToApply->UpdateNodeType(IVT, TP);
359 //===----------------------------------------------------------------------===//
360 // SDNodeInfo implementation
362 SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
363 EnumName = R->getValueAsString("Opcode");
364 SDClassName = R->getValueAsString("SDClass");
365 Record *TypeProfile = R->getValueAsDef("TypeProfile");
366 NumResults = TypeProfile->getValueAsInt("NumResults");
367 NumOperands = TypeProfile->getValueAsInt("NumOperands");
369 // Parse the properties.
371 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
372 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
373 if (PropList[i]->getName() == "SDNPCommutative") {
374 Properties |= 1 << SDNPCommutative;
375 } else if (PropList[i]->getName() == "SDNPAssociative") {
376 Properties |= 1 << SDNPAssociative;
377 } else if (PropList[i]->getName() == "SDNPHasChain") {
378 Properties |= 1 << SDNPHasChain;
379 } else if (PropList[i]->getName() == "SDNPOutFlag") {
380 Properties |= 1 << SDNPOutFlag;
381 } else if (PropList[i]->getName() == "SDNPInFlag") {
382 Properties |= 1 << SDNPInFlag;
383 } else if (PropList[i]->getName() == "SDNPOptInFlag") {
384 Properties |= 1 << SDNPOptInFlag;
385 } else if (PropList[i]->getName() == "SDNPMayStore") {
386 Properties |= 1 << SDNPMayStore;
387 } else if (PropList[i]->getName() == "SDNPMayLoad") {
388 Properties |= 1 << SDNPMayLoad;
389 } else if (PropList[i]->getName() == "SDNPSideEffect") {
390 Properties |= 1 << SDNPSideEffect;
392 cerr << "Unknown SD Node property '" << PropList[i]->getName()
393 << "' on node '" << R->getName() << "'!\n";
399 // Parse the type constraints.
400 std::vector<Record*> ConstraintList =
401 TypeProfile->getValueAsListOfDefs("Constraints");
402 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
405 //===----------------------------------------------------------------------===//
406 // TreePatternNode implementation
409 TreePatternNode::~TreePatternNode() {
410 #if 0 // FIXME: implement refcounted tree nodes!
411 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
416 /// UpdateNodeType - Set the node type of N to VT if VT contains
417 /// information. If N already contains a conflicting type, then throw an
418 /// exception. This returns true if any information was updated.
420 bool TreePatternNode::UpdateNodeType(const std::vector<unsigned char> &ExtVTs,
422 assert(!ExtVTs.empty() && "Cannot update node type with empty type vector!");
424 if (ExtVTs[0] == MVT::isUnknown || LHSIsSubsetOfRHS(getExtTypes(), ExtVTs))
426 if (isTypeCompletelyUnknown() || LHSIsSubsetOfRHS(ExtVTs, getExtTypes())) {
431 if (getExtTypeNum(0) == MVT::iPTR) {
432 if (ExtVTs[0] == MVT::iPTR || ExtVTs[0] == MVT::isInt)
434 if (MVT::isExtIntegerInVTs(ExtVTs)) {
435 std::vector<unsigned char> FVTs = FilterEVTs(ExtVTs, MVT::isInteger);
443 if (ExtVTs[0] == MVT::isInt && MVT::isExtIntegerInVTs(getExtTypes())) {
444 assert(hasTypeSet() && "should be handled above!");
445 std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), MVT::isInteger);
446 if (getExtTypes() == FVTs)
451 if (ExtVTs[0] == MVT::iPTR && MVT::isExtIntegerInVTs(getExtTypes())) {
452 //assert(hasTypeSet() && "should be handled above!");
453 std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), MVT::isInteger);
454 if (getExtTypes() == FVTs)
461 if (ExtVTs[0] == MVT::isFP && MVT::isExtFloatingPointInVTs(getExtTypes())) {
462 assert(hasTypeSet() && "should be handled above!");
463 std::vector<unsigned char> FVTs =
464 FilterEVTs(getExtTypes(), MVT::isFloatingPoint);
465 if (getExtTypes() == FVTs)
471 // If we know this is an int or fp type, and we are told it is a specific one,
474 // Similarly, we should probably set the type here to the intersection of
475 // {isInt|isFP} and ExtVTs
476 if ((getExtTypeNum(0) == MVT::isInt && MVT::isExtIntegerInVTs(ExtVTs)) ||
477 (getExtTypeNum(0) == MVT::isFP && MVT::isExtFloatingPointInVTs(ExtVTs))){
481 if (getExtTypeNum(0) == MVT::isInt && ExtVTs[0] == MVT::iPTR) {
489 TP.error("Type inference contradiction found in node!");
491 TP.error("Type inference contradiction found in node " +
492 getOperator()->getName() + "!");
494 return true; // unreachable
498 void TreePatternNode::print(std::ostream &OS) const {
500 OS << *getLeafValue();
502 OS << "(" << getOperator()->getName();
505 // FIXME: At some point we should handle printing all the value types for
506 // nodes that are multiply typed.
507 switch (getExtTypeNum(0)) {
508 case MVT::Other: OS << ":Other"; break;
509 case MVT::isInt: OS << ":isInt"; break;
510 case MVT::isFP : OS << ":isFP"; break;
511 case MVT::isUnknown: ; /*OS << ":?";*/ break;
512 case MVT::iPTR: OS << ":iPTR"; break;
514 std::string VTName = llvm::getName(getTypeNum(0));
515 // Strip off MVT:: prefix if present.
516 if (VTName.substr(0,5) == "MVT::")
517 VTName = VTName.substr(5);
524 if (getNumChildren() != 0) {
526 getChild(0)->print(OS);
527 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
529 getChild(i)->print(OS);
535 if (!PredicateFn.empty())
536 OS << "<<P:" << PredicateFn << ">>";
538 OS << "<<X:" << TransformFn->getName() << ">>";
539 if (!getName().empty())
540 OS << ":$" << getName();
543 void TreePatternNode::dump() const {
544 print(*cerr.stream());
547 /// isIsomorphicTo - Return true if this node is recursively
548 /// isomorphic to the specified node. For this comparison, the node's
549 /// entire state is considered. The assigned name is ignored, since
550 /// nodes with differing names are considered isomorphic. However, if
551 /// the assigned name is present in the dependent variable set, then
552 /// the assigned name is considered significant and the node is
553 /// isomorphic if the names match.
554 bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
555 const MultipleUseVarSet &DepVars) const {
556 if (N == this) return true;
557 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
558 getPredicateFn() != N->getPredicateFn() ||
559 getTransformFn() != N->getTransformFn())
563 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
564 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue())) {
565 return ((DI->getDef() == NDI->getDef())
566 && (DepVars.find(getName()) == DepVars.end()
567 || getName() == N->getName()));
570 return getLeafValue() == N->getLeafValue();
573 if (N->getOperator() != getOperator() ||
574 N->getNumChildren() != getNumChildren()) return false;
575 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
576 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
581 /// clone - Make a copy of this tree and all of its children.
583 TreePatternNode *TreePatternNode::clone() const {
584 TreePatternNode *New;
586 New = new TreePatternNode(getLeafValue());
588 std::vector<TreePatternNode*> CChildren;
589 CChildren.reserve(Children.size());
590 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
591 CChildren.push_back(getChild(i)->clone());
592 New = new TreePatternNode(getOperator(), CChildren);
594 New->setName(getName());
595 New->setTypes(getExtTypes());
596 New->setPredicateFn(getPredicateFn());
597 New->setTransformFn(getTransformFn());
601 /// SubstituteFormalArguments - Replace the formal arguments in this tree
602 /// with actual values specified by ArgMap.
603 void TreePatternNode::
604 SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
605 if (isLeaf()) return;
607 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
608 TreePatternNode *Child = getChild(i);
609 if (Child->isLeaf()) {
610 Init *Val = Child->getLeafValue();
611 if (dynamic_cast<DefInit*>(Val) &&
612 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
613 // We found a use of a formal argument, replace it with its value.
614 Child = ArgMap[Child->getName()];
615 assert(Child && "Couldn't find formal argument!");
619 getChild(i)->SubstituteFormalArguments(ArgMap);
625 /// InlinePatternFragments - If this pattern refers to any pattern
626 /// fragments, inline them into place, giving us a pattern without any
627 /// PatFrag references.
628 TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
629 if (isLeaf()) return this; // nothing to do.
630 Record *Op = getOperator();
632 if (!Op->isSubClassOf("PatFrag")) {
633 // Just recursively inline children nodes.
634 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
635 setChild(i, getChild(i)->InlinePatternFragments(TP));
639 // Otherwise, we found a reference to a fragment. First, look up its
640 // TreePattern record.
641 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
643 // Verify that we are passing the right number of operands.
644 if (Frag->getNumArgs() != Children.size())
645 TP.error("'" + Op->getName() + "' fragment requires " +
646 utostr(Frag->getNumArgs()) + " operands!");
648 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
650 // Resolve formal arguments to their actual value.
651 if (Frag->getNumArgs()) {
652 // Compute the map of formal to actual arguments.
653 std::map<std::string, TreePatternNode*> ArgMap;
654 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
655 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
657 FragTree->SubstituteFormalArguments(ArgMap);
660 FragTree->setName(getName());
661 FragTree->UpdateNodeType(getExtTypes(), TP);
663 // Get a new copy of this fragment to stitch into here.
664 //delete this; // FIXME: implement refcounting!
668 /// getImplicitType - Check to see if the specified record has an implicit
669 /// type which should be applied to it. This infer the type of register
670 /// references from the register file information, for example.
672 static std::vector<unsigned char> getImplicitType(Record *R, bool NotRegisters,
674 // Some common return values
675 std::vector<unsigned char> Unknown(1, MVT::isUnknown);
676 std::vector<unsigned char> Other(1, MVT::Other);
678 // Check to see if this is a register or a register class...
679 if (R->isSubClassOf("RegisterClass")) {
682 const CodeGenRegisterClass &RC =
683 TP.getDAGPatterns().getTargetInfo().getRegisterClass(R);
684 return ConvertVTs(RC.getValueTypes());
685 } else if (R->isSubClassOf("PatFrag")) {
686 // Pattern fragment types will be resolved when they are inlined.
688 } else if (R->isSubClassOf("Register")) {
691 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
692 return T.getRegisterVTs(R);
693 } else if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
694 // Using a VTSDNode or CondCodeSDNode.
696 } else if (R->isSubClassOf("ComplexPattern")) {
699 std::vector<unsigned char>
700 ComplexPat(1, TP.getDAGPatterns().getComplexPattern(R).getValueType());
702 } else if (R->getName() == "ptr_rc") {
703 Other[0] = MVT::iPTR;
705 } else if (R->getName() == "node" || R->getName() == "srcvalue" ||
706 R->getName() == "zero_reg") {
711 TP.error("Unknown node flavor used in pattern: " + R->getName());
716 /// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
717 /// CodeGenIntrinsic information for it, otherwise return a null pointer.
718 const CodeGenIntrinsic *TreePatternNode::
719 getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
720 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
721 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
722 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
726 dynamic_cast<IntInit*>(getChild(0)->getLeafValue())->getValue();
727 return &CDP.getIntrinsicInfo(IID);
731 /// ApplyTypeConstraints - Apply all of the type constraints relevent to
732 /// this node and its children in the tree. This returns true if it makes a
733 /// change, false otherwise. If a type contradiction is found, throw an
735 bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
736 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
738 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
739 // If it's a regclass or something else known, include the type.
740 return UpdateNodeType(getImplicitType(DI->getDef(), NotRegisters, TP),TP);
741 } else if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
742 // Int inits are always integers. :)
743 bool MadeChange = UpdateNodeType(MVT::isInt, TP);
746 // At some point, it may make sense for this tree pattern to have
747 // multiple types. Assert here that it does not, so we revisit this
748 // code when appropriate.
749 assert(getExtTypes().size() >= 1 && "TreePattern doesn't have a type!");
750 MVT::ValueType VT = getTypeNum(0);
751 for (unsigned i = 1, e = getExtTypes().size(); i != e; ++i)
752 assert(getTypeNum(i) == VT && "TreePattern has too many types!");
755 if (VT != MVT::iPTR) {
756 unsigned Size = MVT::getSizeInBits(VT);
757 // Make sure that the value is representable for this type.
759 int Val = (II->getValue() << (32-Size)) >> (32-Size);
760 if (Val != II->getValue()) {
761 // If sign-extended doesn't fit, does it fit as unsigned?
762 unsigned ValueMask = unsigned(MVT::getIntVTBitMask(VT));
763 unsigned UnsignedVal = unsigned(II->getValue());
765 if ((ValueMask & UnsignedVal) != UnsignedVal) {
766 TP.error("Integer value '" + itostr(II->getValue())+
767 "' is out of range for type '" +
768 getEnumName(getTypeNum(0)) + "'!");
780 // special handling for set, which isn't really an SDNode.
781 if (getOperator()->getName() == "set") {
782 assert (getNumChildren() >= 2 && "Missing RHS of a set?");
783 unsigned NC = getNumChildren();
784 bool MadeChange = false;
785 for (unsigned i = 0; i < NC-1; ++i) {
786 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
787 MadeChange |= getChild(NC-1)->ApplyTypeConstraints(TP, NotRegisters);
789 // Types of operands must match.
790 MadeChange |= getChild(i)->UpdateNodeType(getChild(NC-1)->getExtTypes(),
792 MadeChange |= getChild(NC-1)->UpdateNodeType(getChild(i)->getExtTypes(),
794 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
797 } else if (getOperator()->getName() == "implicit" ||
798 getOperator()->getName() == "parallel") {
799 bool MadeChange = false;
800 for (unsigned i = 0; i < getNumChildren(); ++i)
801 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
802 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
804 } else if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
805 bool MadeChange = false;
807 // Apply the result type to the node.
808 MadeChange = UpdateNodeType(Int->ArgVTs[0], TP);
810 if (getNumChildren() != Int->ArgVTs.size())
811 TP.error("Intrinsic '" + Int->Name + "' expects " +
812 utostr(Int->ArgVTs.size()-1) + " operands, not " +
813 utostr(getNumChildren()-1) + " operands!");
815 // Apply type info to the intrinsic ID.
816 MadeChange |= getChild(0)->UpdateNodeType(MVT::iPTR, TP);
818 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
819 MVT::ValueType OpVT = Int->ArgVTs[i];
820 MadeChange |= getChild(i)->UpdateNodeType(OpVT, TP);
821 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
824 } else if (getOperator()->isSubClassOf("SDNode")) {
825 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
827 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
828 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
829 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
830 // Branch, etc. do not produce results and top-level forms in instr pattern
831 // must have void types.
832 if (NI.getNumResults() == 0)
833 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
835 // If this is a vector_shuffle operation, apply types to the build_vector
836 // operation. The types of the integers don't matter, but this ensures they
837 // won't get checked.
838 if (getOperator()->getName() == "vector_shuffle" &&
839 getChild(2)->getOperator()->getName() == "build_vector") {
840 TreePatternNode *BV = getChild(2);
841 const std::vector<MVT::ValueType> &LegalVTs
842 = CDP.getTargetInfo().getLegalValueTypes();
843 MVT::ValueType LegalIntVT = MVT::Other;
844 for (unsigned i = 0, e = LegalVTs.size(); i != e; ++i)
845 if (MVT::isInteger(LegalVTs[i]) && !MVT::isVector(LegalVTs[i])) {
846 LegalIntVT = LegalVTs[i];
849 assert(LegalIntVT != MVT::Other && "No legal integer VT?");
851 for (unsigned i = 0, e = BV->getNumChildren(); i != e; ++i)
852 MadeChange |= BV->getChild(i)->UpdateNodeType(LegalIntVT, TP);
855 } else if (getOperator()->isSubClassOf("Instruction")) {
856 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
857 bool MadeChange = false;
858 unsigned NumResults = Inst.getNumResults();
860 assert(NumResults <= 1 &&
861 "Only supports zero or one result instrs!");
863 CodeGenInstruction &InstInfo =
864 CDP.getTargetInfo().getInstruction(getOperator()->getName());
865 // Apply the result type to the node
866 if (NumResults == 0 || InstInfo.NumDefs == 0) {
867 MadeChange = UpdateNodeType(MVT::isVoid, TP);
869 Record *ResultNode = Inst.getResult(0);
871 if (ResultNode->getName() == "ptr_rc") {
872 std::vector<unsigned char> VT;
873 VT.push_back(MVT::iPTR);
874 MadeChange = UpdateNodeType(VT, TP);
875 } else if (ResultNode->getName() == "unknown") {
876 std::vector<unsigned char> VT;
877 VT.push_back(MVT::isUnknown);
878 MadeChange = UpdateNodeType(VT, TP);
880 assert(ResultNode->isSubClassOf("RegisterClass") &&
881 "Operands should be register classes!");
883 const CodeGenRegisterClass &RC =
884 CDP.getTargetInfo().getRegisterClass(ResultNode);
885 MadeChange = UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
889 unsigned ChildNo = 0;
890 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
891 Record *OperandNode = Inst.getOperand(i);
893 // If the instruction expects a predicate or optional def operand, we
894 // codegen this by setting the operand to it's default value if it has a
895 // non-empty DefaultOps field.
896 if ((OperandNode->isSubClassOf("PredicateOperand") ||
897 OperandNode->isSubClassOf("OptionalDefOperand")) &&
898 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
901 // Verify that we didn't run out of provided operands.
902 if (ChildNo >= getNumChildren())
903 TP.error("Instruction '" + getOperator()->getName() +
904 "' expects more operands than were provided.");
907 TreePatternNode *Child = getChild(ChildNo++);
908 if (OperandNode->isSubClassOf("RegisterClass")) {
909 const CodeGenRegisterClass &RC =
910 CDP.getTargetInfo().getRegisterClass(OperandNode);
911 MadeChange |= Child->UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
912 } else if (OperandNode->isSubClassOf("Operand")) {
913 VT = getValueType(OperandNode->getValueAsDef("Type"));
914 MadeChange |= Child->UpdateNodeType(VT, TP);
915 } else if (OperandNode->getName() == "ptr_rc") {
916 MadeChange |= Child->UpdateNodeType(MVT::iPTR, TP);
917 } else if (OperandNode->getName() == "unknown") {
918 MadeChange |= Child->UpdateNodeType(MVT::isUnknown, TP);
920 assert(0 && "Unknown operand type!");
923 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
926 if (ChildNo != getNumChildren())
927 TP.error("Instruction '" + getOperator()->getName() +
928 "' was provided too many operands!");
932 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
934 // Node transforms always take one operand.
935 if (getNumChildren() != 1)
936 TP.error("Node transform '" + getOperator()->getName() +
937 "' requires one operand!");
939 // If either the output or input of the xform does not have exact
940 // type info. We assume they must be the same. Otherwise, it is perfectly
941 // legal to transform from one type to a completely different type.
942 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
943 bool MadeChange = UpdateNodeType(getChild(0)->getExtTypes(), TP);
944 MadeChange |= getChild(0)->UpdateNodeType(getExtTypes(), TP);
951 /// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
952 /// RHS of a commutative operation, not the on LHS.
953 static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
954 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
956 if (N->isLeaf() && dynamic_cast<IntInit*>(N->getLeafValue()))
962 /// canPatternMatch - If it is impossible for this pattern to match on this
963 /// target, fill in Reason and return false. Otherwise, return true. This is
964 /// used as a santity check for .td files (to prevent people from writing stuff
965 /// that can never possibly work), and to prevent the pattern permuter from
966 /// generating stuff that is useless.
967 bool TreePatternNode::canPatternMatch(std::string &Reason,
968 CodeGenDAGPatterns &CDP){
969 if (isLeaf()) return true;
971 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
972 if (!getChild(i)->canPatternMatch(Reason, CDP))
975 // If this is an intrinsic, handle cases that would make it not match. For
976 // example, if an operand is required to be an immediate.
977 if (getOperator()->isSubClassOf("Intrinsic")) {
982 // If this node is a commutative operator, check that the LHS isn't an
984 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
985 if (NodeInfo.hasProperty(SDNPCommutative)) {
986 // Scan all of the operands of the node and make sure that only the last one
987 // is a constant node, unless the RHS also is.
988 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
989 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i)
990 if (OnlyOnRHSOfCommutative(getChild(i))) {
991 Reason="Immediate value must be on the RHS of commutative operators!";
1000 //===----------------------------------------------------------------------===//
1001 // TreePattern implementation
1004 TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
1005 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
1006 isInputPattern = isInput;
1007 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
1008 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
1011 TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
1012 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
1013 isInputPattern = isInput;
1014 Trees.push_back(ParseTreePattern(Pat));
1017 TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
1018 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
1019 isInputPattern = isInput;
1020 Trees.push_back(Pat);
1025 void TreePattern::error(const std::string &Msg) const {
1027 throw "In " + TheRecord->getName() + ": " + Msg;
1030 TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
1031 DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
1032 if (!OpDef) error("Pattern has unexpected operator type!");
1033 Record *Operator = OpDef->getDef();
1035 if (Operator->isSubClassOf("ValueType")) {
1036 // If the operator is a ValueType, then this must be "type cast" of a leaf
1038 if (Dag->getNumArgs() != 1)
1039 error("Type cast only takes one operand!");
1041 Init *Arg = Dag->getArg(0);
1042 TreePatternNode *New;
1043 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
1044 Record *R = DI->getDef();
1045 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
1046 Dag->setArg(0, new DagInit(DI,
1047 std::vector<std::pair<Init*, std::string> >()));
1048 return ParseTreePattern(Dag);
1050 New = new TreePatternNode(DI);
1051 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
1052 New = ParseTreePattern(DI);
1053 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
1054 New = new TreePatternNode(II);
1055 if (!Dag->getArgName(0).empty())
1056 error("Constant int argument should not have a name!");
1057 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
1058 // Turn this into an IntInit.
1059 Init *II = BI->convertInitializerTo(new IntRecTy());
1060 if (II == 0 || !dynamic_cast<IntInit*>(II))
1061 error("Bits value must be constants!");
1063 New = new TreePatternNode(dynamic_cast<IntInit*>(II));
1064 if (!Dag->getArgName(0).empty())
1065 error("Constant int argument should not have a name!");
1068 error("Unknown leaf value for tree pattern!");
1072 // Apply the type cast.
1073 New->UpdateNodeType(getValueType(Operator), *this);
1074 New->setName(Dag->getArgName(0));
1078 // Verify that this is something that makes sense for an operator.
1079 if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
1080 !Operator->isSubClassOf("Instruction") &&
1081 !Operator->isSubClassOf("SDNodeXForm") &&
1082 !Operator->isSubClassOf("Intrinsic") &&
1083 Operator->getName() != "set" &&
1084 Operator->getName() != "implicit" &&
1085 Operator->getName() != "parallel")
1086 error("Unrecognized node '" + Operator->getName() + "'!");
1088 // Check to see if this is something that is illegal in an input pattern.
1089 if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
1090 Operator->isSubClassOf("SDNodeXForm")))
1091 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
1093 std::vector<TreePatternNode*> Children;
1095 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
1096 Init *Arg = Dag->getArg(i);
1097 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
1098 Children.push_back(ParseTreePattern(DI));
1099 if (Children.back()->getName().empty())
1100 Children.back()->setName(Dag->getArgName(i));
1101 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
1102 Record *R = DefI->getDef();
1103 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
1104 // TreePatternNode if its own.
1105 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
1106 Dag->setArg(i, new DagInit(DefI,
1107 std::vector<std::pair<Init*, std::string> >()));
1108 --i; // Revisit this node...
1110 TreePatternNode *Node = new TreePatternNode(DefI);
1111 Node->setName(Dag->getArgName(i));
1112 Children.push_back(Node);
1115 if (R->getName() == "node") {
1116 if (Dag->getArgName(i).empty())
1117 error("'node' argument requires a name to match with operand list");
1118 Args.push_back(Dag->getArgName(i));
1121 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
1122 TreePatternNode *Node = new TreePatternNode(II);
1123 if (!Dag->getArgName(i).empty())
1124 error("Constant int argument should not have a name!");
1125 Children.push_back(Node);
1126 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
1127 // Turn this into an IntInit.
1128 Init *II = BI->convertInitializerTo(new IntRecTy());
1129 if (II == 0 || !dynamic_cast<IntInit*>(II))
1130 error("Bits value must be constants!");
1132 TreePatternNode *Node = new TreePatternNode(dynamic_cast<IntInit*>(II));
1133 if (!Dag->getArgName(i).empty())
1134 error("Constant int argument should not have a name!");
1135 Children.push_back(Node);
1140 error("Unknown leaf value for tree pattern!");
1144 // If the operator is an intrinsic, then this is just syntactic sugar for for
1145 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
1146 // convert the intrinsic name to a number.
1147 if (Operator->isSubClassOf("Intrinsic")) {
1148 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
1149 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
1151 // If this intrinsic returns void, it must have side-effects and thus a
1153 if (Int.ArgVTs[0] == MVT::isVoid) {
1154 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
1155 } else if (Int.ModRef != CodeGenIntrinsic::NoMem) {
1156 // Has side-effects, requires chain.
1157 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
1159 // Otherwise, no chain.
1160 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
1163 TreePatternNode *IIDNode = new TreePatternNode(new IntInit(IID));
1164 Children.insert(Children.begin(), IIDNode);
1167 return new TreePatternNode(Operator, Children);
1170 /// InferAllTypes - Infer/propagate as many types throughout the expression
1171 /// patterns as possible. Return true if all types are infered, false
1172 /// otherwise. Throw an exception if a type contradiction is found.
1173 bool TreePattern::InferAllTypes() {
1174 bool MadeChange = true;
1175 while (MadeChange) {
1177 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1178 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
1181 bool HasUnresolvedTypes = false;
1182 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1183 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
1184 return !HasUnresolvedTypes;
1187 void TreePattern::print(std::ostream &OS) const {
1188 OS << getRecord()->getName();
1189 if (!Args.empty()) {
1190 OS << "(" << Args[0];
1191 for (unsigned i = 1, e = Args.size(); i != e; ++i)
1192 OS << ", " << Args[i];
1197 if (Trees.size() > 1)
1199 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
1201 Trees[i]->print(OS);
1205 if (Trees.size() > 1)
1209 void TreePattern::dump() const { print(*cerr.stream()); }
1211 //===----------------------------------------------------------------------===//
1212 // CodeGenDAGPatterns implementation
1215 // FIXME: REMOVE OSTREAM ARGUMENT
1216 CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) : Records(R) {
1217 Intrinsics = LoadIntrinsics(Records);
1219 ParseNodeTransforms();
1220 ParseComplexPatterns();
1221 ParsePatternFragments();
1222 ParseDefaultOperands();
1223 ParseInstructions();
1226 // Generate variants. For example, commutative patterns can match
1227 // multiple ways. Add them to PatternsToMatch as well.
1231 CodeGenDAGPatterns::~CodeGenDAGPatterns() {
1232 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
1233 E = PatternFragments.end(); I != E; ++I)
1238 Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
1239 Record *N = Records.getDef(Name);
1240 if (!N || !N->isSubClassOf("SDNode")) {
1241 cerr << "Error getting SDNode '" << Name << "'!\n";
1247 // Parse all of the SDNode definitions for the target, populating SDNodes.
1248 void CodeGenDAGPatterns::ParseNodeInfo() {
1249 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
1250 while (!Nodes.empty()) {
1251 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
1255 // Get the buildin intrinsic nodes.
1256 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
1257 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
1258 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
1261 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
1262 /// map, and emit them to the file as functions.
1263 void CodeGenDAGPatterns::ParseNodeTransforms() {
1264 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
1265 while (!Xforms.empty()) {
1266 Record *XFormNode = Xforms.back();
1267 Record *SDNode = XFormNode->getValueAsDef("Opcode");
1268 std::string Code = XFormNode->getValueAsCode("XFormFunction");
1269 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
1275 void CodeGenDAGPatterns::ParseComplexPatterns() {
1276 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
1277 while (!AMs.empty()) {
1278 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
1284 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
1285 /// file, building up the PatternFragments map. After we've collected them all,
1286 /// inline fragments together as necessary, so that there are no references left
1287 /// inside a pattern fragment to a pattern fragment.
1289 void CodeGenDAGPatterns::ParsePatternFragments() {
1290 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
1292 // First step, parse all of the fragments.
1293 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1294 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
1295 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
1296 PatternFragments[Fragments[i]] = P;
1298 // Validate the argument list, converting it to set, to discard duplicates.
1299 std::vector<std::string> &Args = P->getArgList();
1300 std::set<std::string> OperandsSet(Args.begin(), Args.end());
1302 if (OperandsSet.count(""))
1303 P->error("Cannot have unnamed 'node' values in pattern fragment!");
1305 // Parse the operands list.
1306 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
1307 DefInit *OpsOp = dynamic_cast<DefInit*>(OpsList->getOperator());
1308 // Special cases: ops == outs == ins. Different names are used to
1309 // improve readibility.
1311 (OpsOp->getDef()->getName() != "ops" &&
1312 OpsOp->getDef()->getName() != "outs" &&
1313 OpsOp->getDef()->getName() != "ins"))
1314 P->error("Operands list should start with '(ops ... '!");
1316 // Copy over the arguments.
1318 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
1319 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
1320 static_cast<DefInit*>(OpsList->getArg(j))->
1321 getDef()->getName() != "node")
1322 P->error("Operands list should all be 'node' values.");
1323 if (OpsList->getArgName(j).empty())
1324 P->error("Operands list should have names for each operand!");
1325 if (!OperandsSet.count(OpsList->getArgName(j)))
1326 P->error("'" + OpsList->getArgName(j) +
1327 "' does not occur in pattern or was multiply specified!");
1328 OperandsSet.erase(OpsList->getArgName(j));
1329 Args.push_back(OpsList->getArgName(j));
1332 if (!OperandsSet.empty())
1333 P->error("Operands list does not contain an entry for operand '" +
1334 *OperandsSet.begin() + "'!");
1336 // If there is a code init for this fragment, keep track of the fact that
1337 // this fragment uses it.
1338 std::string Code = Fragments[i]->getValueAsCode("Predicate");
1340 P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
1342 // If there is a node transformation corresponding to this, keep track of
1344 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
1345 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
1346 P->getOnlyTree()->setTransformFn(Transform);
1349 // Now that we've parsed all of the tree fragments, do a closure on them so
1350 // that there are not references to PatFrags left inside of them.
1351 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
1352 E = PatternFragments.end(); I != E; ++I) {
1353 TreePattern *ThePat = I->second;
1354 ThePat->InlinePatternFragments();
1356 // Infer as many types as possible. Don't worry about it if we don't infer
1357 // all of them, some may depend on the inputs of the pattern.
1359 ThePat->InferAllTypes();
1361 // If this pattern fragment is not supported by this target (no types can
1362 // satisfy its constraints), just ignore it. If the bogus pattern is
1363 // actually used by instructions, the type consistency error will be
1367 // If debugging, print out the pattern fragment result.
1368 DEBUG(ThePat->dump());
1372 void CodeGenDAGPatterns::ParseDefaultOperands() {
1373 std::vector<Record*> DefaultOps[2];
1374 DefaultOps[0] = Records.getAllDerivedDefinitions("PredicateOperand");
1375 DefaultOps[1] = Records.getAllDerivedDefinitions("OptionalDefOperand");
1377 // Find some SDNode.
1378 assert(!SDNodes.empty() && "No SDNodes parsed?");
1379 Init *SomeSDNode = new DefInit(SDNodes.begin()->first);
1381 for (unsigned iter = 0; iter != 2; ++iter) {
1382 for (unsigned i = 0, e = DefaultOps[iter].size(); i != e; ++i) {
1383 DagInit *DefaultInfo = DefaultOps[iter][i]->getValueAsDag("DefaultOps");
1385 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
1386 // SomeSDnode so that we can parse this.
1387 std::vector<std::pair<Init*, std::string> > Ops;
1388 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
1389 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
1390 DefaultInfo->getArgName(op)));
1391 DagInit *DI = new DagInit(SomeSDNode, Ops);
1393 // Create a TreePattern to parse this.
1394 TreePattern P(DefaultOps[iter][i], DI, false, *this);
1395 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
1397 // Copy the operands over into a DAGDefaultOperand.
1398 DAGDefaultOperand DefaultOpInfo;
1400 TreePatternNode *T = P.getTree(0);
1401 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
1402 TreePatternNode *TPN = T->getChild(op);
1403 while (TPN->ApplyTypeConstraints(P, false))
1404 /* Resolve all types */;
1406 if (TPN->ContainsUnresolvedType()) {
1408 throw "Value #" + utostr(i) + " of PredicateOperand '" +
1409 DefaultOps[iter][i]->getName() + "' doesn't have a concrete type!";
1411 throw "Value #" + utostr(i) + " of OptionalDefOperand '" +
1412 DefaultOps[iter][i]->getName() + "' doesn't have a concrete type!";
1414 DefaultOpInfo.DefaultOps.push_back(TPN);
1417 // Insert it into the DefaultOperands map so we can find it later.
1418 DefaultOperands[DefaultOps[iter][i]] = DefaultOpInfo;
1423 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
1424 /// instruction input. Return true if this is a real use.
1425 static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
1426 std::map<std::string, TreePatternNode*> &InstInputs,
1427 std::vector<Record*> &InstImpInputs) {
1428 // No name -> not interesting.
1429 if (Pat->getName().empty()) {
1430 if (Pat->isLeaf()) {
1431 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1432 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1433 I->error("Input " + DI->getDef()->getName() + " must be named!");
1434 else if (DI && DI->getDef()->isSubClassOf("Register"))
1435 InstImpInputs.push_back(DI->getDef());
1442 if (Pat->isLeaf()) {
1443 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1444 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
1447 assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
1448 Rec = Pat->getOperator();
1451 // SRCVALUE nodes are ignored.
1452 if (Rec->getName() == "srcvalue")
1455 TreePatternNode *&Slot = InstInputs[Pat->getName()];
1460 if (Slot->isLeaf()) {
1461 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
1463 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
1464 SlotRec = Slot->getOperator();
1467 // Ensure that the inputs agree if we've already seen this input.
1469 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1470 if (Slot->getExtTypes() != Pat->getExtTypes())
1471 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1476 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
1477 /// part of "I", the instruction), computing the set of inputs and outputs of
1478 /// the pattern. Report errors if we see anything naughty.
1479 void CodeGenDAGPatterns::
1480 FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
1481 std::map<std::string, TreePatternNode*> &InstInputs,
1482 std::map<std::string, TreePatternNode*>&InstResults,
1483 std::vector<Record*> &InstImpInputs,
1484 std::vector<Record*> &InstImpResults) {
1485 if (Pat->isLeaf()) {
1486 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1487 if (!isUse && Pat->getTransformFn())
1488 I->error("Cannot specify a transform function for a non-input value!");
1490 } else if (Pat->getOperator()->getName() == "implicit") {
1491 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1492 TreePatternNode *Dest = Pat->getChild(i);
1493 if (!Dest->isLeaf())
1494 I->error("implicitly defined value should be a register!");
1496 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1497 if (!Val || !Val->getDef()->isSubClassOf("Register"))
1498 I->error("implicitly defined value should be a register!");
1499 InstImpResults.push_back(Val->getDef());
1502 } else if (Pat->getOperator()->getName() != "set") {
1503 // If this is not a set, verify that the children nodes are not void typed,
1505 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1506 if (Pat->getChild(i)->getExtTypeNum(0) == MVT::isVoid)
1507 I->error("Cannot have void nodes inside of patterns!");
1508 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
1509 InstImpInputs, InstImpResults);
1512 // If this is a non-leaf node with no children, treat it basically as if
1513 // it were a leaf. This handles nodes like (imm).
1515 if (Pat->getNumChildren() == 0)
1516 isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1518 if (!isUse && Pat->getTransformFn())
1519 I->error("Cannot specify a transform function for a non-input value!");
1523 // Otherwise, this is a set, validate and collect instruction results.
1524 if (Pat->getNumChildren() == 0)
1525 I->error("set requires operands!");
1527 if (Pat->getTransformFn())
1528 I->error("Cannot specify a transform function on a set node!");
1530 // Check the set destinations.
1531 unsigned NumDests = Pat->getNumChildren()-1;
1532 for (unsigned i = 0; i != NumDests; ++i) {
1533 TreePatternNode *Dest = Pat->getChild(i);
1534 if (!Dest->isLeaf())
1535 I->error("set destination should be a register!");
1537 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1539 I->error("set destination should be a register!");
1541 if (Val->getDef()->isSubClassOf("RegisterClass") ||
1542 Val->getDef()->getName() == "ptr_rc") {
1543 if (Dest->getName().empty())
1544 I->error("set destination must have a name!");
1545 if (InstResults.count(Dest->getName()))
1546 I->error("cannot set '" + Dest->getName() +"' multiple times");
1547 InstResults[Dest->getName()] = Dest;
1548 } else if (Val->getDef()->isSubClassOf("Register")) {
1549 InstImpResults.push_back(Val->getDef());
1551 I->error("set destination should be a register!");
1555 // Verify and collect info from the computation.
1556 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
1557 InstInputs, InstResults,
1558 InstImpInputs, InstImpResults);
1561 /// ParseInstructions - Parse all of the instructions, inlining and resolving
1562 /// any fragments involved. This populates the Instructions list with fully
1563 /// resolved instructions.
1564 void CodeGenDAGPatterns::ParseInstructions() {
1565 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
1567 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
1570 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
1571 LI = Instrs[i]->getValueAsListInit("Pattern");
1573 // If there is no pattern, only collect minimal information about the
1574 // instruction for its operand list. We have to assume that there is one
1575 // result, as we have no detailed info.
1576 if (!LI || LI->getSize() == 0) {
1577 std::vector<Record*> Results;
1578 std::vector<Record*> Operands;
1580 CodeGenInstruction &InstInfo =Target.getInstruction(Instrs[i]->getName());
1582 if (InstInfo.OperandList.size() != 0) {
1583 if (InstInfo.NumDefs == 0) {
1584 // These produce no results
1585 for (unsigned j = 0, e = InstInfo.OperandList.size(); j < e; ++j)
1586 Operands.push_back(InstInfo.OperandList[j].Rec);
1588 // Assume the first operand is the result.
1589 Results.push_back(InstInfo.OperandList[0].Rec);
1591 // The rest are inputs.
1592 for (unsigned j = 1, e = InstInfo.OperandList.size(); j < e; ++j)
1593 Operands.push_back(InstInfo.OperandList[j].Rec);
1597 // Create and insert the instruction.
1598 std::vector<Record*> ImpResults;
1599 std::vector<Record*> ImpOperands;
1600 Instructions.insert(std::make_pair(Instrs[i],
1601 DAGInstruction(0, Results, Operands, ImpResults,
1603 continue; // no pattern.
1606 // Parse the instruction.
1607 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
1608 // Inline pattern fragments into it.
1609 I->InlinePatternFragments();
1611 // Infer as many types as possible. If we cannot infer all of them, we can
1612 // never do anything with this instruction pattern: report it to the user.
1613 if (!I->InferAllTypes())
1614 I->error("Could not infer all types in pattern!");
1616 // InstInputs - Keep track of all of the inputs of the instruction, along
1617 // with the record they are declared as.
1618 std::map<std::string, TreePatternNode*> InstInputs;
1620 // InstResults - Keep track of all the virtual registers that are 'set'
1621 // in the instruction, including what reg class they are.
1622 std::map<std::string, TreePatternNode*> InstResults;
1624 std::vector<Record*> InstImpInputs;
1625 std::vector<Record*> InstImpResults;
1627 // Verify that the top-level forms in the instruction are of void type, and
1628 // fill in the InstResults map.
1629 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
1630 TreePatternNode *Pat = I->getTree(j);
1631 if (Pat->getExtTypeNum(0) != MVT::isVoid)
1632 I->error("Top-level forms in instruction pattern should have"
1635 // Find inputs and outputs, and verify the structure of the uses/defs.
1636 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
1637 InstImpInputs, InstImpResults);
1640 // Now that we have inputs and outputs of the pattern, inspect the operands
1641 // list for the instruction. This determines the order that operands are
1642 // added to the machine instruction the node corresponds to.
1643 unsigned NumResults = InstResults.size();
1645 // Parse the operands list from the (ops) list, validating it.
1646 assert(I->getArgList().empty() && "Args list should still be empty here!");
1647 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
1649 // Check that all of the results occur first in the list.
1650 std::vector<Record*> Results;
1651 TreePatternNode *Res0Node = NULL;
1652 for (unsigned i = 0; i != NumResults; ++i) {
1653 if (i == CGI.OperandList.size())
1654 I->error("'" + InstResults.begin()->first +
1655 "' set but does not appear in operand list!");
1656 const std::string &OpName = CGI.OperandList[i].Name;
1658 // Check that it exists in InstResults.
1659 TreePatternNode *RNode = InstResults[OpName];
1661 I->error("Operand $" + OpName + " does not exist in operand list!");
1665 Record *R = dynamic_cast<DefInit*>(RNode->getLeafValue())->getDef();
1667 I->error("Operand $" + OpName + " should be a set destination: all "
1668 "outputs must occur before inputs in operand list!");
1670 if (CGI.OperandList[i].Rec != R)
1671 I->error("Operand $" + OpName + " class mismatch!");
1673 // Remember the return type.
1674 Results.push_back(CGI.OperandList[i].Rec);
1676 // Okay, this one checks out.
1677 InstResults.erase(OpName);
1680 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
1681 // the copy while we're checking the inputs.
1682 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
1684 std::vector<TreePatternNode*> ResultNodeOperands;
1685 std::vector<Record*> Operands;
1686 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
1687 CodeGenInstruction::OperandInfo &Op = CGI.OperandList[i];
1688 const std::string &OpName = Op.Name;
1690 I->error("Operand #" + utostr(i) + " in operands list has no name!");
1692 if (!InstInputsCheck.count(OpName)) {
1693 // If this is an predicate operand or optional def operand with an
1694 // DefaultOps set filled in, we can ignore this. When we codegen it,
1695 // we will do so as always executed.
1696 if (Op.Rec->isSubClassOf("PredicateOperand") ||
1697 Op.Rec->isSubClassOf("OptionalDefOperand")) {
1698 // Does it have a non-empty DefaultOps field? If so, ignore this
1700 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
1703 I->error("Operand $" + OpName +
1704 " does not appear in the instruction pattern");
1706 TreePatternNode *InVal = InstInputsCheck[OpName];
1707 InstInputsCheck.erase(OpName); // It occurred, remove from map.
1709 if (InVal->isLeaf() &&
1710 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
1711 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
1712 if (Op.Rec != InRec && !InRec->isSubClassOf("ComplexPattern"))
1713 I->error("Operand $" + OpName + "'s register class disagrees"
1714 " between the operand and pattern");
1716 Operands.push_back(Op.Rec);
1718 // Construct the result for the dest-pattern operand list.
1719 TreePatternNode *OpNode = InVal->clone();
1721 // No predicate is useful on the result.
1722 OpNode->setPredicateFn("");
1724 // Promote the xform function to be an explicit node if set.
1725 if (Record *Xform = OpNode->getTransformFn()) {
1726 OpNode->setTransformFn(0);
1727 std::vector<TreePatternNode*> Children;
1728 Children.push_back(OpNode);
1729 OpNode = new TreePatternNode(Xform, Children);
1732 ResultNodeOperands.push_back(OpNode);
1735 if (!InstInputsCheck.empty())
1736 I->error("Input operand $" + InstInputsCheck.begin()->first +
1737 " occurs in pattern but not in operands list!");
1739 TreePatternNode *ResultPattern =
1740 new TreePatternNode(I->getRecord(), ResultNodeOperands);
1741 // Copy fully inferred output node type to instruction result pattern.
1743 ResultPattern->setTypes(Res0Node->getExtTypes());
1745 // Create and insert the instruction.
1746 // FIXME: InstImpResults and InstImpInputs should not be part of
1748 DAGInstruction TheInst(I, Results, Operands, InstImpResults, InstImpInputs);
1749 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
1751 // Use a temporary tree pattern to infer all types and make sure that the
1752 // constructed result is correct. This depends on the instruction already
1753 // being inserted into the Instructions map.
1754 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
1755 Temp.InferAllTypes();
1757 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
1758 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
1763 // If we can, convert the instructions to be patterns that are matched!
1764 for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
1765 E = Instructions.end(); II != E; ++II) {
1766 DAGInstruction &TheInst = II->second;
1767 const TreePattern *I = TheInst.getPattern();
1768 if (I == 0) continue; // No pattern.
1770 // FIXME: Assume only the first tree is the pattern. The others are clobber
1772 TreePatternNode *Pattern = I->getTree(0);
1773 TreePatternNode *SrcPattern;
1774 if (Pattern->getOperator()->getName() == "set") {
1775 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
1777 // Not a set (store or something?)
1778 SrcPattern = Pattern;
1782 if (!SrcPattern->canPatternMatch(Reason, *this))
1783 I->error("Instruction can never match: " + Reason);
1785 Record *Instr = II->first;
1786 TreePatternNode *DstPattern = TheInst.getResultPattern();
1788 push_back(PatternToMatch(Instr->getValueAsListInit("Predicates"),
1789 SrcPattern, DstPattern, TheInst.getImpResults(),
1790 Instr->getValueAsInt("AddedComplexity")));
1794 void CodeGenDAGPatterns::ParsePatterns() {
1795 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
1797 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1798 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
1799 DefInit *OpDef = dynamic_cast<DefInit*>(Tree->getOperator());
1800 Record *Operator = OpDef->getDef();
1801 TreePattern *Pattern;
1802 if (Operator->getName() != "parallel")
1803 Pattern = new TreePattern(Patterns[i], Tree, true, *this);
1805 std::vector<Init*> Values;
1806 for (unsigned j = 0, ee = Tree->getNumArgs(); j != ee; ++j)
1807 Values.push_back(Tree->getArg(j));
1808 ListInit *LI = new ListInit(Values);
1809 Pattern = new TreePattern(Patterns[i], LI, true, *this);
1812 // Inline pattern fragments into it.
1813 Pattern->InlinePatternFragments();
1815 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
1816 if (LI->getSize() == 0) continue; // no pattern.
1818 // Parse the instruction.
1819 TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
1821 // Inline pattern fragments into it.
1822 Result->InlinePatternFragments();
1824 if (Result->getNumTrees() != 1)
1825 Result->error("Cannot handle instructions producing instructions "
1826 "with temporaries yet!");
1828 bool IterateInference;
1829 bool InferredAllPatternTypes, InferredAllResultTypes;
1831 // Infer as many types as possible. If we cannot infer all of them, we
1832 // can never do anything with this pattern: report it to the user.
1833 InferredAllPatternTypes = Pattern->InferAllTypes();
1835 // Infer as many types as possible. If we cannot infer all of them, we
1836 // can never do anything with this pattern: report it to the user.
1837 InferredAllResultTypes = Result->InferAllTypes();
1839 // Apply the type of the result to the source pattern. This helps us
1840 // resolve cases where the input type is known to be a pointer type (which
1841 // is considered resolved), but the result knows it needs to be 32- or
1842 // 64-bits. Infer the other way for good measure.
1843 IterateInference = Pattern->getTree(0)->
1844 UpdateNodeType(Result->getTree(0)->getExtTypes(), *Result);
1845 IterateInference |= Result->getTree(0)->
1846 UpdateNodeType(Pattern->getTree(0)->getExtTypes(), *Result);
1847 } while (IterateInference);
1849 // Verify that we inferred enough types that we can do something with the
1850 // pattern and result. If these fire the user has to add type casts.
1851 if (!InferredAllPatternTypes)
1852 Pattern->error("Could not infer all types in pattern!");
1853 if (!InferredAllResultTypes)
1854 Result->error("Could not infer all types in pattern result!");
1856 // Validate that the input pattern is correct.
1857 std::map<std::string, TreePatternNode*> InstInputs;
1858 std::map<std::string, TreePatternNode*> InstResults;
1859 std::vector<Record*> InstImpInputs;
1860 std::vector<Record*> InstImpResults;
1861 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
1862 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
1863 InstInputs, InstResults,
1864 InstImpInputs, InstImpResults);
1866 // Promote the xform function to be an explicit node if set.
1867 TreePatternNode *DstPattern = Result->getOnlyTree();
1868 std::vector<TreePatternNode*> ResultNodeOperands;
1869 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
1870 TreePatternNode *OpNode = DstPattern->getChild(ii);
1871 if (Record *Xform = OpNode->getTransformFn()) {
1872 OpNode->setTransformFn(0);
1873 std::vector<TreePatternNode*> Children;
1874 Children.push_back(OpNode);
1875 OpNode = new TreePatternNode(Xform, Children);
1877 ResultNodeOperands.push_back(OpNode);
1879 DstPattern = Result->getOnlyTree();
1880 if (!DstPattern->isLeaf())
1881 DstPattern = new TreePatternNode(DstPattern->getOperator(),
1882 ResultNodeOperands);
1883 DstPattern->setTypes(Result->getOnlyTree()->getExtTypes());
1884 TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
1885 Temp.InferAllTypes();
1888 if (!Pattern->getTree(0)->canPatternMatch(Reason, *this))
1889 Pattern->error("Pattern can never match: " + Reason);
1892 push_back(PatternToMatch(Patterns[i]->getValueAsListInit("Predicates"),
1893 Pattern->getTree(0),
1894 Temp.getOnlyTree(), InstImpResults,
1895 Patterns[i]->getValueAsInt("AddedComplexity")));
1899 /// CombineChildVariants - Given a bunch of permutations of each child of the
1900 /// 'operator' node, put them together in all possible ways.
1901 static void CombineChildVariants(TreePatternNode *Orig,
1902 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
1903 std::vector<TreePatternNode*> &OutVariants,
1904 CodeGenDAGPatterns &CDP,
1905 const MultipleUseVarSet &DepVars) {
1906 // Make sure that each operand has at least one variant to choose from.
1907 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1908 if (ChildVariants[i].empty())
1911 // The end result is an all-pairs construction of the resultant pattern.
1912 std::vector<unsigned> Idxs;
1913 Idxs.resize(ChildVariants.size());
1917 if (DebugFlag && !Idxs.empty()) {
1918 cerr << Orig->getOperator()->getName() << ": Idxs = [ ";
1919 for (unsigned i = 0; i < Idxs.size(); ++i) {
1920 cerr << Idxs[i] << " ";
1925 // Create the variant and add it to the output list.
1926 std::vector<TreePatternNode*> NewChildren;
1927 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1928 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
1929 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
1931 // Copy over properties.
1932 R->setName(Orig->getName());
1933 R->setPredicateFn(Orig->getPredicateFn());
1934 R->setTransformFn(Orig->getTransformFn());
1935 R->setTypes(Orig->getExtTypes());
1937 // If this pattern cannot match, do not include it as a variant.
1938 std::string ErrString;
1939 if (!R->canPatternMatch(ErrString, CDP)) {
1942 bool AlreadyExists = false;
1944 // Scan to see if this pattern has already been emitted. We can get
1945 // duplication due to things like commuting:
1946 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
1947 // which are the same pattern. Ignore the dups.
1948 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
1949 if (R->isIsomorphicTo(OutVariants[i], DepVars)) {
1950 AlreadyExists = true;
1957 OutVariants.push_back(R);
1960 // Increment indices to the next permutation by incrementing the
1961 // indicies from last index backward, e.g., generate the sequence
1962 // [0, 0], [0, 1], [1, 0], [1, 1].
1964 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
1965 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
1970 NotDone = (IdxsIdx >= 0);
1974 /// CombineChildVariants - A helper function for binary operators.
1976 static void CombineChildVariants(TreePatternNode *Orig,
1977 const std::vector<TreePatternNode*> &LHS,
1978 const std::vector<TreePatternNode*> &RHS,
1979 std::vector<TreePatternNode*> &OutVariants,
1980 CodeGenDAGPatterns &CDP,
1981 const MultipleUseVarSet &DepVars) {
1982 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1983 ChildVariants.push_back(LHS);
1984 ChildVariants.push_back(RHS);
1985 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
1989 static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
1990 std::vector<TreePatternNode *> &Children) {
1991 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
1992 Record *Operator = N->getOperator();
1994 // Only permit raw nodes.
1995 if (!N->getName().empty() || !N->getPredicateFn().empty() ||
1996 N->getTransformFn()) {
1997 Children.push_back(N);
2001 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
2002 Children.push_back(N->getChild(0));
2004 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
2006 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
2007 Children.push_back(N->getChild(1));
2009 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
2012 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
2013 /// the (potentially recursive) pattern by using algebraic laws.
2015 static void GenerateVariantsOf(TreePatternNode *N,
2016 std::vector<TreePatternNode*> &OutVariants,
2017 CodeGenDAGPatterns &CDP,
2018 const MultipleUseVarSet &DepVars) {
2019 // We cannot permute leaves.
2021 OutVariants.push_back(N);
2025 // Look up interesting info about the node.
2026 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
2028 // If this node is associative, reassociate.
2029 if (NodeInfo.hasProperty(SDNPAssociative)) {
2030 // Reassociate by pulling together all of the linked operators
2031 std::vector<TreePatternNode*> MaximalChildren;
2032 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
2034 // Only handle child sizes of 3. Otherwise we'll end up trying too many
2036 if (MaximalChildren.size() == 3) {
2037 // Find the variants of all of our maximal children.
2038 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
2039 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
2040 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
2041 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
2043 // There are only two ways we can permute the tree:
2044 // (A op B) op C and A op (B op C)
2045 // Within these forms, we can also permute A/B/C.
2047 // Generate legal pair permutations of A/B/C.
2048 std::vector<TreePatternNode*> ABVariants;
2049 std::vector<TreePatternNode*> BAVariants;
2050 std::vector<TreePatternNode*> ACVariants;
2051 std::vector<TreePatternNode*> CAVariants;
2052 std::vector<TreePatternNode*> BCVariants;
2053 std::vector<TreePatternNode*> CBVariants;
2054 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
2055 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
2056 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
2057 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
2058 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
2059 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
2061 // Combine those into the result: (x op x) op x
2062 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
2063 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
2064 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
2065 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
2066 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
2067 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
2069 // Combine those into the result: x op (x op x)
2070 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
2071 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
2072 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
2073 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
2074 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
2075 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
2080 // Compute permutations of all children.
2081 std::vector<std::vector<TreePatternNode*> > ChildVariants;
2082 ChildVariants.resize(N->getNumChildren());
2083 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2084 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
2086 // Build all permutations based on how the children were formed.
2087 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
2089 // If this node is commutative, consider the commuted order.
2090 if (NodeInfo.hasProperty(SDNPCommutative)) {
2091 assert(N->getNumChildren()==2 &&"Commutative but doesn't have 2 children!");
2092 // Don't count children which are actually register references.
2094 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2095 TreePatternNode *Child = N->getChild(i);
2096 if (Child->isLeaf())
2097 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2098 Record *RR = DI->getDef();
2099 if (RR->isSubClassOf("Register"))
2104 // Consider the commuted order.
2106 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
2107 OutVariants, CDP, DepVars);
2112 // GenerateVariants - Generate variants. For example, commutative patterns can
2113 // match multiple ways. Add them to PatternsToMatch as well.
2114 void CodeGenDAGPatterns::GenerateVariants() {
2115 DOUT << "Generating instruction variants.\n";
2117 // Loop over all of the patterns we've collected, checking to see if we can
2118 // generate variants of the instruction, through the exploitation of
2119 // identities. This permits the target to provide agressive matching without
2120 // the .td file having to contain tons of variants of instructions.
2122 // Note that this loop adds new patterns to the PatternsToMatch list, but we
2123 // intentionally do not reconsider these. Any variants of added patterns have
2124 // already been added.
2126 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
2127 MultipleUseVarSet DepVars;
2128 std::vector<TreePatternNode*> Variants;
2129 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
2130 DOUT << "Dependent/multiply used variables: ";
2131 DEBUG(DumpDepVars(DepVars));
2133 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this, DepVars);
2135 assert(!Variants.empty() && "Must create at least original variant!");
2136 Variants.erase(Variants.begin()); // Remove the original pattern.
2138 if (Variants.empty()) // No variants for this pattern.
2141 DOUT << "FOUND VARIANTS OF: ";
2142 DEBUG(PatternsToMatch[i].getSrcPattern()->dump());
2145 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
2146 TreePatternNode *Variant = Variants[v];
2148 DOUT << " VAR#" << v << ": ";
2149 DEBUG(Variant->dump());
2152 // Scan to see if an instruction or explicit pattern already matches this.
2153 bool AlreadyExists = false;
2154 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
2155 // Check to see if this variant already exists.
2156 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(), DepVars)) {
2157 DOUT << " *** ALREADY EXISTS, ignoring variant.\n";
2158 AlreadyExists = true;
2162 // If we already have it, ignore the variant.
2163 if (AlreadyExists) continue;
2165 // Otherwise, add it to the list of patterns we have.
2167 push_back(PatternToMatch(PatternsToMatch[i].getPredicates(),
2168 Variant, PatternsToMatch[i].getDstPattern(),
2169 PatternsToMatch[i].getDstRegs(),
2170 PatternsToMatch[i].getAddedComplexity()));