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);
876 assert(ResultNode->isSubClassOf("RegisterClass") &&
877 "Operands should be register classes!");
879 const CodeGenRegisterClass &RC =
880 CDP.getTargetInfo().getRegisterClass(ResultNode);
881 MadeChange = UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
885 unsigned ChildNo = 0;
886 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
887 Record *OperandNode = Inst.getOperand(i);
889 // If the instruction expects a predicate or optional def operand, we
890 // codegen this by setting the operand to it's default value if it has a
891 // non-empty DefaultOps field.
892 if ((OperandNode->isSubClassOf("PredicateOperand") ||
893 OperandNode->isSubClassOf("OptionalDefOperand")) &&
894 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
897 // Verify that we didn't run out of provided operands.
898 if (ChildNo >= getNumChildren())
899 TP.error("Instruction '" + getOperator()->getName() +
900 "' expects more operands than were provided.");
903 TreePatternNode *Child = getChild(ChildNo++);
904 if (OperandNode->isSubClassOf("RegisterClass")) {
905 const CodeGenRegisterClass &RC =
906 CDP.getTargetInfo().getRegisterClass(OperandNode);
907 MadeChange |= Child->UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
908 } else if (OperandNode->isSubClassOf("Operand")) {
909 VT = getValueType(OperandNode->getValueAsDef("Type"));
910 MadeChange |= Child->UpdateNodeType(VT, TP);
911 } else if (OperandNode->getName() == "ptr_rc") {
912 MadeChange |= Child->UpdateNodeType(MVT::iPTR, TP);
914 assert(0 && "Unknown operand type!");
917 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
920 if (ChildNo != getNumChildren())
921 TP.error("Instruction '" + getOperator()->getName() +
922 "' was provided too many operands!");
926 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
928 // Node transforms always take one operand.
929 if (getNumChildren() != 1)
930 TP.error("Node transform '" + getOperator()->getName() +
931 "' requires one operand!");
933 // If either the output or input of the xform does not have exact
934 // type info. We assume they must be the same. Otherwise, it is perfectly
935 // legal to transform from one type to a completely different type.
936 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
937 bool MadeChange = UpdateNodeType(getChild(0)->getExtTypes(), TP);
938 MadeChange |= getChild(0)->UpdateNodeType(getExtTypes(), TP);
945 /// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
946 /// RHS of a commutative operation, not the on LHS.
947 static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
948 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
950 if (N->isLeaf() && dynamic_cast<IntInit*>(N->getLeafValue()))
956 /// canPatternMatch - If it is impossible for this pattern to match on this
957 /// target, fill in Reason and return false. Otherwise, return true. This is
958 /// used as a santity check for .td files (to prevent people from writing stuff
959 /// that can never possibly work), and to prevent the pattern permuter from
960 /// generating stuff that is useless.
961 bool TreePatternNode::canPatternMatch(std::string &Reason,
962 CodeGenDAGPatterns &CDP){
963 if (isLeaf()) return true;
965 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
966 if (!getChild(i)->canPatternMatch(Reason, CDP))
969 // If this is an intrinsic, handle cases that would make it not match. For
970 // example, if an operand is required to be an immediate.
971 if (getOperator()->isSubClassOf("Intrinsic")) {
976 // If this node is a commutative operator, check that the LHS isn't an
978 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
979 if (NodeInfo.hasProperty(SDNPCommutative)) {
980 // Scan all of the operands of the node and make sure that only the last one
981 // is a constant node, unless the RHS also is.
982 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
983 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i)
984 if (OnlyOnRHSOfCommutative(getChild(i))) {
985 Reason="Immediate value must be on the RHS of commutative operators!";
994 //===----------------------------------------------------------------------===//
995 // TreePattern implementation
998 TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
999 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
1000 isInputPattern = isInput;
1001 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
1002 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
1005 TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
1006 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
1007 isInputPattern = isInput;
1008 Trees.push_back(ParseTreePattern(Pat));
1011 TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
1012 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
1013 isInputPattern = isInput;
1014 Trees.push_back(Pat);
1019 void TreePattern::error(const std::string &Msg) const {
1021 throw "In " + TheRecord->getName() + ": " + Msg;
1024 TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
1025 DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
1026 if (!OpDef) error("Pattern has unexpected operator type!");
1027 Record *Operator = OpDef->getDef();
1029 if (Operator->isSubClassOf("ValueType")) {
1030 // If the operator is a ValueType, then this must be "type cast" of a leaf
1032 if (Dag->getNumArgs() != 1)
1033 error("Type cast only takes one operand!");
1035 Init *Arg = Dag->getArg(0);
1036 TreePatternNode *New;
1037 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
1038 Record *R = DI->getDef();
1039 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
1040 Dag->setArg(0, new DagInit(DI,
1041 std::vector<std::pair<Init*, std::string> >()));
1042 return ParseTreePattern(Dag);
1044 New = new TreePatternNode(DI);
1045 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
1046 New = ParseTreePattern(DI);
1047 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
1048 New = new TreePatternNode(II);
1049 if (!Dag->getArgName(0).empty())
1050 error("Constant int argument should not have a name!");
1051 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
1052 // Turn this into an IntInit.
1053 Init *II = BI->convertInitializerTo(new IntRecTy());
1054 if (II == 0 || !dynamic_cast<IntInit*>(II))
1055 error("Bits value must be constants!");
1057 New = new TreePatternNode(dynamic_cast<IntInit*>(II));
1058 if (!Dag->getArgName(0).empty())
1059 error("Constant int argument should not have a name!");
1062 error("Unknown leaf value for tree pattern!");
1066 // Apply the type cast.
1067 New->UpdateNodeType(getValueType(Operator), *this);
1068 New->setName(Dag->getArgName(0));
1072 // Verify that this is something that makes sense for an operator.
1073 if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
1074 !Operator->isSubClassOf("Instruction") &&
1075 !Operator->isSubClassOf("SDNodeXForm") &&
1076 !Operator->isSubClassOf("Intrinsic") &&
1077 Operator->getName() != "set" &&
1078 Operator->getName() != "implicit" &&
1079 Operator->getName() != "parallel")
1080 error("Unrecognized node '" + Operator->getName() + "'!");
1082 // Check to see if this is something that is illegal in an input pattern.
1083 if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
1084 Operator->isSubClassOf("SDNodeXForm")))
1085 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
1087 std::vector<TreePatternNode*> Children;
1089 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
1090 Init *Arg = Dag->getArg(i);
1091 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
1092 Children.push_back(ParseTreePattern(DI));
1093 if (Children.back()->getName().empty())
1094 Children.back()->setName(Dag->getArgName(i));
1095 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
1096 Record *R = DefI->getDef();
1097 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
1098 // TreePatternNode if its own.
1099 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
1100 Dag->setArg(i, new DagInit(DefI,
1101 std::vector<std::pair<Init*, std::string> >()));
1102 --i; // Revisit this node...
1104 TreePatternNode *Node = new TreePatternNode(DefI);
1105 Node->setName(Dag->getArgName(i));
1106 Children.push_back(Node);
1109 if (R->getName() == "node") {
1110 if (Dag->getArgName(i).empty())
1111 error("'node' argument requires a name to match with operand list");
1112 Args.push_back(Dag->getArgName(i));
1115 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
1116 TreePatternNode *Node = new TreePatternNode(II);
1117 if (!Dag->getArgName(i).empty())
1118 error("Constant int argument should not have a name!");
1119 Children.push_back(Node);
1120 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
1121 // Turn this into an IntInit.
1122 Init *II = BI->convertInitializerTo(new IntRecTy());
1123 if (II == 0 || !dynamic_cast<IntInit*>(II))
1124 error("Bits value must be constants!");
1126 TreePatternNode *Node = new TreePatternNode(dynamic_cast<IntInit*>(II));
1127 if (!Dag->getArgName(i).empty())
1128 error("Constant int argument should not have a name!");
1129 Children.push_back(Node);
1134 error("Unknown leaf value for tree pattern!");
1138 // If the operator is an intrinsic, then this is just syntactic sugar for for
1139 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
1140 // convert the intrinsic name to a number.
1141 if (Operator->isSubClassOf("Intrinsic")) {
1142 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
1143 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
1145 // If this intrinsic returns void, it must have side-effects and thus a
1147 if (Int.ArgVTs[0] == MVT::isVoid) {
1148 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
1149 } else if (Int.ModRef != CodeGenIntrinsic::NoMem) {
1150 // Has side-effects, requires chain.
1151 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
1153 // Otherwise, no chain.
1154 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
1157 TreePatternNode *IIDNode = new TreePatternNode(new IntInit(IID));
1158 Children.insert(Children.begin(), IIDNode);
1161 return new TreePatternNode(Operator, Children);
1164 /// InferAllTypes - Infer/propagate as many types throughout the expression
1165 /// patterns as possible. Return true if all types are infered, false
1166 /// otherwise. Throw an exception if a type contradiction is found.
1167 bool TreePattern::InferAllTypes() {
1168 bool MadeChange = true;
1169 while (MadeChange) {
1171 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1172 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
1175 bool HasUnresolvedTypes = false;
1176 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1177 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
1178 return !HasUnresolvedTypes;
1181 void TreePattern::print(std::ostream &OS) const {
1182 OS << getRecord()->getName();
1183 if (!Args.empty()) {
1184 OS << "(" << Args[0];
1185 for (unsigned i = 1, e = Args.size(); i != e; ++i)
1186 OS << ", " << Args[i];
1191 if (Trees.size() > 1)
1193 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
1195 Trees[i]->print(OS);
1199 if (Trees.size() > 1)
1203 void TreePattern::dump() const { print(*cerr.stream()); }
1205 //===----------------------------------------------------------------------===//
1206 // CodeGenDAGPatterns implementation
1209 // FIXME: REMOVE OSTREAM ARGUMENT
1210 CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) : Records(R) {
1211 Intrinsics = LoadIntrinsics(Records);
1213 ParseNodeTransforms();
1214 ParseComplexPatterns();
1215 ParsePatternFragments();
1216 ParseDefaultOperands();
1217 ParseInstructions();
1220 // Generate variants. For example, commutative patterns can match
1221 // multiple ways. Add them to PatternsToMatch as well.
1225 CodeGenDAGPatterns::~CodeGenDAGPatterns() {
1226 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
1227 E = PatternFragments.end(); I != E; ++I)
1232 Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
1233 Record *N = Records.getDef(Name);
1234 if (!N || !N->isSubClassOf("SDNode")) {
1235 cerr << "Error getting SDNode '" << Name << "'!\n";
1241 // Parse all of the SDNode definitions for the target, populating SDNodes.
1242 void CodeGenDAGPatterns::ParseNodeInfo() {
1243 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
1244 while (!Nodes.empty()) {
1245 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
1249 // Get the buildin intrinsic nodes.
1250 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
1251 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
1252 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
1255 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
1256 /// map, and emit them to the file as functions.
1257 void CodeGenDAGPatterns::ParseNodeTransforms() {
1258 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
1259 while (!Xforms.empty()) {
1260 Record *XFormNode = Xforms.back();
1261 Record *SDNode = XFormNode->getValueAsDef("Opcode");
1262 std::string Code = XFormNode->getValueAsCode("XFormFunction");
1263 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
1269 void CodeGenDAGPatterns::ParseComplexPatterns() {
1270 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
1271 while (!AMs.empty()) {
1272 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
1278 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
1279 /// file, building up the PatternFragments map. After we've collected them all,
1280 /// inline fragments together as necessary, so that there are no references left
1281 /// inside a pattern fragment to a pattern fragment.
1283 void CodeGenDAGPatterns::ParsePatternFragments() {
1284 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
1286 // First step, parse all of the fragments.
1287 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1288 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
1289 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
1290 PatternFragments[Fragments[i]] = P;
1292 // Validate the argument list, converting it to set, to discard duplicates.
1293 std::vector<std::string> &Args = P->getArgList();
1294 std::set<std::string> OperandsSet(Args.begin(), Args.end());
1296 if (OperandsSet.count(""))
1297 P->error("Cannot have unnamed 'node' values in pattern fragment!");
1299 // Parse the operands list.
1300 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
1301 DefInit *OpsOp = dynamic_cast<DefInit*>(OpsList->getOperator());
1302 // Special cases: ops == outs == ins. Different names are used to
1303 // improve readibility.
1305 (OpsOp->getDef()->getName() != "ops" &&
1306 OpsOp->getDef()->getName() != "outs" &&
1307 OpsOp->getDef()->getName() != "ins"))
1308 P->error("Operands list should start with '(ops ... '!");
1310 // Copy over the arguments.
1312 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
1313 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
1314 static_cast<DefInit*>(OpsList->getArg(j))->
1315 getDef()->getName() != "node")
1316 P->error("Operands list should all be 'node' values.");
1317 if (OpsList->getArgName(j).empty())
1318 P->error("Operands list should have names for each operand!");
1319 if (!OperandsSet.count(OpsList->getArgName(j)))
1320 P->error("'" + OpsList->getArgName(j) +
1321 "' does not occur in pattern or was multiply specified!");
1322 OperandsSet.erase(OpsList->getArgName(j));
1323 Args.push_back(OpsList->getArgName(j));
1326 if (!OperandsSet.empty())
1327 P->error("Operands list does not contain an entry for operand '" +
1328 *OperandsSet.begin() + "'!");
1330 // If there is a code init for this fragment, keep track of the fact that
1331 // this fragment uses it.
1332 std::string Code = Fragments[i]->getValueAsCode("Predicate");
1334 P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
1336 // If there is a node transformation corresponding to this, keep track of
1338 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
1339 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
1340 P->getOnlyTree()->setTransformFn(Transform);
1343 // Now that we've parsed all of the tree fragments, do a closure on them so
1344 // that there are not references to PatFrags left inside of them.
1345 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
1346 E = PatternFragments.end(); I != E; ++I) {
1347 TreePattern *ThePat = I->second;
1348 ThePat->InlinePatternFragments();
1350 // Infer as many types as possible. Don't worry about it if we don't infer
1351 // all of them, some may depend on the inputs of the pattern.
1353 ThePat->InferAllTypes();
1355 // If this pattern fragment is not supported by this target (no types can
1356 // satisfy its constraints), just ignore it. If the bogus pattern is
1357 // actually used by instructions, the type consistency error will be
1361 // If debugging, print out the pattern fragment result.
1362 DEBUG(ThePat->dump());
1366 void CodeGenDAGPatterns::ParseDefaultOperands() {
1367 std::vector<Record*> DefaultOps[2];
1368 DefaultOps[0] = Records.getAllDerivedDefinitions("PredicateOperand");
1369 DefaultOps[1] = Records.getAllDerivedDefinitions("OptionalDefOperand");
1371 // Find some SDNode.
1372 assert(!SDNodes.empty() && "No SDNodes parsed?");
1373 Init *SomeSDNode = new DefInit(SDNodes.begin()->first);
1375 for (unsigned iter = 0; iter != 2; ++iter) {
1376 for (unsigned i = 0, e = DefaultOps[iter].size(); i != e; ++i) {
1377 DagInit *DefaultInfo = DefaultOps[iter][i]->getValueAsDag("DefaultOps");
1379 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
1380 // SomeSDnode so that we can parse this.
1381 std::vector<std::pair<Init*, std::string> > Ops;
1382 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
1383 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
1384 DefaultInfo->getArgName(op)));
1385 DagInit *DI = new DagInit(SomeSDNode, Ops);
1387 // Create a TreePattern to parse this.
1388 TreePattern P(DefaultOps[iter][i], DI, false, *this);
1389 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
1391 // Copy the operands over into a DAGDefaultOperand.
1392 DAGDefaultOperand DefaultOpInfo;
1394 TreePatternNode *T = P.getTree(0);
1395 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
1396 TreePatternNode *TPN = T->getChild(op);
1397 while (TPN->ApplyTypeConstraints(P, false))
1398 /* Resolve all types */;
1400 if (TPN->ContainsUnresolvedType()) {
1402 throw "Value #" + utostr(i) + " of PredicateOperand '" +
1403 DefaultOps[iter][i]->getName() + "' doesn't have a concrete type!";
1405 throw "Value #" + utostr(i) + " of OptionalDefOperand '" +
1406 DefaultOps[iter][i]->getName() + "' doesn't have a concrete type!";
1408 DefaultOpInfo.DefaultOps.push_back(TPN);
1411 // Insert it into the DefaultOperands map so we can find it later.
1412 DefaultOperands[DefaultOps[iter][i]] = DefaultOpInfo;
1417 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
1418 /// instruction input. Return true if this is a real use.
1419 static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
1420 std::map<std::string, TreePatternNode*> &InstInputs,
1421 std::vector<Record*> &InstImpInputs) {
1422 // No name -> not interesting.
1423 if (Pat->getName().empty()) {
1424 if (Pat->isLeaf()) {
1425 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1426 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1427 I->error("Input " + DI->getDef()->getName() + " must be named!");
1428 else if (DI && DI->getDef()->isSubClassOf("Register"))
1429 InstImpInputs.push_back(DI->getDef());
1436 if (Pat->isLeaf()) {
1437 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1438 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
1441 assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
1442 Rec = Pat->getOperator();
1445 // SRCVALUE nodes are ignored.
1446 if (Rec->getName() == "srcvalue")
1449 TreePatternNode *&Slot = InstInputs[Pat->getName()];
1454 if (Slot->isLeaf()) {
1455 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
1457 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
1458 SlotRec = Slot->getOperator();
1461 // Ensure that the inputs agree if we've already seen this input.
1463 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1464 if (Slot->getExtTypes() != Pat->getExtTypes())
1465 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1470 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
1471 /// part of "I", the instruction), computing the set of inputs and outputs of
1472 /// the pattern. Report errors if we see anything naughty.
1473 void CodeGenDAGPatterns::
1474 FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
1475 std::map<std::string, TreePatternNode*> &InstInputs,
1476 std::map<std::string, TreePatternNode*>&InstResults,
1477 std::vector<Record*> &InstImpInputs,
1478 std::vector<Record*> &InstImpResults) {
1479 if (Pat->isLeaf()) {
1480 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1481 if (!isUse && Pat->getTransformFn())
1482 I->error("Cannot specify a transform function for a non-input value!");
1484 } else if (Pat->getOperator()->getName() == "implicit") {
1485 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1486 TreePatternNode *Dest = Pat->getChild(i);
1487 if (!Dest->isLeaf())
1488 I->error("implicitly defined value should be a register!");
1490 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1491 if (!Val || !Val->getDef()->isSubClassOf("Register"))
1492 I->error("implicitly defined value should be a register!");
1493 InstImpResults.push_back(Val->getDef());
1496 } else if (Pat->getOperator()->getName() != "set") {
1497 // If this is not a set, verify that the children nodes are not void typed,
1499 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1500 if (Pat->getChild(i)->getExtTypeNum(0) == MVT::isVoid)
1501 I->error("Cannot have void nodes inside of patterns!");
1502 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
1503 InstImpInputs, InstImpResults);
1506 // If this is a non-leaf node with no children, treat it basically as if
1507 // it were a leaf. This handles nodes like (imm).
1509 if (Pat->getNumChildren() == 0)
1510 isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1512 if (!isUse && Pat->getTransformFn())
1513 I->error("Cannot specify a transform function for a non-input value!");
1517 // Otherwise, this is a set, validate and collect instruction results.
1518 if (Pat->getNumChildren() == 0)
1519 I->error("set requires operands!");
1521 if (Pat->getTransformFn())
1522 I->error("Cannot specify a transform function on a set node!");
1524 // Check the set destinations.
1525 unsigned NumDests = Pat->getNumChildren()-1;
1526 for (unsigned i = 0; i != NumDests; ++i) {
1527 TreePatternNode *Dest = Pat->getChild(i);
1528 if (!Dest->isLeaf())
1529 I->error("set destination should be a register!");
1531 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1533 I->error("set destination should be a register!");
1535 if (Val->getDef()->isSubClassOf("RegisterClass") ||
1536 Val->getDef()->getName() == "ptr_rc") {
1537 if (Dest->getName().empty())
1538 I->error("set destination must have a name!");
1539 if (InstResults.count(Dest->getName()))
1540 I->error("cannot set '" + Dest->getName() +"' multiple times");
1541 InstResults[Dest->getName()] = Dest;
1542 } else if (Val->getDef()->isSubClassOf("Register")) {
1543 InstImpResults.push_back(Val->getDef());
1545 I->error("set destination should be a register!");
1549 // Verify and collect info from the computation.
1550 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
1551 InstInputs, InstResults,
1552 InstImpInputs, InstImpResults);
1555 /// ParseInstructions - Parse all of the instructions, inlining and resolving
1556 /// any fragments involved. This populates the Instructions list with fully
1557 /// resolved instructions.
1558 void CodeGenDAGPatterns::ParseInstructions() {
1559 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
1561 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
1564 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
1565 LI = Instrs[i]->getValueAsListInit("Pattern");
1567 // If there is no pattern, only collect minimal information about the
1568 // instruction for its operand list. We have to assume that there is one
1569 // result, as we have no detailed info.
1570 if (!LI || LI->getSize() == 0) {
1571 std::vector<Record*> Results;
1572 std::vector<Record*> Operands;
1574 CodeGenInstruction &InstInfo =Target.getInstruction(Instrs[i]->getName());
1576 if (InstInfo.OperandList.size() != 0) {
1577 if (InstInfo.NumDefs == 0) {
1578 // These produce no results
1579 for (unsigned j = 0, e = InstInfo.OperandList.size(); j < e; ++j)
1580 Operands.push_back(InstInfo.OperandList[j].Rec);
1582 // Assume the first operand is the result.
1583 Results.push_back(InstInfo.OperandList[0].Rec);
1585 // The rest are inputs.
1586 for (unsigned j = 1, e = InstInfo.OperandList.size(); j < e; ++j)
1587 Operands.push_back(InstInfo.OperandList[j].Rec);
1591 // Create and insert the instruction.
1592 std::vector<Record*> ImpResults;
1593 std::vector<Record*> ImpOperands;
1594 Instructions.insert(std::make_pair(Instrs[i],
1595 DAGInstruction(0, Results, Operands, ImpResults,
1597 continue; // no pattern.
1600 // Parse the instruction.
1601 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
1602 // Inline pattern fragments into it.
1603 I->InlinePatternFragments();
1605 // Infer as many types as possible. If we cannot infer all of them, we can
1606 // never do anything with this instruction pattern: report it to the user.
1607 if (!I->InferAllTypes())
1608 I->error("Could not infer all types in pattern!");
1610 // InstInputs - Keep track of all of the inputs of the instruction, along
1611 // with the record they are declared as.
1612 std::map<std::string, TreePatternNode*> InstInputs;
1614 // InstResults - Keep track of all the virtual registers that are 'set'
1615 // in the instruction, including what reg class they are.
1616 std::map<std::string, TreePatternNode*> InstResults;
1618 std::vector<Record*> InstImpInputs;
1619 std::vector<Record*> InstImpResults;
1621 // Verify that the top-level forms in the instruction are of void type, and
1622 // fill in the InstResults map.
1623 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
1624 TreePatternNode *Pat = I->getTree(j);
1625 if (Pat->getExtTypeNum(0) != MVT::isVoid)
1626 I->error("Top-level forms in instruction pattern should have"
1629 // Find inputs and outputs, and verify the structure of the uses/defs.
1630 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
1631 InstImpInputs, InstImpResults);
1634 // Now that we have inputs and outputs of the pattern, inspect the operands
1635 // list for the instruction. This determines the order that operands are
1636 // added to the machine instruction the node corresponds to.
1637 unsigned NumResults = InstResults.size();
1639 // Parse the operands list from the (ops) list, validating it.
1640 assert(I->getArgList().empty() && "Args list should still be empty here!");
1641 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
1643 // Check that all of the results occur first in the list.
1644 std::vector<Record*> Results;
1645 TreePatternNode *Res0Node = NULL;
1646 for (unsigned i = 0; i != NumResults; ++i) {
1647 if (i == CGI.OperandList.size())
1648 I->error("'" + InstResults.begin()->first +
1649 "' set but does not appear in operand list!");
1650 const std::string &OpName = CGI.OperandList[i].Name;
1652 // Check that it exists in InstResults.
1653 TreePatternNode *RNode = InstResults[OpName];
1655 I->error("Operand $" + OpName + " does not exist in operand list!");
1659 Record *R = dynamic_cast<DefInit*>(RNode->getLeafValue())->getDef();
1661 I->error("Operand $" + OpName + " should be a set destination: all "
1662 "outputs must occur before inputs in operand list!");
1664 if (CGI.OperandList[i].Rec != R)
1665 I->error("Operand $" + OpName + " class mismatch!");
1667 // Remember the return type.
1668 Results.push_back(CGI.OperandList[i].Rec);
1670 // Okay, this one checks out.
1671 InstResults.erase(OpName);
1674 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
1675 // the copy while we're checking the inputs.
1676 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
1678 std::vector<TreePatternNode*> ResultNodeOperands;
1679 std::vector<Record*> Operands;
1680 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
1681 CodeGenInstruction::OperandInfo &Op = CGI.OperandList[i];
1682 const std::string &OpName = Op.Name;
1684 I->error("Operand #" + utostr(i) + " in operands list has no name!");
1686 if (!InstInputsCheck.count(OpName)) {
1687 // If this is an predicate operand or optional def operand with an
1688 // DefaultOps set filled in, we can ignore this. When we codegen it,
1689 // we will do so as always executed.
1690 if (Op.Rec->isSubClassOf("PredicateOperand") ||
1691 Op.Rec->isSubClassOf("OptionalDefOperand")) {
1692 // Does it have a non-empty DefaultOps field? If so, ignore this
1694 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
1697 I->error("Operand $" + OpName +
1698 " does not appear in the instruction pattern");
1700 TreePatternNode *InVal = InstInputsCheck[OpName];
1701 InstInputsCheck.erase(OpName); // It occurred, remove from map.
1703 if (InVal->isLeaf() &&
1704 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
1705 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
1706 if (Op.Rec != InRec && !InRec->isSubClassOf("ComplexPattern"))
1707 I->error("Operand $" + OpName + "'s register class disagrees"
1708 " between the operand and pattern");
1710 Operands.push_back(Op.Rec);
1712 // Construct the result for the dest-pattern operand list.
1713 TreePatternNode *OpNode = InVal->clone();
1715 // No predicate is useful on the result.
1716 OpNode->setPredicateFn("");
1718 // Promote the xform function to be an explicit node if set.
1719 if (Record *Xform = OpNode->getTransformFn()) {
1720 OpNode->setTransformFn(0);
1721 std::vector<TreePatternNode*> Children;
1722 Children.push_back(OpNode);
1723 OpNode = new TreePatternNode(Xform, Children);
1726 ResultNodeOperands.push_back(OpNode);
1729 if (!InstInputsCheck.empty())
1730 I->error("Input operand $" + InstInputsCheck.begin()->first +
1731 " occurs in pattern but not in operands list!");
1733 TreePatternNode *ResultPattern =
1734 new TreePatternNode(I->getRecord(), ResultNodeOperands);
1735 // Copy fully inferred output node type to instruction result pattern.
1737 ResultPattern->setTypes(Res0Node->getExtTypes());
1739 // Create and insert the instruction.
1740 // FIXME: InstImpResults and InstImpInputs should not be part of
1742 DAGInstruction TheInst(I, Results, Operands, InstImpResults, InstImpInputs);
1743 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
1745 // Use a temporary tree pattern to infer all types and make sure that the
1746 // constructed result is correct. This depends on the instruction already
1747 // being inserted into the Instructions map.
1748 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
1749 Temp.InferAllTypes();
1751 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
1752 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
1757 // If we can, convert the instructions to be patterns that are matched!
1758 for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
1759 E = Instructions.end(); II != E; ++II) {
1760 DAGInstruction &TheInst = II->second;
1761 const TreePattern *I = TheInst.getPattern();
1762 if (I == 0) continue; // No pattern.
1764 // FIXME: Assume only the first tree is the pattern. The others are clobber
1766 TreePatternNode *Pattern = I->getTree(0);
1767 TreePatternNode *SrcPattern;
1768 if (Pattern->getOperator()->getName() == "set") {
1769 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
1771 // Not a set (store or something?)
1772 SrcPattern = Pattern;
1776 if (!SrcPattern->canPatternMatch(Reason, *this))
1777 I->error("Instruction can never match: " + Reason);
1779 Record *Instr = II->first;
1780 TreePatternNode *DstPattern = TheInst.getResultPattern();
1782 push_back(PatternToMatch(Instr->getValueAsListInit("Predicates"),
1783 SrcPattern, DstPattern, TheInst.getImpResults(),
1784 Instr->getValueAsInt("AddedComplexity")));
1788 void CodeGenDAGPatterns::ParsePatterns() {
1789 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
1791 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1792 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
1793 DefInit *OpDef = dynamic_cast<DefInit*>(Tree->getOperator());
1794 Record *Operator = OpDef->getDef();
1795 TreePattern *Pattern;
1796 if (Operator->getName() != "parallel")
1797 Pattern = new TreePattern(Patterns[i], Tree, true, *this);
1799 std::vector<Init*> Values;
1800 for (unsigned j = 0, ee = Tree->getNumArgs(); j != ee; ++j)
1801 Values.push_back(Tree->getArg(j));
1802 ListInit *LI = new ListInit(Values);
1803 Pattern = new TreePattern(Patterns[i], LI, true, *this);
1806 // Inline pattern fragments into it.
1807 Pattern->InlinePatternFragments();
1809 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
1810 if (LI->getSize() == 0) continue; // no pattern.
1812 // Parse the instruction.
1813 TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
1815 // Inline pattern fragments into it.
1816 Result->InlinePatternFragments();
1818 if (Result->getNumTrees() != 1)
1819 Result->error("Cannot handle instructions producing instructions "
1820 "with temporaries yet!");
1822 bool IterateInference;
1823 bool InferredAllPatternTypes, InferredAllResultTypes;
1825 // Infer as many types as possible. If we cannot infer all of them, we
1826 // can never do anything with this pattern: report it to the user.
1827 InferredAllPatternTypes = Pattern->InferAllTypes();
1829 // Infer as many types as possible. If we cannot infer all of them, we
1830 // can never do anything with this pattern: report it to the user.
1831 InferredAllResultTypes = Result->InferAllTypes();
1833 // Apply the type of the result to the source pattern. This helps us
1834 // resolve cases where the input type is known to be a pointer type (which
1835 // is considered resolved), but the result knows it needs to be 32- or
1836 // 64-bits. Infer the other way for good measure.
1837 IterateInference = Pattern->getTree(0)->
1838 UpdateNodeType(Result->getTree(0)->getExtTypes(), *Result);
1839 IterateInference |= Result->getTree(0)->
1840 UpdateNodeType(Pattern->getTree(0)->getExtTypes(), *Result);
1841 } while (IterateInference);
1843 // Verify that we inferred enough types that we can do something with the
1844 // pattern and result. If these fire the user has to add type casts.
1845 if (!InferredAllPatternTypes)
1846 Pattern->error("Could not infer all types in pattern!");
1847 if (!InferredAllResultTypes)
1848 Result->error("Could not infer all types in pattern result!");
1850 // Validate that the input pattern is correct.
1851 std::map<std::string, TreePatternNode*> InstInputs;
1852 std::map<std::string, TreePatternNode*> InstResults;
1853 std::vector<Record*> InstImpInputs;
1854 std::vector<Record*> InstImpResults;
1855 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
1856 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
1857 InstInputs, InstResults,
1858 InstImpInputs, InstImpResults);
1860 // Promote the xform function to be an explicit node if set.
1861 TreePatternNode *DstPattern = Result->getOnlyTree();
1862 std::vector<TreePatternNode*> ResultNodeOperands;
1863 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
1864 TreePatternNode *OpNode = DstPattern->getChild(ii);
1865 if (Record *Xform = OpNode->getTransformFn()) {
1866 OpNode->setTransformFn(0);
1867 std::vector<TreePatternNode*> Children;
1868 Children.push_back(OpNode);
1869 OpNode = new TreePatternNode(Xform, Children);
1871 ResultNodeOperands.push_back(OpNode);
1873 DstPattern = Result->getOnlyTree();
1874 if (!DstPattern->isLeaf())
1875 DstPattern = new TreePatternNode(DstPattern->getOperator(),
1876 ResultNodeOperands);
1877 DstPattern->setTypes(Result->getOnlyTree()->getExtTypes());
1878 TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
1879 Temp.InferAllTypes();
1882 if (!Pattern->getTree(0)->canPatternMatch(Reason, *this))
1883 Pattern->error("Pattern can never match: " + Reason);
1886 push_back(PatternToMatch(Patterns[i]->getValueAsListInit("Predicates"),
1887 Pattern->getTree(0),
1888 Temp.getOnlyTree(), InstImpResults,
1889 Patterns[i]->getValueAsInt("AddedComplexity")));
1893 /// CombineChildVariants - Given a bunch of permutations of each child of the
1894 /// 'operator' node, put them together in all possible ways.
1895 static void CombineChildVariants(TreePatternNode *Orig,
1896 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
1897 std::vector<TreePatternNode*> &OutVariants,
1898 CodeGenDAGPatterns &CDP,
1899 const MultipleUseVarSet &DepVars) {
1900 // Make sure that each operand has at least one variant to choose from.
1901 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1902 if (ChildVariants[i].empty())
1905 // The end result is an all-pairs construction of the resultant pattern.
1906 std::vector<unsigned> Idxs;
1907 Idxs.resize(ChildVariants.size());
1911 if (DebugFlag && !Idxs.empty()) {
1912 cerr << Orig->getOperator()->getName() << ": Idxs = [ ";
1913 for (unsigned i = 0; i < Idxs.size(); ++i) {
1914 cerr << Idxs[i] << " ";
1919 // Create the variant and add it to the output list.
1920 std::vector<TreePatternNode*> NewChildren;
1921 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1922 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
1923 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
1925 // Copy over properties.
1926 R->setName(Orig->getName());
1927 R->setPredicateFn(Orig->getPredicateFn());
1928 R->setTransformFn(Orig->getTransformFn());
1929 R->setTypes(Orig->getExtTypes());
1931 // If this pattern cannot match, do not include it as a variant.
1932 std::string ErrString;
1933 if (!R->canPatternMatch(ErrString, CDP)) {
1936 bool AlreadyExists = false;
1938 // Scan to see if this pattern has already been emitted. We can get
1939 // duplication due to things like commuting:
1940 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
1941 // which are the same pattern. Ignore the dups.
1942 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
1943 if (R->isIsomorphicTo(OutVariants[i], DepVars)) {
1944 AlreadyExists = true;
1951 OutVariants.push_back(R);
1954 // Increment indices to the next permutation by incrementing the
1955 // indicies from last index backward, e.g., generate the sequence
1956 // [0, 0], [0, 1], [1, 0], [1, 1].
1958 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
1959 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
1964 NotDone = (IdxsIdx >= 0);
1968 /// CombineChildVariants - A helper function for binary operators.
1970 static void CombineChildVariants(TreePatternNode *Orig,
1971 const std::vector<TreePatternNode*> &LHS,
1972 const std::vector<TreePatternNode*> &RHS,
1973 std::vector<TreePatternNode*> &OutVariants,
1974 CodeGenDAGPatterns &CDP,
1975 const MultipleUseVarSet &DepVars) {
1976 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1977 ChildVariants.push_back(LHS);
1978 ChildVariants.push_back(RHS);
1979 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
1983 static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
1984 std::vector<TreePatternNode *> &Children) {
1985 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
1986 Record *Operator = N->getOperator();
1988 // Only permit raw nodes.
1989 if (!N->getName().empty() || !N->getPredicateFn().empty() ||
1990 N->getTransformFn()) {
1991 Children.push_back(N);
1995 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
1996 Children.push_back(N->getChild(0));
1998 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
2000 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
2001 Children.push_back(N->getChild(1));
2003 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
2006 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
2007 /// the (potentially recursive) pattern by using algebraic laws.
2009 static void GenerateVariantsOf(TreePatternNode *N,
2010 std::vector<TreePatternNode*> &OutVariants,
2011 CodeGenDAGPatterns &CDP,
2012 const MultipleUseVarSet &DepVars) {
2013 // We cannot permute leaves.
2015 OutVariants.push_back(N);
2019 // Look up interesting info about the node.
2020 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
2022 // If this node is associative, reassociate.
2023 if (NodeInfo.hasProperty(SDNPAssociative)) {
2024 // Reassociate by pulling together all of the linked operators
2025 std::vector<TreePatternNode*> MaximalChildren;
2026 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
2028 // Only handle child sizes of 3. Otherwise we'll end up trying too many
2030 if (MaximalChildren.size() == 3) {
2031 // Find the variants of all of our maximal children.
2032 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
2033 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
2034 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
2035 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
2037 // There are only two ways we can permute the tree:
2038 // (A op B) op C and A op (B op C)
2039 // Within these forms, we can also permute A/B/C.
2041 // Generate legal pair permutations of A/B/C.
2042 std::vector<TreePatternNode*> ABVariants;
2043 std::vector<TreePatternNode*> BAVariants;
2044 std::vector<TreePatternNode*> ACVariants;
2045 std::vector<TreePatternNode*> CAVariants;
2046 std::vector<TreePatternNode*> BCVariants;
2047 std::vector<TreePatternNode*> CBVariants;
2048 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
2049 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
2050 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
2051 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
2052 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
2053 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
2055 // Combine those into the result: (x op x) op x
2056 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
2057 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
2058 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
2059 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
2060 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
2061 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
2063 // Combine those into the result: x op (x op x)
2064 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
2065 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
2066 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
2067 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
2068 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
2069 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
2074 // Compute permutations of all children.
2075 std::vector<std::vector<TreePatternNode*> > ChildVariants;
2076 ChildVariants.resize(N->getNumChildren());
2077 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2078 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
2080 // Build all permutations based on how the children were formed.
2081 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
2083 // If this node is commutative, consider the commuted order.
2084 if (NodeInfo.hasProperty(SDNPCommutative)) {
2085 assert(N->getNumChildren()==2 &&"Commutative but doesn't have 2 children!");
2086 // Don't count children which are actually register references.
2088 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2089 TreePatternNode *Child = N->getChild(i);
2090 if (Child->isLeaf())
2091 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2092 Record *RR = DI->getDef();
2093 if (RR->isSubClassOf("Register"))
2098 // Consider the commuted order.
2100 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
2101 OutVariants, CDP, DepVars);
2106 // GenerateVariants - Generate variants. For example, commutative patterns can
2107 // match multiple ways. Add them to PatternsToMatch as well.
2108 void CodeGenDAGPatterns::GenerateVariants() {
2109 DOUT << "Generating instruction variants.\n";
2111 // Loop over all of the patterns we've collected, checking to see if we can
2112 // generate variants of the instruction, through the exploitation of
2113 // identities. This permits the target to provide agressive matching without
2114 // the .td file having to contain tons of variants of instructions.
2116 // Note that this loop adds new patterns to the PatternsToMatch list, but we
2117 // intentionally do not reconsider these. Any variants of added patterns have
2118 // already been added.
2120 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
2121 MultipleUseVarSet DepVars;
2122 std::vector<TreePatternNode*> Variants;
2123 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
2124 DOUT << "Dependent/multiply used variables: ";
2125 DEBUG(DumpDepVars(DepVars));
2127 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this, DepVars);
2129 assert(!Variants.empty() && "Must create at least original variant!");
2130 Variants.erase(Variants.begin()); // Remove the original pattern.
2132 if (Variants.empty()) // No variants for this pattern.
2135 DOUT << "FOUND VARIANTS OF: ";
2136 DEBUG(PatternsToMatch[i].getSrcPattern()->dump());
2139 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
2140 TreePatternNode *Variant = Variants[v];
2142 DOUT << " VAR#" << v << ": ";
2143 DEBUG(Variant->dump());
2146 // Scan to see if an instruction or explicit pattern already matches this.
2147 bool AlreadyExists = false;
2148 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
2149 // Check to see if this variant already exists.
2150 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(), DepVars)) {
2151 DOUT << " *** ALREADY EXISTS, ignoring variant.\n";
2152 AlreadyExists = true;
2156 // If we already have it, ignore the variant.
2157 if (AlreadyExists) continue;
2159 // Otherwise, add it to the list of patterns we have.
2161 push_back(PatternToMatch(PatternsToMatch[i].getPredicates(),
2162 Variant, PatternsToMatch[i].getDstPattern(),
2163 PatternsToMatch[i].getDstRegs(),
2164 PatternsToMatch[i].getAddedComplexity()));