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"
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::SimpleValueType>
31 FilterVTs(const std::vector<MVT::SimpleValueType> &InVTs, T Filter) {
32 std::vector<MVT::SimpleValueType> 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::SimpleValueType)InVTs[i]))
45 Result.push_back(InVTs[i]);
49 static std::vector<unsigned char>
50 ConvertVTs(const std::vector<MVT::SimpleValueType> &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 inline bool isInteger(MVT::SimpleValueType VT) {
58 return EVT(VT).isInteger();
61 static inline bool isFloatingPoint(MVT::SimpleValueType VT) {
62 return EVT(VT).isFloatingPoint();
65 static inline bool isVector(MVT::SimpleValueType VT) {
66 return EVT(VT).isVector();
69 static bool LHSIsSubsetOfRHS(const std::vector<unsigned char> &LHS,
70 const std::vector<unsigned char> &RHS) {
71 if (LHS.size() > RHS.size()) return false;
72 for (unsigned i = 0, e = LHS.size(); i != e; ++i)
73 if (std::find(RHS.begin(), RHS.end(), LHS[i]) == RHS.end())
80 /// isExtIntegerInVTs - Return true if the specified extended value type vector
81 /// contains isInt or an integer value type.
82 bool isExtIntegerInVTs(const std::vector<unsigned char> &EVTs) {
83 assert(!EVTs.empty() && "Cannot check for integer in empty ExtVT list!");
84 return EVTs[0] == isInt || !(FilterEVTs(EVTs, isInteger).empty());
87 /// isExtFloatingPointInVTs - Return true if the specified extended value type
88 /// vector contains isFP or a FP value type.
89 bool isExtFloatingPointInVTs(const std::vector<unsigned char> &EVTs) {
90 assert(!EVTs.empty() && "Cannot check for FP in empty ExtVT list!");
91 return EVTs[0] == isFP || !(FilterEVTs(EVTs, isFloatingPoint).empty());
94 /// isExtVectorInVTs - Return true if the specified extended value type
95 /// vector contains a vector value type.
96 bool isExtVectorInVTs(const std::vector<unsigned char> &EVTs) {
97 assert(!EVTs.empty() && "Cannot check for vector in empty ExtVT list!");
98 return EVTs[0] == isVec || !(FilterEVTs(EVTs, isVector).empty());
100 } // end namespace EEVT.
101 } // end namespace llvm.
103 bool RecordPtrCmp::operator()(const Record *LHS, const Record *RHS) const {
104 return LHS->getID() < RHS->getID();
107 /// Dependent variable map for CodeGenDAGPattern variant generation
108 typedef std::map<std::string, int> DepVarMap;
110 /// Const iterator shorthand for DepVarMap
111 typedef DepVarMap::const_iterator DepVarMap_citer;
114 void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
116 if (dynamic_cast<DefInit*>(N->getLeafValue()) != NULL) {
117 DepMap[N->getName()]++;
120 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
121 FindDepVarsOf(N->getChild(i), DepMap);
125 //! Find dependent variables within child patterns
128 void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
130 FindDepVarsOf(N, depcounts);
131 for (DepVarMap_citer i = depcounts.begin(); i != depcounts.end(); ++i) {
132 if (i->second > 1) { // std::pair<std::string, int>
133 DepVars.insert(i->first);
138 //! Dump the dependent variable set:
139 void DumpDepVars(MultipleUseVarSet &DepVars) {
140 if (DepVars.empty()) {
141 DEBUG(errs() << "<empty set>");
143 DEBUG(errs() << "[ ");
144 for (MultipleUseVarSet::const_iterator i = DepVars.begin(), e = DepVars.end();
146 DEBUG(errs() << (*i) << " ");
148 DEBUG(errs() << "]");
153 //===----------------------------------------------------------------------===//
154 // PatternToMatch implementation
157 /// getPredicateCheck - Return a single string containing all of this
158 /// pattern's predicates concatenated with "&&" operators.
160 std::string PatternToMatch::getPredicateCheck() const {
161 std::string PredicateCheck;
162 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
163 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
164 Record *Def = Pred->getDef();
165 if (!Def->isSubClassOf("Predicate")) {
169 assert(0 && "Unknown predicate type!");
171 if (!PredicateCheck.empty())
172 PredicateCheck += " && ";
173 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
177 return PredicateCheck;
180 //===----------------------------------------------------------------------===//
181 // SDTypeConstraint implementation
184 SDTypeConstraint::SDTypeConstraint(Record *R) {
185 OperandNo = R->getValueAsInt("OperandNum");
187 if (R->isSubClassOf("SDTCisVT")) {
188 ConstraintType = SDTCisVT;
189 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
190 } else if (R->isSubClassOf("SDTCisPtrTy")) {
191 ConstraintType = SDTCisPtrTy;
192 } else if (R->isSubClassOf("SDTCisInt")) {
193 ConstraintType = SDTCisInt;
194 } else if (R->isSubClassOf("SDTCisFP")) {
195 ConstraintType = SDTCisFP;
196 } else if (R->isSubClassOf("SDTCisVec")) {
197 ConstraintType = SDTCisVec;
198 } else if (R->isSubClassOf("SDTCisSameAs")) {
199 ConstraintType = SDTCisSameAs;
200 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
201 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
202 ConstraintType = SDTCisVTSmallerThanOp;
203 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
204 R->getValueAsInt("OtherOperandNum");
205 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
206 ConstraintType = SDTCisOpSmallerThanOp;
207 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
208 R->getValueAsInt("BigOperandNum");
209 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
210 ConstraintType = SDTCisEltOfVec;
211 x.SDTCisEltOfVec_Info.OtherOperandNum =
212 R->getValueAsInt("OtherOpNum");
214 errs() << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
219 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
220 /// N, which has NumResults results.
221 TreePatternNode *SDTypeConstraint::getOperandNum(unsigned OpNo,
223 unsigned NumResults) const {
224 assert(NumResults <= 1 &&
225 "We only work with nodes with zero or one result so far!");
227 if (OpNo >= (NumResults + N->getNumChildren())) {
228 errs() << "Invalid operand number " << OpNo << " ";
234 if (OpNo < NumResults)
235 return N; // FIXME: need value #
237 return N->getChild(OpNo-NumResults);
240 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
241 /// constraint to the nodes operands. This returns true if it makes a
242 /// change, false otherwise. If a type contradiction is found, throw an
244 bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
245 const SDNodeInfo &NodeInfo,
246 TreePattern &TP) const {
247 unsigned NumResults = NodeInfo.getNumResults();
248 assert(NumResults <= 1 &&
249 "We only work with nodes with zero or one result so far!");
251 // Check that the number of operands is sane. Negative operands -> varargs.
252 if (NodeInfo.getNumOperands() >= 0) {
253 if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands())
254 TP.error(N->getOperator()->getName() + " node requires exactly " +
255 itostr(NodeInfo.getNumOperands()) + " operands!");
258 const CodeGenTarget &CGT = TP.getDAGPatterns().getTargetInfo();
260 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NumResults);
262 switch (ConstraintType) {
263 default: assert(0 && "Unknown constraint type!");
265 // Operand must be a particular type.
266 return NodeToApply->UpdateNodeType(x.SDTCisVT_Info.VT, TP);
268 // Operand must be same as target pointer type.
269 return NodeToApply->UpdateNodeType(MVT::iPTR, TP);
272 // If there is only one integer type supported, this must be it.
273 std::vector<MVT::SimpleValueType> IntVTs =
274 FilterVTs(CGT.getLegalValueTypes(), isInteger);
276 // If we found exactly one supported integer type, apply it.
277 if (IntVTs.size() == 1)
278 return NodeToApply->UpdateNodeType(IntVTs[0], TP);
279 return NodeToApply->UpdateNodeType(EEVT::isInt, TP);
282 // If there is only one FP type supported, this must be it.
283 std::vector<MVT::SimpleValueType> FPVTs =
284 FilterVTs(CGT.getLegalValueTypes(), isFloatingPoint);
286 // If we found exactly one supported FP type, apply it.
287 if (FPVTs.size() == 1)
288 return NodeToApply->UpdateNodeType(FPVTs[0], TP);
289 return NodeToApply->UpdateNodeType(EEVT::isFP, TP);
292 // If there is only one vector type supported, this must be it.
293 std::vector<MVT::SimpleValueType> VecVTs =
294 FilterVTs(CGT.getLegalValueTypes(), isVector);
296 // If we found exactly one supported vector type, apply it.
297 if (VecVTs.size() == 1)
298 return NodeToApply->UpdateNodeType(VecVTs[0], TP);
299 return NodeToApply->UpdateNodeType(EEVT::isVec, TP);
302 TreePatternNode *OtherNode =
303 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NumResults);
304 return NodeToApply->UpdateNodeType(OtherNode->getExtTypes(), TP) |
305 OtherNode->UpdateNodeType(NodeToApply->getExtTypes(), TP);
307 case SDTCisVTSmallerThanOp: {
308 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
309 // have an integer type that is smaller than the VT.
310 if (!NodeToApply->isLeaf() ||
311 !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
312 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
313 ->isSubClassOf("ValueType"))
314 TP.error(N->getOperator()->getName() + " expects a VT operand!");
315 MVT::SimpleValueType VT =
316 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
318 TP.error(N->getOperator()->getName() + " VT operand must be integer!");
320 TreePatternNode *OtherNode =
321 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N,NumResults);
323 // It must be integer.
324 bool MadeChange = false;
325 MadeChange |= OtherNode->UpdateNodeType(EEVT::isInt, TP);
327 // This code only handles nodes that have one type set. Assert here so
328 // that we can change this if we ever need to deal with multiple value
329 // types at this point.
330 assert(OtherNode->getExtTypes().size() == 1 && "Node has too many types!");
331 if (OtherNode->hasTypeSet() && OtherNode->getTypeNum(0) <= VT)
332 OtherNode->UpdateNodeType(MVT::Other, TP); // Throw an error.
335 case SDTCisOpSmallerThanOp: {
336 TreePatternNode *BigOperand =
337 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NumResults);
339 // Both operands must be integer or FP, but we don't care which.
340 bool MadeChange = false;
342 // This code does not currently handle nodes which have multiple types,
343 // where some types are integer, and some are fp. Assert that this is not
345 assert(!(EEVT::isExtIntegerInVTs(NodeToApply->getExtTypes()) &&
346 EEVT::isExtFloatingPointInVTs(NodeToApply->getExtTypes())) &&
347 !(EEVT::isExtIntegerInVTs(BigOperand->getExtTypes()) &&
348 EEVT::isExtFloatingPointInVTs(BigOperand->getExtTypes())) &&
349 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
350 if (EEVT::isExtIntegerInVTs(NodeToApply->getExtTypes()))
351 MadeChange |= BigOperand->UpdateNodeType(EEVT::isInt, TP);
352 else if (EEVT::isExtFloatingPointInVTs(NodeToApply->getExtTypes()))
353 MadeChange |= BigOperand->UpdateNodeType(EEVT::isFP, TP);
354 if (EEVT::isExtIntegerInVTs(BigOperand->getExtTypes()))
355 MadeChange |= NodeToApply->UpdateNodeType(EEVT::isInt, TP);
356 else if (EEVT::isExtFloatingPointInVTs(BigOperand->getExtTypes()))
357 MadeChange |= NodeToApply->UpdateNodeType(EEVT::isFP, TP);
359 std::vector<MVT::SimpleValueType> VTs = CGT.getLegalValueTypes();
361 if (EEVT::isExtIntegerInVTs(NodeToApply->getExtTypes())) {
362 VTs = FilterVTs(VTs, isInteger);
363 } else if (EEVT::isExtFloatingPointInVTs(NodeToApply->getExtTypes())) {
364 VTs = FilterVTs(VTs, isFloatingPoint);
369 switch (VTs.size()) {
370 default: // Too many VT's to pick from.
371 case 0: break; // No info yet.
373 // Only one VT of this flavor. Cannot ever satisfy the constraints.
374 return NodeToApply->UpdateNodeType(MVT::Other, TP); // throw
376 // If we have exactly two possible types, the little operand must be the
377 // small one, the big operand should be the big one. Common with
378 // float/double for example.
379 assert(VTs[0] < VTs[1] && "Should be sorted!");
380 MadeChange |= NodeToApply->UpdateNodeType(VTs[0], TP);
381 MadeChange |= BigOperand->UpdateNodeType(VTs[1], TP);
386 case SDTCisEltOfVec: {
387 TreePatternNode *OtherOperand =
388 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum,
390 if (OtherOperand->hasTypeSet()) {
391 if (!isVector(OtherOperand->getTypeNum(0)))
392 TP.error(N->getOperator()->getName() + " VT operand must be a vector!");
393 EVT IVT = OtherOperand->getTypeNum(0);
394 IVT = IVT.getVectorElementType();
395 return NodeToApply->UpdateNodeType(IVT.getSimpleVT().SimpleTy, TP);
403 //===----------------------------------------------------------------------===//
404 // SDNodeInfo implementation
406 SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
407 EnumName = R->getValueAsString("Opcode");
408 SDClassName = R->getValueAsString("SDClass");
409 Record *TypeProfile = R->getValueAsDef("TypeProfile");
410 NumResults = TypeProfile->getValueAsInt("NumResults");
411 NumOperands = TypeProfile->getValueAsInt("NumOperands");
413 // Parse the properties.
415 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
416 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
417 if (PropList[i]->getName() == "SDNPCommutative") {
418 Properties |= 1 << SDNPCommutative;
419 } else if (PropList[i]->getName() == "SDNPAssociative") {
420 Properties |= 1 << SDNPAssociative;
421 } else if (PropList[i]->getName() == "SDNPHasChain") {
422 Properties |= 1 << SDNPHasChain;
423 } else if (PropList[i]->getName() == "SDNPOutFlag") {
424 Properties |= 1 << SDNPOutFlag;
425 } else if (PropList[i]->getName() == "SDNPInFlag") {
426 Properties |= 1 << SDNPInFlag;
427 } else if (PropList[i]->getName() == "SDNPOptInFlag") {
428 Properties |= 1 << SDNPOptInFlag;
429 } else if (PropList[i]->getName() == "SDNPMayStore") {
430 Properties |= 1 << SDNPMayStore;
431 } else if (PropList[i]->getName() == "SDNPMayLoad") {
432 Properties |= 1 << SDNPMayLoad;
433 } else if (PropList[i]->getName() == "SDNPSideEffect") {
434 Properties |= 1 << SDNPSideEffect;
435 } else if (PropList[i]->getName() == "SDNPMemOperand") {
436 Properties |= 1 << SDNPMemOperand;
438 errs() << "Unknown SD Node property '" << PropList[i]->getName()
439 << "' on node '" << R->getName() << "'!\n";
445 // Parse the type constraints.
446 std::vector<Record*> ConstraintList =
447 TypeProfile->getValueAsListOfDefs("Constraints");
448 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
451 //===----------------------------------------------------------------------===//
452 // TreePatternNode implementation
455 TreePatternNode::~TreePatternNode() {
456 #if 0 // FIXME: implement refcounted tree nodes!
457 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
462 /// UpdateNodeType - Set the node type of N to VT if VT contains
463 /// information. If N already contains a conflicting type, then throw an
464 /// exception. This returns true if any information was updated.
466 bool TreePatternNode::UpdateNodeType(const std::vector<unsigned char> &ExtVTs,
468 assert(!ExtVTs.empty() && "Cannot update node type with empty type vector!");
470 if (ExtVTs[0] == EEVT::isUnknown || LHSIsSubsetOfRHS(getExtTypes(), ExtVTs))
472 if (isTypeCompletelyUnknown() || LHSIsSubsetOfRHS(ExtVTs, getExtTypes())) {
477 if (getExtTypeNum(0) == MVT::iPTR || getExtTypeNum(0) == MVT::iPTRAny) {
478 if (ExtVTs[0] == MVT::iPTR || ExtVTs[0] == MVT::iPTRAny ||
479 ExtVTs[0] == EEVT::isInt)
481 if (EEVT::isExtIntegerInVTs(ExtVTs)) {
482 std::vector<unsigned char> FVTs = FilterEVTs(ExtVTs, isInteger);
490 if ((ExtVTs[0] == EEVT::isInt || ExtVTs[0] == MVT::iAny) &&
491 EEVT::isExtIntegerInVTs(getExtTypes())) {
492 assert(hasTypeSet() && "should be handled above!");
493 std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), isInteger);
494 if (getExtTypes() == FVTs)
499 if ((ExtVTs[0] == MVT::iPTR || ExtVTs[0] == MVT::iPTRAny) &&
500 EEVT::isExtIntegerInVTs(getExtTypes())) {
501 //assert(hasTypeSet() && "should be handled above!");
502 std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), isInteger);
503 if (getExtTypes() == FVTs)
510 if ((ExtVTs[0] == EEVT::isFP || ExtVTs[0] == MVT::fAny) &&
511 EEVT::isExtFloatingPointInVTs(getExtTypes())) {
512 assert(hasTypeSet() && "should be handled above!");
513 std::vector<unsigned char> FVTs =
514 FilterEVTs(getExtTypes(), isFloatingPoint);
515 if (getExtTypes() == FVTs)
520 if ((ExtVTs[0] == EEVT::isVec || ExtVTs[0] == MVT::vAny) &&
521 EEVT::isExtVectorInVTs(getExtTypes())) {
522 assert(hasTypeSet() && "should be handled above!");
523 std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), isVector);
524 if (getExtTypes() == FVTs)
530 // If we know this is an int, FP, or vector type, and we are told it is a
531 // specific one, take the advice.
533 // Similarly, we should probably set the type here to the intersection of
534 // {isInt|isFP|isVec} and ExtVTs
535 if (((getExtTypeNum(0) == EEVT::isInt || getExtTypeNum(0) == MVT::iAny) &&
536 EEVT::isExtIntegerInVTs(ExtVTs)) ||
537 ((getExtTypeNum(0) == EEVT::isFP || getExtTypeNum(0) == MVT::fAny) &&
538 EEVT::isExtFloatingPointInVTs(ExtVTs)) ||
539 ((getExtTypeNum(0) == EEVT::isVec || getExtTypeNum(0) == MVT::vAny) &&
540 EEVT::isExtVectorInVTs(ExtVTs))) {
544 if (getExtTypeNum(0) == EEVT::isInt &&
545 (ExtVTs[0] == MVT::iPTR || ExtVTs[0] == MVT::iPTRAny)) {
553 TP.error("Type inference contradiction found in node!");
555 TP.error("Type inference contradiction found in node " +
556 getOperator()->getName() + "!");
558 return true; // unreachable
562 void TreePatternNode::print(raw_ostream &OS) const {
564 OS << *getLeafValue();
566 OS << "(" << getOperator()->getName();
569 // FIXME: At some point we should handle printing all the value types for
570 // nodes that are multiply typed.
571 switch (getExtTypeNum(0)) {
572 case MVT::Other: OS << ":Other"; break;
573 case EEVT::isInt: OS << ":isInt"; break;
574 case EEVT::isFP : OS << ":isFP"; break;
575 case EEVT::isVec: OS << ":isVec"; break;
576 case EEVT::isUnknown: ; /*OS << ":?";*/ break;
577 case MVT::iPTR: OS << ":iPTR"; break;
578 case MVT::iPTRAny: OS << ":iPTRAny"; break;
580 std::string VTName = llvm::getName(getTypeNum(0));
581 // Strip off EVT:: prefix if present.
582 if (VTName.substr(0,5) == "MVT::")
583 VTName = VTName.substr(5);
590 if (getNumChildren() != 0) {
592 getChild(0)->print(OS);
593 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
595 getChild(i)->print(OS);
601 for (unsigned i = 0, e = PredicateFns.size(); i != e; ++i)
602 OS << "<<P:" << PredicateFns[i] << ">>";
604 OS << "<<X:" << TransformFn->getName() << ">>";
605 if (!getName().empty())
606 OS << ":$" << getName();
609 void TreePatternNode::dump() const {
613 /// isIsomorphicTo - Return true if this node is recursively
614 /// isomorphic to the specified node. For this comparison, the node's
615 /// entire state is considered. The assigned name is ignored, since
616 /// nodes with differing names are considered isomorphic. However, if
617 /// the assigned name is present in the dependent variable set, then
618 /// the assigned name is considered significant and the node is
619 /// isomorphic if the names match.
620 bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
621 const MultipleUseVarSet &DepVars) const {
622 if (N == this) return true;
623 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
624 getPredicateFns() != N->getPredicateFns() ||
625 getTransformFn() != N->getTransformFn())
629 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
630 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue())) {
631 return ((DI->getDef() == NDI->getDef())
632 && (DepVars.find(getName()) == DepVars.end()
633 || getName() == N->getName()));
636 return getLeafValue() == N->getLeafValue();
639 if (N->getOperator() != getOperator() ||
640 N->getNumChildren() != getNumChildren()) return false;
641 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
642 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
647 /// clone - Make a copy of this tree and all of its children.
649 TreePatternNode *TreePatternNode::clone() const {
650 TreePatternNode *New;
652 New = new TreePatternNode(getLeafValue());
654 std::vector<TreePatternNode*> CChildren;
655 CChildren.reserve(Children.size());
656 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
657 CChildren.push_back(getChild(i)->clone());
658 New = new TreePatternNode(getOperator(), CChildren);
660 New->setName(getName());
661 New->setTypes(getExtTypes());
662 New->setPredicateFns(getPredicateFns());
663 New->setTransformFn(getTransformFn());
667 /// SubstituteFormalArguments - Replace the formal arguments in this tree
668 /// with actual values specified by ArgMap.
669 void TreePatternNode::
670 SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
671 if (isLeaf()) return;
673 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
674 TreePatternNode *Child = getChild(i);
675 if (Child->isLeaf()) {
676 Init *Val = Child->getLeafValue();
677 if (dynamic_cast<DefInit*>(Val) &&
678 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
679 // We found a use of a formal argument, replace it with its value.
680 TreePatternNode *NewChild = ArgMap[Child->getName()];
681 assert(NewChild && "Couldn't find formal argument!");
682 assert((Child->getPredicateFns().empty() ||
683 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
684 "Non-empty child predicate clobbered!");
685 setChild(i, NewChild);
688 getChild(i)->SubstituteFormalArguments(ArgMap);
694 /// InlinePatternFragments - If this pattern refers to any pattern
695 /// fragments, inline them into place, giving us a pattern without any
696 /// PatFrag references.
697 TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
698 if (isLeaf()) return this; // nothing to do.
699 Record *Op = getOperator();
701 if (!Op->isSubClassOf("PatFrag")) {
702 // Just recursively inline children nodes.
703 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
704 TreePatternNode *Child = getChild(i);
705 TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
707 assert((Child->getPredicateFns().empty() ||
708 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
709 "Non-empty child predicate clobbered!");
711 setChild(i, NewChild);
716 // Otherwise, we found a reference to a fragment. First, look up its
717 // TreePattern record.
718 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
720 // Verify that we are passing the right number of operands.
721 if (Frag->getNumArgs() != Children.size())
722 TP.error("'" + Op->getName() + "' fragment requires " +
723 utostr(Frag->getNumArgs()) + " operands!");
725 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
727 std::string Code = Op->getValueAsCode("Predicate");
729 FragTree->addPredicateFn("Predicate_"+Op->getName());
731 // Resolve formal arguments to their actual value.
732 if (Frag->getNumArgs()) {
733 // Compute the map of formal to actual arguments.
734 std::map<std::string, TreePatternNode*> ArgMap;
735 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
736 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
738 FragTree->SubstituteFormalArguments(ArgMap);
741 FragTree->setName(getName());
742 FragTree->UpdateNodeType(getExtTypes(), TP);
744 // Transfer in the old predicates.
745 for (unsigned i = 0, e = getPredicateFns().size(); i != e; ++i)
746 FragTree->addPredicateFn(getPredicateFns()[i]);
748 // Get a new copy of this fragment to stitch into here.
749 //delete this; // FIXME: implement refcounting!
751 // The fragment we inlined could have recursive inlining that is needed. See
752 // if there are any pattern fragments in it and inline them as needed.
753 return FragTree->InlinePatternFragments(TP);
756 /// getImplicitType - Check to see if the specified record has an implicit
757 /// type which should be applied to it. This will infer the type of register
758 /// references from the register file information, for example.
760 static std::vector<unsigned char> getImplicitType(Record *R, bool NotRegisters,
762 // Some common return values
763 std::vector<unsigned char> Unknown(1, EEVT::isUnknown);
764 std::vector<unsigned char> Other(1, MVT::Other);
766 // Check to see if this is a register or a register class...
767 if (R->isSubClassOf("RegisterClass")) {
770 const CodeGenRegisterClass &RC =
771 TP.getDAGPatterns().getTargetInfo().getRegisterClass(R);
772 return ConvertVTs(RC.getValueTypes());
773 } else if (R->isSubClassOf("PatFrag")) {
774 // Pattern fragment types will be resolved when they are inlined.
776 } else if (R->isSubClassOf("Register")) {
779 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
780 return T.getRegisterVTs(R);
781 } else if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
782 // Using a VTSDNode or CondCodeSDNode.
784 } else if (R->isSubClassOf("ComplexPattern")) {
787 std::vector<unsigned char>
788 ComplexPat(1, TP.getDAGPatterns().getComplexPattern(R).getValueType());
790 } else if (R->isSubClassOf("PointerLikeRegClass")) {
791 Other[0] = MVT::iPTR;
793 } else if (R->getName() == "node" || R->getName() == "srcvalue" ||
794 R->getName() == "zero_reg") {
799 TP.error("Unknown node flavor used in pattern: " + R->getName());
804 /// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
805 /// CodeGenIntrinsic information for it, otherwise return a null pointer.
806 const CodeGenIntrinsic *TreePatternNode::
807 getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
808 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
809 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
810 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
814 dynamic_cast<IntInit*>(getChild(0)->getLeafValue())->getValue();
815 return &CDP.getIntrinsicInfo(IID);
818 /// isCommutativeIntrinsic - Return true if the node corresponds to a
819 /// commutative intrinsic.
821 TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
822 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
823 return Int->isCommutative;
828 /// ApplyTypeConstraints - Apply all of the type constraints relevant to
829 /// this node and its children in the tree. This returns true if it makes a
830 /// change, false otherwise. If a type contradiction is found, throw an
832 bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
833 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
835 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
836 // If it's a regclass or something else known, include the type.
837 return UpdateNodeType(getImplicitType(DI->getDef(), NotRegisters, TP),TP);
838 } else if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
839 // Int inits are always integers. :)
840 bool MadeChange = UpdateNodeType(EEVT::isInt, TP);
843 // At some point, it may make sense for this tree pattern to have
844 // multiple types. Assert here that it does not, so we revisit this
845 // code when appropriate.
846 assert(getExtTypes().size() >= 1 && "TreePattern doesn't have a type!");
847 MVT::SimpleValueType VT = getTypeNum(0);
848 for (unsigned i = 1, e = getExtTypes().size(); i != e; ++i)
849 assert(getTypeNum(i) == VT && "TreePattern has too many types!");
852 if (VT != MVT::iPTR && VT != MVT::iPTRAny) {
853 unsigned Size = EVT(VT).getSizeInBits();
854 // Make sure that the value is representable for this type.
856 int Val = (II->getValue() << (32-Size)) >> (32-Size);
857 if (Val != II->getValue()) {
858 // If sign-extended doesn't fit, does it fit as unsigned?
860 unsigned UnsignedVal;
861 ValueMask = unsigned(~uint32_t(0UL) >> (32-Size));
862 UnsignedVal = unsigned(II->getValue());
864 if ((ValueMask & UnsignedVal) != UnsignedVal) {
865 TP.error("Integer value '" + itostr(II->getValue())+
866 "' is out of range for type '" +
867 getEnumName(getTypeNum(0)) + "'!");
879 // special handling for set, which isn't really an SDNode.
880 if (getOperator()->getName() == "set") {
881 assert (getNumChildren() >= 2 && "Missing RHS of a set?");
882 unsigned NC = getNumChildren();
883 bool MadeChange = false;
884 for (unsigned i = 0; i < NC-1; ++i) {
885 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
886 MadeChange |= getChild(NC-1)->ApplyTypeConstraints(TP, NotRegisters);
888 // Types of operands must match.
889 MadeChange |= getChild(i)->UpdateNodeType(getChild(NC-1)->getExtTypes(),
891 MadeChange |= getChild(NC-1)->UpdateNodeType(getChild(i)->getExtTypes(),
893 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
896 } else if (getOperator()->getName() == "implicit" ||
897 getOperator()->getName() == "parallel") {
898 bool MadeChange = false;
899 for (unsigned i = 0; i < getNumChildren(); ++i)
900 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
901 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
903 } else if (getOperator()->getName() == "COPY_TO_REGCLASS") {
904 bool MadeChange = false;
905 MadeChange |= getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
906 MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
907 MadeChange |= UpdateNodeType(getChild(1)->getTypeNum(0), TP);
909 } else if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
910 bool MadeChange = false;
912 // Apply the result type to the node.
913 unsigned NumRetVTs = Int->IS.RetVTs.size();
914 unsigned NumParamVTs = Int->IS.ParamVTs.size();
916 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
917 MadeChange |= UpdateNodeType(Int->IS.RetVTs[i], TP);
919 if (getNumChildren() != NumParamVTs + NumRetVTs)
920 TP.error("Intrinsic '" + Int->Name + "' expects " +
921 utostr(NumParamVTs + NumRetVTs - 1) + " operands, not " +
922 utostr(getNumChildren() - 1) + " operands!");
924 // Apply type info to the intrinsic ID.
925 MadeChange |= getChild(0)->UpdateNodeType(MVT::iPTR, TP);
927 for (unsigned i = NumRetVTs, e = getNumChildren(); i != e; ++i) {
928 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i - NumRetVTs];
929 MadeChange |= getChild(i)->UpdateNodeType(OpVT, TP);
930 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
933 } else if (getOperator()->isSubClassOf("SDNode")) {
934 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
936 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
937 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
938 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
939 // Branch, etc. do not produce results and top-level forms in instr pattern
940 // must have void types.
941 if (NI.getNumResults() == 0)
942 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
945 } else if (getOperator()->isSubClassOf("Instruction")) {
946 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
947 bool MadeChange = false;
948 unsigned NumResults = Inst.getNumResults();
950 assert(NumResults <= 1 &&
951 "Only supports zero or one result instrs!");
953 CodeGenInstruction &InstInfo =
954 CDP.getTargetInfo().getInstruction(getOperator()->getName());
955 // Apply the result type to the node
956 if (NumResults == 0 || InstInfo.NumDefs == 0) {
957 MadeChange = UpdateNodeType(MVT::isVoid, TP);
959 Record *ResultNode = Inst.getResult(0);
961 if (ResultNode->isSubClassOf("PointerLikeRegClass")) {
962 std::vector<unsigned char> VT;
963 VT.push_back(MVT::iPTR);
964 MadeChange = UpdateNodeType(VT, TP);
965 } else if (ResultNode->getName() == "unknown") {
966 std::vector<unsigned char> VT;
967 VT.push_back(EEVT::isUnknown);
968 MadeChange = UpdateNodeType(VT, TP);
970 assert(ResultNode->isSubClassOf("RegisterClass") &&
971 "Operands should be register classes!");
973 const CodeGenRegisterClass &RC =
974 CDP.getTargetInfo().getRegisterClass(ResultNode);
975 MadeChange = UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
979 unsigned ChildNo = 0;
980 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
981 Record *OperandNode = Inst.getOperand(i);
983 // If the instruction expects a predicate or optional def operand, we
984 // codegen this by setting the operand to it's default value if it has a
985 // non-empty DefaultOps field.
986 if ((OperandNode->isSubClassOf("PredicateOperand") ||
987 OperandNode->isSubClassOf("OptionalDefOperand")) &&
988 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
991 // Verify that we didn't run out of provided operands.
992 if (ChildNo >= getNumChildren())
993 TP.error("Instruction '" + getOperator()->getName() +
994 "' expects more operands than were provided.");
996 MVT::SimpleValueType VT;
997 TreePatternNode *Child = getChild(ChildNo++);
998 if (OperandNode->isSubClassOf("RegisterClass")) {
999 const CodeGenRegisterClass &RC =
1000 CDP.getTargetInfo().getRegisterClass(OperandNode);
1001 MadeChange |= Child->UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
1002 } else if (OperandNode->isSubClassOf("Operand")) {
1003 VT = getValueType(OperandNode->getValueAsDef("Type"));
1004 MadeChange |= Child->UpdateNodeType(VT, TP);
1005 } else if (OperandNode->isSubClassOf("PointerLikeRegClass")) {
1006 MadeChange |= Child->UpdateNodeType(MVT::iPTR, TP);
1007 } else if (OperandNode->getName() == "unknown") {
1008 MadeChange |= Child->UpdateNodeType(EEVT::isUnknown, TP);
1010 assert(0 && "Unknown operand type!");
1013 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
1016 if (ChildNo != getNumChildren())
1017 TP.error("Instruction '" + getOperator()->getName() +
1018 "' was provided too many operands!");
1022 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
1024 // Node transforms always take one operand.
1025 if (getNumChildren() != 1)
1026 TP.error("Node transform '" + getOperator()->getName() +
1027 "' requires one operand!");
1029 // If either the output or input of the xform does not have exact
1030 // type info. We assume they must be the same. Otherwise, it is perfectly
1031 // legal to transform from one type to a completely different type.
1032 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
1033 bool MadeChange = UpdateNodeType(getChild(0)->getExtTypes(), TP);
1034 MadeChange |= getChild(0)->UpdateNodeType(getExtTypes(), TP);
1041 /// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
1042 /// RHS of a commutative operation, not the on LHS.
1043 static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
1044 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
1046 if (N->isLeaf() && dynamic_cast<IntInit*>(N->getLeafValue()))
1052 /// canPatternMatch - If it is impossible for this pattern to match on this
1053 /// target, fill in Reason and return false. Otherwise, return true. This is
1054 /// used as a sanity check for .td files (to prevent people from writing stuff
1055 /// that can never possibly work), and to prevent the pattern permuter from
1056 /// generating stuff that is useless.
1057 bool TreePatternNode::canPatternMatch(std::string &Reason,
1058 const CodeGenDAGPatterns &CDP) {
1059 if (isLeaf()) return true;
1061 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1062 if (!getChild(i)->canPatternMatch(Reason, CDP))
1065 // If this is an intrinsic, handle cases that would make it not match. For
1066 // example, if an operand is required to be an immediate.
1067 if (getOperator()->isSubClassOf("Intrinsic")) {
1072 // If this node is a commutative operator, check that the LHS isn't an
1074 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
1075 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
1076 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
1077 // Scan all of the operands of the node and make sure that only the last one
1078 // is a constant node, unless the RHS also is.
1079 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
1080 bool Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
1081 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
1082 if (OnlyOnRHSOfCommutative(getChild(i))) {
1083 Reason="Immediate value must be on the RHS of commutative operators!";
1092 //===----------------------------------------------------------------------===//
1093 // TreePattern implementation
1096 TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
1097 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
1098 isInputPattern = isInput;
1099 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
1100 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
1103 TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
1104 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
1105 isInputPattern = isInput;
1106 Trees.push_back(ParseTreePattern(Pat));
1109 TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
1110 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
1111 isInputPattern = isInput;
1112 Trees.push_back(Pat);
1117 void TreePattern::error(const std::string &Msg) const {
1119 throw TGError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
1122 TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
1123 DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
1124 if (!OpDef) error("Pattern has unexpected operator type!");
1125 Record *Operator = OpDef->getDef();
1127 if (Operator->isSubClassOf("ValueType")) {
1128 // If the operator is a ValueType, then this must be "type cast" of a leaf
1130 if (Dag->getNumArgs() != 1)
1131 error("Type cast only takes one operand!");
1133 Init *Arg = Dag->getArg(0);
1134 TreePatternNode *New;
1135 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
1136 Record *R = DI->getDef();
1137 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
1138 Dag->setArg(0, new DagInit(DI, "",
1139 std::vector<std::pair<Init*, std::string> >()));
1140 return ParseTreePattern(Dag);
1142 New = new TreePatternNode(DI);
1143 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
1144 New = ParseTreePattern(DI);
1145 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
1146 New = new TreePatternNode(II);
1147 if (!Dag->getArgName(0).empty())
1148 error("Constant int argument should not have a name!");
1149 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
1150 // Turn this into an IntInit.
1151 Init *II = BI->convertInitializerTo(new IntRecTy());
1152 if (II == 0 || !dynamic_cast<IntInit*>(II))
1153 error("Bits value must be constants!");
1155 New = new TreePatternNode(dynamic_cast<IntInit*>(II));
1156 if (!Dag->getArgName(0).empty())
1157 error("Constant int argument should not have a name!");
1160 error("Unknown leaf value for tree pattern!");
1164 // Apply the type cast.
1165 New->UpdateNodeType(getValueType(Operator), *this);
1166 if (New->getNumChildren() == 0)
1167 New->setName(Dag->getArgName(0));
1171 // Verify that this is something that makes sense for an operator.
1172 if (!Operator->isSubClassOf("PatFrag") &&
1173 !Operator->isSubClassOf("SDNode") &&
1174 !Operator->isSubClassOf("Instruction") &&
1175 !Operator->isSubClassOf("SDNodeXForm") &&
1176 !Operator->isSubClassOf("Intrinsic") &&
1177 Operator->getName() != "set" &&
1178 Operator->getName() != "implicit" &&
1179 Operator->getName() != "parallel")
1180 error("Unrecognized node '" + Operator->getName() + "'!");
1182 // Check to see if this is something that is illegal in an input pattern.
1183 if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
1184 Operator->isSubClassOf("SDNodeXForm")))
1185 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
1187 std::vector<TreePatternNode*> Children;
1189 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
1190 Init *Arg = Dag->getArg(i);
1191 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
1192 Children.push_back(ParseTreePattern(DI));
1193 if (Children.back()->getName().empty())
1194 Children.back()->setName(Dag->getArgName(i));
1195 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
1196 Record *R = DefI->getDef();
1197 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
1198 // TreePatternNode if its own.
1199 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
1200 Dag->setArg(i, new DagInit(DefI, "",
1201 std::vector<std::pair<Init*, std::string> >()));
1202 --i; // Revisit this node...
1204 TreePatternNode *Node = new TreePatternNode(DefI);
1205 Node->setName(Dag->getArgName(i));
1206 Children.push_back(Node);
1209 if (R->getName() == "node") {
1210 if (Dag->getArgName(i).empty())
1211 error("'node' argument requires a name to match with operand list");
1212 Args.push_back(Dag->getArgName(i));
1215 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
1216 TreePatternNode *Node = new TreePatternNode(II);
1217 if (!Dag->getArgName(i).empty())
1218 error("Constant int argument should not have a name!");
1219 Children.push_back(Node);
1220 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
1221 // Turn this into an IntInit.
1222 Init *II = BI->convertInitializerTo(new IntRecTy());
1223 if (II == 0 || !dynamic_cast<IntInit*>(II))
1224 error("Bits value must be constants!");
1226 TreePatternNode *Node = new TreePatternNode(dynamic_cast<IntInit*>(II));
1227 if (!Dag->getArgName(i).empty())
1228 error("Constant int argument should not have a name!");
1229 Children.push_back(Node);
1234 error("Unknown leaf value for tree pattern!");
1238 // If the operator is an intrinsic, then this is just syntactic sugar for for
1239 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
1240 // convert the intrinsic name to a number.
1241 if (Operator->isSubClassOf("Intrinsic")) {
1242 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
1243 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
1245 // If this intrinsic returns void, it must have side-effects and thus a
1247 if (Int.IS.RetVTs[0] == MVT::isVoid) {
1248 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
1249 } else if (Int.ModRef != CodeGenIntrinsic::NoMem) {
1250 // Has side-effects, requires chain.
1251 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
1253 // Otherwise, no chain.
1254 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
1257 TreePatternNode *IIDNode = new TreePatternNode(new IntInit(IID));
1258 Children.insert(Children.begin(), IIDNode);
1261 TreePatternNode *Result = new TreePatternNode(Operator, Children);
1262 Result->setName(Dag->getName());
1266 /// InferAllTypes - Infer/propagate as many types throughout the expression
1267 /// patterns as possible. Return true if all types are inferred, false
1268 /// otherwise. Throw an exception if a type contradiction is found.
1269 bool TreePattern::InferAllTypes() {
1270 bool MadeChange = true;
1271 while (MadeChange) {
1273 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1274 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
1277 bool HasUnresolvedTypes = false;
1278 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1279 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
1280 return !HasUnresolvedTypes;
1283 void TreePattern::print(raw_ostream &OS) const {
1284 OS << getRecord()->getName();
1285 if (!Args.empty()) {
1286 OS << "(" << Args[0];
1287 for (unsigned i = 1, e = Args.size(); i != e; ++i)
1288 OS << ", " << Args[i];
1293 if (Trees.size() > 1)
1295 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
1297 Trees[i]->print(OS);
1301 if (Trees.size() > 1)
1305 void TreePattern::dump() const { print(errs()); }
1307 //===----------------------------------------------------------------------===//
1308 // CodeGenDAGPatterns implementation
1311 // FIXME: REMOVE OSTREAM ARGUMENT
1312 CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) : Records(R) {
1313 Intrinsics = LoadIntrinsics(Records, false);
1314 TgtIntrinsics = LoadIntrinsics(Records, true);
1316 ParseNodeTransforms();
1317 ParseComplexPatterns();
1318 ParsePatternFragments();
1319 ParseDefaultOperands();
1320 ParseInstructions();
1323 // Generate variants. For example, commutative patterns can match
1324 // multiple ways. Add them to PatternsToMatch as well.
1327 // Infer instruction flags. For example, we can detect loads,
1328 // stores, and side effects in many cases by examining an
1329 // instruction's pattern.
1330 InferInstructionFlags();
1333 CodeGenDAGPatterns::~CodeGenDAGPatterns() {
1334 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
1335 E = PatternFragments.end(); I != E; ++I)
1340 Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
1341 Record *N = Records.getDef(Name);
1342 if (!N || !N->isSubClassOf("SDNode")) {
1343 errs() << "Error getting SDNode '" << Name << "'!\n";
1349 // Parse all of the SDNode definitions for the target, populating SDNodes.
1350 void CodeGenDAGPatterns::ParseNodeInfo() {
1351 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
1352 while (!Nodes.empty()) {
1353 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
1357 // Get the builtin intrinsic nodes.
1358 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
1359 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
1360 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
1363 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
1364 /// map, and emit them to the file as functions.
1365 void CodeGenDAGPatterns::ParseNodeTransforms() {
1366 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
1367 while (!Xforms.empty()) {
1368 Record *XFormNode = Xforms.back();
1369 Record *SDNode = XFormNode->getValueAsDef("Opcode");
1370 std::string Code = XFormNode->getValueAsCode("XFormFunction");
1371 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
1377 void CodeGenDAGPatterns::ParseComplexPatterns() {
1378 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
1379 while (!AMs.empty()) {
1380 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
1386 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
1387 /// file, building up the PatternFragments map. After we've collected them all,
1388 /// inline fragments together as necessary, so that there are no references left
1389 /// inside a pattern fragment to a pattern fragment.
1391 void CodeGenDAGPatterns::ParsePatternFragments() {
1392 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
1394 // First step, parse all of the fragments.
1395 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1396 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
1397 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
1398 PatternFragments[Fragments[i]] = P;
1400 // Validate the argument list, converting it to set, to discard duplicates.
1401 std::vector<std::string> &Args = P->getArgList();
1402 std::set<std::string> OperandsSet(Args.begin(), Args.end());
1404 if (OperandsSet.count(""))
1405 P->error("Cannot have unnamed 'node' values in pattern fragment!");
1407 // Parse the operands list.
1408 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
1409 DefInit *OpsOp = dynamic_cast<DefInit*>(OpsList->getOperator());
1410 // Special cases: ops == outs == ins. Different names are used to
1411 // improve readability.
1413 (OpsOp->getDef()->getName() != "ops" &&
1414 OpsOp->getDef()->getName() != "outs" &&
1415 OpsOp->getDef()->getName() != "ins"))
1416 P->error("Operands list should start with '(ops ... '!");
1418 // Copy over the arguments.
1420 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
1421 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
1422 static_cast<DefInit*>(OpsList->getArg(j))->
1423 getDef()->getName() != "node")
1424 P->error("Operands list should all be 'node' values.");
1425 if (OpsList->getArgName(j).empty())
1426 P->error("Operands list should have names for each operand!");
1427 if (!OperandsSet.count(OpsList->getArgName(j)))
1428 P->error("'" + OpsList->getArgName(j) +
1429 "' does not occur in pattern or was multiply specified!");
1430 OperandsSet.erase(OpsList->getArgName(j));
1431 Args.push_back(OpsList->getArgName(j));
1434 if (!OperandsSet.empty())
1435 P->error("Operands list does not contain an entry for operand '" +
1436 *OperandsSet.begin() + "'!");
1438 // If there is a code init for this fragment, keep track of the fact that
1439 // this fragment uses it.
1440 std::string Code = Fragments[i]->getValueAsCode("Predicate");
1442 P->getOnlyTree()->addPredicateFn("Predicate_"+Fragments[i]->getName());
1444 // If there is a node transformation corresponding to this, keep track of
1446 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
1447 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
1448 P->getOnlyTree()->setTransformFn(Transform);
1451 // Now that we've parsed all of the tree fragments, do a closure on them so
1452 // that there are not references to PatFrags left inside of them.
1453 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1454 TreePattern *ThePat = PatternFragments[Fragments[i]];
1455 ThePat->InlinePatternFragments();
1457 // Infer as many types as possible. Don't worry about it if we don't infer
1458 // all of them, some may depend on the inputs of the pattern.
1460 ThePat->InferAllTypes();
1462 // If this pattern fragment is not supported by this target (no types can
1463 // satisfy its constraints), just ignore it. If the bogus pattern is
1464 // actually used by instructions, the type consistency error will be
1468 // If debugging, print out the pattern fragment result.
1469 DEBUG(ThePat->dump());
1473 void CodeGenDAGPatterns::ParseDefaultOperands() {
1474 std::vector<Record*> DefaultOps[2];
1475 DefaultOps[0] = Records.getAllDerivedDefinitions("PredicateOperand");
1476 DefaultOps[1] = Records.getAllDerivedDefinitions("OptionalDefOperand");
1478 // Find some SDNode.
1479 assert(!SDNodes.empty() && "No SDNodes parsed?");
1480 Init *SomeSDNode = new DefInit(SDNodes.begin()->first);
1482 for (unsigned iter = 0; iter != 2; ++iter) {
1483 for (unsigned i = 0, e = DefaultOps[iter].size(); i != e; ++i) {
1484 DagInit *DefaultInfo = DefaultOps[iter][i]->getValueAsDag("DefaultOps");
1486 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
1487 // SomeSDnode so that we can parse this.
1488 std::vector<std::pair<Init*, std::string> > Ops;
1489 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
1490 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
1491 DefaultInfo->getArgName(op)));
1492 DagInit *DI = new DagInit(SomeSDNode, "", Ops);
1494 // Create a TreePattern to parse this.
1495 TreePattern P(DefaultOps[iter][i], DI, false, *this);
1496 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
1498 // Copy the operands over into a DAGDefaultOperand.
1499 DAGDefaultOperand DefaultOpInfo;
1501 TreePatternNode *T = P.getTree(0);
1502 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
1503 TreePatternNode *TPN = T->getChild(op);
1504 while (TPN->ApplyTypeConstraints(P, false))
1505 /* Resolve all types */;
1507 if (TPN->ContainsUnresolvedType()) {
1509 throw "Value #" + utostr(i) + " of PredicateOperand '" +
1510 DefaultOps[iter][i]->getName() + "' doesn't have a concrete type!";
1512 throw "Value #" + utostr(i) + " of OptionalDefOperand '" +
1513 DefaultOps[iter][i]->getName() + "' doesn't have a concrete type!";
1515 DefaultOpInfo.DefaultOps.push_back(TPN);
1518 // Insert it into the DefaultOperands map so we can find it later.
1519 DefaultOperands[DefaultOps[iter][i]] = DefaultOpInfo;
1524 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
1525 /// instruction input. Return true if this is a real use.
1526 static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
1527 std::map<std::string, TreePatternNode*> &InstInputs,
1528 std::vector<Record*> &InstImpInputs) {
1529 // No name -> not interesting.
1530 if (Pat->getName().empty()) {
1531 if (Pat->isLeaf()) {
1532 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1533 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1534 I->error("Input " + DI->getDef()->getName() + " must be named!");
1535 else if (DI && DI->getDef()->isSubClassOf("Register"))
1536 InstImpInputs.push_back(DI->getDef());
1542 if (Pat->isLeaf()) {
1543 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1544 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
1547 Rec = Pat->getOperator();
1550 // SRCVALUE nodes are ignored.
1551 if (Rec->getName() == "srcvalue")
1554 TreePatternNode *&Slot = InstInputs[Pat->getName()];
1559 if (Slot->isLeaf()) {
1560 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
1562 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
1563 SlotRec = Slot->getOperator();
1566 // Ensure that the inputs agree if we've already seen this input.
1568 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1569 if (Slot->getExtTypes() != Pat->getExtTypes())
1570 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1575 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
1576 /// part of "I", the instruction), computing the set of inputs and outputs of
1577 /// the pattern. Report errors if we see anything naughty.
1578 void CodeGenDAGPatterns::
1579 FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
1580 std::map<std::string, TreePatternNode*> &InstInputs,
1581 std::map<std::string, TreePatternNode*>&InstResults,
1582 std::vector<Record*> &InstImpInputs,
1583 std::vector<Record*> &InstImpResults) {
1584 if (Pat->isLeaf()) {
1585 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1586 if (!isUse && Pat->getTransformFn())
1587 I->error("Cannot specify a transform function for a non-input value!");
1589 } else if (Pat->getOperator()->getName() == "implicit") {
1590 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1591 TreePatternNode *Dest = Pat->getChild(i);
1592 if (!Dest->isLeaf())
1593 I->error("implicitly defined value should be a register!");
1595 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1596 if (!Val || !Val->getDef()->isSubClassOf("Register"))
1597 I->error("implicitly defined value should be a register!");
1598 InstImpResults.push_back(Val->getDef());
1601 } else if (Pat->getOperator()->getName() != "set") {
1602 // If this is not a set, verify that the children nodes are not void typed,
1604 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1605 if (Pat->getChild(i)->getExtTypeNum(0) == MVT::isVoid)
1606 I->error("Cannot have void nodes inside of patterns!");
1607 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
1608 InstImpInputs, InstImpResults);
1611 // If this is a non-leaf node with no children, treat it basically as if
1612 // it were a leaf. This handles nodes like (imm).
1613 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1615 if (!isUse && Pat->getTransformFn())
1616 I->error("Cannot specify a transform function for a non-input value!");
1620 // Otherwise, this is a set, validate and collect instruction results.
1621 if (Pat->getNumChildren() == 0)
1622 I->error("set requires operands!");
1624 if (Pat->getTransformFn())
1625 I->error("Cannot specify a transform function on a set node!");
1627 // Check the set destinations.
1628 unsigned NumDests = Pat->getNumChildren()-1;
1629 for (unsigned i = 0; i != NumDests; ++i) {
1630 TreePatternNode *Dest = Pat->getChild(i);
1631 if (!Dest->isLeaf())
1632 I->error("set destination should be a register!");
1634 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1636 I->error("set destination should be a register!");
1638 if (Val->getDef()->isSubClassOf("RegisterClass") ||
1639 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
1640 if (Dest->getName().empty())
1641 I->error("set destination must have a name!");
1642 if (InstResults.count(Dest->getName()))
1643 I->error("cannot set '" + Dest->getName() +"' multiple times");
1644 InstResults[Dest->getName()] = Dest;
1645 } else if (Val->getDef()->isSubClassOf("Register")) {
1646 InstImpResults.push_back(Val->getDef());
1648 I->error("set destination should be a register!");
1652 // Verify and collect info from the computation.
1653 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
1654 InstInputs, InstResults,
1655 InstImpInputs, InstImpResults);
1658 //===----------------------------------------------------------------------===//
1659 // Instruction Analysis
1660 //===----------------------------------------------------------------------===//
1662 class InstAnalyzer {
1663 const CodeGenDAGPatterns &CDP;
1666 bool &HasSideEffects;
1668 InstAnalyzer(const CodeGenDAGPatterns &cdp,
1669 bool &maystore, bool &mayload, bool &hse)
1670 : CDP(cdp), mayStore(maystore), mayLoad(mayload), HasSideEffects(hse){
1673 /// Analyze - Analyze the specified instruction, returning true if the
1674 /// instruction had a pattern.
1675 bool Analyze(Record *InstRecord) {
1676 const TreePattern *Pattern = CDP.getInstruction(InstRecord).getPattern();
1679 return false; // No pattern.
1682 // FIXME: Assume only the first tree is the pattern. The others are clobber
1684 AnalyzeNode(Pattern->getTree(0));
1689 void AnalyzeNode(const TreePatternNode *N) {
1691 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
1692 Record *LeafRec = DI->getDef();
1693 // Handle ComplexPattern leaves.
1694 if (LeafRec->isSubClassOf("ComplexPattern")) {
1695 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
1696 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
1697 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
1698 if (CP.hasProperty(SDNPSideEffect)) HasSideEffects = true;
1704 // Analyze children.
1705 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1706 AnalyzeNode(N->getChild(i));
1708 // Ignore set nodes, which are not SDNodes.
1709 if (N->getOperator()->getName() == "set")
1712 // Get information about the SDNode for the operator.
1713 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N->getOperator());
1715 // Notice properties of the node.
1716 if (OpInfo.hasProperty(SDNPMayStore)) mayStore = true;
1717 if (OpInfo.hasProperty(SDNPMayLoad)) mayLoad = true;
1718 if (OpInfo.hasProperty(SDNPSideEffect)) HasSideEffects = true;
1720 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
1721 // If this is an intrinsic, analyze it.
1722 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
1723 mayLoad = true;// These may load memory.
1725 if (IntInfo->ModRef >= CodeGenIntrinsic::WriteArgMem)
1726 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
1728 if (IntInfo->ModRef >= CodeGenIntrinsic::WriteMem)
1729 // WriteMem intrinsics can have other strange effects.
1730 HasSideEffects = true;
1736 static void InferFromPattern(const CodeGenInstruction &Inst,
1737 bool &MayStore, bool &MayLoad,
1738 bool &HasSideEffects,
1739 const CodeGenDAGPatterns &CDP) {
1740 MayStore = MayLoad = HasSideEffects = false;
1743 InstAnalyzer(CDP, MayStore, MayLoad, HasSideEffects).Analyze(Inst.TheDef);
1745 // InstAnalyzer only correctly analyzes mayStore/mayLoad so far.
1746 if (Inst.mayStore) { // If the .td file explicitly sets mayStore, use it.
1747 // If we decided that this is a store from the pattern, then the .td file
1748 // entry is redundant.
1751 "Warning: mayStore flag explicitly set on instruction '%s'"
1752 " but flag already inferred from pattern.\n",
1753 Inst.TheDef->getName().c_str());
1757 if (Inst.mayLoad) { // If the .td file explicitly sets mayLoad, use it.
1758 // If we decided that this is a load from the pattern, then the .td file
1759 // entry is redundant.
1762 "Warning: mayLoad flag explicitly set on instruction '%s'"
1763 " but flag already inferred from pattern.\n",
1764 Inst.TheDef->getName().c_str());
1768 if (Inst.neverHasSideEffects) {
1770 fprintf(stderr, "Warning: neverHasSideEffects set on instruction '%s' "
1771 "which already has a pattern\n", Inst.TheDef->getName().c_str());
1772 HasSideEffects = false;
1775 if (Inst.hasSideEffects) {
1777 fprintf(stderr, "Warning: hasSideEffects set on instruction '%s' "
1778 "which already inferred this.\n", Inst.TheDef->getName().c_str());
1779 HasSideEffects = true;
1783 /// ParseInstructions - Parse all of the instructions, inlining and resolving
1784 /// any fragments involved. This populates the Instructions list with fully
1785 /// resolved instructions.
1786 void CodeGenDAGPatterns::ParseInstructions() {
1787 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
1789 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
1792 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
1793 LI = Instrs[i]->getValueAsListInit("Pattern");
1795 // If there is no pattern, only collect minimal information about the
1796 // instruction for its operand list. We have to assume that there is one
1797 // result, as we have no detailed info.
1798 if (!LI || LI->getSize() == 0) {
1799 std::vector<Record*> Results;
1800 std::vector<Record*> Operands;
1802 CodeGenInstruction &InstInfo =Target.getInstruction(Instrs[i]->getName());
1804 if (InstInfo.OperandList.size() != 0) {
1805 if (InstInfo.NumDefs == 0) {
1806 // These produce no results
1807 for (unsigned j = 0, e = InstInfo.OperandList.size(); j < e; ++j)
1808 Operands.push_back(InstInfo.OperandList[j].Rec);
1810 // Assume the first operand is the result.
1811 Results.push_back(InstInfo.OperandList[0].Rec);
1813 // The rest are inputs.
1814 for (unsigned j = 1, e = InstInfo.OperandList.size(); j < e; ++j)
1815 Operands.push_back(InstInfo.OperandList[j].Rec);
1819 // Create and insert the instruction.
1820 std::vector<Record*> ImpResults;
1821 std::vector<Record*> ImpOperands;
1822 Instructions.insert(std::make_pair(Instrs[i],
1823 DAGInstruction(0, Results, Operands, ImpResults,
1825 continue; // no pattern.
1828 // Parse the instruction.
1829 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
1830 // Inline pattern fragments into it.
1831 I->InlinePatternFragments();
1833 // Infer as many types as possible. If we cannot infer all of them, we can
1834 // never do anything with this instruction pattern: report it to the user.
1835 if (!I->InferAllTypes())
1836 I->error("Could not infer all types in pattern!");
1838 // InstInputs - Keep track of all of the inputs of the instruction, along
1839 // with the record they are declared as.
1840 std::map<std::string, TreePatternNode*> InstInputs;
1842 // InstResults - Keep track of all the virtual registers that are 'set'
1843 // in the instruction, including what reg class they are.
1844 std::map<std::string, TreePatternNode*> InstResults;
1846 std::vector<Record*> InstImpInputs;
1847 std::vector<Record*> InstImpResults;
1849 // Verify that the top-level forms in the instruction are of void type, and
1850 // fill in the InstResults map.
1851 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
1852 TreePatternNode *Pat = I->getTree(j);
1853 if (Pat->getExtTypeNum(0) != MVT::isVoid)
1854 I->error("Top-level forms in instruction pattern should have"
1857 // Find inputs and outputs, and verify the structure of the uses/defs.
1858 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
1859 InstImpInputs, InstImpResults);
1862 // Now that we have inputs and outputs of the pattern, inspect the operands
1863 // list for the instruction. This determines the order that operands are
1864 // added to the machine instruction the node corresponds to.
1865 unsigned NumResults = InstResults.size();
1867 // Parse the operands list from the (ops) list, validating it.
1868 assert(I->getArgList().empty() && "Args list should still be empty here!");
1869 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
1871 // Check that all of the results occur first in the list.
1872 std::vector<Record*> Results;
1873 TreePatternNode *Res0Node = NULL;
1874 for (unsigned i = 0; i != NumResults; ++i) {
1875 if (i == CGI.OperandList.size())
1876 I->error("'" + InstResults.begin()->first +
1877 "' set but does not appear in operand list!");
1878 const std::string &OpName = CGI.OperandList[i].Name;
1880 // Check that it exists in InstResults.
1881 TreePatternNode *RNode = InstResults[OpName];
1883 I->error("Operand $" + OpName + " does not exist in operand list!");
1887 Record *R = dynamic_cast<DefInit*>(RNode->getLeafValue())->getDef();
1889 I->error("Operand $" + OpName + " should be a set destination: all "
1890 "outputs must occur before inputs in operand list!");
1892 if (CGI.OperandList[i].Rec != R)
1893 I->error("Operand $" + OpName + " class mismatch!");
1895 // Remember the return type.
1896 Results.push_back(CGI.OperandList[i].Rec);
1898 // Okay, this one checks out.
1899 InstResults.erase(OpName);
1902 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
1903 // the copy while we're checking the inputs.
1904 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
1906 std::vector<TreePatternNode*> ResultNodeOperands;
1907 std::vector<Record*> Operands;
1908 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
1909 CodeGenInstruction::OperandInfo &Op = CGI.OperandList[i];
1910 const std::string &OpName = Op.Name;
1912 I->error("Operand #" + utostr(i) + " in operands list has no name!");
1914 if (!InstInputsCheck.count(OpName)) {
1915 // If this is an predicate operand or optional def operand with an
1916 // DefaultOps set filled in, we can ignore this. When we codegen it,
1917 // we will do so as always executed.
1918 if (Op.Rec->isSubClassOf("PredicateOperand") ||
1919 Op.Rec->isSubClassOf("OptionalDefOperand")) {
1920 // Does it have a non-empty DefaultOps field? If so, ignore this
1922 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
1925 I->error("Operand $" + OpName +
1926 " does not appear in the instruction pattern");
1928 TreePatternNode *InVal = InstInputsCheck[OpName];
1929 InstInputsCheck.erase(OpName); // It occurred, remove from map.
1931 if (InVal->isLeaf() &&
1932 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
1933 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
1934 if (Op.Rec != InRec && !InRec->isSubClassOf("ComplexPattern"))
1935 I->error("Operand $" + OpName + "'s register class disagrees"
1936 " between the operand and pattern");
1938 Operands.push_back(Op.Rec);
1940 // Construct the result for the dest-pattern operand list.
1941 TreePatternNode *OpNode = InVal->clone();
1943 // No predicate is useful on the result.
1944 OpNode->clearPredicateFns();
1946 // Promote the xform function to be an explicit node if set.
1947 if (Record *Xform = OpNode->getTransformFn()) {
1948 OpNode->setTransformFn(0);
1949 std::vector<TreePatternNode*> Children;
1950 Children.push_back(OpNode);
1951 OpNode = new TreePatternNode(Xform, Children);
1954 ResultNodeOperands.push_back(OpNode);
1957 if (!InstInputsCheck.empty())
1958 I->error("Input operand $" + InstInputsCheck.begin()->first +
1959 " occurs in pattern but not in operands list!");
1961 TreePatternNode *ResultPattern =
1962 new TreePatternNode(I->getRecord(), ResultNodeOperands);
1963 // Copy fully inferred output node type to instruction result pattern.
1965 ResultPattern->setTypes(Res0Node->getExtTypes());
1967 // Create and insert the instruction.
1968 // FIXME: InstImpResults and InstImpInputs should not be part of
1970 DAGInstruction TheInst(I, Results, Operands, InstImpResults, InstImpInputs);
1971 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
1973 // Use a temporary tree pattern to infer all types and make sure that the
1974 // constructed result is correct. This depends on the instruction already
1975 // being inserted into the Instructions map.
1976 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
1977 Temp.InferAllTypes();
1979 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
1980 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
1985 // If we can, convert the instructions to be patterns that are matched!
1986 for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
1987 E = Instructions.end(); II != E; ++II) {
1988 DAGInstruction &TheInst = II->second;
1989 const TreePattern *I = TheInst.getPattern();
1990 if (I == 0) continue; // No pattern.
1992 // FIXME: Assume only the first tree is the pattern. The others are clobber
1994 TreePatternNode *Pattern = I->getTree(0);
1995 TreePatternNode *SrcPattern;
1996 if (Pattern->getOperator()->getName() == "set") {
1997 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
1999 // Not a set (store or something?)
2000 SrcPattern = Pattern;
2004 if (!SrcPattern->canPatternMatch(Reason, *this))
2005 I->error("Instruction can never match: " + Reason);
2007 Record *Instr = II->first;
2008 TreePatternNode *DstPattern = TheInst.getResultPattern();
2010 push_back(PatternToMatch(Instr->getValueAsListInit("Predicates"),
2011 SrcPattern, DstPattern, TheInst.getImpResults(),
2012 Instr->getValueAsInt("AddedComplexity")));
2017 void CodeGenDAGPatterns::InferInstructionFlags() {
2018 std::map<std::string, CodeGenInstruction> &InstrDescs =
2019 Target.getInstructions();
2020 for (std::map<std::string, CodeGenInstruction>::iterator
2021 II = InstrDescs.begin(), E = InstrDescs.end(); II != E; ++II) {
2022 CodeGenInstruction &InstInfo = II->second;
2023 // Determine properties of the instruction from its pattern.
2024 bool MayStore, MayLoad, HasSideEffects;
2025 InferFromPattern(InstInfo, MayStore, MayLoad, HasSideEffects, *this);
2026 InstInfo.mayStore = MayStore;
2027 InstInfo.mayLoad = MayLoad;
2028 InstInfo.hasSideEffects = HasSideEffects;
2032 void CodeGenDAGPatterns::ParsePatterns() {
2033 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
2035 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
2036 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
2037 DefInit *OpDef = dynamic_cast<DefInit*>(Tree->getOperator());
2038 Record *Operator = OpDef->getDef();
2039 TreePattern *Pattern;
2040 if (Operator->getName() != "parallel")
2041 Pattern = new TreePattern(Patterns[i], Tree, true, *this);
2043 std::vector<Init*> Values;
2045 for (unsigned j = 0, ee = Tree->getNumArgs(); j != ee; ++j) {
2046 Values.push_back(Tree->getArg(j));
2047 TypedInit *TArg = dynamic_cast<TypedInit*>(Tree->getArg(j));
2049 errs() << "In dag: " << Tree->getAsString();
2050 errs() << " -- Untyped argument in pattern\n";
2051 assert(0 && "Untyped argument in pattern");
2054 ListTy = resolveTypes(ListTy, TArg->getType());
2056 errs() << "In dag: " << Tree->getAsString();
2057 errs() << " -- Incompatible types in pattern arguments\n";
2058 assert(0 && "Incompatible types in pattern arguments");
2062 ListTy = TArg->getType();
2065 ListInit *LI = new ListInit(Values, new ListRecTy(ListTy));
2066 Pattern = new TreePattern(Patterns[i], LI, true, *this);
2069 // Inline pattern fragments into it.
2070 Pattern->InlinePatternFragments();
2072 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
2073 if (LI->getSize() == 0) continue; // no pattern.
2075 // Parse the instruction.
2076 TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
2078 // Inline pattern fragments into it.
2079 Result->InlinePatternFragments();
2081 if (Result->getNumTrees() != 1)
2082 Result->error("Cannot handle instructions producing instructions "
2083 "with temporaries yet!");
2085 bool IterateInference;
2086 bool InferredAllPatternTypes, InferredAllResultTypes;
2088 // Infer as many types as possible. If we cannot infer all of them, we
2089 // can never do anything with this pattern: report it to the user.
2090 InferredAllPatternTypes = Pattern->InferAllTypes();
2092 // Infer as many types as possible. If we cannot infer all of them, we
2093 // can never do anything with this pattern: report it to the user.
2094 InferredAllResultTypes = Result->InferAllTypes();
2096 // Apply the type of the result to the source pattern. This helps us
2097 // resolve cases where the input type is known to be a pointer type (which
2098 // is considered resolved), but the result knows it needs to be 32- or
2099 // 64-bits. Infer the other way for good measure.
2100 IterateInference = Pattern->getTree(0)->
2101 UpdateNodeType(Result->getTree(0)->getExtTypes(), *Result);
2102 IterateInference |= Result->getTree(0)->
2103 UpdateNodeType(Pattern->getTree(0)->getExtTypes(), *Result);
2104 } while (IterateInference);
2106 // Verify that we inferred enough types that we can do something with the
2107 // pattern and result. If these fire the user has to add type casts.
2108 if (!InferredAllPatternTypes)
2109 Pattern->error("Could not infer all types in pattern!");
2110 if (!InferredAllResultTypes)
2111 Result->error("Could not infer all types in pattern result!");
2113 // Validate that the input pattern is correct.
2114 std::map<std::string, TreePatternNode*> InstInputs;
2115 std::map<std::string, TreePatternNode*> InstResults;
2116 std::vector<Record*> InstImpInputs;
2117 std::vector<Record*> InstImpResults;
2118 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
2119 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
2120 InstInputs, InstResults,
2121 InstImpInputs, InstImpResults);
2123 // Promote the xform function to be an explicit node if set.
2124 TreePatternNode *DstPattern = Result->getOnlyTree();
2125 std::vector<TreePatternNode*> ResultNodeOperands;
2126 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
2127 TreePatternNode *OpNode = DstPattern->getChild(ii);
2128 if (Record *Xform = OpNode->getTransformFn()) {
2129 OpNode->setTransformFn(0);
2130 std::vector<TreePatternNode*> Children;
2131 Children.push_back(OpNode);
2132 OpNode = new TreePatternNode(Xform, Children);
2134 ResultNodeOperands.push_back(OpNode);
2136 DstPattern = Result->getOnlyTree();
2137 if (!DstPattern->isLeaf())
2138 DstPattern = new TreePatternNode(DstPattern->getOperator(),
2139 ResultNodeOperands);
2140 DstPattern->setTypes(Result->getOnlyTree()->getExtTypes());
2141 TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
2142 Temp.InferAllTypes();
2145 if (!Pattern->getTree(0)->canPatternMatch(Reason, *this))
2146 Pattern->error("Pattern can never match: " + Reason);
2149 push_back(PatternToMatch(Patterns[i]->getValueAsListInit("Predicates"),
2150 Pattern->getTree(0),
2151 Temp.getOnlyTree(), InstImpResults,
2152 Patterns[i]->getValueAsInt("AddedComplexity")));
2156 /// CombineChildVariants - Given a bunch of permutations of each child of the
2157 /// 'operator' node, put them together in all possible ways.
2158 static void CombineChildVariants(TreePatternNode *Orig,
2159 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
2160 std::vector<TreePatternNode*> &OutVariants,
2161 CodeGenDAGPatterns &CDP,
2162 const MultipleUseVarSet &DepVars) {
2163 // Make sure that each operand has at least one variant to choose from.
2164 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2165 if (ChildVariants[i].empty())
2168 // The end result is an all-pairs construction of the resultant pattern.
2169 std::vector<unsigned> Idxs;
2170 Idxs.resize(ChildVariants.size());
2174 if (DebugFlag && !Idxs.empty()) {
2175 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
2176 for (unsigned i = 0; i < Idxs.size(); ++i) {
2177 errs() << Idxs[i] << " ";
2182 // Create the variant and add it to the output list.
2183 std::vector<TreePatternNode*> NewChildren;
2184 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2185 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
2186 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
2188 // Copy over properties.
2189 R->setName(Orig->getName());
2190 R->setPredicateFns(Orig->getPredicateFns());
2191 R->setTransformFn(Orig->getTransformFn());
2192 R->setTypes(Orig->getExtTypes());
2194 // If this pattern cannot match, do not include it as a variant.
2195 std::string ErrString;
2196 if (!R->canPatternMatch(ErrString, CDP)) {
2199 bool AlreadyExists = false;
2201 // Scan to see if this pattern has already been emitted. We can get
2202 // duplication due to things like commuting:
2203 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
2204 // which are the same pattern. Ignore the dups.
2205 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
2206 if (R->isIsomorphicTo(OutVariants[i], DepVars)) {
2207 AlreadyExists = true;
2214 OutVariants.push_back(R);
2217 // Increment indices to the next permutation by incrementing the
2218 // indicies from last index backward, e.g., generate the sequence
2219 // [0, 0], [0, 1], [1, 0], [1, 1].
2221 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
2222 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
2227 NotDone = (IdxsIdx >= 0);
2231 /// CombineChildVariants - A helper function for binary operators.
2233 static void CombineChildVariants(TreePatternNode *Orig,
2234 const std::vector<TreePatternNode*> &LHS,
2235 const std::vector<TreePatternNode*> &RHS,
2236 std::vector<TreePatternNode*> &OutVariants,
2237 CodeGenDAGPatterns &CDP,
2238 const MultipleUseVarSet &DepVars) {
2239 std::vector<std::vector<TreePatternNode*> > ChildVariants;
2240 ChildVariants.push_back(LHS);
2241 ChildVariants.push_back(RHS);
2242 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
2246 static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
2247 std::vector<TreePatternNode *> &Children) {
2248 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
2249 Record *Operator = N->getOperator();
2251 // Only permit raw nodes.
2252 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
2253 N->getTransformFn()) {
2254 Children.push_back(N);
2258 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
2259 Children.push_back(N->getChild(0));
2261 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
2263 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
2264 Children.push_back(N->getChild(1));
2266 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
2269 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
2270 /// the (potentially recursive) pattern by using algebraic laws.
2272 static void GenerateVariantsOf(TreePatternNode *N,
2273 std::vector<TreePatternNode*> &OutVariants,
2274 CodeGenDAGPatterns &CDP,
2275 const MultipleUseVarSet &DepVars) {
2276 // We cannot permute leaves.
2278 OutVariants.push_back(N);
2282 // Look up interesting info about the node.
2283 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
2285 // If this node is associative, re-associate.
2286 if (NodeInfo.hasProperty(SDNPAssociative)) {
2287 // Re-associate by pulling together all of the linked operators
2288 std::vector<TreePatternNode*> MaximalChildren;
2289 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
2291 // Only handle child sizes of 3. Otherwise we'll end up trying too many
2293 if (MaximalChildren.size() == 3) {
2294 // Find the variants of all of our maximal children.
2295 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
2296 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
2297 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
2298 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
2300 // There are only two ways we can permute the tree:
2301 // (A op B) op C and A op (B op C)
2302 // Within these forms, we can also permute A/B/C.
2304 // Generate legal pair permutations of A/B/C.
2305 std::vector<TreePatternNode*> ABVariants;
2306 std::vector<TreePatternNode*> BAVariants;
2307 std::vector<TreePatternNode*> ACVariants;
2308 std::vector<TreePatternNode*> CAVariants;
2309 std::vector<TreePatternNode*> BCVariants;
2310 std::vector<TreePatternNode*> CBVariants;
2311 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
2312 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
2313 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
2314 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
2315 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
2316 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
2318 // Combine those into the result: (x op x) op x
2319 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
2320 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
2321 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
2322 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
2323 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
2324 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
2326 // Combine those into the result: x op (x op x)
2327 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
2328 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
2329 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
2330 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
2331 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
2332 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
2337 // Compute permutations of all children.
2338 std::vector<std::vector<TreePatternNode*> > ChildVariants;
2339 ChildVariants.resize(N->getNumChildren());
2340 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2341 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
2343 // Build all permutations based on how the children were formed.
2344 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
2346 // If this node is commutative, consider the commuted order.
2347 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
2348 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
2349 assert((N->getNumChildren()==2 || isCommIntrinsic) &&
2350 "Commutative but doesn't have 2 children!");
2351 // Don't count children which are actually register references.
2353 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2354 TreePatternNode *Child = N->getChild(i);
2355 if (Child->isLeaf())
2356 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2357 Record *RR = DI->getDef();
2358 if (RR->isSubClassOf("Register"))
2363 // Consider the commuted order.
2364 if (isCommIntrinsic) {
2365 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
2366 // operands are the commutative operands, and there might be more operands
2369 "Commutative intrinsic should have at least 3 childrean!");
2370 std::vector<std::vector<TreePatternNode*> > Variants;
2371 Variants.push_back(ChildVariants[0]); // Intrinsic id.
2372 Variants.push_back(ChildVariants[2]);
2373 Variants.push_back(ChildVariants[1]);
2374 for (unsigned i = 3; i != NC; ++i)
2375 Variants.push_back(ChildVariants[i]);
2376 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
2378 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
2379 OutVariants, CDP, DepVars);
2384 // GenerateVariants - Generate variants. For example, commutative patterns can
2385 // match multiple ways. Add them to PatternsToMatch as well.
2386 void CodeGenDAGPatterns::GenerateVariants() {
2387 DEBUG(errs() << "Generating instruction variants.\n");
2389 // Loop over all of the patterns we've collected, checking to see if we can
2390 // generate variants of the instruction, through the exploitation of
2391 // identities. This permits the target to provide aggressive matching without
2392 // the .td file having to contain tons of variants of instructions.
2394 // Note that this loop adds new patterns to the PatternsToMatch list, but we
2395 // intentionally do not reconsider these. Any variants of added patterns have
2396 // already been added.
2398 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
2399 MultipleUseVarSet DepVars;
2400 std::vector<TreePatternNode*> Variants;
2401 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
2402 DEBUG(errs() << "Dependent/multiply used variables: ");
2403 DEBUG(DumpDepVars(DepVars));
2404 DEBUG(errs() << "\n");
2405 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this, DepVars);
2407 assert(!Variants.empty() && "Must create at least original variant!");
2408 Variants.erase(Variants.begin()); // Remove the original pattern.
2410 if (Variants.empty()) // No variants for this pattern.
2413 DEBUG(errs() << "FOUND VARIANTS OF: ";
2414 PatternsToMatch[i].getSrcPattern()->dump();
2417 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
2418 TreePatternNode *Variant = Variants[v];
2420 DEBUG(errs() << " VAR#" << v << ": ";
2424 // Scan to see if an instruction or explicit pattern already matches this.
2425 bool AlreadyExists = false;
2426 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
2427 // Skip if the top level predicates do not match.
2428 if (PatternsToMatch[i].getPredicates() !=
2429 PatternsToMatch[p].getPredicates())
2431 // Check to see if this variant already exists.
2432 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(), DepVars)) {
2433 DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
2434 AlreadyExists = true;
2438 // If we already have it, ignore the variant.
2439 if (AlreadyExists) continue;
2441 // Otherwise, add it to the list of patterns we have.
2443 push_back(PatternToMatch(PatternsToMatch[i].getPredicates(),
2444 Variant, PatternsToMatch[i].getDstPattern(),
2445 PatternsToMatch[i].getDstRegs(),
2446 PatternsToMatch[i].getAddedComplexity()));
2449 DEBUG(errs() << "\n");