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"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/Support/Debug.h"
25 //===----------------------------------------------------------------------===//
26 // EEVT::TypeSet Implementation
27 //===----------------------------------------------------------------------===//
29 static inline bool isInteger(MVT::SimpleValueType VT) {
30 return EVT(VT).isInteger();
32 static inline bool isFloatingPoint(MVT::SimpleValueType VT) {
33 return EVT(VT).isFloatingPoint();
35 static inline bool isVector(MVT::SimpleValueType VT) {
36 return EVT(VT).isVector();
38 static inline bool isScalar(MVT::SimpleValueType VT) {
39 return !EVT(VT).isVector();
42 EEVT::TypeSet::TypeSet(MVT::SimpleValueType VT, TreePattern &TP) {
45 else if (VT == MVT::fAny)
46 EnforceFloatingPoint(TP);
47 else if (VT == MVT::vAny)
50 assert((VT < MVT::LAST_VALUETYPE || VT == MVT::iPTR ||
51 VT == MVT::iPTRAny) && "Not a concrete type!");
52 TypeVec.push_back(VT);
57 EEVT::TypeSet::TypeSet(const std::vector<MVT::SimpleValueType> &VTList) {
58 assert(!VTList.empty() && "empty list?");
59 TypeVec.append(VTList.begin(), VTList.end());
62 assert(VTList[0] != MVT::iAny && VTList[0] != MVT::vAny &&
63 VTList[0] != MVT::fAny);
65 // Verify no duplicates.
66 array_pod_sort(TypeVec.begin(), TypeVec.end());
67 assert(std::unique(TypeVec.begin(), TypeVec.end()) == TypeVec.end());
70 /// FillWithPossibleTypes - Set to all legal types and return true, only valid
71 /// on completely unknown type sets.
72 bool EEVT::TypeSet::FillWithPossibleTypes(TreePattern &TP,
73 bool (*Pred)(MVT::SimpleValueType),
74 const char *PredicateName) {
75 assert(isCompletelyUnknown());
76 const std::vector<MVT::SimpleValueType> &LegalTypes =
77 TP.getDAGPatterns().getTargetInfo().getLegalValueTypes();
79 for (unsigned i = 0, e = LegalTypes.size(); i != e; ++i)
80 if (Pred == 0 || Pred(LegalTypes[i]))
81 TypeVec.push_back(LegalTypes[i]);
83 // If we have nothing that matches the predicate, bail out.
85 TP.error("Type inference contradiction found, no " +
86 std::string(PredicateName) + " types found");
87 // No need to sort with one element.
88 if (TypeVec.size() == 1) return true;
91 array_pod_sort(TypeVec.begin(), TypeVec.end());
92 TypeVec.erase(std::unique(TypeVec.begin(), TypeVec.end()), TypeVec.end());
97 /// hasIntegerTypes - Return true if this TypeSet contains iAny or an
98 /// integer value type.
99 bool EEVT::TypeSet::hasIntegerTypes() const {
100 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
101 if (isInteger(TypeVec[i]))
106 /// hasFloatingPointTypes - Return true if this TypeSet contains an fAny or
107 /// a floating point value type.
108 bool EEVT::TypeSet::hasFloatingPointTypes() const {
109 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
110 if (isFloatingPoint(TypeVec[i]))
115 /// hasVectorTypes - Return true if this TypeSet contains a vAny or a vector
117 bool EEVT::TypeSet::hasVectorTypes() const {
118 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
119 if (isVector(TypeVec[i]))
125 std::string EEVT::TypeSet::getName() const {
126 if (TypeVec.empty()) return "<empty>";
130 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i) {
131 std::string VTName = llvm::getEnumName(TypeVec[i]);
132 // Strip off MVT:: prefix if present.
133 if (VTName.substr(0,5) == "MVT::")
134 VTName = VTName.substr(5);
135 if (i) Result += ':';
139 if (TypeVec.size() == 1)
141 return "{" + Result + "}";
144 /// MergeInTypeInfo - This merges in type information from the specified
145 /// argument. If 'this' changes, it returns true. If the two types are
146 /// contradictory (e.g. merge f32 into i32) then this throws an exception.
147 bool EEVT::TypeSet::MergeInTypeInfo(const EEVT::TypeSet &InVT, TreePattern &TP){
148 if (InVT.isCompletelyUnknown() || *this == InVT)
151 if (isCompletelyUnknown()) {
156 assert(TypeVec.size() >= 1 && InVT.TypeVec.size() >= 1 && "No unknowns");
158 // Handle the abstract cases, seeing if we can resolve them better.
159 switch (TypeVec[0]) {
163 if (InVT.hasIntegerTypes()) {
164 EEVT::TypeSet InCopy(InVT);
165 InCopy.EnforceInteger(TP);
166 InCopy.EnforceScalar(TP);
168 if (InCopy.isConcrete()) {
169 // If the RHS has one integer type, upgrade iPTR to i32.
170 TypeVec[0] = InVT.TypeVec[0];
174 // If the input has multiple scalar integers, this doesn't add any info.
175 if (!InCopy.isCompletelyUnknown())
181 // If the input constraint is iAny/iPTR and this is an integer type list,
182 // remove non-integer types from the list.
183 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
185 bool MadeChange = EnforceInteger(TP);
187 // If we're merging in iPTR/iPTRAny and the node currently has a list of
188 // multiple different integer types, replace them with a single iPTR.
189 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
190 TypeVec.size() != 1) {
192 TypeVec[0] = InVT.TypeVec[0];
199 // If this is a type list and the RHS is a typelist as well, eliminate entries
200 // from this list that aren't in the other one.
201 bool MadeChange = false;
202 TypeSet InputSet(*this);
204 for (unsigned i = 0; i != TypeVec.size(); ++i) {
206 for (unsigned j = 0, e = InVT.TypeVec.size(); j != e; ++j)
207 if (TypeVec[i] == InVT.TypeVec[j]) {
212 if (InInVT) continue;
213 TypeVec.erase(TypeVec.begin()+i--);
217 // If we removed all of our types, we have a type contradiction.
218 if (!TypeVec.empty())
221 // FIXME: Really want an SMLoc here!
222 TP.error("Type inference contradiction found, merging '" +
223 InVT.getName() + "' into '" + InputSet.getName() + "'");
224 return true; // unreachable
227 /// EnforceInteger - Remove all non-integer types from this set.
228 bool EEVT::TypeSet::EnforceInteger(TreePattern &TP) {
229 // If we know nothing, then get the full set.
231 return FillWithPossibleTypes(TP, isInteger, "integer");
232 if (!hasFloatingPointTypes())
235 TypeSet InputSet(*this);
237 // Filter out all the fp types.
238 for (unsigned i = 0; i != TypeVec.size(); ++i)
239 if (!isInteger(TypeVec[i]))
240 TypeVec.erase(TypeVec.begin()+i--);
243 TP.error("Type inference contradiction found, '" +
244 InputSet.getName() + "' needs to be integer");
248 /// EnforceFloatingPoint - Remove all integer types from this set.
249 bool EEVT::TypeSet::EnforceFloatingPoint(TreePattern &TP) {
250 // If we know nothing, then get the full set.
252 return FillWithPossibleTypes(TP, isFloatingPoint, "floating point");
254 if (!hasIntegerTypes())
257 TypeSet InputSet(*this);
259 // Filter out all the fp types.
260 for (unsigned i = 0; i != TypeVec.size(); ++i)
261 if (!isFloatingPoint(TypeVec[i]))
262 TypeVec.erase(TypeVec.begin()+i--);
265 TP.error("Type inference contradiction found, '" +
266 InputSet.getName() + "' needs to be floating point");
270 /// EnforceScalar - Remove all vector types from this.
271 bool EEVT::TypeSet::EnforceScalar(TreePattern &TP) {
272 // If we know nothing, then get the full set.
274 return FillWithPossibleTypes(TP, isScalar, "scalar");
276 if (!hasVectorTypes())
279 TypeSet InputSet(*this);
281 // Filter out all the vector types.
282 for (unsigned i = 0; i != TypeVec.size(); ++i)
283 if (!isScalar(TypeVec[i]))
284 TypeVec.erase(TypeVec.begin()+i--);
287 TP.error("Type inference contradiction found, '" +
288 InputSet.getName() + "' needs to be scalar");
292 /// EnforceVector - Remove all vector types from this.
293 bool EEVT::TypeSet::EnforceVector(TreePattern &TP) {
294 // If we know nothing, then get the full set.
296 return FillWithPossibleTypes(TP, isVector, "vector");
298 TypeSet InputSet(*this);
299 bool MadeChange = false;
301 // Filter out all the scalar types.
302 for (unsigned i = 0; i != TypeVec.size(); ++i)
303 if (!isVector(TypeVec[i])) {
304 TypeVec.erase(TypeVec.begin()+i--);
309 TP.error("Type inference contradiction found, '" +
310 InputSet.getName() + "' needs to be a vector");
316 /// EnforceSmallerThan - 'this' must be a smaller VT than Other. Update
317 /// this an other based on this information.
318 bool EEVT::TypeSet::EnforceSmallerThan(EEVT::TypeSet &Other, TreePattern &TP) {
319 // Both operands must be integer or FP, but we don't care which.
320 bool MadeChange = false;
322 if (isCompletelyUnknown())
323 MadeChange = FillWithPossibleTypes(TP);
325 if (Other.isCompletelyUnknown())
326 MadeChange = Other.FillWithPossibleTypes(TP);
328 // If one side is known to be integer or known to be FP but the other side has
329 // no information, get at least the type integrality info in there.
330 if (!hasFloatingPointTypes())
331 MadeChange |= Other.EnforceInteger(TP);
332 else if (!hasIntegerTypes())
333 MadeChange |= Other.EnforceFloatingPoint(TP);
334 if (!Other.hasFloatingPointTypes())
335 MadeChange |= EnforceInteger(TP);
336 else if (!Other.hasIntegerTypes())
337 MadeChange |= EnforceFloatingPoint(TP);
339 assert(!isCompletelyUnknown() && !Other.isCompletelyUnknown() &&
340 "Should have a type list now");
342 // If one contains vectors but the other doesn't pull vectors out.
343 if (!hasVectorTypes())
344 MadeChange |= Other.EnforceScalar(TP);
345 if (!hasVectorTypes())
346 MadeChange |= EnforceScalar(TP);
348 if (TypeVec.size() == 1 && Other.TypeVec.size() == 1) {
349 // If we are down to concrete types, this code does not currently
350 // handle nodes which have multiple types, where some types are
351 // integer, and some are fp. Assert that this is not the case.
352 assert(!(hasIntegerTypes() && hasFloatingPointTypes()) &&
353 !(Other.hasIntegerTypes() && Other.hasFloatingPointTypes()) &&
354 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
356 // Otherwise, if these are both vector types, either this vector
357 // must have a larger bitsize than the other, or this element type
358 // must be larger than the other.
359 EVT Type(TypeVec[0]);
360 EVT OtherType(Other.TypeVec[0]);
362 if (hasVectorTypes() && Other.hasVectorTypes()) {
363 if (Type.getSizeInBits() >= OtherType.getSizeInBits())
364 if (Type.getVectorElementType().getSizeInBits()
365 >= OtherType.getVectorElementType().getSizeInBits())
366 TP.error("Type inference contradiction found, '" +
367 getName() + "' element type not smaller than '" +
368 Other.getName() +"'!");
371 // For scalar types, the bitsize of this type must be larger
372 // than that of the other.
373 if (Type.getSizeInBits() >= OtherType.getSizeInBits())
374 TP.error("Type inference contradiction found, '" +
375 getName() + "' is not smaller than '" +
376 Other.getName() +"'!");
381 // Handle int and fp as disjoint sets. This won't work for patterns
382 // that have mixed fp/int types but those are likely rare and would
383 // not have been accepted by this code previously.
385 // Okay, find the smallest type from the current set and remove it from the
387 MVT::SimpleValueType SmallestInt = MVT::LAST_VALUETYPE;
388 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
389 if (isInteger(TypeVec[i])) {
390 SmallestInt = TypeVec[i];
393 for (unsigned i = 1, e = TypeVec.size(); i != e; ++i)
394 if (isInteger(TypeVec[i]) && TypeVec[i] < SmallestInt)
395 SmallestInt = TypeVec[i];
397 MVT::SimpleValueType SmallestFP = MVT::LAST_VALUETYPE;
398 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
399 if (isFloatingPoint(TypeVec[i])) {
400 SmallestFP = TypeVec[i];
403 for (unsigned i = 1, e = TypeVec.size(); i != e; ++i)
404 if (isFloatingPoint(TypeVec[i]) && TypeVec[i] < SmallestFP)
405 SmallestFP = TypeVec[i];
407 int OtherIntSize = 0;
409 for (SmallVector<MVT::SimpleValueType, 2>::iterator TVI =
410 Other.TypeVec.begin();
411 TVI != Other.TypeVec.end();
413 if (isInteger(*TVI)) {
415 if (*TVI == SmallestInt) {
416 TVI = Other.TypeVec.erase(TVI);
422 else if (isFloatingPoint(*TVI)) {
424 if (*TVI == SmallestFP) {
425 TVI = Other.TypeVec.erase(TVI);
434 // If this is the only type in the large set, the constraint can never be
436 if ((Other.hasIntegerTypes() && OtherIntSize == 0)
437 || (Other.hasFloatingPointTypes() && OtherFPSize == 0))
438 TP.error("Type inference contradiction found, '" +
439 Other.getName() + "' has nothing larger than '" + getName() +"'!");
441 // Okay, find the largest type in the Other set and remove it from the
443 MVT::SimpleValueType LargestInt = MVT::Other;
444 for (unsigned i = 0, e = Other.TypeVec.size(); i != e; ++i)
445 if (isInteger(Other.TypeVec[i])) {
446 LargestInt = Other.TypeVec[i];
449 for (unsigned i = 1, e = Other.TypeVec.size(); i != e; ++i)
450 if (isInteger(Other.TypeVec[i]) && Other.TypeVec[i] > LargestInt)
451 LargestInt = Other.TypeVec[i];
453 MVT::SimpleValueType LargestFP = MVT::Other;
454 for (unsigned i = 0, e = Other.TypeVec.size(); i != e; ++i)
455 if (isFloatingPoint(Other.TypeVec[i])) {
456 LargestFP = Other.TypeVec[i];
459 for (unsigned i = 1, e = Other.TypeVec.size(); i != e; ++i)
460 if (isFloatingPoint(Other.TypeVec[i]) && Other.TypeVec[i] > LargestFP)
461 LargestFP = Other.TypeVec[i];
465 for (SmallVector<MVT::SimpleValueType, 2>::iterator TVI =
467 TVI != TypeVec.end();
469 if (isInteger(*TVI)) {
471 if (*TVI == LargestInt) {
472 TVI = TypeVec.erase(TVI);
478 else if (isFloatingPoint(*TVI)) {
480 if (*TVI == LargestFP) {
481 TVI = TypeVec.erase(TVI);
490 // If this is the only type in the small set, the constraint can never be
492 if ((hasIntegerTypes() && IntSize == 0)
493 || (hasFloatingPointTypes() && FPSize == 0))
494 TP.error("Type inference contradiction found, '" +
495 getName() + "' has nothing smaller than '" + Other.getName()+"'!");
500 /// EnforceVectorEltTypeIs - 'this' is now constrainted to be a vector type
501 /// whose element is specified by VTOperand.
502 bool EEVT::TypeSet::EnforceVectorEltTypeIs(EEVT::TypeSet &VTOperand,
504 // "This" must be a vector and "VTOperand" must be a scalar.
505 bool MadeChange = false;
506 MadeChange |= EnforceVector(TP);
507 MadeChange |= VTOperand.EnforceScalar(TP);
509 // If we know the vector type, it forces the scalar to agree.
511 EVT IVT = getConcrete();
512 IVT = IVT.getVectorElementType();
514 VTOperand.MergeInTypeInfo(IVT.getSimpleVT().SimpleTy, TP);
517 // If the scalar type is known, filter out vector types whose element types
519 if (!VTOperand.isConcrete())
522 MVT::SimpleValueType VT = VTOperand.getConcrete();
524 TypeSet InputSet(*this);
526 // Filter out all the types which don't have the right element type.
527 for (unsigned i = 0; i != TypeVec.size(); ++i) {
528 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
529 if (EVT(TypeVec[i]).getVectorElementType().getSimpleVT().SimpleTy != VT) {
530 TypeVec.erase(TypeVec.begin()+i--);
535 if (TypeVec.empty()) // FIXME: Really want an SMLoc here!
536 TP.error("Type inference contradiction found, forcing '" +
537 InputSet.getName() + "' to have a vector element");
541 /// EnforceVectorSubVectorTypeIs - 'this' is now constrainted to be a
542 /// vector type specified by VTOperand.
543 bool EEVT::TypeSet::EnforceVectorSubVectorTypeIs(EEVT::TypeSet &VTOperand,
545 // "This" must be a vector and "VTOperand" must be a vector.
546 bool MadeChange = false;
547 MadeChange |= EnforceVector(TP);
548 MadeChange |= VTOperand.EnforceVector(TP);
550 // "This" must be larger than "VTOperand."
551 MadeChange |= VTOperand.EnforceSmallerThan(*this, TP);
553 // If we know the vector type, it forces the scalar types to agree.
555 EVT IVT = getConcrete();
556 IVT = IVT.getVectorElementType();
558 EEVT::TypeSet EltTypeSet(IVT.getSimpleVT().SimpleTy, TP);
559 MadeChange |= VTOperand.EnforceVectorEltTypeIs(EltTypeSet, TP);
560 } else if (VTOperand.isConcrete()) {
561 EVT IVT = VTOperand.getConcrete();
562 IVT = IVT.getVectorElementType();
564 EEVT::TypeSet EltTypeSet(IVT.getSimpleVT().SimpleTy, TP);
565 MadeChange |= EnforceVectorEltTypeIs(EltTypeSet, TP);
571 //===----------------------------------------------------------------------===//
572 // Helpers for working with extended types.
574 bool RecordPtrCmp::operator()(const Record *LHS, const Record *RHS) const {
575 return LHS->getID() < RHS->getID();
578 /// Dependent variable map for CodeGenDAGPattern variant generation
579 typedef std::map<std::string, int> DepVarMap;
581 /// Const iterator shorthand for DepVarMap
582 typedef DepVarMap::const_iterator DepVarMap_citer;
584 static void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
586 if (dynamic_cast<const DefInit*>(N->getLeafValue()) != NULL)
587 DepMap[N->getName()]++;
589 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
590 FindDepVarsOf(N->getChild(i), DepMap);
594 /// Find dependent variables within child patterns
595 static void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
597 FindDepVarsOf(N, depcounts);
598 for (DepVarMap_citer i = depcounts.begin(); i != depcounts.end(); ++i) {
599 if (i->second > 1) // std::pair<std::string, int>
600 DepVars.insert(i->first);
605 /// Dump the dependent variable set:
606 static void DumpDepVars(MultipleUseVarSet &DepVars) {
607 if (DepVars.empty()) {
608 DEBUG(errs() << "<empty set>");
610 DEBUG(errs() << "[ ");
611 for (MultipleUseVarSet::const_iterator i = DepVars.begin(),
612 e = DepVars.end(); i != e; ++i) {
613 DEBUG(errs() << (*i) << " ");
615 DEBUG(errs() << "]");
621 //===----------------------------------------------------------------------===//
622 // TreePredicateFn Implementation
623 //===----------------------------------------------------------------------===//
625 /// TreePredicateFn constructor. Here 'N' is a subclass of PatFrag.
626 TreePredicateFn::TreePredicateFn(TreePattern *N) : PatFragRec(N) {
627 assert((getPredCode().empty() || getImmCode().empty()) &&
628 ".td file corrupt: can't have a node predicate *and* an imm predicate");
631 std::string TreePredicateFn::getPredCode() const {
632 return PatFragRec->getRecord()->getValueAsCode("PredicateCode");
635 std::string TreePredicateFn::getImmCode() const {
636 return PatFragRec->getRecord()->getValueAsCode("ImmediateCode");
640 /// isAlwaysTrue - Return true if this is a noop predicate.
641 bool TreePredicateFn::isAlwaysTrue() const {
642 return getPredCode().empty() && getImmCode().empty();
645 /// Return the name to use in the generated code to reference this, this is
646 /// "Predicate_foo" if from a pattern fragment "foo".
647 std::string TreePredicateFn::getFnName() const {
648 return "Predicate_" + PatFragRec->getRecord()->getName();
651 /// getCodeToRunOnSDNode - Return the code for the function body that
652 /// evaluates this predicate. The argument is expected to be in "Node",
653 /// not N. This handles casting and conversion to a concrete node type as
655 std::string TreePredicateFn::getCodeToRunOnSDNode() const {
656 // Handle immediate predicates first.
657 std::string ImmCode = getImmCode();
658 if (!ImmCode.empty()) {
660 " int64_t Imm = cast<ConstantSDNode>(Node)->getSExtValue();\n";
661 return Result + ImmCode;
664 // Handle arbitrary node predicates.
665 assert(!getPredCode().empty() && "Don't have any predicate code!");
666 std::string ClassName;
667 if (PatFragRec->getOnlyTree()->isLeaf())
668 ClassName = "SDNode";
670 Record *Op = PatFragRec->getOnlyTree()->getOperator();
671 ClassName = PatFragRec->getDAGPatterns().getSDNodeInfo(Op).getSDClassName();
674 if (ClassName == "SDNode")
675 Result = " SDNode *N = Node;\n";
677 Result = " " + ClassName + "*N = cast<" + ClassName + ">(Node);\n";
679 return Result + getPredCode();
682 //===----------------------------------------------------------------------===//
683 // PatternToMatch implementation
687 /// getPatternSize - Return the 'size' of this pattern. We want to match large
688 /// patterns before small ones. This is used to determine the size of a
690 static unsigned getPatternSize(const TreePatternNode *P,
691 const CodeGenDAGPatterns &CGP) {
692 unsigned Size = 3; // The node itself.
693 // If the root node is a ConstantSDNode, increases its size.
694 // e.g. (set R32:$dst, 0).
695 if (P->isLeaf() && dynamic_cast<const IntInit*>(P->getLeafValue()))
698 // FIXME: This is a hack to statically increase the priority of patterns
699 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
700 // Later we can allow complexity / cost for each pattern to be (optionally)
701 // specified. To get best possible pattern match we'll need to dynamically
702 // calculate the complexity of all patterns a dag can potentially map to.
703 const ComplexPattern *AM = P->getComplexPatternInfo(CGP);
705 Size += AM->getNumOperands() * 3;
707 // If this node has some predicate function that must match, it adds to the
708 // complexity of this node.
709 if (!P->getPredicateFns().empty())
712 // Count children in the count if they are also nodes.
713 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
714 TreePatternNode *Child = P->getChild(i);
715 if (!Child->isLeaf() && Child->getNumTypes() &&
716 Child->getType(0) != MVT::Other)
717 Size += getPatternSize(Child, CGP);
718 else if (Child->isLeaf()) {
719 if (dynamic_cast<const IntInit*>(Child->getLeafValue()))
720 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
721 else if (Child->getComplexPatternInfo(CGP))
722 Size += getPatternSize(Child, CGP);
723 else if (!Child->getPredicateFns().empty())
731 /// Compute the complexity metric for the input pattern. This roughly
732 /// corresponds to the number of nodes that are covered.
733 unsigned PatternToMatch::
734 getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
735 return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();
739 /// getPredicateCheck - Return a single string containing all of this
740 /// pattern's predicates concatenated with "&&" operators.
742 std::string PatternToMatch::getPredicateCheck() const {
743 std::string PredicateCheck;
744 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
745 if (const DefInit *Pred = dynamic_cast<const DefInit*>(Predicates->getElement(i))) {
746 Record *Def = Pred->getDef();
747 if (!Def->isSubClassOf("Predicate")) {
751 assert(0 && "Unknown predicate type!");
753 if (!PredicateCheck.empty())
754 PredicateCheck += " && ";
755 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
759 return PredicateCheck;
762 //===----------------------------------------------------------------------===//
763 // SDTypeConstraint implementation
766 SDTypeConstraint::SDTypeConstraint(Record *R) {
767 OperandNo = R->getValueAsInt("OperandNum");
769 if (R->isSubClassOf("SDTCisVT")) {
770 ConstraintType = SDTCisVT;
771 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
772 if (x.SDTCisVT_Info.VT == MVT::isVoid)
773 throw TGError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
775 } else if (R->isSubClassOf("SDTCisPtrTy")) {
776 ConstraintType = SDTCisPtrTy;
777 } else if (R->isSubClassOf("SDTCisInt")) {
778 ConstraintType = SDTCisInt;
779 } else if (R->isSubClassOf("SDTCisFP")) {
780 ConstraintType = SDTCisFP;
781 } else if (R->isSubClassOf("SDTCisVec")) {
782 ConstraintType = SDTCisVec;
783 } else if (R->isSubClassOf("SDTCisSameAs")) {
784 ConstraintType = SDTCisSameAs;
785 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
786 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
787 ConstraintType = SDTCisVTSmallerThanOp;
788 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
789 R->getValueAsInt("OtherOperandNum");
790 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
791 ConstraintType = SDTCisOpSmallerThanOp;
792 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
793 R->getValueAsInt("BigOperandNum");
794 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
795 ConstraintType = SDTCisEltOfVec;
796 x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
797 } else if (R->isSubClassOf("SDTCisSubVecOfVec")) {
798 ConstraintType = SDTCisSubVecOfVec;
799 x.SDTCisSubVecOfVec_Info.OtherOperandNum =
800 R->getValueAsInt("OtherOpNum");
802 errs() << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
807 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
808 /// N, and the result number in ResNo.
809 static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
810 const SDNodeInfo &NodeInfo,
812 unsigned NumResults = NodeInfo.getNumResults();
813 if (OpNo < NumResults) {
820 if (OpNo >= N->getNumChildren()) {
821 errs() << "Invalid operand number in type constraint "
822 << (OpNo+NumResults) << " ";
828 return N->getChild(OpNo);
831 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
832 /// constraint to the nodes operands. This returns true if it makes a
833 /// change, false otherwise. If a type contradiction is found, throw an
835 bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
836 const SDNodeInfo &NodeInfo,
837 TreePattern &TP) const {
838 unsigned ResNo = 0; // The result number being referenced.
839 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
841 switch (ConstraintType) {
842 default: assert(0 && "Unknown constraint type!");
844 // Operand must be a particular type.
845 return NodeToApply->UpdateNodeType(ResNo, x.SDTCisVT_Info.VT, TP);
847 // Operand must be same as target pointer type.
848 return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
850 // Require it to be one of the legal integer VTs.
851 return NodeToApply->getExtType(ResNo).EnforceInteger(TP);
853 // Require it to be one of the legal fp VTs.
854 return NodeToApply->getExtType(ResNo).EnforceFloatingPoint(TP);
856 // Require it to be one of the legal vector VTs.
857 return NodeToApply->getExtType(ResNo).EnforceVector(TP);
860 TreePatternNode *OtherNode =
861 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
862 return NodeToApply->UpdateNodeType(OResNo, OtherNode->getExtType(ResNo),TP)|
863 OtherNode->UpdateNodeType(ResNo,NodeToApply->getExtType(OResNo),TP);
865 case SDTCisVTSmallerThanOp: {
866 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
867 // have an integer type that is smaller than the VT.
868 if (!NodeToApply->isLeaf() ||
869 !dynamic_cast<const DefInit*>(NodeToApply->getLeafValue()) ||
870 !static_cast<const DefInit*>(NodeToApply->getLeafValue())->getDef()
871 ->isSubClassOf("ValueType"))
872 TP.error(N->getOperator()->getName() + " expects a VT operand!");
873 MVT::SimpleValueType VT =
874 getValueType(static_cast<const DefInit*>(NodeToApply->getLeafValue())->getDef());
876 EEVT::TypeSet TypeListTmp(VT, TP);
879 TreePatternNode *OtherNode =
880 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
883 return TypeListTmp.EnforceSmallerThan(OtherNode->getExtType(OResNo), TP);
885 case SDTCisOpSmallerThanOp: {
887 TreePatternNode *BigOperand =
888 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
890 return NodeToApply->getExtType(ResNo).
891 EnforceSmallerThan(BigOperand->getExtType(BResNo), TP);
893 case SDTCisEltOfVec: {
895 TreePatternNode *VecOperand =
896 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
899 // Filter vector types out of VecOperand that don't have the right element
901 return VecOperand->getExtType(VResNo).
902 EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), TP);
904 case SDTCisSubVecOfVec: {
906 TreePatternNode *BigVecOperand =
907 getOperandNum(x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo,
910 // Filter vector types out of BigVecOperand that don't have the
911 // right subvector type.
912 return BigVecOperand->getExtType(VResNo).
913 EnforceVectorSubVectorTypeIs(NodeToApply->getExtType(ResNo), TP);
919 //===----------------------------------------------------------------------===//
920 // SDNodeInfo implementation
922 SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
923 EnumName = R->getValueAsString("Opcode");
924 SDClassName = R->getValueAsString("SDClass");
925 Record *TypeProfile = R->getValueAsDef("TypeProfile");
926 NumResults = TypeProfile->getValueAsInt("NumResults");
927 NumOperands = TypeProfile->getValueAsInt("NumOperands");
929 // Parse the properties.
931 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
932 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
933 if (PropList[i]->getName() == "SDNPCommutative") {
934 Properties |= 1 << SDNPCommutative;
935 } else if (PropList[i]->getName() == "SDNPAssociative") {
936 Properties |= 1 << SDNPAssociative;
937 } else if (PropList[i]->getName() == "SDNPHasChain") {
938 Properties |= 1 << SDNPHasChain;
939 } else if (PropList[i]->getName() == "SDNPOutGlue") {
940 Properties |= 1 << SDNPOutGlue;
941 } else if (PropList[i]->getName() == "SDNPInGlue") {
942 Properties |= 1 << SDNPInGlue;
943 } else if (PropList[i]->getName() == "SDNPOptInGlue") {
944 Properties |= 1 << SDNPOptInGlue;
945 } else if (PropList[i]->getName() == "SDNPMayStore") {
946 Properties |= 1 << SDNPMayStore;
947 } else if (PropList[i]->getName() == "SDNPMayLoad") {
948 Properties |= 1 << SDNPMayLoad;
949 } else if (PropList[i]->getName() == "SDNPSideEffect") {
950 Properties |= 1 << SDNPSideEffect;
951 } else if (PropList[i]->getName() == "SDNPMemOperand") {
952 Properties |= 1 << SDNPMemOperand;
953 } else if (PropList[i]->getName() == "SDNPVariadic") {
954 Properties |= 1 << SDNPVariadic;
956 errs() << "Unknown SD Node property '" << PropList[i]->getName()
957 << "' on node '" << R->getName() << "'!\n";
963 // Parse the type constraints.
964 std::vector<Record*> ConstraintList =
965 TypeProfile->getValueAsListOfDefs("Constraints");
966 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
969 /// getKnownType - If the type constraints on this node imply a fixed type
970 /// (e.g. all stores return void, etc), then return it as an
971 /// MVT::SimpleValueType. Otherwise, return EEVT::Other.
972 MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
973 unsigned NumResults = getNumResults();
974 assert(NumResults <= 1 &&
975 "We only work with nodes with zero or one result so far!");
976 assert(ResNo == 0 && "Only handles single result nodes so far");
978 for (unsigned i = 0, e = TypeConstraints.size(); i != e; ++i) {
979 // Make sure that this applies to the correct node result.
980 if (TypeConstraints[i].OperandNo >= NumResults) // FIXME: need value #
983 switch (TypeConstraints[i].ConstraintType) {
985 case SDTypeConstraint::SDTCisVT:
986 return TypeConstraints[i].x.SDTCisVT_Info.VT;
987 case SDTypeConstraint::SDTCisPtrTy:
994 //===----------------------------------------------------------------------===//
995 // TreePatternNode implementation
998 TreePatternNode::~TreePatternNode() {
999 #if 0 // FIXME: implement refcounted tree nodes!
1000 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1005 static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
1006 if (Operator->getName() == "set" ||
1007 Operator->getName() == "implicit")
1008 return 0; // All return nothing.
1010 if (Operator->isSubClassOf("Intrinsic"))
1011 return CDP.getIntrinsic(Operator).IS.RetVTs.size();
1013 if (Operator->isSubClassOf("SDNode"))
1014 return CDP.getSDNodeInfo(Operator).getNumResults();
1016 if (Operator->isSubClassOf("PatFrag")) {
1017 // If we've already parsed this pattern fragment, get it. Otherwise, handle
1018 // the forward reference case where one pattern fragment references another
1019 // before it is processed.
1020 if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator))
1021 return PFRec->getOnlyTree()->getNumTypes();
1023 // Get the result tree.
1024 const DagInit *Tree = Operator->getValueAsDag("Fragment");
1026 if (Tree && dynamic_cast<const DefInit*>(Tree->getOperator()))
1027 Op = dynamic_cast<const DefInit*>(Tree->getOperator())->getDef();
1028 assert(Op && "Invalid Fragment");
1029 return GetNumNodeResults(Op, CDP);
1032 if (Operator->isSubClassOf("Instruction")) {
1033 CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
1035 // FIXME: Should allow access to all the results here.
1036 unsigned NumDefsToAdd = InstInfo.Operands.NumDefs ? 1 : 0;
1038 // Add on one implicit def if it has a resolvable type.
1039 if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
1041 return NumDefsToAdd;
1044 if (Operator->isSubClassOf("SDNodeXForm"))
1045 return 1; // FIXME: Generalize SDNodeXForm
1048 errs() << "Unhandled node in GetNumNodeResults\n";
1052 void TreePatternNode::print(raw_ostream &OS) const {
1054 OS << *getLeafValue();
1056 OS << '(' << getOperator()->getName();
1058 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1059 OS << ':' << getExtType(i).getName();
1062 if (getNumChildren() != 0) {
1064 getChild(0)->print(OS);
1065 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
1067 getChild(i)->print(OS);
1073 for (unsigned i = 0, e = PredicateFns.size(); i != e; ++i)
1074 OS << "<<P:" << PredicateFns[i].getFnName() << ">>";
1076 OS << "<<X:" << TransformFn->getName() << ">>";
1077 if (!getName().empty())
1078 OS << ":$" << getName();
1081 void TreePatternNode::dump() const {
1085 /// isIsomorphicTo - Return true if this node is recursively
1086 /// isomorphic to the specified node. For this comparison, the node's
1087 /// entire state is considered. The assigned name is ignored, since
1088 /// nodes with differing names are considered isomorphic. However, if
1089 /// the assigned name is present in the dependent variable set, then
1090 /// the assigned name is considered significant and the node is
1091 /// isomorphic if the names match.
1092 bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
1093 const MultipleUseVarSet &DepVars) const {
1094 if (N == this) return true;
1095 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
1096 getPredicateFns() != N->getPredicateFns() ||
1097 getTransformFn() != N->getTransformFn())
1101 if (const DefInit *DI = dynamic_cast<const DefInit*>(getLeafValue())) {
1102 if (const DefInit *NDI = dynamic_cast<const DefInit*>(N->getLeafValue())) {
1103 return ((DI->getDef() == NDI->getDef())
1104 && (DepVars.find(getName()) == DepVars.end()
1105 || getName() == N->getName()));
1108 return getLeafValue() == N->getLeafValue();
1111 if (N->getOperator() != getOperator() ||
1112 N->getNumChildren() != getNumChildren()) return false;
1113 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1114 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
1119 /// clone - Make a copy of this tree and all of its children.
1121 TreePatternNode *TreePatternNode::clone() const {
1122 TreePatternNode *New;
1124 New = new TreePatternNode(getLeafValue(), getNumTypes());
1126 std::vector<TreePatternNode*> CChildren;
1127 CChildren.reserve(Children.size());
1128 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1129 CChildren.push_back(getChild(i)->clone());
1130 New = new TreePatternNode(getOperator(), CChildren, getNumTypes());
1132 New->setName(getName());
1134 New->setPredicateFns(getPredicateFns());
1135 New->setTransformFn(getTransformFn());
1139 /// RemoveAllTypes - Recursively strip all the types of this tree.
1140 void TreePatternNode::RemoveAllTypes() {
1141 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1142 Types[i] = EEVT::TypeSet(); // Reset to unknown type.
1143 if (isLeaf()) return;
1144 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1145 getChild(i)->RemoveAllTypes();
1149 /// SubstituteFormalArguments - Replace the formal arguments in this tree
1150 /// with actual values specified by ArgMap.
1151 void TreePatternNode::
1152 SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
1153 if (isLeaf()) return;
1155 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1156 TreePatternNode *Child = getChild(i);
1157 if (Child->isLeaf()) {
1158 const Init *Val = Child->getLeafValue();
1159 if (dynamic_cast<const DefInit*>(Val) &&
1160 static_cast<const DefInit*>(Val)->getDef()->getName() == "node") {
1161 // We found a use of a formal argument, replace it with its value.
1162 TreePatternNode *NewChild = ArgMap[Child->getName()];
1163 assert(NewChild && "Couldn't find formal argument!");
1164 assert((Child->getPredicateFns().empty() ||
1165 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1166 "Non-empty child predicate clobbered!");
1167 setChild(i, NewChild);
1170 getChild(i)->SubstituteFormalArguments(ArgMap);
1176 /// InlinePatternFragments - If this pattern refers to any pattern
1177 /// fragments, inline them into place, giving us a pattern without any
1178 /// PatFrag references.
1179 TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
1180 if (isLeaf()) return this; // nothing to do.
1181 Record *Op = getOperator();
1183 if (!Op->isSubClassOf("PatFrag")) {
1184 // Just recursively inline children nodes.
1185 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1186 TreePatternNode *Child = getChild(i);
1187 TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
1189 assert((Child->getPredicateFns().empty() ||
1190 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1191 "Non-empty child predicate clobbered!");
1193 setChild(i, NewChild);
1198 // Otherwise, we found a reference to a fragment. First, look up its
1199 // TreePattern record.
1200 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
1202 // Verify that we are passing the right number of operands.
1203 if (Frag->getNumArgs() != Children.size())
1204 TP.error("'" + Op->getName() + "' fragment requires " +
1205 utostr(Frag->getNumArgs()) + " operands!");
1207 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
1209 TreePredicateFn PredFn(Frag);
1210 if (!PredFn.isAlwaysTrue())
1211 FragTree->addPredicateFn(PredFn);
1213 // Resolve formal arguments to their actual value.
1214 if (Frag->getNumArgs()) {
1215 // Compute the map of formal to actual arguments.
1216 std::map<std::string, TreePatternNode*> ArgMap;
1217 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
1218 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
1220 FragTree->SubstituteFormalArguments(ArgMap);
1223 FragTree->setName(getName());
1224 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1225 FragTree->UpdateNodeType(i, getExtType(i), TP);
1227 // Transfer in the old predicates.
1228 for (unsigned i = 0, e = getPredicateFns().size(); i != e; ++i)
1229 FragTree->addPredicateFn(getPredicateFns()[i]);
1231 // Get a new copy of this fragment to stitch into here.
1232 //delete this; // FIXME: implement refcounting!
1234 // The fragment we inlined could have recursive inlining that is needed. See
1235 // if there are any pattern fragments in it and inline them as needed.
1236 return FragTree->InlinePatternFragments(TP);
1239 /// getImplicitType - Check to see if the specified record has an implicit
1240 /// type which should be applied to it. This will infer the type of register
1241 /// references from the register file information, for example.
1243 static EEVT::TypeSet getImplicitType(Record *R, unsigned ResNo,
1244 bool NotRegisters, TreePattern &TP) {
1245 // Check to see if this is a register operand.
1246 if (R->isSubClassOf("RegisterOperand")) {
1247 assert(ResNo == 0 && "Regoperand ref only has one result!");
1249 return EEVT::TypeSet(); // Unknown.
1250 Record *RegClass = R->getValueAsDef("RegClass");
1251 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1252 return EEVT::TypeSet(T.getRegisterClass(RegClass).getValueTypes());
1255 // Check to see if this is a register or a register class.
1256 if (R->isSubClassOf("RegisterClass")) {
1257 assert(ResNo == 0 && "Regclass ref only has one result!");
1259 return EEVT::TypeSet(); // Unknown.
1260 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1261 return EEVT::TypeSet(T.getRegisterClass(R).getValueTypes());
1264 if (R->isSubClassOf("PatFrag")) {
1265 assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
1266 // Pattern fragment types will be resolved when they are inlined.
1267 return EEVT::TypeSet(); // Unknown.
1270 if (R->isSubClassOf("Register")) {
1271 assert(ResNo == 0 && "Registers only produce one result!");
1273 return EEVT::TypeSet(); // Unknown.
1274 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1275 return EEVT::TypeSet(T.getRegisterVTs(R));
1278 if (R->isSubClassOf("SubRegIndex")) {
1279 assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
1280 return EEVT::TypeSet();
1283 if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
1284 assert(ResNo == 0 && "This node only has one result!");
1285 // Using a VTSDNode or CondCodeSDNode.
1286 return EEVT::TypeSet(MVT::Other, TP);
1289 if (R->isSubClassOf("ComplexPattern")) {
1290 assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
1292 return EEVT::TypeSet(); // Unknown.
1293 return EEVT::TypeSet(TP.getDAGPatterns().getComplexPattern(R).getValueType(),
1296 if (R->isSubClassOf("PointerLikeRegClass")) {
1297 assert(ResNo == 0 && "Regclass can only have one result!");
1298 return EEVT::TypeSet(MVT::iPTR, TP);
1301 if (R->getName() == "node" || R->getName() == "srcvalue" ||
1302 R->getName() == "zero_reg") {
1304 return EEVT::TypeSet(); // Unknown.
1307 TP.error("Unknown node flavor used in pattern: " + R->getName());
1308 return EEVT::TypeSet(MVT::Other, TP);
1312 /// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
1313 /// CodeGenIntrinsic information for it, otherwise return a null pointer.
1314 const CodeGenIntrinsic *TreePatternNode::
1315 getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
1316 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
1317 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
1318 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
1322 dynamic_cast<const IntInit*>(getChild(0)->getLeafValue())->getValue();
1323 return &CDP.getIntrinsicInfo(IID);
1326 /// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
1327 /// return the ComplexPattern information, otherwise return null.
1328 const ComplexPattern *
1329 TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
1330 if (!isLeaf()) return 0;
1332 const DefInit *DI = dynamic_cast<const DefInit*>(getLeafValue());
1333 if (DI && DI->getDef()->isSubClassOf("ComplexPattern"))
1334 return &CGP.getComplexPattern(DI->getDef());
1338 /// NodeHasProperty - Return true if this node has the specified property.
1339 bool TreePatternNode::NodeHasProperty(SDNP Property,
1340 const CodeGenDAGPatterns &CGP) const {
1342 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1343 return CP->hasProperty(Property);
1347 Record *Operator = getOperator();
1348 if (!Operator->isSubClassOf("SDNode")) return false;
1350 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
1356 /// TreeHasProperty - Return true if any node in this tree has the specified
1358 bool TreePatternNode::TreeHasProperty(SDNP Property,
1359 const CodeGenDAGPatterns &CGP) const {
1360 if (NodeHasProperty(Property, CGP))
1362 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1363 if (getChild(i)->TreeHasProperty(Property, CGP))
1368 /// isCommutativeIntrinsic - Return true if the node corresponds to a
1369 /// commutative intrinsic.
1371 TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
1372 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
1373 return Int->isCommutative;
1378 /// ApplyTypeConstraints - Apply all of the type constraints relevant to
1379 /// this node and its children in the tree. This returns true if it makes a
1380 /// change, false otherwise. If a type contradiction is found, throw an
1382 bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
1383 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
1385 if (const DefInit *DI = dynamic_cast<const DefInit*>(getLeafValue())) {
1386 // If it's a regclass or something else known, include the type.
1387 bool MadeChange = false;
1388 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1389 MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
1390 NotRegisters, TP), TP);
1394 if (const IntInit *II = dynamic_cast<const IntInit*>(getLeafValue())) {
1395 assert(Types.size() == 1 && "Invalid IntInit");
1397 // Int inits are always integers. :)
1398 bool MadeChange = Types[0].EnforceInteger(TP);
1400 if (!Types[0].isConcrete())
1403 MVT::SimpleValueType VT = getType(0);
1404 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
1407 unsigned Size = EVT(VT).getSizeInBits();
1408 // Make sure that the value is representable for this type.
1409 if (Size >= 32) return MadeChange;
1411 int Val = (II->getValue() << (32-Size)) >> (32-Size);
1412 if (Val == II->getValue()) return MadeChange;
1414 // If sign-extended doesn't fit, does it fit as unsigned?
1416 unsigned UnsignedVal;
1417 ValueMask = unsigned(~uint32_t(0UL) >> (32-Size));
1418 UnsignedVal = unsigned(II->getValue());
1420 if ((ValueMask & UnsignedVal) == UnsignedVal)
1423 TP.error("Integer value '" + itostr(II->getValue())+
1424 "' is out of range for type '" + getEnumName(getType(0)) + "'!");
1430 // special handling for set, which isn't really an SDNode.
1431 if (getOperator()->getName() == "set") {
1432 assert(getNumTypes() == 0 && "Set doesn't produce a value");
1433 assert(getNumChildren() >= 2 && "Missing RHS of a set?");
1434 unsigned NC = getNumChildren();
1436 TreePatternNode *SetVal = getChild(NC-1);
1437 bool MadeChange = SetVal->ApplyTypeConstraints(TP, NotRegisters);
1439 for (unsigned i = 0; i < NC-1; ++i) {
1440 TreePatternNode *Child = getChild(i);
1441 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
1443 // Types of operands must match.
1444 MadeChange |= Child->UpdateNodeType(0, SetVal->getExtType(i), TP);
1445 MadeChange |= SetVal->UpdateNodeType(i, Child->getExtType(0), TP);
1450 if (getOperator()->getName() == "implicit") {
1451 assert(getNumTypes() == 0 && "Node doesn't produce a value");
1453 bool MadeChange = false;
1454 for (unsigned i = 0; i < getNumChildren(); ++i)
1455 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1459 if (getOperator()->getName() == "COPY_TO_REGCLASS") {
1460 bool MadeChange = false;
1461 MadeChange |= getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1462 MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
1464 assert(getChild(0)->getNumTypes() == 1 &&
1465 getChild(1)->getNumTypes() == 1 && "Unhandled case");
1467 // child #1 of COPY_TO_REGCLASS should be a register class. We don't care
1468 // what type it gets, so if it didn't get a concrete type just give it the
1469 // first viable type from the reg class.
1470 if (!getChild(1)->hasTypeSet(0) &&
1471 !getChild(1)->getExtType(0).isCompletelyUnknown()) {
1472 MVT::SimpleValueType RCVT = getChild(1)->getExtType(0).getTypeList()[0];
1473 MadeChange |= getChild(1)->UpdateNodeType(0, RCVT, TP);
1478 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
1479 bool MadeChange = false;
1481 // Apply the result type to the node.
1482 unsigned NumRetVTs = Int->IS.RetVTs.size();
1483 unsigned NumParamVTs = Int->IS.ParamVTs.size();
1485 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
1486 MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
1488 if (getNumChildren() != NumParamVTs + 1)
1489 TP.error("Intrinsic '" + Int->Name + "' expects " +
1490 utostr(NumParamVTs) + " operands, not " +
1491 utostr(getNumChildren() - 1) + " operands!");
1493 // Apply type info to the intrinsic ID.
1494 MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
1496 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
1497 MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
1499 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
1500 assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
1501 MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
1506 if (getOperator()->isSubClassOf("SDNode")) {
1507 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
1509 // Check that the number of operands is sane. Negative operands -> varargs.
1510 if (NI.getNumOperands() >= 0 &&
1511 getNumChildren() != (unsigned)NI.getNumOperands())
1512 TP.error(getOperator()->getName() + " node requires exactly " +
1513 itostr(NI.getNumOperands()) + " operands!");
1515 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
1516 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1517 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1521 if (getOperator()->isSubClassOf("Instruction")) {
1522 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
1523 CodeGenInstruction &InstInfo =
1524 CDP.getTargetInfo().getInstruction(getOperator());
1526 bool MadeChange = false;
1528 // Apply the result types to the node, these come from the things in the
1529 // (outs) list of the instruction.
1530 // FIXME: Cap at one result so far.
1531 unsigned NumResultsToAdd = InstInfo.Operands.NumDefs ? 1 : 0;
1532 for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo) {
1533 Record *ResultNode = Inst.getResult(ResNo);
1535 if (ResultNode->isSubClassOf("PointerLikeRegClass")) {
1536 MadeChange |= UpdateNodeType(ResNo, MVT::iPTR, TP);
1537 } else if (ResultNode->isSubClassOf("RegisterOperand")) {
1538 Record *RegClass = ResultNode->getValueAsDef("RegClass");
1539 const CodeGenRegisterClass &RC =
1540 CDP.getTargetInfo().getRegisterClass(RegClass);
1541 MadeChange |= UpdateNodeType(ResNo, RC.getValueTypes(), TP);
1542 } else if (ResultNode->getName() == "unknown") {
1545 assert(ResultNode->isSubClassOf("RegisterClass") &&
1546 "Operands should be register classes!");
1547 const CodeGenRegisterClass &RC =
1548 CDP.getTargetInfo().getRegisterClass(ResultNode);
1549 MadeChange |= UpdateNodeType(ResNo, RC.getValueTypes(), TP);
1553 // If the instruction has implicit defs, we apply the first one as a result.
1554 // FIXME: This sucks, it should apply all implicit defs.
1555 if (!InstInfo.ImplicitDefs.empty()) {
1556 unsigned ResNo = NumResultsToAdd;
1558 // FIXME: Generalize to multiple possible types and multiple possible
1560 MVT::SimpleValueType VT =
1561 InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
1563 if (VT != MVT::Other)
1564 MadeChange |= UpdateNodeType(ResNo, VT, TP);
1567 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
1569 if (getOperator()->getName() == "INSERT_SUBREG") {
1570 assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
1571 MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
1572 MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
1575 unsigned ChildNo = 0;
1576 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
1577 Record *OperandNode = Inst.getOperand(i);
1579 // If the instruction expects a predicate or optional def operand, we
1580 // codegen this by setting the operand to it's default value if it has a
1581 // non-empty DefaultOps field.
1582 if ((OperandNode->isSubClassOf("PredicateOperand") ||
1583 OperandNode->isSubClassOf("OptionalDefOperand")) &&
1584 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1587 // Verify that we didn't run out of provided operands.
1588 if (ChildNo >= getNumChildren())
1589 TP.error("Instruction '" + getOperator()->getName() +
1590 "' expects more operands than were provided.");
1592 MVT::SimpleValueType VT;
1593 TreePatternNode *Child = getChild(ChildNo++);
1594 unsigned ChildResNo = 0; // Instructions always use res #0 of their op.
1596 if (OperandNode->isSubClassOf("RegisterClass")) {
1597 const CodeGenRegisterClass &RC =
1598 CDP.getTargetInfo().getRegisterClass(OperandNode);
1599 MadeChange |= Child->UpdateNodeType(ChildResNo, RC.getValueTypes(), TP);
1600 } else if (OperandNode->isSubClassOf("RegisterOperand")) {
1601 Record *RegClass = OperandNode->getValueAsDef("RegClass");
1602 const CodeGenRegisterClass &RC =
1603 CDP.getTargetInfo().getRegisterClass(RegClass);
1604 MadeChange |= Child->UpdateNodeType(ChildResNo, RC.getValueTypes(), TP);
1605 } else if (OperandNode->isSubClassOf("Operand")) {
1606 VT = getValueType(OperandNode->getValueAsDef("Type"));
1607 MadeChange |= Child->UpdateNodeType(ChildResNo, VT, TP);
1608 } else if (OperandNode->isSubClassOf("PointerLikeRegClass")) {
1609 MadeChange |= Child->UpdateNodeType(ChildResNo, MVT::iPTR, TP);
1610 } else if (OperandNode->getName() == "unknown") {
1613 assert(0 && "Unknown operand type!");
1616 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
1619 if (ChildNo != getNumChildren())
1620 TP.error("Instruction '" + getOperator()->getName() +
1621 "' was provided too many operands!");
1626 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
1628 // Node transforms always take one operand.
1629 if (getNumChildren() != 1)
1630 TP.error("Node transform '" + getOperator()->getName() +
1631 "' requires one operand!");
1633 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1636 // If either the output or input of the xform does not have exact
1637 // type info. We assume they must be the same. Otherwise, it is perfectly
1638 // legal to transform from one type to a completely different type.
1640 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
1641 bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
1642 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
1649 /// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
1650 /// RHS of a commutative operation, not the on LHS.
1651 static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
1652 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
1654 if (N->isLeaf() && dynamic_cast<const IntInit*>(N->getLeafValue()))
1660 /// canPatternMatch - If it is impossible for this pattern to match on this
1661 /// target, fill in Reason and return false. Otherwise, return true. This is
1662 /// used as a sanity check for .td files (to prevent people from writing stuff
1663 /// that can never possibly work), and to prevent the pattern permuter from
1664 /// generating stuff that is useless.
1665 bool TreePatternNode::canPatternMatch(std::string &Reason,
1666 const CodeGenDAGPatterns &CDP) {
1667 if (isLeaf()) return true;
1669 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1670 if (!getChild(i)->canPatternMatch(Reason, CDP))
1673 // If this is an intrinsic, handle cases that would make it not match. For
1674 // example, if an operand is required to be an immediate.
1675 if (getOperator()->isSubClassOf("Intrinsic")) {
1680 // If this node is a commutative operator, check that the LHS isn't an
1682 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
1683 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
1684 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
1685 // Scan all of the operands of the node and make sure that only the last one
1686 // is a constant node, unless the RHS also is.
1687 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
1688 bool Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
1689 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
1690 if (OnlyOnRHSOfCommutative(getChild(i))) {
1691 Reason="Immediate value must be on the RHS of commutative operators!";
1700 //===----------------------------------------------------------------------===//
1701 // TreePattern implementation
1704 TreePattern::TreePattern(Record *TheRec, const ListInit *RawPat, bool isInput,
1705 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
1706 isInputPattern = isInput;
1707 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
1708 Trees.push_back(ParseTreePattern(RawPat->getElement(i), ""));
1711 TreePattern::TreePattern(Record *TheRec, const DagInit *Pat, bool isInput,
1712 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
1713 isInputPattern = isInput;
1714 Trees.push_back(ParseTreePattern(Pat, ""));
1717 TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
1718 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
1719 isInputPattern = isInput;
1720 Trees.push_back(Pat);
1723 void TreePattern::error(const std::string &Msg) const {
1725 throw TGError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
1728 void TreePattern::ComputeNamedNodes() {
1729 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1730 ComputeNamedNodes(Trees[i]);
1733 void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
1734 if (!N->getName().empty())
1735 NamedNodes[N->getName()].push_back(N);
1737 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1738 ComputeNamedNodes(N->getChild(i));
1742 TreePatternNode *TreePattern::ParseTreePattern(const Init *TheInit, StringRef OpName){
1743 if (const DefInit *DI = dynamic_cast<const DefInit*>(TheInit)) {
1744 Record *R = DI->getDef();
1746 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
1747 // TreePatternNode of its own. For example:
1748 /// (foo GPR, imm) -> (foo GPR, (imm))
1749 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag"))
1750 return ParseTreePattern(
1751 DagInit::get(DI, "",
1752 std::vector<std::pair<const Init*, std::string> >()),
1756 TreePatternNode *Res = new TreePatternNode(DI, 1);
1757 if (R->getName() == "node" && !OpName.empty()) {
1759 error("'node' argument requires a name to match with operand list");
1760 Args.push_back(OpName);
1763 Res->setName(OpName);
1767 if (const IntInit *II = dynamic_cast<const IntInit*>(TheInit)) {
1768 if (!OpName.empty())
1769 error("Constant int argument should not have a name!");
1770 return new TreePatternNode(II, 1);
1773 if (const BitsInit *BI = dynamic_cast<const BitsInit*>(TheInit)) {
1774 // Turn this into an IntInit.
1775 const Init *II = BI->convertInitializerTo(IntRecTy::get());
1776 if (II == 0 || !dynamic_cast<const IntInit*>(II))
1777 error("Bits value must be constants!");
1778 return ParseTreePattern(II, OpName);
1781 const DagInit *Dag = dynamic_cast<const DagInit*>(TheInit);
1784 error("Pattern has unexpected init kind!");
1786 const DefInit *OpDef = dynamic_cast<const DefInit*>(Dag->getOperator());
1787 if (!OpDef) error("Pattern has unexpected operator type!");
1788 Record *Operator = OpDef->getDef();
1790 if (Operator->isSubClassOf("ValueType")) {
1791 // If the operator is a ValueType, then this must be "type cast" of a leaf
1793 if (Dag->getNumArgs() != 1)
1794 error("Type cast only takes one operand!");
1796 TreePatternNode *New = ParseTreePattern(Dag->getArg(0), Dag->getArgName(0));
1798 // Apply the type cast.
1799 assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
1800 New->UpdateNodeType(0, getValueType(Operator), *this);
1802 if (!OpName.empty())
1803 error("ValueType cast should not have a name!");
1807 // Verify that this is something that makes sense for an operator.
1808 if (!Operator->isSubClassOf("PatFrag") &&
1809 !Operator->isSubClassOf("SDNode") &&
1810 !Operator->isSubClassOf("Instruction") &&
1811 !Operator->isSubClassOf("SDNodeXForm") &&
1812 !Operator->isSubClassOf("Intrinsic") &&
1813 Operator->getName() != "set" &&
1814 Operator->getName() != "implicit")
1815 error("Unrecognized node '" + Operator->getName() + "'!");
1817 // Check to see if this is something that is illegal in an input pattern.
1818 if (isInputPattern) {
1819 if (Operator->isSubClassOf("Instruction") ||
1820 Operator->isSubClassOf("SDNodeXForm"))
1821 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
1823 if (Operator->isSubClassOf("Intrinsic"))
1824 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
1826 if (Operator->isSubClassOf("SDNode") &&
1827 Operator->getName() != "imm" &&
1828 Operator->getName() != "fpimm" &&
1829 Operator->getName() != "tglobaltlsaddr" &&
1830 Operator->getName() != "tconstpool" &&
1831 Operator->getName() != "tjumptable" &&
1832 Operator->getName() != "tframeindex" &&
1833 Operator->getName() != "texternalsym" &&
1834 Operator->getName() != "tblockaddress" &&
1835 Operator->getName() != "tglobaladdr" &&
1836 Operator->getName() != "bb" &&
1837 Operator->getName() != "vt")
1838 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
1841 std::vector<TreePatternNode*> Children;
1843 // Parse all the operands.
1844 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
1845 Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgName(i)));
1847 // If the operator is an intrinsic, then this is just syntactic sugar for for
1848 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
1849 // convert the intrinsic name to a number.
1850 if (Operator->isSubClassOf("Intrinsic")) {
1851 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
1852 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
1854 // If this intrinsic returns void, it must have side-effects and thus a
1856 if (Int.IS.RetVTs.empty())
1857 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
1858 else if (Int.ModRef != CodeGenIntrinsic::NoMem)
1859 // Has side-effects, requires chain.
1860 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
1861 else // Otherwise, no chain.
1862 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
1864 TreePatternNode *IIDNode = new TreePatternNode(IntInit::get(IID), 1);
1865 Children.insert(Children.begin(), IIDNode);
1868 unsigned NumResults = GetNumNodeResults(Operator, CDP);
1869 TreePatternNode *Result = new TreePatternNode(Operator, Children, NumResults);
1870 Result->setName(OpName);
1872 if (!Dag->getName().empty()) {
1873 assert(Result->getName().empty());
1874 Result->setName(Dag->getName());
1879 /// SimplifyTree - See if we can simplify this tree to eliminate something that
1880 /// will never match in favor of something obvious that will. This is here
1881 /// strictly as a convenience to target authors because it allows them to write
1882 /// more type generic things and have useless type casts fold away.
1884 /// This returns true if any change is made.
1885 static bool SimplifyTree(TreePatternNode *&N) {
1889 // If we have a bitconvert with a resolved type and if the source and
1890 // destination types are the same, then the bitconvert is useless, remove it.
1891 if (N->getOperator()->getName() == "bitconvert" &&
1892 N->getExtType(0).isConcrete() &&
1893 N->getExtType(0) == N->getChild(0)->getExtType(0) &&
1894 N->getName().empty()) {
1900 // Walk all children.
1901 bool MadeChange = false;
1902 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
1903 TreePatternNode *Child = N->getChild(i);
1904 MadeChange |= SimplifyTree(Child);
1905 N->setChild(i, Child);
1912 /// InferAllTypes - Infer/propagate as many types throughout the expression
1913 /// patterns as possible. Return true if all types are inferred, false
1914 /// otherwise. Throw an exception if a type contradiction is found.
1916 InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
1917 if (NamedNodes.empty())
1918 ComputeNamedNodes();
1920 bool MadeChange = true;
1921 while (MadeChange) {
1923 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
1924 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
1925 MadeChange |= SimplifyTree(Trees[i]);
1928 // If there are constraints on our named nodes, apply them.
1929 for (StringMap<SmallVector<TreePatternNode*,1> >::iterator
1930 I = NamedNodes.begin(), E = NamedNodes.end(); I != E; ++I) {
1931 SmallVectorImpl<TreePatternNode*> &Nodes = I->second;
1933 // If we have input named node types, propagate their types to the named
1936 // FIXME: Should be error?
1937 assert(InNamedTypes->count(I->getKey()) &&
1938 "Named node in output pattern but not input pattern?");
1940 const SmallVectorImpl<TreePatternNode*> &InNodes =
1941 InNamedTypes->find(I->getKey())->second;
1943 // The input types should be fully resolved by now.
1944 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
1945 // If this node is a register class, and it is the root of the pattern
1946 // then we're mapping something onto an input register. We allow
1947 // changing the type of the input register in this case. This allows
1948 // us to match things like:
1949 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
1950 if (Nodes[i] == Trees[0] && Nodes[i]->isLeaf()) {
1951 const DefInit *DI = dynamic_cast<const DefInit*>(Nodes[i]->getLeafValue());
1952 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
1953 DI->getDef()->isSubClassOf("RegisterOperand")))
1957 assert(Nodes[i]->getNumTypes() == 1 &&
1958 InNodes[0]->getNumTypes() == 1 &&
1959 "FIXME: cannot name multiple result nodes yet");
1960 MadeChange |= Nodes[i]->UpdateNodeType(0, InNodes[0]->getExtType(0),
1965 // If there are multiple nodes with the same name, they must all have the
1967 if (I->second.size() > 1) {
1968 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
1969 TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
1970 assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
1971 "FIXME: cannot name multiple result nodes yet");
1973 MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
1974 MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
1980 bool HasUnresolvedTypes = false;
1981 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1982 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
1983 return !HasUnresolvedTypes;
1986 void TreePattern::print(raw_ostream &OS) const {
1987 OS << getRecord()->getName();
1988 if (!Args.empty()) {
1989 OS << "(" << Args[0];
1990 for (unsigned i = 1, e = Args.size(); i != e; ++i)
1991 OS << ", " << Args[i];
1996 if (Trees.size() > 1)
1998 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
2000 Trees[i]->print(OS);
2004 if (Trees.size() > 1)
2008 void TreePattern::dump() const { print(errs()); }
2010 //===----------------------------------------------------------------------===//
2011 // CodeGenDAGPatterns implementation
2014 CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) :
2015 Records(R), Target(R) {
2017 Intrinsics = LoadIntrinsics(Records, false);
2018 TgtIntrinsics = LoadIntrinsics(Records, true);
2020 ParseNodeTransforms();
2021 ParseComplexPatterns();
2022 ParsePatternFragments();
2023 ParseDefaultOperands();
2024 ParseInstructions();
2027 // Generate variants. For example, commutative patterns can match
2028 // multiple ways. Add them to PatternsToMatch as well.
2031 // Infer instruction flags. For example, we can detect loads,
2032 // stores, and side effects in many cases by examining an
2033 // instruction's pattern.
2034 InferInstructionFlags();
2037 CodeGenDAGPatterns::~CodeGenDAGPatterns() {
2038 for (pf_iterator I = PatternFragments.begin(),
2039 E = PatternFragments.end(); I != E; ++I)
2044 Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
2045 Record *N = Records.getDef(Name);
2046 if (!N || !N->isSubClassOf("SDNode")) {
2047 errs() << "Error getting SDNode '" << Name << "'!\n";
2053 // Parse all of the SDNode definitions for the target, populating SDNodes.
2054 void CodeGenDAGPatterns::ParseNodeInfo() {
2055 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
2056 while (!Nodes.empty()) {
2057 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
2061 // Get the builtin intrinsic nodes.
2062 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
2063 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
2064 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
2067 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
2068 /// map, and emit them to the file as functions.
2069 void CodeGenDAGPatterns::ParseNodeTransforms() {
2070 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
2071 while (!Xforms.empty()) {
2072 Record *XFormNode = Xforms.back();
2073 Record *SDNode = XFormNode->getValueAsDef("Opcode");
2074 std::string Code = XFormNode->getValueAsCode("XFormFunction");
2075 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
2081 void CodeGenDAGPatterns::ParseComplexPatterns() {
2082 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
2083 while (!AMs.empty()) {
2084 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
2090 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
2091 /// file, building up the PatternFragments map. After we've collected them all,
2092 /// inline fragments together as necessary, so that there are no references left
2093 /// inside a pattern fragment to a pattern fragment.
2095 void CodeGenDAGPatterns::ParsePatternFragments() {
2096 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
2098 // First step, parse all of the fragments.
2099 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
2100 const DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
2101 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
2102 PatternFragments[Fragments[i]] = P;
2104 // Validate the argument list, converting it to set, to discard duplicates.
2105 std::vector<std::string> &Args = P->getArgList();
2106 std::set<std::string> OperandsSet(Args.begin(), Args.end());
2108 if (OperandsSet.count(""))
2109 P->error("Cannot have unnamed 'node' values in pattern fragment!");
2111 // Parse the operands list.
2112 const DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
2113 const DefInit *OpsOp = dynamic_cast<const DefInit*>(OpsList->getOperator());
2114 // Special cases: ops == outs == ins. Different names are used to
2115 // improve readability.
2117 (OpsOp->getDef()->getName() != "ops" &&
2118 OpsOp->getDef()->getName() != "outs" &&
2119 OpsOp->getDef()->getName() != "ins"))
2120 P->error("Operands list should start with '(ops ... '!");
2122 // Copy over the arguments.
2124 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
2125 if (!dynamic_cast<const DefInit*>(OpsList->getArg(j)) ||
2126 static_cast<const DefInit*>(OpsList->getArg(j))->
2127 getDef()->getName() != "node")
2128 P->error("Operands list should all be 'node' values.");
2129 if (OpsList->getArgName(j).empty())
2130 P->error("Operands list should have names for each operand!");
2131 if (!OperandsSet.count(OpsList->getArgName(j)))
2132 P->error("'" + OpsList->getArgName(j) +
2133 "' does not occur in pattern or was multiply specified!");
2134 OperandsSet.erase(OpsList->getArgName(j));
2135 Args.push_back(OpsList->getArgName(j));
2138 if (!OperandsSet.empty())
2139 P->error("Operands list does not contain an entry for operand '" +
2140 *OperandsSet.begin() + "'!");
2142 // If there is a code init for this fragment, keep track of the fact that
2143 // this fragment uses it.
2144 TreePredicateFn PredFn(P);
2145 if (!PredFn.isAlwaysTrue())
2146 P->getOnlyTree()->addPredicateFn(PredFn);
2148 // If there is a node transformation corresponding to this, keep track of
2150 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
2151 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
2152 P->getOnlyTree()->setTransformFn(Transform);
2155 // Now that we've parsed all of the tree fragments, do a closure on them so
2156 // that there are not references to PatFrags left inside of them.
2157 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
2158 TreePattern *ThePat = PatternFragments[Fragments[i]];
2159 ThePat->InlinePatternFragments();
2161 // Infer as many types as possible. Don't worry about it if we don't infer
2162 // all of them, some may depend on the inputs of the pattern.
2164 ThePat->InferAllTypes();
2166 // If this pattern fragment is not supported by this target (no types can
2167 // satisfy its constraints), just ignore it. If the bogus pattern is
2168 // actually used by instructions, the type consistency error will be
2172 // If debugging, print out the pattern fragment result.
2173 DEBUG(ThePat->dump());
2177 void CodeGenDAGPatterns::ParseDefaultOperands() {
2178 std::vector<Record*> DefaultOps[2];
2179 DefaultOps[0] = Records.getAllDerivedDefinitions("PredicateOperand");
2180 DefaultOps[1] = Records.getAllDerivedDefinitions("OptionalDefOperand");
2182 // Find some SDNode.
2183 assert(!SDNodes.empty() && "No SDNodes parsed?");
2184 const Init *SomeSDNode = DefInit::get(SDNodes.begin()->first);
2186 for (unsigned iter = 0; iter != 2; ++iter) {
2187 for (unsigned i = 0, e = DefaultOps[iter].size(); i != e; ++i) {
2188 const DagInit *DefaultInfo = DefaultOps[iter][i]->getValueAsDag("DefaultOps");
2190 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
2191 // SomeSDnode so that we can parse this.
2192 std::vector<std::pair<const Init*, std::string> > Ops;
2193 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
2194 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
2195 DefaultInfo->getArgName(op)));
2196 const DagInit *DI = DagInit::get(SomeSDNode, "", Ops);
2198 // Create a TreePattern to parse this.
2199 TreePattern P(DefaultOps[iter][i], DI, false, *this);
2200 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
2202 // Copy the operands over into a DAGDefaultOperand.
2203 DAGDefaultOperand DefaultOpInfo;
2205 TreePatternNode *T = P.getTree(0);
2206 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
2207 TreePatternNode *TPN = T->getChild(op);
2208 while (TPN->ApplyTypeConstraints(P, false))
2209 /* Resolve all types */;
2211 if (TPN->ContainsUnresolvedType()) {
2213 throw "Value #" + utostr(i) + " of PredicateOperand '" +
2214 DefaultOps[iter][i]->getName() +"' doesn't have a concrete type!";
2216 throw "Value #" + utostr(i) + " of OptionalDefOperand '" +
2217 DefaultOps[iter][i]->getName() +"' doesn't have a concrete type!";
2219 DefaultOpInfo.DefaultOps.push_back(TPN);
2222 // Insert it into the DefaultOperands map so we can find it later.
2223 DefaultOperands[DefaultOps[iter][i]] = DefaultOpInfo;
2228 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
2229 /// instruction input. Return true if this is a real use.
2230 static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
2231 std::map<std::string, TreePatternNode*> &InstInputs) {
2232 // No name -> not interesting.
2233 if (Pat->getName().empty()) {
2234 if (Pat->isLeaf()) {
2235 const DefInit *DI = dynamic_cast<const DefInit*>(Pat->getLeafValue());
2236 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2237 DI->getDef()->isSubClassOf("RegisterOperand")))
2238 I->error("Input " + DI->getDef()->getName() + " must be named!");
2244 if (Pat->isLeaf()) {
2245 const DefInit *DI = dynamic_cast<const DefInit*>(Pat->getLeafValue());
2246 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
2249 Rec = Pat->getOperator();
2252 // SRCVALUE nodes are ignored.
2253 if (Rec->getName() == "srcvalue")
2256 TreePatternNode *&Slot = InstInputs[Pat->getName()];
2262 if (Slot->isLeaf()) {
2263 SlotRec = dynamic_cast<const DefInit*>(Slot->getLeafValue())->getDef();
2265 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
2266 SlotRec = Slot->getOperator();
2269 // Ensure that the inputs agree if we've already seen this input.
2271 I->error("All $" + Pat->getName() + " inputs must agree with each other");
2272 if (Slot->getExtTypes() != Pat->getExtTypes())
2273 I->error("All $" + Pat->getName() + " inputs must agree with each other");
2277 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
2278 /// part of "I", the instruction), computing the set of inputs and outputs of
2279 /// the pattern. Report errors if we see anything naughty.
2280 void CodeGenDAGPatterns::
2281 FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
2282 std::map<std::string, TreePatternNode*> &InstInputs,
2283 std::map<std::string, TreePatternNode*>&InstResults,
2284 std::vector<Record*> &InstImpResults) {
2285 if (Pat->isLeaf()) {
2286 bool isUse = HandleUse(I, Pat, InstInputs);
2287 if (!isUse && Pat->getTransformFn())
2288 I->error("Cannot specify a transform function for a non-input value!");
2292 if (Pat->getOperator()->getName() == "implicit") {
2293 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2294 TreePatternNode *Dest = Pat->getChild(i);
2295 if (!Dest->isLeaf())
2296 I->error("implicitly defined value should be a register!");
2298 const DefInit *Val = dynamic_cast<const DefInit*>(Dest->getLeafValue());
2299 if (!Val || !Val->getDef()->isSubClassOf("Register"))
2300 I->error("implicitly defined value should be a register!");
2301 InstImpResults.push_back(Val->getDef());
2306 if (Pat->getOperator()->getName() != "set") {
2307 // If this is not a set, verify that the children nodes are not void typed,
2309 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2310 if (Pat->getChild(i)->getNumTypes() == 0)
2311 I->error("Cannot have void nodes inside of patterns!");
2312 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
2316 // If this is a non-leaf node with no children, treat it basically as if
2317 // it were a leaf. This handles nodes like (imm).
2318 bool isUse = HandleUse(I, Pat, InstInputs);
2320 if (!isUse && Pat->getTransformFn())
2321 I->error("Cannot specify a transform function for a non-input value!");
2325 // Otherwise, this is a set, validate and collect instruction results.
2326 if (Pat->getNumChildren() == 0)
2327 I->error("set requires operands!");
2329 if (Pat->getTransformFn())
2330 I->error("Cannot specify a transform function on a set node!");
2332 // Check the set destinations.
2333 unsigned NumDests = Pat->getNumChildren()-1;
2334 for (unsigned i = 0; i != NumDests; ++i) {
2335 TreePatternNode *Dest = Pat->getChild(i);
2336 if (!Dest->isLeaf())
2337 I->error("set destination should be a register!");
2339 const DefInit *Val = dynamic_cast<const DefInit*>(Dest->getLeafValue());
2341 I->error("set destination should be a register!");
2343 if (Val->getDef()->isSubClassOf("RegisterClass") ||
2344 Val->getDef()->isSubClassOf("RegisterOperand") ||
2345 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
2346 if (Dest->getName().empty())
2347 I->error("set destination must have a name!");
2348 if (InstResults.count(Dest->getName()))
2349 I->error("cannot set '" + Dest->getName() +"' multiple times");
2350 InstResults[Dest->getName()] = Dest;
2351 } else if (Val->getDef()->isSubClassOf("Register")) {
2352 InstImpResults.push_back(Val->getDef());
2354 I->error("set destination should be a register!");
2358 // Verify and collect info from the computation.
2359 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
2360 InstInputs, InstResults, InstImpResults);
2363 //===----------------------------------------------------------------------===//
2364 // Instruction Analysis
2365 //===----------------------------------------------------------------------===//
2367 class InstAnalyzer {
2368 const CodeGenDAGPatterns &CDP;
2372 bool &HasSideEffects;
2375 InstAnalyzer(const CodeGenDAGPatterns &cdp,
2376 bool &maystore, bool &mayload, bool &isbc, bool &hse, bool &isv)
2377 : CDP(cdp), mayStore(maystore), mayLoad(mayload), IsBitcast(isbc),
2378 HasSideEffects(hse), IsVariadic(isv) {
2381 /// Analyze - Analyze the specified instruction, returning true if the
2382 /// instruction had a pattern.
2383 bool Analyze(Record *InstRecord) {
2384 const TreePattern *Pattern = CDP.getInstruction(InstRecord).getPattern();
2387 return false; // No pattern.
2390 // FIXME: Assume only the first tree is the pattern. The others are clobber
2392 AnalyzeNode(Pattern->getTree(0));
2397 bool IsNodeBitcast(const TreePatternNode *N) const {
2398 if (HasSideEffects || mayLoad || mayStore || IsVariadic)
2401 if (N->getNumChildren() != 2)
2404 const TreePatternNode *N0 = N->getChild(0);
2405 if (!N0->isLeaf() || !dynamic_cast<const DefInit*>(N0->getLeafValue()))
2408 const TreePatternNode *N1 = N->getChild(1);
2411 if (N1->getNumChildren() != 1 || !N1->getChild(0)->isLeaf())
2414 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N1->getOperator());
2415 if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1)
2417 return OpInfo.getEnumName() == "ISD::BITCAST";
2420 void AnalyzeNode(const TreePatternNode *N) {
2422 if (const DefInit *DI = dynamic_cast<const DefInit*>(N->getLeafValue())) {
2423 Record *LeafRec = DI->getDef();
2424 // Handle ComplexPattern leaves.
2425 if (LeafRec->isSubClassOf("ComplexPattern")) {
2426 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
2427 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
2428 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
2429 if (CP.hasProperty(SDNPSideEffect)) HasSideEffects = true;
2435 // Analyze children.
2436 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2437 AnalyzeNode(N->getChild(i));
2439 // Ignore set nodes, which are not SDNodes.
2440 if (N->getOperator()->getName() == "set") {
2441 IsBitcast = IsNodeBitcast(N);
2445 // Get information about the SDNode for the operator.
2446 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N->getOperator());
2448 // Notice properties of the node.
2449 if (OpInfo.hasProperty(SDNPMayStore)) mayStore = true;
2450 if (OpInfo.hasProperty(SDNPMayLoad)) mayLoad = true;
2451 if (OpInfo.hasProperty(SDNPSideEffect)) HasSideEffects = true;
2452 if (OpInfo.hasProperty(SDNPVariadic)) IsVariadic = true;
2454 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
2455 // If this is an intrinsic, analyze it.
2456 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
2457 mayLoad = true;// These may load memory.
2459 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteArgMem)
2460 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
2462 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem)
2463 // WriteMem intrinsics can have other strange effects.
2464 HasSideEffects = true;
2470 static void InferFromPattern(const CodeGenInstruction &Inst,
2471 bool &MayStore, bool &MayLoad,
2473 bool &HasSideEffects, bool &IsVariadic,
2474 const CodeGenDAGPatterns &CDP) {
2475 MayStore = MayLoad = IsBitcast = HasSideEffects = IsVariadic = false;
2478 InstAnalyzer(CDP, MayStore, MayLoad, IsBitcast, HasSideEffects, IsVariadic)
2479 .Analyze(Inst.TheDef);
2481 // InstAnalyzer only correctly analyzes mayStore/mayLoad so far.
2482 if (Inst.mayStore) { // If the .td file explicitly sets mayStore, use it.
2483 // If we decided that this is a store from the pattern, then the .td file
2484 // entry is redundant.
2487 "Warning: mayStore flag explicitly set on instruction '%s'"
2488 " but flag already inferred from pattern.\n",
2489 Inst.TheDef->getName().c_str());
2493 if (Inst.mayLoad) { // If the .td file explicitly sets mayLoad, use it.
2494 // If we decided that this is a load from the pattern, then the .td file
2495 // entry is redundant.
2498 "Warning: mayLoad flag explicitly set on instruction '%s'"
2499 " but flag already inferred from pattern.\n",
2500 Inst.TheDef->getName().c_str());
2504 if (Inst.neverHasSideEffects) {
2506 fprintf(stderr, "Warning: neverHasSideEffects set on instruction '%s' "
2507 "which already has a pattern\n", Inst.TheDef->getName().c_str());
2508 HasSideEffects = false;
2511 if (Inst.hasSideEffects) {
2513 fprintf(stderr, "Warning: hasSideEffects set on instruction '%s' "
2514 "which already inferred this.\n", Inst.TheDef->getName().c_str());
2515 HasSideEffects = true;
2518 if (Inst.Operands.isVariadic)
2519 IsVariadic = true; // Can warn if we want.
2522 /// ParseInstructions - Parse all of the instructions, inlining and resolving
2523 /// any fragments involved. This populates the Instructions list with fully
2524 /// resolved instructions.
2525 void CodeGenDAGPatterns::ParseInstructions() {
2526 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
2528 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
2529 const ListInit *LI = 0;
2531 if (dynamic_cast<const ListInit*>(Instrs[i]->getValueInit("Pattern")))
2532 LI = Instrs[i]->getValueAsListInit("Pattern");
2534 // If there is no pattern, only collect minimal information about the
2535 // instruction for its operand list. We have to assume that there is one
2536 // result, as we have no detailed info.
2537 if (!LI || LI->getSize() == 0) {
2538 std::vector<Record*> Results;
2539 std::vector<Record*> Operands;
2541 CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
2543 if (InstInfo.Operands.size() != 0) {
2544 if (InstInfo.Operands.NumDefs == 0) {
2545 // These produce no results
2546 for (unsigned j = 0, e = InstInfo.Operands.size(); j < e; ++j)
2547 Operands.push_back(InstInfo.Operands[j].Rec);
2549 // Assume the first operand is the result.
2550 Results.push_back(InstInfo.Operands[0].Rec);
2552 // The rest are inputs.
2553 for (unsigned j = 1, e = InstInfo.Operands.size(); j < e; ++j)
2554 Operands.push_back(InstInfo.Operands[j].Rec);
2558 // Create and insert the instruction.
2559 std::vector<Record*> ImpResults;
2560 Instructions.insert(std::make_pair(Instrs[i],
2561 DAGInstruction(0, Results, Operands, ImpResults)));
2562 continue; // no pattern.
2565 // Parse the instruction.
2566 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
2567 // Inline pattern fragments into it.
2568 I->InlinePatternFragments();
2570 // Infer as many types as possible. If we cannot infer all of them, we can
2571 // never do anything with this instruction pattern: report it to the user.
2572 if (!I->InferAllTypes())
2573 I->error("Could not infer all types in pattern!");
2575 // InstInputs - Keep track of all of the inputs of the instruction, along
2576 // with the record they are declared as.
2577 std::map<std::string, TreePatternNode*> InstInputs;
2579 // InstResults - Keep track of all the virtual registers that are 'set'
2580 // in the instruction, including what reg class they are.
2581 std::map<std::string, TreePatternNode*> InstResults;
2583 std::vector<Record*> InstImpResults;
2585 // Verify that the top-level forms in the instruction are of void type, and
2586 // fill in the InstResults map.
2587 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
2588 TreePatternNode *Pat = I->getTree(j);
2589 if (Pat->getNumTypes() != 0)
2590 I->error("Top-level forms in instruction pattern should have"
2593 // Find inputs and outputs, and verify the structure of the uses/defs.
2594 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
2598 // Now that we have inputs and outputs of the pattern, inspect the operands
2599 // list for the instruction. This determines the order that operands are
2600 // added to the machine instruction the node corresponds to.
2601 unsigned NumResults = InstResults.size();
2603 // Parse the operands list from the (ops) list, validating it.
2604 assert(I->getArgList().empty() && "Args list should still be empty here!");
2605 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]);
2607 // Check that all of the results occur first in the list.
2608 std::vector<Record*> Results;
2609 TreePatternNode *Res0Node = 0;
2610 for (unsigned i = 0; i != NumResults; ++i) {
2611 if (i == CGI.Operands.size())
2612 I->error("'" + InstResults.begin()->first +
2613 "' set but does not appear in operand list!");
2614 const std::string &OpName = CGI.Operands[i].Name;
2616 // Check that it exists in InstResults.
2617 TreePatternNode *RNode = InstResults[OpName];
2619 I->error("Operand $" + OpName + " does not exist in operand list!");
2623 Record *R = dynamic_cast<const DefInit*>(RNode->getLeafValue())->getDef();
2625 I->error("Operand $" + OpName + " should be a set destination: all "
2626 "outputs must occur before inputs in operand list!");
2628 if (CGI.Operands[i].Rec != R)
2629 I->error("Operand $" + OpName + " class mismatch!");
2631 // Remember the return type.
2632 Results.push_back(CGI.Operands[i].Rec);
2634 // Okay, this one checks out.
2635 InstResults.erase(OpName);
2638 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
2639 // the copy while we're checking the inputs.
2640 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
2642 std::vector<TreePatternNode*> ResultNodeOperands;
2643 std::vector<Record*> Operands;
2644 for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
2645 CGIOperandList::OperandInfo &Op = CGI.Operands[i];
2646 const std::string &OpName = Op.Name;
2648 I->error("Operand #" + utostr(i) + " in operands list has no name!");
2650 if (!InstInputsCheck.count(OpName)) {
2651 // If this is an predicate operand or optional def operand with an
2652 // DefaultOps set filled in, we can ignore this. When we codegen it,
2653 // we will do so as always executed.
2654 if (Op.Rec->isSubClassOf("PredicateOperand") ||
2655 Op.Rec->isSubClassOf("OptionalDefOperand")) {
2656 // Does it have a non-empty DefaultOps field? If so, ignore this
2658 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
2661 I->error("Operand $" + OpName +
2662 " does not appear in the instruction pattern");
2664 TreePatternNode *InVal = InstInputsCheck[OpName];
2665 InstInputsCheck.erase(OpName); // It occurred, remove from map.
2667 if (InVal->isLeaf() &&
2668 dynamic_cast<const DefInit*>(InVal->getLeafValue())) {
2669 Record *InRec = static_cast<const DefInit*>(InVal->getLeafValue())->getDef();
2670 if (Op.Rec != InRec && !InRec->isSubClassOf("ComplexPattern"))
2671 I->error("Operand $" + OpName + "'s register class disagrees"
2672 " between the operand and pattern");
2674 Operands.push_back(Op.Rec);
2676 // Construct the result for the dest-pattern operand list.
2677 TreePatternNode *OpNode = InVal->clone();
2679 // No predicate is useful on the result.
2680 OpNode->clearPredicateFns();
2682 // Promote the xform function to be an explicit node if set.
2683 if (Record *Xform = OpNode->getTransformFn()) {
2684 OpNode->setTransformFn(0);
2685 std::vector<TreePatternNode*> Children;
2686 Children.push_back(OpNode);
2687 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
2690 ResultNodeOperands.push_back(OpNode);
2693 if (!InstInputsCheck.empty())
2694 I->error("Input operand $" + InstInputsCheck.begin()->first +
2695 " occurs in pattern but not in operands list!");
2697 TreePatternNode *ResultPattern =
2698 new TreePatternNode(I->getRecord(), ResultNodeOperands,
2699 GetNumNodeResults(I->getRecord(), *this));
2700 // Copy fully inferred output node type to instruction result pattern.
2701 for (unsigned i = 0; i != NumResults; ++i)
2702 ResultPattern->setType(i, Res0Node->getExtType(i));
2704 // Create and insert the instruction.
2705 // FIXME: InstImpResults should not be part of DAGInstruction.
2706 DAGInstruction TheInst(I, Results, Operands, InstImpResults);
2707 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
2709 // Use a temporary tree pattern to infer all types and make sure that the
2710 // constructed result is correct. This depends on the instruction already
2711 // being inserted into the Instructions map.
2712 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
2713 Temp.InferAllTypes(&I->getNamedNodesMap());
2715 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
2716 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
2721 // If we can, convert the instructions to be patterns that are matched!
2722 for (std::map<Record*, DAGInstruction, RecordPtrCmp>::iterator II =
2723 Instructions.begin(),
2724 E = Instructions.end(); II != E; ++II) {
2725 DAGInstruction &TheInst = II->second;
2726 const TreePattern *I = TheInst.getPattern();
2727 if (I == 0) continue; // No pattern.
2729 // FIXME: Assume only the first tree is the pattern. The others are clobber
2731 TreePatternNode *Pattern = I->getTree(0);
2732 TreePatternNode *SrcPattern;
2733 if (Pattern->getOperator()->getName() == "set") {
2734 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
2736 // Not a set (store or something?)
2737 SrcPattern = Pattern;
2740 Record *Instr = II->first;
2741 AddPatternToMatch(I,
2742 PatternToMatch(Instr,
2743 Instr->getValueAsListInit("Predicates"),
2745 TheInst.getResultPattern(),
2746 TheInst.getImpResults(),
2747 Instr->getValueAsInt("AddedComplexity"),
2753 typedef std::pair<const TreePatternNode*, unsigned> NameRecord;
2755 static void FindNames(const TreePatternNode *P,
2756 std::map<std::string, NameRecord> &Names,
2757 const TreePattern *PatternTop) {
2758 if (!P->getName().empty()) {
2759 NameRecord &Rec = Names[P->getName()];
2760 // If this is the first instance of the name, remember the node.
2761 if (Rec.second++ == 0)
2763 else if (Rec.first->getExtTypes() != P->getExtTypes())
2764 PatternTop->error("repetition of value: $" + P->getName() +
2765 " where different uses have different types!");
2769 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
2770 FindNames(P->getChild(i), Names, PatternTop);
2774 void CodeGenDAGPatterns::AddPatternToMatch(const TreePattern *Pattern,
2775 const PatternToMatch &PTM) {
2776 // Do some sanity checking on the pattern we're about to match.
2778 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this))
2779 Pattern->error("Pattern can never match: " + Reason);
2781 // If the source pattern's root is a complex pattern, that complex pattern
2782 // must specify the nodes it can potentially match.
2783 if (const ComplexPattern *CP =
2784 PTM.getSrcPattern()->getComplexPatternInfo(*this))
2785 if (CP->getRootNodes().empty())
2786 Pattern->error("ComplexPattern at root must specify list of opcodes it"
2790 // Find all of the named values in the input and output, ensure they have the
2792 std::map<std::string, NameRecord> SrcNames, DstNames;
2793 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
2794 FindNames(PTM.getDstPattern(), DstNames, Pattern);
2796 // Scan all of the named values in the destination pattern, rejecting them if
2797 // they don't exist in the input pattern.
2798 for (std::map<std::string, NameRecord>::iterator
2799 I = DstNames.begin(), E = DstNames.end(); I != E; ++I) {
2800 if (SrcNames[I->first].first == 0)
2801 Pattern->error("Pattern has input without matching name in output: $" +
2805 // Scan all of the named values in the source pattern, rejecting them if the
2806 // name isn't used in the dest, and isn't used to tie two values together.
2807 for (std::map<std::string, NameRecord>::iterator
2808 I = SrcNames.begin(), E = SrcNames.end(); I != E; ++I)
2809 if (DstNames[I->first].first == 0 && SrcNames[I->first].second == 1)
2810 Pattern->error("Pattern has dead named input: $" + I->first);
2812 PatternsToMatch.push_back(PTM);
2817 void CodeGenDAGPatterns::InferInstructionFlags() {
2818 const std::vector<const CodeGenInstruction*> &Instructions =
2819 Target.getInstructionsByEnumValue();
2820 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
2821 CodeGenInstruction &InstInfo =
2822 const_cast<CodeGenInstruction &>(*Instructions[i]);
2823 // Determine properties of the instruction from its pattern.
2824 bool MayStore, MayLoad, IsBitcast, HasSideEffects, IsVariadic;
2825 InferFromPattern(InstInfo, MayStore, MayLoad, IsBitcast,
2826 HasSideEffects, IsVariadic, *this);
2827 InstInfo.mayStore = MayStore;
2828 InstInfo.mayLoad = MayLoad;
2829 InstInfo.isBitcast = IsBitcast;
2830 InstInfo.hasSideEffects = HasSideEffects;
2831 InstInfo.Operands.isVariadic = IsVariadic;
2835 /// Given a pattern result with an unresolved type, see if we can find one
2836 /// instruction with an unresolved result type. Force this result type to an
2837 /// arbitrary element if it's possible types to converge results.
2838 static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
2842 // Analyze children.
2843 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2844 if (ForceArbitraryInstResultType(N->getChild(i), TP))
2847 if (!N->getOperator()->isSubClassOf("Instruction"))
2850 // If this type is already concrete or completely unknown we can't do
2852 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
2853 if (N->getExtType(i).isCompletelyUnknown() || N->getExtType(i).isConcrete())
2856 // Otherwise, force its type to the first possibility (an arbitrary choice).
2857 if (N->getExtType(i).MergeInTypeInfo(N->getExtType(i).getTypeList()[0], TP))
2864 void CodeGenDAGPatterns::ParsePatterns() {
2865 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
2867 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
2868 Record *CurPattern = Patterns[i];
2869 const DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
2870 TreePattern *Pattern = new TreePattern(CurPattern, Tree, true, *this);
2872 // Inline pattern fragments into it.
2873 Pattern->InlinePatternFragments();
2875 const ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
2876 if (LI->getSize() == 0) continue; // no pattern.
2878 // Parse the instruction.
2879 TreePattern *Result = new TreePattern(CurPattern, LI, false, *this);
2881 // Inline pattern fragments into it.
2882 Result->InlinePatternFragments();
2884 if (Result->getNumTrees() != 1)
2885 Result->error("Cannot handle instructions producing instructions "
2886 "with temporaries yet!");
2888 bool IterateInference;
2889 bool InferredAllPatternTypes, InferredAllResultTypes;
2891 // Infer as many types as possible. If we cannot infer all of them, we
2892 // can never do anything with this pattern: report it to the user.
2893 InferredAllPatternTypes =
2894 Pattern->InferAllTypes(&Pattern->getNamedNodesMap());
2896 // Infer as many types as possible. If we cannot infer all of them, we
2897 // can never do anything with this pattern: report it to the user.
2898 InferredAllResultTypes =
2899 Result->InferAllTypes(&Pattern->getNamedNodesMap());
2901 IterateInference = false;
2903 // Apply the type of the result to the source pattern. This helps us
2904 // resolve cases where the input type is known to be a pointer type (which
2905 // is considered resolved), but the result knows it needs to be 32- or
2906 // 64-bits. Infer the other way for good measure.
2907 for (unsigned i = 0, e = std::min(Result->getTree(0)->getNumTypes(),
2908 Pattern->getTree(0)->getNumTypes());
2910 IterateInference = Pattern->getTree(0)->
2911 UpdateNodeType(i, Result->getTree(0)->getExtType(i), *Result);
2912 IterateInference |= Result->getTree(0)->
2913 UpdateNodeType(i, Pattern->getTree(0)->getExtType(i), *Result);
2916 // If our iteration has converged and the input pattern's types are fully
2917 // resolved but the result pattern is not fully resolved, we may have a
2918 // situation where we have two instructions in the result pattern and
2919 // the instructions require a common register class, but don't care about
2920 // what actual MVT is used. This is actually a bug in our modelling:
2921 // output patterns should have register classes, not MVTs.
2923 // In any case, to handle this, we just go through and disambiguate some
2924 // arbitrary types to the result pattern's nodes.
2925 if (!IterateInference && InferredAllPatternTypes &&
2926 !InferredAllResultTypes)
2927 IterateInference = ForceArbitraryInstResultType(Result->getTree(0),
2929 } while (IterateInference);
2931 // Verify that we inferred enough types that we can do something with the
2932 // pattern and result. If these fire the user has to add type casts.
2933 if (!InferredAllPatternTypes)
2934 Pattern->error("Could not infer all types in pattern!");
2935 if (!InferredAllResultTypes) {
2937 Result->error("Could not infer all types in pattern result!");
2940 // Validate that the input pattern is correct.
2941 std::map<std::string, TreePatternNode*> InstInputs;
2942 std::map<std::string, TreePatternNode*> InstResults;
2943 std::vector<Record*> InstImpResults;
2944 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
2945 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
2946 InstInputs, InstResults,
2949 // Promote the xform function to be an explicit node if set.
2950 TreePatternNode *DstPattern = Result->getOnlyTree();
2951 std::vector<TreePatternNode*> ResultNodeOperands;
2952 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
2953 TreePatternNode *OpNode = DstPattern->getChild(ii);
2954 if (Record *Xform = OpNode->getTransformFn()) {
2955 OpNode->setTransformFn(0);
2956 std::vector<TreePatternNode*> Children;
2957 Children.push_back(OpNode);
2958 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
2960 ResultNodeOperands.push_back(OpNode);
2962 DstPattern = Result->getOnlyTree();
2963 if (!DstPattern->isLeaf())
2964 DstPattern = new TreePatternNode(DstPattern->getOperator(),
2966 DstPattern->getNumTypes());
2968 for (unsigned i = 0, e = Result->getOnlyTree()->getNumTypes(); i != e; ++i)
2969 DstPattern->setType(i, Result->getOnlyTree()->getExtType(i));
2971 TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
2972 Temp.InferAllTypes();
2975 AddPatternToMatch(Pattern,
2976 PatternToMatch(CurPattern,
2977 CurPattern->getValueAsListInit("Predicates"),
2978 Pattern->getTree(0),
2979 Temp.getOnlyTree(), InstImpResults,
2980 CurPattern->getValueAsInt("AddedComplexity"),
2981 CurPattern->getID()));
2985 /// CombineChildVariants - Given a bunch of permutations of each child of the
2986 /// 'operator' node, put them together in all possible ways.
2987 static void CombineChildVariants(TreePatternNode *Orig,
2988 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
2989 std::vector<TreePatternNode*> &OutVariants,
2990 CodeGenDAGPatterns &CDP,
2991 const MultipleUseVarSet &DepVars) {
2992 // Make sure that each operand has at least one variant to choose from.
2993 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2994 if (ChildVariants[i].empty())
2997 // The end result is an all-pairs construction of the resultant pattern.
2998 std::vector<unsigned> Idxs;
2999 Idxs.resize(ChildVariants.size());
3003 DEBUG(if (!Idxs.empty()) {
3004 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
3005 for (unsigned i = 0; i < Idxs.size(); ++i) {
3006 errs() << Idxs[i] << " ";
3011 // Create the variant and add it to the output list.
3012 std::vector<TreePatternNode*> NewChildren;
3013 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
3014 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
3015 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren,
3016 Orig->getNumTypes());
3018 // Copy over properties.
3019 R->setName(Orig->getName());
3020 R->setPredicateFns(Orig->getPredicateFns());
3021 R->setTransformFn(Orig->getTransformFn());
3022 for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
3023 R->setType(i, Orig->getExtType(i));
3025 // If this pattern cannot match, do not include it as a variant.
3026 std::string ErrString;
3027 if (!R->canPatternMatch(ErrString, CDP)) {
3030 bool AlreadyExists = false;
3032 // Scan to see if this pattern has already been emitted. We can get
3033 // duplication due to things like commuting:
3034 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
3035 // which are the same pattern. Ignore the dups.
3036 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
3037 if (R->isIsomorphicTo(OutVariants[i], DepVars)) {
3038 AlreadyExists = true;
3045 OutVariants.push_back(R);
3048 // Increment indices to the next permutation by incrementing the
3049 // indicies from last index backward, e.g., generate the sequence
3050 // [0, 0], [0, 1], [1, 0], [1, 1].
3052 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
3053 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
3058 NotDone = (IdxsIdx >= 0);
3062 /// CombineChildVariants - A helper function for binary operators.
3064 static void CombineChildVariants(TreePatternNode *Orig,
3065 const std::vector<TreePatternNode*> &LHS,
3066 const std::vector<TreePatternNode*> &RHS,
3067 std::vector<TreePatternNode*> &OutVariants,
3068 CodeGenDAGPatterns &CDP,
3069 const MultipleUseVarSet &DepVars) {
3070 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3071 ChildVariants.push_back(LHS);
3072 ChildVariants.push_back(RHS);
3073 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
3077 static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
3078 std::vector<TreePatternNode *> &Children) {
3079 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
3080 Record *Operator = N->getOperator();
3082 // Only permit raw nodes.
3083 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
3084 N->getTransformFn()) {
3085 Children.push_back(N);
3089 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
3090 Children.push_back(N->getChild(0));
3092 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
3094 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
3095 Children.push_back(N->getChild(1));
3097 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
3100 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
3101 /// the (potentially recursive) pattern by using algebraic laws.
3103 static void GenerateVariantsOf(TreePatternNode *N,
3104 std::vector<TreePatternNode*> &OutVariants,
3105 CodeGenDAGPatterns &CDP,
3106 const MultipleUseVarSet &DepVars) {
3107 // We cannot permute leaves.
3109 OutVariants.push_back(N);
3113 // Look up interesting info about the node.
3114 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
3116 // If this node is associative, re-associate.
3117 if (NodeInfo.hasProperty(SDNPAssociative)) {
3118 // Re-associate by pulling together all of the linked operators
3119 std::vector<TreePatternNode*> MaximalChildren;
3120 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
3122 // Only handle child sizes of 3. Otherwise we'll end up trying too many
3124 if (MaximalChildren.size() == 3) {
3125 // Find the variants of all of our maximal children.
3126 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
3127 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
3128 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
3129 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
3131 // There are only two ways we can permute the tree:
3132 // (A op B) op C and A op (B op C)
3133 // Within these forms, we can also permute A/B/C.
3135 // Generate legal pair permutations of A/B/C.
3136 std::vector<TreePatternNode*> ABVariants;
3137 std::vector<TreePatternNode*> BAVariants;
3138 std::vector<TreePatternNode*> ACVariants;
3139 std::vector<TreePatternNode*> CAVariants;
3140 std::vector<TreePatternNode*> BCVariants;
3141 std::vector<TreePatternNode*> CBVariants;
3142 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
3143 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
3144 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
3145 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
3146 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
3147 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
3149 // Combine those into the result: (x op x) op x
3150 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
3151 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
3152 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
3153 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
3154 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
3155 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
3157 // Combine those into the result: x op (x op x)
3158 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
3159 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
3160 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
3161 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
3162 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
3163 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
3168 // Compute permutations of all children.
3169 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3170 ChildVariants.resize(N->getNumChildren());
3171 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3172 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
3174 // Build all permutations based on how the children were formed.
3175 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
3177 // If this node is commutative, consider the commuted order.
3178 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
3179 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
3180 assert((N->getNumChildren()==2 || isCommIntrinsic) &&
3181 "Commutative but doesn't have 2 children!");
3182 // Don't count children which are actually register references.
3184 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
3185 TreePatternNode *Child = N->getChild(i);
3186 if (Child->isLeaf())
3187 if (const DefInit *DI = dynamic_cast<const DefInit*>(Child->getLeafValue())) {
3188 Record *RR = DI->getDef();
3189 if (RR->isSubClassOf("Register"))
3194 // Consider the commuted order.
3195 if (isCommIntrinsic) {
3196 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
3197 // operands are the commutative operands, and there might be more operands
3200 "Commutative intrinsic should have at least 3 childrean!");
3201 std::vector<std::vector<TreePatternNode*> > Variants;
3202 Variants.push_back(ChildVariants[0]); // Intrinsic id.
3203 Variants.push_back(ChildVariants[2]);
3204 Variants.push_back(ChildVariants[1]);
3205 for (unsigned i = 3; i != NC; ++i)
3206 Variants.push_back(ChildVariants[i]);
3207 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
3209 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
3210 OutVariants, CDP, DepVars);
3215 // GenerateVariants - Generate variants. For example, commutative patterns can
3216 // match multiple ways. Add them to PatternsToMatch as well.
3217 void CodeGenDAGPatterns::GenerateVariants() {
3218 DEBUG(errs() << "Generating instruction variants.\n");
3220 // Loop over all of the patterns we've collected, checking to see if we can
3221 // generate variants of the instruction, through the exploitation of
3222 // identities. This permits the target to provide aggressive matching without
3223 // the .td file having to contain tons of variants of instructions.
3225 // Note that this loop adds new patterns to the PatternsToMatch list, but we
3226 // intentionally do not reconsider these. Any variants of added patterns have
3227 // already been added.
3229 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
3230 MultipleUseVarSet DepVars;
3231 std::vector<TreePatternNode*> Variants;
3232 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
3233 DEBUG(errs() << "Dependent/multiply used variables: ");
3234 DEBUG(DumpDepVars(DepVars));
3235 DEBUG(errs() << "\n");
3236 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this,
3239 assert(!Variants.empty() && "Must create at least original variant!");
3240 Variants.erase(Variants.begin()); // Remove the original pattern.
3242 if (Variants.empty()) // No variants for this pattern.
3245 DEBUG(errs() << "FOUND VARIANTS OF: ";
3246 PatternsToMatch[i].getSrcPattern()->dump();
3249 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
3250 TreePatternNode *Variant = Variants[v];
3252 DEBUG(errs() << " VAR#" << v << ": ";
3256 // Scan to see if an instruction or explicit pattern already matches this.
3257 bool AlreadyExists = false;
3258 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
3259 // Skip if the top level predicates do not match.
3260 if (PatternsToMatch[i].getPredicates() !=
3261 PatternsToMatch[p].getPredicates())
3263 // Check to see if this variant already exists.
3264 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),
3266 DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
3267 AlreadyExists = true;
3271 // If we already have it, ignore the variant.
3272 if (AlreadyExists) continue;
3274 // Otherwise, add it to the list of patterns we have.
3276 push_back(PatternToMatch(PatternsToMatch[i].getSrcRecord(),
3277 PatternsToMatch[i].getPredicates(),
3278 Variant, PatternsToMatch[i].getDstPattern(),
3279 PatternsToMatch[i].getDstRegs(),
3280 PatternsToMatch[i].getAddedComplexity(),
3281 Record::getNewUID()));
3284 DEBUG(errs() << "\n");