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"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/ADT/Twine.h"
19 #include "llvm/Support/Debug.h"
20 #include "llvm/Support/ErrorHandling.h"
21 #include "llvm/TableGen/Error.h"
22 #include "llvm/TableGen/Record.h"
28 //===----------------------------------------------------------------------===//
29 // EEVT::TypeSet Implementation
30 //===----------------------------------------------------------------------===//
32 static inline bool isInteger(MVT::SimpleValueType VT) {
33 return EVT(VT).isInteger();
35 static inline bool isFloatingPoint(MVT::SimpleValueType VT) {
36 return EVT(VT).isFloatingPoint();
38 static inline bool isVector(MVT::SimpleValueType VT) {
39 return EVT(VT).isVector();
41 static inline bool isScalar(MVT::SimpleValueType VT) {
42 return !EVT(VT).isVector();
45 EEVT::TypeSet::TypeSet(MVT::SimpleValueType VT, TreePattern &TP) {
48 else if (VT == MVT::fAny)
49 EnforceFloatingPoint(TP);
50 else if (VT == MVT::vAny)
53 assert((VT < MVT::LAST_VALUETYPE || VT == MVT::iPTR ||
54 VT == MVT::iPTRAny) && "Not a concrete type!");
55 TypeVec.push_back(VT);
60 EEVT::TypeSet::TypeSet(ArrayRef<MVT::SimpleValueType> VTList) {
61 assert(!VTList.empty() && "empty list?");
62 TypeVec.append(VTList.begin(), VTList.end());
65 assert(VTList[0] != MVT::iAny && VTList[0] != MVT::vAny &&
66 VTList[0] != MVT::fAny);
68 // Verify no duplicates.
69 array_pod_sort(TypeVec.begin(), TypeVec.end());
70 assert(std::unique(TypeVec.begin(), TypeVec.end()) == TypeVec.end());
73 /// FillWithPossibleTypes - Set to all legal types and return true, only valid
74 /// on completely unknown type sets.
75 bool EEVT::TypeSet::FillWithPossibleTypes(TreePattern &TP,
76 bool (*Pred)(MVT::SimpleValueType),
77 const char *PredicateName) {
78 assert(isCompletelyUnknown());
79 ArrayRef<MVT::SimpleValueType> LegalTypes =
80 TP.getDAGPatterns().getTargetInfo().getLegalValueTypes();
85 for (unsigned i = 0, e = LegalTypes.size(); i != e; ++i)
86 if (Pred == 0 || Pred(LegalTypes[i]))
87 TypeVec.push_back(LegalTypes[i]);
89 // If we have nothing that matches the predicate, bail out.
90 if (TypeVec.empty()) {
91 TP.error("Type inference contradiction found, no " +
92 std::string(PredicateName) + " types found");
95 // No need to sort with one element.
96 if (TypeVec.size() == 1) return true;
99 array_pod_sort(TypeVec.begin(), TypeVec.end());
100 TypeVec.erase(std::unique(TypeVec.begin(), TypeVec.end()), TypeVec.end());
105 /// hasIntegerTypes - Return true if this TypeSet contains iAny or an
106 /// integer value type.
107 bool EEVT::TypeSet::hasIntegerTypes() const {
108 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
109 if (isInteger(TypeVec[i]))
114 /// hasFloatingPointTypes - Return true if this TypeSet contains an fAny or
115 /// a floating point value type.
116 bool EEVT::TypeSet::hasFloatingPointTypes() const {
117 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
118 if (isFloatingPoint(TypeVec[i]))
123 /// hasVectorTypes - Return true if this TypeSet contains a vAny or a vector
125 bool EEVT::TypeSet::hasVectorTypes() const {
126 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
127 if (isVector(TypeVec[i]))
133 std::string EEVT::TypeSet::getName() const {
134 if (TypeVec.empty()) return "<empty>";
138 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i) {
139 std::string VTName = llvm::getEnumName(TypeVec[i]);
140 // Strip off MVT:: prefix if present.
141 if (VTName.substr(0,5) == "MVT::")
142 VTName = VTName.substr(5);
143 if (i) Result += ':';
147 if (TypeVec.size() == 1)
149 return "{" + Result + "}";
152 /// MergeInTypeInfo - This merges in type information from the specified
153 /// argument. If 'this' changes, it returns true. If the two types are
154 /// contradictory (e.g. merge f32 into i32) then this flags an error.
155 bool EEVT::TypeSet::MergeInTypeInfo(const EEVT::TypeSet &InVT, TreePattern &TP){
156 if (InVT.isCompletelyUnknown() || *this == InVT || TP.hasError())
159 if (isCompletelyUnknown()) {
164 assert(TypeVec.size() >= 1 && InVT.TypeVec.size() >= 1 && "No unknowns");
166 // Handle the abstract cases, seeing if we can resolve them better.
167 switch (TypeVec[0]) {
171 if (InVT.hasIntegerTypes()) {
172 EEVT::TypeSet InCopy(InVT);
173 InCopy.EnforceInteger(TP);
174 InCopy.EnforceScalar(TP);
176 if (InCopy.isConcrete()) {
177 // If the RHS has one integer type, upgrade iPTR to i32.
178 TypeVec[0] = InVT.TypeVec[0];
182 // If the input has multiple scalar integers, this doesn't add any info.
183 if (!InCopy.isCompletelyUnknown())
189 // If the input constraint is iAny/iPTR and this is an integer type list,
190 // remove non-integer types from the list.
191 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
193 bool MadeChange = EnforceInteger(TP);
195 // If we're merging in iPTR/iPTRAny and the node currently has a list of
196 // multiple different integer types, replace them with a single iPTR.
197 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
198 TypeVec.size() != 1) {
200 TypeVec[0] = InVT.TypeVec[0];
207 // If this is a type list and the RHS is a typelist as well, eliminate entries
208 // from this list that aren't in the other one.
209 bool MadeChange = false;
210 TypeSet InputSet(*this);
212 for (unsigned i = 0; i != TypeVec.size(); ++i) {
214 for (unsigned j = 0, e = InVT.TypeVec.size(); j != e; ++j)
215 if (TypeVec[i] == InVT.TypeVec[j]) {
220 if (InInVT) continue;
221 TypeVec.erase(TypeVec.begin()+i--);
225 // If we removed all of our types, we have a type contradiction.
226 if (!TypeVec.empty())
229 // FIXME: Really want an SMLoc here!
230 TP.error("Type inference contradiction found, merging '" +
231 InVT.getName() + "' into '" + InputSet.getName() + "'");
235 /// EnforceInteger - Remove all non-integer types from this set.
236 bool EEVT::TypeSet::EnforceInteger(TreePattern &TP) {
239 // If we know nothing, then get the full set.
241 return FillWithPossibleTypes(TP, isInteger, "integer");
242 if (!hasFloatingPointTypes())
245 TypeSet InputSet(*this);
247 // Filter out all the fp types.
248 for (unsigned i = 0; i != TypeVec.size(); ++i)
249 if (!isInteger(TypeVec[i]))
250 TypeVec.erase(TypeVec.begin()+i--);
252 if (TypeVec.empty()) {
253 TP.error("Type inference contradiction found, '" +
254 InputSet.getName() + "' needs to be integer");
260 /// EnforceFloatingPoint - Remove all integer types from this set.
261 bool EEVT::TypeSet::EnforceFloatingPoint(TreePattern &TP) {
264 // If we know nothing, then get the full set.
266 return FillWithPossibleTypes(TP, isFloatingPoint, "floating point");
268 if (!hasIntegerTypes())
271 TypeSet InputSet(*this);
273 // Filter out all the fp types.
274 for (unsigned i = 0; i != TypeVec.size(); ++i)
275 if (!isFloatingPoint(TypeVec[i]))
276 TypeVec.erase(TypeVec.begin()+i--);
278 if (TypeVec.empty()) {
279 TP.error("Type inference contradiction found, '" +
280 InputSet.getName() + "' needs to be floating point");
286 /// EnforceScalar - Remove all vector types from this.
287 bool EEVT::TypeSet::EnforceScalar(TreePattern &TP) {
291 // If we know nothing, then get the full set.
293 return FillWithPossibleTypes(TP, isScalar, "scalar");
295 if (!hasVectorTypes())
298 TypeSet InputSet(*this);
300 // Filter out all the vector types.
301 for (unsigned i = 0; i != TypeVec.size(); ++i)
302 if (!isScalar(TypeVec[i]))
303 TypeVec.erase(TypeVec.begin()+i--);
305 if (TypeVec.empty()) {
306 TP.error("Type inference contradiction found, '" +
307 InputSet.getName() + "' needs to be scalar");
313 /// EnforceVector - Remove all vector types from this.
314 bool EEVT::TypeSet::EnforceVector(TreePattern &TP) {
318 // If we know nothing, then get the full set.
320 return FillWithPossibleTypes(TP, isVector, "vector");
322 TypeSet InputSet(*this);
323 bool MadeChange = false;
325 // Filter out all the scalar types.
326 for (unsigned i = 0; i != TypeVec.size(); ++i)
327 if (!isVector(TypeVec[i])) {
328 TypeVec.erase(TypeVec.begin()+i--);
332 if (TypeVec.empty()) {
333 TP.error("Type inference contradiction found, '" +
334 InputSet.getName() + "' needs to be a vector");
342 /// EnforceSmallerThan - 'this' must be a smaller VT than Other. Update
343 /// this an other based on this information.
344 bool EEVT::TypeSet::EnforceSmallerThan(EEVT::TypeSet &Other, TreePattern &TP) {
348 // Both operands must be integer or FP, but we don't care which.
349 bool MadeChange = false;
351 if (isCompletelyUnknown())
352 MadeChange = FillWithPossibleTypes(TP);
354 if (Other.isCompletelyUnknown())
355 MadeChange = Other.FillWithPossibleTypes(TP);
357 // If one side is known to be integer or known to be FP but the other side has
358 // no information, get at least the type integrality info in there.
359 if (!hasFloatingPointTypes())
360 MadeChange |= Other.EnforceInteger(TP);
361 else if (!hasIntegerTypes())
362 MadeChange |= Other.EnforceFloatingPoint(TP);
363 if (!Other.hasFloatingPointTypes())
364 MadeChange |= EnforceInteger(TP);
365 else if (!Other.hasIntegerTypes())
366 MadeChange |= EnforceFloatingPoint(TP);
368 assert(!isCompletelyUnknown() && !Other.isCompletelyUnknown() &&
369 "Should have a type list now");
371 // If one contains vectors but the other doesn't pull vectors out.
372 if (!hasVectorTypes())
373 MadeChange |= Other.EnforceScalar(TP);
374 if (!hasVectorTypes())
375 MadeChange |= EnforceScalar(TP);
377 if (TypeVec.size() == 1 && Other.TypeVec.size() == 1) {
378 // If we are down to concrete types, this code does not currently
379 // handle nodes which have multiple types, where some types are
380 // integer, and some are fp. Assert that this is not the case.
381 assert(!(hasIntegerTypes() && hasFloatingPointTypes()) &&
382 !(Other.hasIntegerTypes() && Other.hasFloatingPointTypes()) &&
383 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
385 // Otherwise, if these are both vector types, either this vector
386 // must have a larger bitsize than the other, or this element type
387 // must be larger than the other.
388 EVT Type(TypeVec[0]);
389 EVT OtherType(Other.TypeVec[0]);
391 if (hasVectorTypes() && Other.hasVectorTypes()) {
392 if (Type.getSizeInBits() >= OtherType.getSizeInBits())
393 if (Type.getVectorElementType().getSizeInBits()
394 >= OtherType.getVectorElementType().getSizeInBits()) {
395 TP.error("Type inference contradiction found, '" +
396 getName() + "' element type not smaller than '" +
397 Other.getName() +"'!");
402 // For scalar types, the bitsize of this type must be larger
403 // than that of the other.
404 if (Type.getSizeInBits() >= OtherType.getSizeInBits()) {
405 TP.error("Type inference contradiction found, '" +
406 getName() + "' is not smaller than '" +
407 Other.getName() +"'!");
413 // Handle int and fp as disjoint sets. This won't work for patterns
414 // that have mixed fp/int types but those are likely rare and would
415 // not have been accepted by this code previously.
417 // Okay, find the smallest type from the current set and remove it from the
419 MVT::SimpleValueType SmallestInt = MVT::LAST_VALUETYPE;
420 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
421 if (isInteger(TypeVec[i])) {
422 SmallestInt = TypeVec[i];
425 for (unsigned i = 1, e = TypeVec.size(); i != e; ++i)
426 if (isInteger(TypeVec[i]) && TypeVec[i] < SmallestInt)
427 SmallestInt = TypeVec[i];
429 MVT::SimpleValueType SmallestFP = MVT::LAST_VALUETYPE;
430 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
431 if (isFloatingPoint(TypeVec[i])) {
432 SmallestFP = TypeVec[i];
435 for (unsigned i = 1, e = TypeVec.size(); i != e; ++i)
436 if (isFloatingPoint(TypeVec[i]) && TypeVec[i] < SmallestFP)
437 SmallestFP = TypeVec[i];
439 int OtherIntSize = 0;
441 for (SmallVector<MVT::SimpleValueType, 2>::iterator TVI =
442 Other.TypeVec.begin();
443 TVI != Other.TypeVec.end();
445 if (isInteger(*TVI)) {
447 if (*TVI == SmallestInt) {
448 TVI = Other.TypeVec.erase(TVI);
454 else if (isFloatingPoint(*TVI)) {
456 if (*TVI == SmallestFP) {
457 TVI = Other.TypeVec.erase(TVI);
466 // If this is the only type in the large set, the constraint can never be
468 if ((Other.hasIntegerTypes() && OtherIntSize == 0)
469 || (Other.hasFloatingPointTypes() && OtherFPSize == 0)) {
470 TP.error("Type inference contradiction found, '" +
471 Other.getName() + "' has nothing larger than '" + getName() +"'!");
475 // Okay, find the largest type in the Other set and remove it from the
477 MVT::SimpleValueType LargestInt = MVT::Other;
478 for (unsigned i = 0, e = Other.TypeVec.size(); i != e; ++i)
479 if (isInteger(Other.TypeVec[i])) {
480 LargestInt = Other.TypeVec[i];
483 for (unsigned i = 1, e = Other.TypeVec.size(); i != e; ++i)
484 if (isInteger(Other.TypeVec[i]) && Other.TypeVec[i] > LargestInt)
485 LargestInt = Other.TypeVec[i];
487 MVT::SimpleValueType LargestFP = MVT::Other;
488 for (unsigned i = 0, e = Other.TypeVec.size(); i != e; ++i)
489 if (isFloatingPoint(Other.TypeVec[i])) {
490 LargestFP = Other.TypeVec[i];
493 for (unsigned i = 1, e = Other.TypeVec.size(); i != e; ++i)
494 if (isFloatingPoint(Other.TypeVec[i]) && Other.TypeVec[i] > LargestFP)
495 LargestFP = Other.TypeVec[i];
499 for (SmallVector<MVT::SimpleValueType, 2>::iterator TVI =
501 TVI != TypeVec.end();
503 if (isInteger(*TVI)) {
505 if (*TVI == LargestInt) {
506 TVI = TypeVec.erase(TVI);
512 else if (isFloatingPoint(*TVI)) {
514 if (*TVI == LargestFP) {
515 TVI = TypeVec.erase(TVI);
524 // If this is the only type in the small set, the constraint can never be
526 if ((hasIntegerTypes() && IntSize == 0)
527 || (hasFloatingPointTypes() && FPSize == 0)) {
528 TP.error("Type inference contradiction found, '" +
529 getName() + "' has nothing smaller than '" + Other.getName()+"'!");
536 /// EnforceVectorEltTypeIs - 'this' is now constrainted to be a vector type
537 /// whose element is specified by VTOperand.
538 bool EEVT::TypeSet::EnforceVectorEltTypeIs(EEVT::TypeSet &VTOperand,
543 // "This" must be a vector and "VTOperand" must be a scalar.
544 bool MadeChange = false;
545 MadeChange |= EnforceVector(TP);
546 MadeChange |= VTOperand.EnforceScalar(TP);
548 // If we know the vector type, it forces the scalar to agree.
550 EVT IVT = getConcrete();
551 IVT = IVT.getVectorElementType();
553 VTOperand.MergeInTypeInfo(IVT.getSimpleVT().SimpleTy, TP);
556 // If the scalar type is known, filter out vector types whose element types
558 if (!VTOperand.isConcrete())
561 MVT::SimpleValueType VT = VTOperand.getConcrete();
563 TypeSet InputSet(*this);
565 // Filter out all the types which don't have the right element type.
566 for (unsigned i = 0; i != TypeVec.size(); ++i) {
567 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
568 if (EVT(TypeVec[i]).getVectorElementType().getSimpleVT().SimpleTy != VT) {
569 TypeVec.erase(TypeVec.begin()+i--);
574 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
575 TP.error("Type inference contradiction found, forcing '" +
576 InputSet.getName() + "' to have a vector element");
582 /// EnforceVectorSubVectorTypeIs - 'this' is now constrainted to be a
583 /// vector type specified by VTOperand.
584 bool EEVT::TypeSet::EnforceVectorSubVectorTypeIs(EEVT::TypeSet &VTOperand,
586 // "This" must be a vector and "VTOperand" must be a vector.
587 bool MadeChange = false;
588 MadeChange |= EnforceVector(TP);
589 MadeChange |= VTOperand.EnforceVector(TP);
591 // "This" must be larger than "VTOperand."
592 MadeChange |= VTOperand.EnforceSmallerThan(*this, TP);
594 // If we know the vector type, it forces the scalar types to agree.
596 EVT IVT = getConcrete();
597 IVT = IVT.getVectorElementType();
599 EEVT::TypeSet EltTypeSet(IVT.getSimpleVT().SimpleTy, TP);
600 MadeChange |= VTOperand.EnforceVectorEltTypeIs(EltTypeSet, TP);
601 } else if (VTOperand.isConcrete()) {
602 EVT IVT = VTOperand.getConcrete();
603 IVT = IVT.getVectorElementType();
605 EEVT::TypeSet EltTypeSet(IVT.getSimpleVT().SimpleTy, TP);
606 MadeChange |= EnforceVectorEltTypeIs(EltTypeSet, TP);
612 //===----------------------------------------------------------------------===//
613 // Helpers for working with extended types.
615 /// Dependent variable map for CodeGenDAGPattern variant generation
616 typedef std::map<std::string, int> DepVarMap;
618 /// Const iterator shorthand for DepVarMap
619 typedef DepVarMap::const_iterator DepVarMap_citer;
621 static void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
623 if (isa<DefInit>(N->getLeafValue()))
624 DepMap[N->getName()]++;
626 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
627 FindDepVarsOf(N->getChild(i), DepMap);
631 /// Find dependent variables within child patterns
632 static void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
634 FindDepVarsOf(N, depcounts);
635 for (DepVarMap_citer i = depcounts.begin(); i != depcounts.end(); ++i) {
636 if (i->second > 1) // std::pair<std::string, int>
637 DepVars.insert(i->first);
642 /// Dump the dependent variable set:
643 static void DumpDepVars(MultipleUseVarSet &DepVars) {
644 if (DepVars.empty()) {
645 DEBUG(errs() << "<empty set>");
647 DEBUG(errs() << "[ ");
648 for (MultipleUseVarSet::const_iterator i = DepVars.begin(),
649 e = DepVars.end(); i != e; ++i) {
650 DEBUG(errs() << (*i) << " ");
652 DEBUG(errs() << "]");
658 //===----------------------------------------------------------------------===//
659 // TreePredicateFn Implementation
660 //===----------------------------------------------------------------------===//
662 /// TreePredicateFn constructor. Here 'N' is a subclass of PatFrag.
663 TreePredicateFn::TreePredicateFn(TreePattern *N) : PatFragRec(N) {
664 assert((getPredCode().empty() || getImmCode().empty()) &&
665 ".td file corrupt: can't have a node predicate *and* an imm predicate");
668 std::string TreePredicateFn::getPredCode() const {
669 return PatFragRec->getRecord()->getValueAsString("PredicateCode");
672 std::string TreePredicateFn::getImmCode() const {
673 return PatFragRec->getRecord()->getValueAsString("ImmediateCode");
677 /// isAlwaysTrue - Return true if this is a noop predicate.
678 bool TreePredicateFn::isAlwaysTrue() const {
679 return getPredCode().empty() && getImmCode().empty();
682 /// Return the name to use in the generated code to reference this, this is
683 /// "Predicate_foo" if from a pattern fragment "foo".
684 std::string TreePredicateFn::getFnName() const {
685 return "Predicate_" + PatFragRec->getRecord()->getName();
688 /// getCodeToRunOnSDNode - Return the code for the function body that
689 /// evaluates this predicate. The argument is expected to be in "Node",
690 /// not N. This handles casting and conversion to a concrete node type as
692 std::string TreePredicateFn::getCodeToRunOnSDNode() const {
693 // Handle immediate predicates first.
694 std::string ImmCode = getImmCode();
695 if (!ImmCode.empty()) {
697 " int64_t Imm = cast<ConstantSDNode>(Node)->getSExtValue();\n";
698 return Result + ImmCode;
701 // Handle arbitrary node predicates.
702 assert(!getPredCode().empty() && "Don't have any predicate code!");
703 std::string ClassName;
704 if (PatFragRec->getOnlyTree()->isLeaf())
705 ClassName = "SDNode";
707 Record *Op = PatFragRec->getOnlyTree()->getOperator();
708 ClassName = PatFragRec->getDAGPatterns().getSDNodeInfo(Op).getSDClassName();
711 if (ClassName == "SDNode")
712 Result = " SDNode *N = Node;\n";
714 Result = " " + ClassName + "*N = cast<" + ClassName + ">(Node);\n";
716 return Result + getPredCode();
719 //===----------------------------------------------------------------------===//
720 // PatternToMatch implementation
724 /// getPatternSize - Return the 'size' of this pattern. We want to match large
725 /// patterns before small ones. This is used to determine the size of a
727 static unsigned getPatternSize(const TreePatternNode *P,
728 const CodeGenDAGPatterns &CGP) {
729 unsigned Size = 3; // The node itself.
730 // If the root node is a ConstantSDNode, increases its size.
731 // e.g. (set R32:$dst, 0).
732 if (P->isLeaf() && isa<IntInit>(P->getLeafValue()))
735 // FIXME: This is a hack to statically increase the priority of patterns
736 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
737 // Later we can allow complexity / cost for each pattern to be (optionally)
738 // specified. To get best possible pattern match we'll need to dynamically
739 // calculate the complexity of all patterns a dag can potentially map to.
740 const ComplexPattern *AM = P->getComplexPatternInfo(CGP);
742 Size += AM->getNumOperands() * 3;
744 // If this node has some predicate function that must match, it adds to the
745 // complexity of this node.
746 if (!P->getPredicateFns().empty())
749 // Count children in the count if they are also nodes.
750 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
751 TreePatternNode *Child = P->getChild(i);
752 if (!Child->isLeaf() && Child->getNumTypes() &&
753 Child->getType(0) != MVT::Other)
754 Size += getPatternSize(Child, CGP);
755 else if (Child->isLeaf()) {
756 if (isa<IntInit>(Child->getLeafValue()))
757 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
758 else if (Child->getComplexPatternInfo(CGP))
759 Size += getPatternSize(Child, CGP);
760 else if (!Child->getPredicateFns().empty())
768 /// Compute the complexity metric for the input pattern. This roughly
769 /// corresponds to the number of nodes that are covered.
770 unsigned PatternToMatch::
771 getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
772 return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();
776 /// getPredicateCheck - Return a single string containing all of this
777 /// pattern's predicates concatenated with "&&" operators.
779 std::string PatternToMatch::getPredicateCheck() const {
780 std::string PredicateCheck;
781 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
782 if (DefInit *Pred = dyn_cast<DefInit>(Predicates->getElement(i))) {
783 Record *Def = Pred->getDef();
784 if (!Def->isSubClassOf("Predicate")) {
788 llvm_unreachable("Unknown predicate type!");
790 if (!PredicateCheck.empty())
791 PredicateCheck += " && ";
792 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
796 return PredicateCheck;
799 //===----------------------------------------------------------------------===//
800 // SDTypeConstraint implementation
803 SDTypeConstraint::SDTypeConstraint(Record *R) {
804 OperandNo = R->getValueAsInt("OperandNum");
806 if (R->isSubClassOf("SDTCisVT")) {
807 ConstraintType = SDTCisVT;
808 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
809 if (x.SDTCisVT_Info.VT == MVT::isVoid)
810 PrintFatalError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
812 } else if (R->isSubClassOf("SDTCisPtrTy")) {
813 ConstraintType = SDTCisPtrTy;
814 } else if (R->isSubClassOf("SDTCisInt")) {
815 ConstraintType = SDTCisInt;
816 } else if (R->isSubClassOf("SDTCisFP")) {
817 ConstraintType = SDTCisFP;
818 } else if (R->isSubClassOf("SDTCisVec")) {
819 ConstraintType = SDTCisVec;
820 } else if (R->isSubClassOf("SDTCisSameAs")) {
821 ConstraintType = SDTCisSameAs;
822 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
823 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
824 ConstraintType = SDTCisVTSmallerThanOp;
825 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
826 R->getValueAsInt("OtherOperandNum");
827 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
828 ConstraintType = SDTCisOpSmallerThanOp;
829 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
830 R->getValueAsInt("BigOperandNum");
831 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
832 ConstraintType = SDTCisEltOfVec;
833 x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
834 } else if (R->isSubClassOf("SDTCisSubVecOfVec")) {
835 ConstraintType = SDTCisSubVecOfVec;
836 x.SDTCisSubVecOfVec_Info.OtherOperandNum =
837 R->getValueAsInt("OtherOpNum");
839 errs() << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
844 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
845 /// N, and the result number in ResNo.
846 static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
847 const SDNodeInfo &NodeInfo,
849 unsigned NumResults = NodeInfo.getNumResults();
850 if (OpNo < NumResults) {
857 if (OpNo >= N->getNumChildren()) {
858 errs() << "Invalid operand number in type constraint "
859 << (OpNo+NumResults) << " ";
865 return N->getChild(OpNo);
868 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
869 /// constraint to the nodes operands. This returns true if it makes a
870 /// change, false otherwise. If a type contradiction is found, flag an error.
871 bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
872 const SDNodeInfo &NodeInfo,
873 TreePattern &TP) const {
877 unsigned ResNo = 0; // The result number being referenced.
878 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
880 switch (ConstraintType) {
882 // Operand must be a particular type.
883 return NodeToApply->UpdateNodeType(ResNo, x.SDTCisVT_Info.VT, TP);
885 // Operand must be same as target pointer type.
886 return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
888 // Require it to be one of the legal integer VTs.
889 return NodeToApply->getExtType(ResNo).EnforceInteger(TP);
891 // Require it to be one of the legal fp VTs.
892 return NodeToApply->getExtType(ResNo).EnforceFloatingPoint(TP);
894 // Require it to be one of the legal vector VTs.
895 return NodeToApply->getExtType(ResNo).EnforceVector(TP);
898 TreePatternNode *OtherNode =
899 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
900 return NodeToApply->UpdateNodeType(OResNo, OtherNode->getExtType(ResNo),TP)|
901 OtherNode->UpdateNodeType(ResNo,NodeToApply->getExtType(OResNo),TP);
903 case SDTCisVTSmallerThanOp: {
904 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
905 // have an integer type that is smaller than the VT.
906 if (!NodeToApply->isLeaf() ||
907 !isa<DefInit>(NodeToApply->getLeafValue()) ||
908 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
909 ->isSubClassOf("ValueType")) {
910 TP.error(N->getOperator()->getName() + " expects a VT operand!");
913 MVT::SimpleValueType VT =
914 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
916 EEVT::TypeSet TypeListTmp(VT, TP);
919 TreePatternNode *OtherNode =
920 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
923 return TypeListTmp.EnforceSmallerThan(OtherNode->getExtType(OResNo), TP);
925 case SDTCisOpSmallerThanOp: {
927 TreePatternNode *BigOperand =
928 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
930 return NodeToApply->getExtType(ResNo).
931 EnforceSmallerThan(BigOperand->getExtType(BResNo), TP);
933 case SDTCisEltOfVec: {
935 TreePatternNode *VecOperand =
936 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
939 // Filter vector types out of VecOperand that don't have the right element
941 return VecOperand->getExtType(VResNo).
942 EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), TP);
944 case SDTCisSubVecOfVec: {
946 TreePatternNode *BigVecOperand =
947 getOperandNum(x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo,
950 // Filter vector types out of BigVecOperand that don't have the
951 // right subvector type.
952 return BigVecOperand->getExtType(VResNo).
953 EnforceVectorSubVectorTypeIs(NodeToApply->getExtType(ResNo), TP);
956 llvm_unreachable("Invalid ConstraintType!");
959 // Update the node type to match an instruction operand or result as specified
960 // in the ins or outs lists on the instruction definition. Return true if the
961 // type was actually changed.
962 bool TreePatternNode::UpdateNodeTypeFromInst(unsigned ResNo,
965 // The 'unknown' operand indicates that types should be inferred from the
967 if (Operand->isSubClassOf("unknown_class"))
970 // The Operand class specifies a type directly.
971 if (Operand->isSubClassOf("Operand"))
972 return UpdateNodeType(ResNo, getValueType(Operand->getValueAsDef("Type")),
975 // PointerLikeRegClass has a type that is determined at runtime.
976 if (Operand->isSubClassOf("PointerLikeRegClass"))
977 return UpdateNodeType(ResNo, MVT::iPTR, TP);
979 // Both RegisterClass and RegisterOperand operands derive their types from a
980 // register class def.
982 if (Operand->isSubClassOf("RegisterClass"))
984 else if (Operand->isSubClassOf("RegisterOperand"))
985 RC = Operand->getValueAsDef("RegClass");
987 assert(RC && "Unknown operand type");
988 CodeGenTarget &Tgt = TP.getDAGPatterns().getTargetInfo();
989 return UpdateNodeType(ResNo, Tgt.getRegisterClass(RC).getValueTypes(), TP);
993 //===----------------------------------------------------------------------===//
994 // SDNodeInfo implementation
996 SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
997 EnumName = R->getValueAsString("Opcode");
998 SDClassName = R->getValueAsString("SDClass");
999 Record *TypeProfile = R->getValueAsDef("TypeProfile");
1000 NumResults = TypeProfile->getValueAsInt("NumResults");
1001 NumOperands = TypeProfile->getValueAsInt("NumOperands");
1003 // Parse the properties.
1005 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
1006 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
1007 if (PropList[i]->getName() == "SDNPCommutative") {
1008 Properties |= 1 << SDNPCommutative;
1009 } else if (PropList[i]->getName() == "SDNPAssociative") {
1010 Properties |= 1 << SDNPAssociative;
1011 } else if (PropList[i]->getName() == "SDNPHasChain") {
1012 Properties |= 1 << SDNPHasChain;
1013 } else if (PropList[i]->getName() == "SDNPOutGlue") {
1014 Properties |= 1 << SDNPOutGlue;
1015 } else if (PropList[i]->getName() == "SDNPInGlue") {
1016 Properties |= 1 << SDNPInGlue;
1017 } else if (PropList[i]->getName() == "SDNPOptInGlue") {
1018 Properties |= 1 << SDNPOptInGlue;
1019 } else if (PropList[i]->getName() == "SDNPMayStore") {
1020 Properties |= 1 << SDNPMayStore;
1021 } else if (PropList[i]->getName() == "SDNPMayLoad") {
1022 Properties |= 1 << SDNPMayLoad;
1023 } else if (PropList[i]->getName() == "SDNPSideEffect") {
1024 Properties |= 1 << SDNPSideEffect;
1025 } else if (PropList[i]->getName() == "SDNPMemOperand") {
1026 Properties |= 1 << SDNPMemOperand;
1027 } else if (PropList[i]->getName() == "SDNPVariadic") {
1028 Properties |= 1 << SDNPVariadic;
1030 errs() << "Unknown SD Node property '" << PropList[i]->getName()
1031 << "' on node '" << R->getName() << "'!\n";
1037 // Parse the type constraints.
1038 std::vector<Record*> ConstraintList =
1039 TypeProfile->getValueAsListOfDefs("Constraints");
1040 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
1043 /// getKnownType - If the type constraints on this node imply a fixed type
1044 /// (e.g. all stores return void, etc), then return it as an
1045 /// MVT::SimpleValueType. Otherwise, return EEVT::Other.
1046 MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
1047 unsigned NumResults = getNumResults();
1048 assert(NumResults <= 1 &&
1049 "We only work with nodes with zero or one result so far!");
1050 assert(ResNo == 0 && "Only handles single result nodes so far");
1052 for (unsigned i = 0, e = TypeConstraints.size(); i != e; ++i) {
1053 // Make sure that this applies to the correct node result.
1054 if (TypeConstraints[i].OperandNo >= NumResults) // FIXME: need value #
1057 switch (TypeConstraints[i].ConstraintType) {
1059 case SDTypeConstraint::SDTCisVT:
1060 return TypeConstraints[i].x.SDTCisVT_Info.VT;
1061 case SDTypeConstraint::SDTCisPtrTy:
1068 //===----------------------------------------------------------------------===//
1069 // TreePatternNode implementation
1072 TreePatternNode::~TreePatternNode() {
1073 #if 0 // FIXME: implement refcounted tree nodes!
1074 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1079 static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
1080 if (Operator->getName() == "set" ||
1081 Operator->getName() == "implicit")
1082 return 0; // All return nothing.
1084 if (Operator->isSubClassOf("Intrinsic"))
1085 return CDP.getIntrinsic(Operator).IS.RetVTs.size();
1087 if (Operator->isSubClassOf("SDNode"))
1088 return CDP.getSDNodeInfo(Operator).getNumResults();
1090 if (Operator->isSubClassOf("PatFrag")) {
1091 // If we've already parsed this pattern fragment, get it. Otherwise, handle
1092 // the forward reference case where one pattern fragment references another
1093 // before it is processed.
1094 if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator))
1095 return PFRec->getOnlyTree()->getNumTypes();
1097 // Get the result tree.
1098 DagInit *Tree = Operator->getValueAsDag("Fragment");
1101 if (DefInit *DI = dyn_cast<DefInit>(Tree->getOperator()))
1103 assert(Op && "Invalid Fragment");
1104 return GetNumNodeResults(Op, CDP);
1107 if (Operator->isSubClassOf("Instruction")) {
1108 CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
1110 // FIXME: Should allow access to all the results here.
1111 unsigned NumDefsToAdd = InstInfo.Operands.NumDefs ? 1 : 0;
1113 // Add on one implicit def if it has a resolvable type.
1114 if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
1116 return NumDefsToAdd;
1119 if (Operator->isSubClassOf("SDNodeXForm"))
1120 return 1; // FIXME: Generalize SDNodeXForm
1123 errs() << "Unhandled node in GetNumNodeResults\n";
1127 void TreePatternNode::print(raw_ostream &OS) const {
1129 OS << *getLeafValue();
1131 OS << '(' << getOperator()->getName();
1133 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1134 OS << ':' << getExtType(i).getName();
1137 if (getNumChildren() != 0) {
1139 getChild(0)->print(OS);
1140 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
1142 getChild(i)->print(OS);
1148 for (unsigned i = 0, e = PredicateFns.size(); i != e; ++i)
1149 OS << "<<P:" << PredicateFns[i].getFnName() << ">>";
1151 OS << "<<X:" << TransformFn->getName() << ">>";
1152 if (!getName().empty())
1153 OS << ":$" << getName();
1156 void TreePatternNode::dump() const {
1160 /// isIsomorphicTo - Return true if this node is recursively
1161 /// isomorphic to the specified node. For this comparison, the node's
1162 /// entire state is considered. The assigned name is ignored, since
1163 /// nodes with differing names are considered isomorphic. However, if
1164 /// the assigned name is present in the dependent variable set, then
1165 /// the assigned name is considered significant and the node is
1166 /// isomorphic if the names match.
1167 bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
1168 const MultipleUseVarSet &DepVars) const {
1169 if (N == this) return true;
1170 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
1171 getPredicateFns() != N->getPredicateFns() ||
1172 getTransformFn() != N->getTransformFn())
1176 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
1177 if (DefInit *NDI = dyn_cast<DefInit>(N->getLeafValue())) {
1178 return ((DI->getDef() == NDI->getDef())
1179 && (DepVars.find(getName()) == DepVars.end()
1180 || getName() == N->getName()));
1183 return getLeafValue() == N->getLeafValue();
1186 if (N->getOperator() != getOperator() ||
1187 N->getNumChildren() != getNumChildren()) return false;
1188 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1189 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
1194 /// clone - Make a copy of this tree and all of its children.
1196 TreePatternNode *TreePatternNode::clone() const {
1197 TreePatternNode *New;
1199 New = new TreePatternNode(getLeafValue(), getNumTypes());
1201 std::vector<TreePatternNode*> CChildren;
1202 CChildren.reserve(Children.size());
1203 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1204 CChildren.push_back(getChild(i)->clone());
1205 New = new TreePatternNode(getOperator(), CChildren, getNumTypes());
1207 New->setName(getName());
1209 New->setPredicateFns(getPredicateFns());
1210 New->setTransformFn(getTransformFn());
1214 /// RemoveAllTypes - Recursively strip all the types of this tree.
1215 void TreePatternNode::RemoveAllTypes() {
1216 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1217 Types[i] = EEVT::TypeSet(); // Reset to unknown type.
1218 if (isLeaf()) return;
1219 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1220 getChild(i)->RemoveAllTypes();
1224 /// SubstituteFormalArguments - Replace the formal arguments in this tree
1225 /// with actual values specified by ArgMap.
1226 void TreePatternNode::
1227 SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
1228 if (isLeaf()) return;
1230 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1231 TreePatternNode *Child = getChild(i);
1232 if (Child->isLeaf()) {
1233 Init *Val = Child->getLeafValue();
1234 if (isa<DefInit>(Val) &&
1235 cast<DefInit>(Val)->getDef()->getName() == "node") {
1236 // We found a use of a formal argument, replace it with its value.
1237 TreePatternNode *NewChild = ArgMap[Child->getName()];
1238 assert(NewChild && "Couldn't find formal argument!");
1239 assert((Child->getPredicateFns().empty() ||
1240 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1241 "Non-empty child predicate clobbered!");
1242 setChild(i, NewChild);
1245 getChild(i)->SubstituteFormalArguments(ArgMap);
1251 /// InlinePatternFragments - If this pattern refers to any pattern
1252 /// fragments, inline them into place, giving us a pattern without any
1253 /// PatFrag references.
1254 TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
1259 return this; // nothing to do.
1260 Record *Op = getOperator();
1262 if (!Op->isSubClassOf("PatFrag")) {
1263 // Just recursively inline children nodes.
1264 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1265 TreePatternNode *Child = getChild(i);
1266 TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
1268 assert((Child->getPredicateFns().empty() ||
1269 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1270 "Non-empty child predicate clobbered!");
1272 setChild(i, NewChild);
1277 // Otherwise, we found a reference to a fragment. First, look up its
1278 // TreePattern record.
1279 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
1281 // Verify that we are passing the right number of operands.
1282 if (Frag->getNumArgs() != Children.size()) {
1283 TP.error("'" + Op->getName() + "' fragment requires " +
1284 utostr(Frag->getNumArgs()) + " operands!");
1288 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
1290 TreePredicateFn PredFn(Frag);
1291 if (!PredFn.isAlwaysTrue())
1292 FragTree->addPredicateFn(PredFn);
1294 // Resolve formal arguments to their actual value.
1295 if (Frag->getNumArgs()) {
1296 // Compute the map of formal to actual arguments.
1297 std::map<std::string, TreePatternNode*> ArgMap;
1298 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
1299 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
1301 FragTree->SubstituteFormalArguments(ArgMap);
1304 FragTree->setName(getName());
1305 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1306 FragTree->UpdateNodeType(i, getExtType(i), TP);
1308 // Transfer in the old predicates.
1309 for (unsigned i = 0, e = getPredicateFns().size(); i != e; ++i)
1310 FragTree->addPredicateFn(getPredicateFns()[i]);
1312 // Get a new copy of this fragment to stitch into here.
1313 //delete this; // FIXME: implement refcounting!
1315 // The fragment we inlined could have recursive inlining that is needed. See
1316 // if there are any pattern fragments in it and inline them as needed.
1317 return FragTree->InlinePatternFragments(TP);
1320 /// getImplicitType - Check to see if the specified record has an implicit
1321 /// type which should be applied to it. This will infer the type of register
1322 /// references from the register file information, for example.
1324 /// When Unnamed is set, return the type of a DAG operand with no name, such as
1325 /// the F8RC register class argument in:
1327 /// (COPY_TO_REGCLASS GPR:$src, F8RC)
1329 /// When Unnamed is false, return the type of a named DAG operand such as the
1330 /// GPR:$src operand above.
1332 static EEVT::TypeSet getImplicitType(Record *R, unsigned ResNo,
1336 // Check to see if this is a register operand.
1337 if (R->isSubClassOf("RegisterOperand")) {
1338 assert(ResNo == 0 && "Regoperand ref only has one result!");
1340 return EEVT::TypeSet(); // Unknown.
1341 Record *RegClass = R->getValueAsDef("RegClass");
1342 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1343 return EEVT::TypeSet(T.getRegisterClass(RegClass).getValueTypes());
1346 // Check to see if this is a register or a register class.
1347 if (R->isSubClassOf("RegisterClass")) {
1348 assert(ResNo == 0 && "Regclass ref only has one result!");
1349 // An unnamed register class represents itself as an i32 immediate, for
1350 // example on a COPY_TO_REGCLASS instruction.
1352 return EEVT::TypeSet(MVT::i32, TP);
1354 // In a named operand, the register class provides the possible set of
1357 return EEVT::TypeSet(); // Unknown.
1358 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1359 return EEVT::TypeSet(T.getRegisterClass(R).getValueTypes());
1362 if (R->isSubClassOf("PatFrag")) {
1363 assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
1364 // Pattern fragment types will be resolved when they are inlined.
1365 return EEVT::TypeSet(); // Unknown.
1368 if (R->isSubClassOf("Register")) {
1369 assert(ResNo == 0 && "Registers only produce one result!");
1371 return EEVT::TypeSet(); // Unknown.
1372 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1373 return EEVT::TypeSet(T.getRegisterVTs(R));
1376 if (R->isSubClassOf("SubRegIndex")) {
1377 assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
1378 return EEVT::TypeSet();
1381 if (R->isSubClassOf("ValueType")) {
1382 assert(ResNo == 0 && "This node only has one result!");
1383 // An unnamed VTSDNode represents itself as an MVT::Other immediate.
1385 // (sext_inreg GPR:$src, i16)
1388 return EEVT::TypeSet(MVT::Other, TP);
1389 // With a name, the ValueType simply provides the type of the named
1392 // (sext_inreg i32:$src, i16)
1394 return EEVT::TypeSet(getValueType(R), TP);
1397 if (R->isSubClassOf("CondCode")) {
1398 assert(ResNo == 0 && "This node only has one result!");
1399 // Using a CondCodeSDNode.
1400 return EEVT::TypeSet(MVT::Other, TP);
1403 if (R->isSubClassOf("ComplexPattern")) {
1404 assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
1406 return EEVT::TypeSet(); // Unknown.
1407 return EEVT::TypeSet(TP.getDAGPatterns().getComplexPattern(R).getValueType(),
1410 if (R->isSubClassOf("PointerLikeRegClass")) {
1411 assert(ResNo == 0 && "Regclass can only have one result!");
1412 return EEVT::TypeSet(MVT::iPTR, TP);
1415 if (R->getName() == "node" || R->getName() == "srcvalue" ||
1416 R->getName() == "zero_reg") {
1418 return EEVT::TypeSet(); // Unknown.
1421 TP.error("Unknown node flavor used in pattern: " + R->getName());
1422 return EEVT::TypeSet(MVT::Other, TP);
1426 /// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
1427 /// CodeGenIntrinsic information for it, otherwise return a null pointer.
1428 const CodeGenIntrinsic *TreePatternNode::
1429 getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
1430 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
1431 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
1432 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
1435 unsigned IID = cast<IntInit>(getChild(0)->getLeafValue())->getValue();
1436 return &CDP.getIntrinsicInfo(IID);
1439 /// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
1440 /// return the ComplexPattern information, otherwise return null.
1441 const ComplexPattern *
1442 TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
1443 if (!isLeaf()) return 0;
1445 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
1446 if (DI && DI->getDef()->isSubClassOf("ComplexPattern"))
1447 return &CGP.getComplexPattern(DI->getDef());
1451 /// NodeHasProperty - Return true if this node has the specified property.
1452 bool TreePatternNode::NodeHasProperty(SDNP Property,
1453 const CodeGenDAGPatterns &CGP) const {
1455 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1456 return CP->hasProperty(Property);
1460 Record *Operator = getOperator();
1461 if (!Operator->isSubClassOf("SDNode")) return false;
1463 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
1469 /// TreeHasProperty - Return true if any node in this tree has the specified
1471 bool TreePatternNode::TreeHasProperty(SDNP Property,
1472 const CodeGenDAGPatterns &CGP) const {
1473 if (NodeHasProperty(Property, CGP))
1475 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1476 if (getChild(i)->TreeHasProperty(Property, CGP))
1481 /// isCommutativeIntrinsic - Return true if the node corresponds to a
1482 /// commutative intrinsic.
1484 TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
1485 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
1486 return Int->isCommutative;
1491 /// ApplyTypeConstraints - Apply all of the type constraints relevant to
1492 /// this node and its children in the tree. This returns true if it makes a
1493 /// change, false otherwise. If a type contradiction is found, flag an error.
1494 bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
1498 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
1500 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
1501 // If it's a regclass or something else known, include the type.
1502 bool MadeChange = false;
1503 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1504 MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
1506 !hasName(), TP), TP);
1510 if (IntInit *II = dyn_cast<IntInit>(getLeafValue())) {
1511 assert(Types.size() == 1 && "Invalid IntInit");
1513 // Int inits are always integers. :)
1514 bool MadeChange = Types[0].EnforceInteger(TP);
1516 if (!Types[0].isConcrete())
1519 MVT::SimpleValueType VT = getType(0);
1520 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
1523 unsigned Size = EVT(VT).getSizeInBits();
1524 // Make sure that the value is representable for this type.
1525 if (Size >= 32) return MadeChange;
1527 // Check that the value doesn't use more bits than we have. It must either
1528 // be a sign- or zero-extended equivalent of the original.
1529 int64_t SignBitAndAbove = II->getValue() >> (Size - 1);
1530 if (SignBitAndAbove == -1 || SignBitAndAbove == 0 || SignBitAndAbove == 1)
1533 TP.error("Integer value '" + itostr(II->getValue()) +
1534 "' is out of range for type '" + getEnumName(getType(0)) + "'!");
1540 // special handling for set, which isn't really an SDNode.
1541 if (getOperator()->getName() == "set") {
1542 assert(getNumTypes() == 0 && "Set doesn't produce a value");
1543 assert(getNumChildren() >= 2 && "Missing RHS of a set?");
1544 unsigned NC = getNumChildren();
1546 TreePatternNode *SetVal = getChild(NC-1);
1547 bool MadeChange = SetVal->ApplyTypeConstraints(TP, NotRegisters);
1549 for (unsigned i = 0; i < NC-1; ++i) {
1550 TreePatternNode *Child = getChild(i);
1551 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
1553 // Types of operands must match.
1554 MadeChange |= Child->UpdateNodeType(0, SetVal->getExtType(i), TP);
1555 MadeChange |= SetVal->UpdateNodeType(i, Child->getExtType(0), TP);
1560 if (getOperator()->getName() == "implicit") {
1561 assert(getNumTypes() == 0 && "Node doesn't produce a value");
1563 bool MadeChange = false;
1564 for (unsigned i = 0; i < getNumChildren(); ++i)
1565 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1569 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
1570 bool MadeChange = false;
1572 // Apply the result type to the node.
1573 unsigned NumRetVTs = Int->IS.RetVTs.size();
1574 unsigned NumParamVTs = Int->IS.ParamVTs.size();
1576 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
1577 MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
1579 if (getNumChildren() != NumParamVTs + 1) {
1580 TP.error("Intrinsic '" + Int->Name + "' expects " +
1581 utostr(NumParamVTs) + " operands, not " +
1582 utostr(getNumChildren() - 1) + " operands!");
1586 // Apply type info to the intrinsic ID.
1587 MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
1589 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
1590 MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
1592 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
1593 assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
1594 MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
1599 if (getOperator()->isSubClassOf("SDNode")) {
1600 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
1602 // Check that the number of operands is sane. Negative operands -> varargs.
1603 if (NI.getNumOperands() >= 0 &&
1604 getNumChildren() != (unsigned)NI.getNumOperands()) {
1605 TP.error(getOperator()->getName() + " node requires exactly " +
1606 itostr(NI.getNumOperands()) + " operands!");
1610 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
1611 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1612 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1616 if (getOperator()->isSubClassOf("Instruction")) {
1617 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
1618 CodeGenInstruction &InstInfo =
1619 CDP.getTargetInfo().getInstruction(getOperator());
1621 bool MadeChange = false;
1623 // Apply the result types to the node, these come from the things in the
1624 // (outs) list of the instruction.
1625 // FIXME: Cap at one result so far.
1626 unsigned NumResultsToAdd = InstInfo.Operands.NumDefs ? 1 : 0;
1627 for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo)
1628 MadeChange |= UpdateNodeTypeFromInst(ResNo, Inst.getResult(ResNo), TP);
1630 // If the instruction has implicit defs, we apply the first one as a result.
1631 // FIXME: This sucks, it should apply all implicit defs.
1632 if (!InstInfo.ImplicitDefs.empty()) {
1633 unsigned ResNo = NumResultsToAdd;
1635 // FIXME: Generalize to multiple possible types and multiple possible
1637 MVT::SimpleValueType VT =
1638 InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
1640 if (VT != MVT::Other)
1641 MadeChange |= UpdateNodeType(ResNo, VT, TP);
1644 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
1646 if (getOperator()->getName() == "INSERT_SUBREG") {
1647 assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
1648 MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
1649 MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
1652 unsigned ChildNo = 0;
1653 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
1654 Record *OperandNode = Inst.getOperand(i);
1656 // If the instruction expects a predicate or optional def operand, we
1657 // codegen this by setting the operand to it's default value if it has a
1658 // non-empty DefaultOps field.
1659 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
1660 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1663 // Verify that we didn't run out of provided operands.
1664 if (ChildNo >= getNumChildren()) {
1665 TP.error("Instruction '" + getOperator()->getName() +
1666 "' expects more operands than were provided.");
1670 TreePatternNode *Child = getChild(ChildNo++);
1671 unsigned ChildResNo = 0; // Instructions always use res #0 of their op.
1673 // If the operand has sub-operands, they may be provided by distinct
1674 // child patterns, so attempt to match each sub-operand separately.
1675 if (OperandNode->isSubClassOf("Operand")) {
1676 DagInit *MIOpInfo = OperandNode->getValueAsDag("MIOperandInfo");
1677 if (unsigned NumArgs = MIOpInfo->getNumArgs()) {
1678 // But don't do that if the whole operand is being provided by
1679 // a single ComplexPattern.
1680 const ComplexPattern *AM = Child->getComplexPatternInfo(CDP);
1681 if (!AM || AM->getNumOperands() < NumArgs) {
1682 // Match first sub-operand against the child we already have.
1683 Record *SubRec = cast<DefInit>(MIOpInfo->getArg(0))->getDef();
1685 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
1687 // And the remaining sub-operands against subsequent children.
1688 for (unsigned Arg = 1; Arg < NumArgs; ++Arg) {
1689 if (ChildNo >= getNumChildren()) {
1690 TP.error("Instruction '" + getOperator()->getName() +
1691 "' expects more operands than were provided.");
1694 Child = getChild(ChildNo++);
1696 SubRec = cast<DefInit>(MIOpInfo->getArg(Arg))->getDef();
1698 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
1705 // If we didn't match by pieces above, attempt to match the whole
1707 MadeChange |= Child->UpdateNodeTypeFromInst(ChildResNo, OperandNode, TP);
1710 if (ChildNo != getNumChildren()) {
1711 TP.error("Instruction '" + getOperator()->getName() +
1712 "' was provided too many operands!");
1716 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1717 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1721 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
1723 // Node transforms always take one operand.
1724 if (getNumChildren() != 1) {
1725 TP.error("Node transform '" + getOperator()->getName() +
1726 "' requires one operand!");
1730 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1733 // If either the output or input of the xform does not have exact
1734 // type info. We assume they must be the same. Otherwise, it is perfectly
1735 // legal to transform from one type to a completely different type.
1737 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
1738 bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
1739 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
1746 /// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
1747 /// RHS of a commutative operation, not the on LHS.
1748 static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
1749 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
1751 if (N->isLeaf() && isa<IntInit>(N->getLeafValue()))
1757 /// canPatternMatch - If it is impossible for this pattern to match on this
1758 /// target, fill in Reason and return false. Otherwise, return true. This is
1759 /// used as a sanity check for .td files (to prevent people from writing stuff
1760 /// that can never possibly work), and to prevent the pattern permuter from
1761 /// generating stuff that is useless.
1762 bool TreePatternNode::canPatternMatch(std::string &Reason,
1763 const CodeGenDAGPatterns &CDP) {
1764 if (isLeaf()) return true;
1766 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1767 if (!getChild(i)->canPatternMatch(Reason, CDP))
1770 // If this is an intrinsic, handle cases that would make it not match. For
1771 // example, if an operand is required to be an immediate.
1772 if (getOperator()->isSubClassOf("Intrinsic")) {
1777 // If this node is a commutative operator, check that the LHS isn't an
1779 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
1780 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
1781 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
1782 // Scan all of the operands of the node and make sure that only the last one
1783 // is a constant node, unless the RHS also is.
1784 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
1785 bool Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
1786 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
1787 if (OnlyOnRHSOfCommutative(getChild(i))) {
1788 Reason="Immediate value must be on the RHS of commutative operators!";
1797 //===----------------------------------------------------------------------===//
1798 // TreePattern implementation
1801 TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
1802 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
1803 isInputPattern(isInput), HasError(false) {
1804 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
1805 Trees.push_back(ParseTreePattern(RawPat->getElement(i), ""));
1808 TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
1809 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
1810 isInputPattern(isInput), HasError(false) {
1811 Trees.push_back(ParseTreePattern(Pat, ""));
1814 TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
1815 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
1816 isInputPattern(isInput), HasError(false) {
1817 Trees.push_back(Pat);
1820 void TreePattern::error(const std::string &Msg) {
1824 PrintError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
1828 void TreePattern::ComputeNamedNodes() {
1829 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1830 ComputeNamedNodes(Trees[i]);
1833 void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
1834 if (!N->getName().empty())
1835 NamedNodes[N->getName()].push_back(N);
1837 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1838 ComputeNamedNodes(N->getChild(i));
1842 TreePatternNode *TreePattern::ParseTreePattern(Init *TheInit, StringRef OpName){
1843 if (DefInit *DI = dyn_cast<DefInit>(TheInit)) {
1844 Record *R = DI->getDef();
1846 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
1847 // TreePatternNode of its own. For example:
1848 /// (foo GPR, imm) -> (foo GPR, (imm))
1849 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag"))
1850 return ParseTreePattern(
1851 DagInit::get(DI, "",
1852 std::vector<std::pair<Init*, std::string> >()),
1856 TreePatternNode *Res = new TreePatternNode(DI, 1);
1857 if (R->getName() == "node" && !OpName.empty()) {
1859 error("'node' argument requires a name to match with operand list");
1860 Args.push_back(OpName);
1863 Res->setName(OpName);
1867 if (IntInit *II = dyn_cast<IntInit>(TheInit)) {
1868 if (!OpName.empty())
1869 error("Constant int argument should not have a name!");
1870 return new TreePatternNode(II, 1);
1873 if (BitsInit *BI = dyn_cast<BitsInit>(TheInit)) {
1874 // Turn this into an IntInit.
1875 Init *II = BI->convertInitializerTo(IntRecTy::get());
1876 if (II == 0 || !isa<IntInit>(II))
1877 error("Bits value must be constants!");
1878 return ParseTreePattern(II, OpName);
1881 DagInit *Dag = dyn_cast<DagInit>(TheInit);
1884 error("Pattern has unexpected init kind!");
1886 DefInit *OpDef = dyn_cast<DefInit>(Dag->getOperator());
1887 if (!OpDef) error("Pattern has unexpected operator type!");
1888 Record *Operator = OpDef->getDef();
1890 if (Operator->isSubClassOf("ValueType")) {
1891 // If the operator is a ValueType, then this must be "type cast" of a leaf
1893 if (Dag->getNumArgs() != 1)
1894 error("Type cast only takes one operand!");
1896 TreePatternNode *New = ParseTreePattern(Dag->getArg(0), Dag->getArgName(0));
1898 // Apply the type cast.
1899 assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
1900 New->UpdateNodeType(0, getValueType(Operator), *this);
1902 if (!OpName.empty())
1903 error("ValueType cast should not have a name!");
1907 // Verify that this is something that makes sense for an operator.
1908 if (!Operator->isSubClassOf("PatFrag") &&
1909 !Operator->isSubClassOf("SDNode") &&
1910 !Operator->isSubClassOf("Instruction") &&
1911 !Operator->isSubClassOf("SDNodeXForm") &&
1912 !Operator->isSubClassOf("Intrinsic") &&
1913 Operator->getName() != "set" &&
1914 Operator->getName() != "implicit")
1915 error("Unrecognized node '" + Operator->getName() + "'!");
1917 // Check to see if this is something that is illegal in an input pattern.
1918 if (isInputPattern) {
1919 if (Operator->isSubClassOf("Instruction") ||
1920 Operator->isSubClassOf("SDNodeXForm"))
1921 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
1923 if (Operator->isSubClassOf("Intrinsic"))
1924 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
1926 if (Operator->isSubClassOf("SDNode") &&
1927 Operator->getName() != "imm" &&
1928 Operator->getName() != "fpimm" &&
1929 Operator->getName() != "tglobaltlsaddr" &&
1930 Operator->getName() != "tconstpool" &&
1931 Operator->getName() != "tjumptable" &&
1932 Operator->getName() != "tframeindex" &&
1933 Operator->getName() != "texternalsym" &&
1934 Operator->getName() != "tblockaddress" &&
1935 Operator->getName() != "tglobaladdr" &&
1936 Operator->getName() != "bb" &&
1937 Operator->getName() != "vt")
1938 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
1941 std::vector<TreePatternNode*> Children;
1943 // Parse all the operands.
1944 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
1945 Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgName(i)));
1947 // If the operator is an intrinsic, then this is just syntactic sugar for for
1948 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
1949 // convert the intrinsic name to a number.
1950 if (Operator->isSubClassOf("Intrinsic")) {
1951 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
1952 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
1954 // If this intrinsic returns void, it must have side-effects and thus a
1956 if (Int.IS.RetVTs.empty())
1957 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
1958 else if (Int.ModRef != CodeGenIntrinsic::NoMem)
1959 // Has side-effects, requires chain.
1960 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
1961 else // Otherwise, no chain.
1962 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
1964 TreePatternNode *IIDNode = new TreePatternNode(IntInit::get(IID), 1);
1965 Children.insert(Children.begin(), IIDNode);
1968 unsigned NumResults = GetNumNodeResults(Operator, CDP);
1969 TreePatternNode *Result = new TreePatternNode(Operator, Children, NumResults);
1970 Result->setName(OpName);
1972 if (!Dag->getName().empty()) {
1973 assert(Result->getName().empty());
1974 Result->setName(Dag->getName());
1979 /// SimplifyTree - See if we can simplify this tree to eliminate something that
1980 /// will never match in favor of something obvious that will. This is here
1981 /// strictly as a convenience to target authors because it allows them to write
1982 /// more type generic things and have useless type casts fold away.
1984 /// This returns true if any change is made.
1985 static bool SimplifyTree(TreePatternNode *&N) {
1989 // If we have a bitconvert with a resolved type and if the source and
1990 // destination types are the same, then the bitconvert is useless, remove it.
1991 if (N->getOperator()->getName() == "bitconvert" &&
1992 N->getExtType(0).isConcrete() &&
1993 N->getExtType(0) == N->getChild(0)->getExtType(0) &&
1994 N->getName().empty()) {
2000 // Walk all children.
2001 bool MadeChange = false;
2002 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2003 TreePatternNode *Child = N->getChild(i);
2004 MadeChange |= SimplifyTree(Child);
2005 N->setChild(i, Child);
2012 /// InferAllTypes - Infer/propagate as many types throughout the expression
2013 /// patterns as possible. Return true if all types are inferred, false
2014 /// otherwise. Flags an error if a type contradiction is found.
2016 InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
2017 if (NamedNodes.empty())
2018 ComputeNamedNodes();
2020 bool MadeChange = true;
2021 while (MadeChange) {
2023 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
2024 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
2025 MadeChange |= SimplifyTree(Trees[i]);
2028 // If there are constraints on our named nodes, apply them.
2029 for (StringMap<SmallVector<TreePatternNode*,1> >::iterator
2030 I = NamedNodes.begin(), E = NamedNodes.end(); I != E; ++I) {
2031 SmallVectorImpl<TreePatternNode*> &Nodes = I->second;
2033 // If we have input named node types, propagate their types to the named
2036 // FIXME: Should be error?
2037 assert(InNamedTypes->count(I->getKey()) &&
2038 "Named node in output pattern but not input pattern?");
2040 const SmallVectorImpl<TreePatternNode*> &InNodes =
2041 InNamedTypes->find(I->getKey())->second;
2043 // The input types should be fully resolved by now.
2044 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
2045 // If this node is a register class, and it is the root of the pattern
2046 // then we're mapping something onto an input register. We allow
2047 // changing the type of the input register in this case. This allows
2048 // us to match things like:
2049 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
2050 if (Nodes[i] == Trees[0] && Nodes[i]->isLeaf()) {
2051 DefInit *DI = dyn_cast<DefInit>(Nodes[i]->getLeafValue());
2052 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2053 DI->getDef()->isSubClassOf("RegisterOperand")))
2057 assert(Nodes[i]->getNumTypes() == 1 &&
2058 InNodes[0]->getNumTypes() == 1 &&
2059 "FIXME: cannot name multiple result nodes yet");
2060 MadeChange |= Nodes[i]->UpdateNodeType(0, InNodes[0]->getExtType(0),
2065 // If there are multiple nodes with the same name, they must all have the
2067 if (I->second.size() > 1) {
2068 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
2069 TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
2070 assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
2071 "FIXME: cannot name multiple result nodes yet");
2073 MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
2074 MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
2080 bool HasUnresolvedTypes = false;
2081 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
2082 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
2083 return !HasUnresolvedTypes;
2086 void TreePattern::print(raw_ostream &OS) const {
2087 OS << getRecord()->getName();
2088 if (!Args.empty()) {
2089 OS << "(" << Args[0];
2090 for (unsigned i = 1, e = Args.size(); i != e; ++i)
2091 OS << ", " << Args[i];
2096 if (Trees.size() > 1)
2098 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
2100 Trees[i]->print(OS);
2104 if (Trees.size() > 1)
2108 void TreePattern::dump() const { print(errs()); }
2110 //===----------------------------------------------------------------------===//
2111 // CodeGenDAGPatterns implementation
2114 CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) :
2115 Records(R), Target(R) {
2117 Intrinsics = LoadIntrinsics(Records, false);
2118 TgtIntrinsics = LoadIntrinsics(Records, true);
2120 ParseNodeTransforms();
2121 ParseComplexPatterns();
2122 ParsePatternFragments();
2123 ParseDefaultOperands();
2124 ParseInstructions();
2127 // Generate variants. For example, commutative patterns can match
2128 // multiple ways. Add them to PatternsToMatch as well.
2131 // Infer instruction flags. For example, we can detect loads,
2132 // stores, and side effects in many cases by examining an
2133 // instruction's pattern.
2134 InferInstructionFlags();
2136 // Verify that instruction flags match the patterns.
2137 VerifyInstructionFlags();
2140 CodeGenDAGPatterns::~CodeGenDAGPatterns() {
2141 for (pf_iterator I = PatternFragments.begin(),
2142 E = PatternFragments.end(); I != E; ++I)
2147 Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
2148 Record *N = Records.getDef(Name);
2149 if (!N || !N->isSubClassOf("SDNode")) {
2150 errs() << "Error getting SDNode '" << Name << "'!\n";
2156 // Parse all of the SDNode definitions for the target, populating SDNodes.
2157 void CodeGenDAGPatterns::ParseNodeInfo() {
2158 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
2159 while (!Nodes.empty()) {
2160 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
2164 // Get the builtin intrinsic nodes.
2165 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
2166 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
2167 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
2170 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
2171 /// map, and emit them to the file as functions.
2172 void CodeGenDAGPatterns::ParseNodeTransforms() {
2173 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
2174 while (!Xforms.empty()) {
2175 Record *XFormNode = Xforms.back();
2176 Record *SDNode = XFormNode->getValueAsDef("Opcode");
2177 std::string Code = XFormNode->getValueAsString("XFormFunction");
2178 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
2184 void CodeGenDAGPatterns::ParseComplexPatterns() {
2185 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
2186 while (!AMs.empty()) {
2187 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
2193 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
2194 /// file, building up the PatternFragments map. After we've collected them all,
2195 /// inline fragments together as necessary, so that there are no references left
2196 /// inside a pattern fragment to a pattern fragment.
2198 void CodeGenDAGPatterns::ParsePatternFragments() {
2199 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
2201 // First step, parse all of the fragments.
2202 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
2203 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
2204 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
2205 PatternFragments[Fragments[i]] = P;
2207 // Validate the argument list, converting it to set, to discard duplicates.
2208 std::vector<std::string> &Args = P->getArgList();
2209 std::set<std::string> OperandsSet(Args.begin(), Args.end());
2211 if (OperandsSet.count(""))
2212 P->error("Cannot have unnamed 'node' values in pattern fragment!");
2214 // Parse the operands list.
2215 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
2216 DefInit *OpsOp = dyn_cast<DefInit>(OpsList->getOperator());
2217 // Special cases: ops == outs == ins. Different names are used to
2218 // improve readability.
2220 (OpsOp->getDef()->getName() != "ops" &&
2221 OpsOp->getDef()->getName() != "outs" &&
2222 OpsOp->getDef()->getName() != "ins"))
2223 P->error("Operands list should start with '(ops ... '!");
2225 // Copy over the arguments.
2227 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
2228 if (!isa<DefInit>(OpsList->getArg(j)) ||
2229 cast<DefInit>(OpsList->getArg(j))->getDef()->getName() != "node")
2230 P->error("Operands list should all be 'node' values.");
2231 if (OpsList->getArgName(j).empty())
2232 P->error("Operands list should have names for each operand!");
2233 if (!OperandsSet.count(OpsList->getArgName(j)))
2234 P->error("'" + OpsList->getArgName(j) +
2235 "' does not occur in pattern or was multiply specified!");
2236 OperandsSet.erase(OpsList->getArgName(j));
2237 Args.push_back(OpsList->getArgName(j));
2240 if (!OperandsSet.empty())
2241 P->error("Operands list does not contain an entry for operand '" +
2242 *OperandsSet.begin() + "'!");
2244 // If there is a code init for this fragment, keep track of the fact that
2245 // this fragment uses it.
2246 TreePredicateFn PredFn(P);
2247 if (!PredFn.isAlwaysTrue())
2248 P->getOnlyTree()->addPredicateFn(PredFn);
2250 // If there is a node transformation corresponding to this, keep track of
2252 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
2253 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
2254 P->getOnlyTree()->setTransformFn(Transform);
2257 // Now that we've parsed all of the tree fragments, do a closure on them so
2258 // that there are not references to PatFrags left inside of them.
2259 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
2260 TreePattern *ThePat = PatternFragments[Fragments[i]];
2261 ThePat->InlinePatternFragments();
2263 // Infer as many types as possible. Don't worry about it if we don't infer
2264 // all of them, some may depend on the inputs of the pattern.
2265 ThePat->InferAllTypes();
2266 ThePat->resetError();
2268 // If debugging, print out the pattern fragment result.
2269 DEBUG(ThePat->dump());
2273 void CodeGenDAGPatterns::ParseDefaultOperands() {
2274 std::vector<Record*> DefaultOps;
2275 DefaultOps = Records.getAllDerivedDefinitions("OperandWithDefaultOps");
2277 // Find some SDNode.
2278 assert(!SDNodes.empty() && "No SDNodes parsed?");
2279 Init *SomeSDNode = DefInit::get(SDNodes.begin()->first);
2281 for (unsigned i = 0, e = DefaultOps.size(); i != e; ++i) {
2282 DagInit *DefaultInfo = DefaultOps[i]->getValueAsDag("DefaultOps");
2284 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
2285 // SomeSDnode so that we can parse this.
2286 std::vector<std::pair<Init*, std::string> > Ops;
2287 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
2288 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
2289 DefaultInfo->getArgName(op)));
2290 DagInit *DI = DagInit::get(SomeSDNode, "", Ops);
2292 // Create a TreePattern to parse this.
2293 TreePattern P(DefaultOps[i], DI, false, *this);
2294 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
2296 // Copy the operands over into a DAGDefaultOperand.
2297 DAGDefaultOperand DefaultOpInfo;
2299 TreePatternNode *T = P.getTree(0);
2300 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
2301 TreePatternNode *TPN = T->getChild(op);
2302 while (TPN->ApplyTypeConstraints(P, false))
2303 /* Resolve all types */;
2305 if (TPN->ContainsUnresolvedType()) {
2306 PrintFatalError("Value #" + utostr(i) + " of OperandWithDefaultOps '" +
2307 DefaultOps[i]->getName() +"' doesn't have a concrete type!");
2309 DefaultOpInfo.DefaultOps.push_back(TPN);
2312 // Insert it into the DefaultOperands map so we can find it later.
2313 DefaultOperands[DefaultOps[i]] = DefaultOpInfo;
2317 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
2318 /// instruction input. Return true if this is a real use.
2319 static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
2320 std::map<std::string, TreePatternNode*> &InstInputs) {
2321 // No name -> not interesting.
2322 if (Pat->getName().empty()) {
2323 if (Pat->isLeaf()) {
2324 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
2325 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2326 DI->getDef()->isSubClassOf("RegisterOperand")))
2327 I->error("Input " + DI->getDef()->getName() + " must be named!");
2333 if (Pat->isLeaf()) {
2334 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
2335 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
2338 Rec = Pat->getOperator();
2341 // SRCVALUE nodes are ignored.
2342 if (Rec->getName() == "srcvalue")
2345 TreePatternNode *&Slot = InstInputs[Pat->getName()];
2351 if (Slot->isLeaf()) {
2352 SlotRec = cast<DefInit>(Slot->getLeafValue())->getDef();
2354 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
2355 SlotRec = Slot->getOperator();
2358 // Ensure that the inputs agree if we've already seen this input.
2360 I->error("All $" + Pat->getName() + " inputs must agree with each other");
2361 if (Slot->getExtTypes() != Pat->getExtTypes())
2362 I->error("All $" + Pat->getName() + " inputs must agree with each other");
2366 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
2367 /// part of "I", the instruction), computing the set of inputs and outputs of
2368 /// the pattern. Report errors if we see anything naughty.
2369 void CodeGenDAGPatterns::
2370 FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
2371 std::map<std::string, TreePatternNode*> &InstInputs,
2372 std::map<std::string, TreePatternNode*>&InstResults,
2373 std::vector<Record*> &InstImpResults) {
2374 if (Pat->isLeaf()) {
2375 bool isUse = HandleUse(I, Pat, InstInputs);
2376 if (!isUse && Pat->getTransformFn())
2377 I->error("Cannot specify a transform function for a non-input value!");
2381 if (Pat->getOperator()->getName() == "implicit") {
2382 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2383 TreePatternNode *Dest = Pat->getChild(i);
2384 if (!Dest->isLeaf())
2385 I->error("implicitly defined value should be a register!");
2387 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
2388 if (!Val || !Val->getDef()->isSubClassOf("Register"))
2389 I->error("implicitly defined value should be a register!");
2390 InstImpResults.push_back(Val->getDef());
2395 if (Pat->getOperator()->getName() != "set") {
2396 // If this is not a set, verify that the children nodes are not void typed,
2398 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2399 if (Pat->getChild(i)->getNumTypes() == 0)
2400 I->error("Cannot have void nodes inside of patterns!");
2401 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
2405 // If this is a non-leaf node with no children, treat it basically as if
2406 // it were a leaf. This handles nodes like (imm).
2407 bool isUse = HandleUse(I, Pat, InstInputs);
2409 if (!isUse && Pat->getTransformFn())
2410 I->error("Cannot specify a transform function for a non-input value!");
2414 // Otherwise, this is a set, validate and collect instruction results.
2415 if (Pat->getNumChildren() == 0)
2416 I->error("set requires operands!");
2418 if (Pat->getTransformFn())
2419 I->error("Cannot specify a transform function on a set node!");
2421 // Check the set destinations.
2422 unsigned NumDests = Pat->getNumChildren()-1;
2423 for (unsigned i = 0; i != NumDests; ++i) {
2424 TreePatternNode *Dest = Pat->getChild(i);
2425 if (!Dest->isLeaf())
2426 I->error("set destination should be a register!");
2428 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
2430 I->error("set destination should be a register!");
2432 if (Val->getDef()->isSubClassOf("RegisterClass") ||
2433 Val->getDef()->isSubClassOf("RegisterOperand") ||
2434 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
2435 if (Dest->getName().empty())
2436 I->error("set destination must have a name!");
2437 if (InstResults.count(Dest->getName()))
2438 I->error("cannot set '" + Dest->getName() +"' multiple times");
2439 InstResults[Dest->getName()] = Dest;
2440 } else if (Val->getDef()->isSubClassOf("Register")) {
2441 InstImpResults.push_back(Val->getDef());
2443 I->error("set destination should be a register!");
2447 // Verify and collect info from the computation.
2448 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
2449 InstInputs, InstResults, InstImpResults);
2452 //===----------------------------------------------------------------------===//
2453 // Instruction Analysis
2454 //===----------------------------------------------------------------------===//
2456 class InstAnalyzer {
2457 const CodeGenDAGPatterns &CDP;
2459 bool hasSideEffects;
2465 InstAnalyzer(const CodeGenDAGPatterns &cdp)
2466 : CDP(cdp), hasSideEffects(false), mayStore(false), mayLoad(false),
2467 isBitcast(false), isVariadic(false) {}
2469 void Analyze(const TreePattern *Pat) {
2470 // Assume only the first tree is the pattern. The others are clobber nodes.
2471 AnalyzeNode(Pat->getTree(0));
2474 void Analyze(const PatternToMatch *Pat) {
2475 AnalyzeNode(Pat->getSrcPattern());
2479 bool IsNodeBitcast(const TreePatternNode *N) const {
2480 if (hasSideEffects || mayLoad || mayStore || isVariadic)
2483 if (N->getNumChildren() != 2)
2486 const TreePatternNode *N0 = N->getChild(0);
2487 if (!N0->isLeaf() || !isa<DefInit>(N0->getLeafValue()))
2490 const TreePatternNode *N1 = N->getChild(1);
2493 if (N1->getNumChildren() != 1 || !N1->getChild(0)->isLeaf())
2496 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N1->getOperator());
2497 if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1)
2499 return OpInfo.getEnumName() == "ISD::BITCAST";
2503 void AnalyzeNode(const TreePatternNode *N) {
2505 if (DefInit *DI = dyn_cast<DefInit>(N->getLeafValue())) {
2506 Record *LeafRec = DI->getDef();
2507 // Handle ComplexPattern leaves.
2508 if (LeafRec->isSubClassOf("ComplexPattern")) {
2509 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
2510 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
2511 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
2512 if (CP.hasProperty(SDNPSideEffect)) hasSideEffects = true;
2518 // Analyze children.
2519 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2520 AnalyzeNode(N->getChild(i));
2522 // Ignore set nodes, which are not SDNodes.
2523 if (N->getOperator()->getName() == "set") {
2524 isBitcast = IsNodeBitcast(N);
2528 // Get information about the SDNode for the operator.
2529 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N->getOperator());
2531 // Notice properties of the node.
2532 if (OpInfo.hasProperty(SDNPMayStore)) mayStore = true;
2533 if (OpInfo.hasProperty(SDNPMayLoad)) mayLoad = true;
2534 if (OpInfo.hasProperty(SDNPSideEffect)) hasSideEffects = true;
2535 if (OpInfo.hasProperty(SDNPVariadic)) isVariadic = true;
2537 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
2538 // If this is an intrinsic, analyze it.
2539 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
2540 mayLoad = true;// These may load memory.
2542 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteArgMem)
2543 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
2545 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem)
2546 // WriteMem intrinsics can have other strange effects.
2547 hasSideEffects = true;
2553 static bool InferFromPattern(CodeGenInstruction &InstInfo,
2554 const InstAnalyzer &PatInfo,
2558 // Remember where InstInfo got its flags.
2559 if (InstInfo.hasUndefFlags())
2560 InstInfo.InferredFrom = PatDef;
2562 // Check explicitly set flags for consistency.
2563 if (InstInfo.hasSideEffects != PatInfo.hasSideEffects &&
2564 !InstInfo.hasSideEffects_Unset) {
2565 // Allow explicitly setting hasSideEffects = 1 on instructions, even when
2566 // the pattern has no side effects. That could be useful for div/rem
2567 // instructions that may trap.
2568 if (!InstInfo.hasSideEffects) {
2570 PrintError(PatDef->getLoc(), "Pattern doesn't match hasSideEffects = " +
2571 Twine(InstInfo.hasSideEffects));
2575 if (InstInfo.mayStore != PatInfo.mayStore && !InstInfo.mayStore_Unset) {
2577 PrintError(PatDef->getLoc(), "Pattern doesn't match mayStore = " +
2578 Twine(InstInfo.mayStore));
2581 if (InstInfo.mayLoad != PatInfo.mayLoad && !InstInfo.mayLoad_Unset) {
2582 // Allow explicitly setting mayLoad = 1, even when the pattern has no loads.
2583 // Some targets translate imediates to loads.
2584 if (!InstInfo.mayLoad) {
2586 PrintError(PatDef->getLoc(), "Pattern doesn't match mayLoad = " +
2587 Twine(InstInfo.mayLoad));
2591 // Transfer inferred flags.
2592 InstInfo.hasSideEffects |= PatInfo.hasSideEffects;
2593 InstInfo.mayStore |= PatInfo.mayStore;
2594 InstInfo.mayLoad |= PatInfo.mayLoad;
2596 // These flags are silently added without any verification.
2597 InstInfo.isBitcast |= PatInfo.isBitcast;
2599 // Don't infer isVariadic. This flag means something different on SDNodes and
2600 // instructions. For example, a CALL SDNode is variadic because it has the
2601 // call arguments as operands, but a CALL instruction is not variadic - it
2602 // has argument registers as implicit, not explicit uses.
2607 /// hasNullFragReference - Return true if the DAG has any reference to the
2608 /// null_frag operator.
2609 static bool hasNullFragReference(DagInit *DI) {
2610 DefInit *OpDef = dyn_cast<DefInit>(DI->getOperator());
2611 if (!OpDef) return false;
2612 Record *Operator = OpDef->getDef();
2614 // If this is the null fragment, return true.
2615 if (Operator->getName() == "null_frag") return true;
2616 // If any of the arguments reference the null fragment, return true.
2617 for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {
2618 DagInit *Arg = dyn_cast<DagInit>(DI->getArg(i));
2619 if (Arg && hasNullFragReference(Arg))
2626 /// hasNullFragReference - Return true if any DAG in the list references
2627 /// the null_frag operator.
2628 static bool hasNullFragReference(ListInit *LI) {
2629 for (unsigned i = 0, e = LI->getSize(); i != e; ++i) {
2630 DagInit *DI = dyn_cast<DagInit>(LI->getElement(i));
2631 assert(DI && "non-dag in an instruction Pattern list?!");
2632 if (hasNullFragReference(DI))
2638 /// Get all the instructions in a tree.
2640 getInstructionsInTree(TreePatternNode *Tree, SmallVectorImpl<Record*> &Instrs) {
2643 if (Tree->getOperator()->isSubClassOf("Instruction"))
2644 Instrs.push_back(Tree->getOperator());
2645 for (unsigned i = 0, e = Tree->getNumChildren(); i != e; ++i)
2646 getInstructionsInTree(Tree->getChild(i), Instrs);
2649 /// ParseInstructions - Parse all of the instructions, inlining and resolving
2650 /// any fragments involved. This populates the Instructions list with fully
2651 /// resolved instructions.
2652 void CodeGenDAGPatterns::ParseInstructions() {
2653 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
2655 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
2658 if (isa<ListInit>(Instrs[i]->getValueInit("Pattern")))
2659 LI = Instrs[i]->getValueAsListInit("Pattern");
2661 // If there is no pattern, only collect minimal information about the
2662 // instruction for its operand list. We have to assume that there is one
2663 // result, as we have no detailed info. A pattern which references the
2664 // null_frag operator is as-if no pattern were specified. Normally this
2665 // is from a multiclass expansion w/ a SDPatternOperator passed in as
2667 if (!LI || LI->getSize() == 0 || hasNullFragReference(LI)) {
2668 std::vector<Record*> Results;
2669 std::vector<Record*> Operands;
2671 CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
2673 if (InstInfo.Operands.size() != 0) {
2674 if (InstInfo.Operands.NumDefs == 0) {
2675 // These produce no results
2676 for (unsigned j = 0, e = InstInfo.Operands.size(); j < e; ++j)
2677 Operands.push_back(InstInfo.Operands[j].Rec);
2679 // Assume the first operand is the result.
2680 Results.push_back(InstInfo.Operands[0].Rec);
2682 // The rest are inputs.
2683 for (unsigned j = 1, e = InstInfo.Operands.size(); j < e; ++j)
2684 Operands.push_back(InstInfo.Operands[j].Rec);
2688 // Create and insert the instruction.
2689 std::vector<Record*> ImpResults;
2690 Instructions.insert(std::make_pair(Instrs[i],
2691 DAGInstruction(0, Results, Operands, ImpResults)));
2692 continue; // no pattern.
2695 // Parse the instruction.
2696 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
2697 // Inline pattern fragments into it.
2698 I->InlinePatternFragments();
2700 // Infer as many types as possible. If we cannot infer all of them, we can
2701 // never do anything with this instruction pattern: report it to the user.
2702 if (!I->InferAllTypes())
2703 I->error("Could not infer all types in pattern!");
2705 // InstInputs - Keep track of all of the inputs of the instruction, along
2706 // with the record they are declared as.
2707 std::map<std::string, TreePatternNode*> InstInputs;
2709 // InstResults - Keep track of all the virtual registers that are 'set'
2710 // in the instruction, including what reg class they are.
2711 std::map<std::string, TreePatternNode*> InstResults;
2713 std::vector<Record*> InstImpResults;
2715 // Verify that the top-level forms in the instruction are of void type, and
2716 // fill in the InstResults map.
2717 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
2718 TreePatternNode *Pat = I->getTree(j);
2719 if (Pat->getNumTypes() != 0)
2720 I->error("Top-level forms in instruction pattern should have"
2723 // Find inputs and outputs, and verify the structure of the uses/defs.
2724 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
2728 // Now that we have inputs and outputs of the pattern, inspect the operands
2729 // list for the instruction. This determines the order that operands are
2730 // added to the machine instruction the node corresponds to.
2731 unsigned NumResults = InstResults.size();
2733 // Parse the operands list from the (ops) list, validating it.
2734 assert(I->getArgList().empty() && "Args list should still be empty here!");
2735 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]);
2737 // Check that all of the results occur first in the list.
2738 std::vector<Record*> Results;
2739 TreePatternNode *Res0Node = 0;
2740 for (unsigned i = 0; i != NumResults; ++i) {
2741 if (i == CGI.Operands.size())
2742 I->error("'" + InstResults.begin()->first +
2743 "' set but does not appear in operand list!");
2744 const std::string &OpName = CGI.Operands[i].Name;
2746 // Check that it exists in InstResults.
2747 TreePatternNode *RNode = InstResults[OpName];
2749 I->error("Operand $" + OpName + " does not exist in operand list!");
2753 Record *R = cast<DefInit>(RNode->getLeafValue())->getDef();
2755 I->error("Operand $" + OpName + " should be a set destination: all "
2756 "outputs must occur before inputs in operand list!");
2758 if (CGI.Operands[i].Rec != R)
2759 I->error("Operand $" + OpName + " class mismatch!");
2761 // Remember the return type.
2762 Results.push_back(CGI.Operands[i].Rec);
2764 // Okay, this one checks out.
2765 InstResults.erase(OpName);
2768 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
2769 // the copy while we're checking the inputs.
2770 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
2772 std::vector<TreePatternNode*> ResultNodeOperands;
2773 std::vector<Record*> Operands;
2774 for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
2775 CGIOperandList::OperandInfo &Op = CGI.Operands[i];
2776 const std::string &OpName = Op.Name;
2778 I->error("Operand #" + utostr(i) + " in operands list has no name!");
2780 if (!InstInputsCheck.count(OpName)) {
2781 // If this is an operand with a DefaultOps set filled in, we can ignore
2782 // this. When we codegen it, we will do so as always executed.
2783 if (Op.Rec->isSubClassOf("OperandWithDefaultOps")) {
2784 // Does it have a non-empty DefaultOps field? If so, ignore this
2786 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
2789 I->error("Operand $" + OpName +
2790 " does not appear in the instruction pattern");
2792 TreePatternNode *InVal = InstInputsCheck[OpName];
2793 InstInputsCheck.erase(OpName); // It occurred, remove from map.
2795 if (InVal->isLeaf() && isa<DefInit>(InVal->getLeafValue())) {
2796 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
2797 if (Op.Rec != InRec && !InRec->isSubClassOf("ComplexPattern"))
2798 I->error("Operand $" + OpName + "'s register class disagrees"
2799 " between the operand and pattern");
2801 Operands.push_back(Op.Rec);
2803 // Construct the result for the dest-pattern operand list.
2804 TreePatternNode *OpNode = InVal->clone();
2806 // No predicate is useful on the result.
2807 OpNode->clearPredicateFns();
2809 // Promote the xform function to be an explicit node if set.
2810 if (Record *Xform = OpNode->getTransformFn()) {
2811 OpNode->setTransformFn(0);
2812 std::vector<TreePatternNode*> Children;
2813 Children.push_back(OpNode);
2814 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
2817 ResultNodeOperands.push_back(OpNode);
2820 if (!InstInputsCheck.empty())
2821 I->error("Input operand $" + InstInputsCheck.begin()->first +
2822 " occurs in pattern but not in operands list!");
2824 TreePatternNode *ResultPattern =
2825 new TreePatternNode(I->getRecord(), ResultNodeOperands,
2826 GetNumNodeResults(I->getRecord(), *this));
2827 // Copy fully inferred output node type to instruction result pattern.
2828 for (unsigned i = 0; i != NumResults; ++i)
2829 ResultPattern->setType(i, Res0Node->getExtType(i));
2831 // Create and insert the instruction.
2832 // FIXME: InstImpResults should not be part of DAGInstruction.
2833 DAGInstruction TheInst(I, Results, Operands, InstImpResults);
2834 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
2836 // Use a temporary tree pattern to infer all types and make sure that the
2837 // constructed result is correct. This depends on the instruction already
2838 // being inserted into the Instructions map.
2839 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
2840 Temp.InferAllTypes(&I->getNamedNodesMap());
2842 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
2843 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
2848 // If we can, convert the instructions to be patterns that are matched!
2849 for (std::map<Record*, DAGInstruction, LessRecordByID>::iterator II =
2850 Instructions.begin(),
2851 E = Instructions.end(); II != E; ++II) {
2852 DAGInstruction &TheInst = II->second;
2853 TreePattern *I = TheInst.getPattern();
2854 if (I == 0) continue; // No pattern.
2856 // FIXME: Assume only the first tree is the pattern. The others are clobber
2858 TreePatternNode *Pattern = I->getTree(0);
2859 TreePatternNode *SrcPattern;
2860 if (Pattern->getOperator()->getName() == "set") {
2861 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
2863 // Not a set (store or something?)
2864 SrcPattern = Pattern;
2867 Record *Instr = II->first;
2868 AddPatternToMatch(I,
2869 PatternToMatch(Instr,
2870 Instr->getValueAsListInit("Predicates"),
2872 TheInst.getResultPattern(),
2873 TheInst.getImpResults(),
2874 Instr->getValueAsInt("AddedComplexity"),
2880 typedef std::pair<const TreePatternNode*, unsigned> NameRecord;
2882 static void FindNames(const TreePatternNode *P,
2883 std::map<std::string, NameRecord> &Names,
2884 TreePattern *PatternTop) {
2885 if (!P->getName().empty()) {
2886 NameRecord &Rec = Names[P->getName()];
2887 // If this is the first instance of the name, remember the node.
2888 if (Rec.second++ == 0)
2890 else if (Rec.first->getExtTypes() != P->getExtTypes())
2891 PatternTop->error("repetition of value: $" + P->getName() +
2892 " where different uses have different types!");
2896 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
2897 FindNames(P->getChild(i), Names, PatternTop);
2901 void CodeGenDAGPatterns::AddPatternToMatch(TreePattern *Pattern,
2902 const PatternToMatch &PTM) {
2903 // Do some sanity checking on the pattern we're about to match.
2905 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this)) {
2906 PrintWarning(Pattern->getRecord()->getLoc(),
2907 Twine("Pattern can never match: ") + Reason);
2911 // If the source pattern's root is a complex pattern, that complex pattern
2912 // must specify the nodes it can potentially match.
2913 if (const ComplexPattern *CP =
2914 PTM.getSrcPattern()->getComplexPatternInfo(*this))
2915 if (CP->getRootNodes().empty())
2916 Pattern->error("ComplexPattern at root must specify list of opcodes it"
2920 // Find all of the named values in the input and output, ensure they have the
2922 std::map<std::string, NameRecord> SrcNames, DstNames;
2923 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
2924 FindNames(PTM.getDstPattern(), DstNames, Pattern);
2926 // Scan all of the named values in the destination pattern, rejecting them if
2927 // they don't exist in the input pattern.
2928 for (std::map<std::string, NameRecord>::iterator
2929 I = DstNames.begin(), E = DstNames.end(); I != E; ++I) {
2930 if (SrcNames[I->first].first == 0)
2931 Pattern->error("Pattern has input without matching name in output: $" +
2935 // Scan all of the named values in the source pattern, rejecting them if the
2936 // name isn't used in the dest, and isn't used to tie two values together.
2937 for (std::map<std::string, NameRecord>::iterator
2938 I = SrcNames.begin(), E = SrcNames.end(); I != E; ++I)
2939 if (DstNames[I->first].first == 0 && SrcNames[I->first].second == 1)
2940 Pattern->error("Pattern has dead named input: $" + I->first);
2942 PatternsToMatch.push_back(PTM);
2947 void CodeGenDAGPatterns::InferInstructionFlags() {
2948 const std::vector<const CodeGenInstruction*> &Instructions =
2949 Target.getInstructionsByEnumValue();
2951 // First try to infer flags from the primary instruction pattern, if any.
2952 SmallVector<CodeGenInstruction*, 8> Revisit;
2953 unsigned Errors = 0;
2954 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
2955 CodeGenInstruction &InstInfo =
2956 const_cast<CodeGenInstruction &>(*Instructions[i]);
2958 // Treat neverHasSideEffects = 1 as the equivalent of hasSideEffects = 0.
2959 // This flag is obsolete and will be removed.
2960 if (InstInfo.neverHasSideEffects) {
2961 assert(!InstInfo.hasSideEffects);
2962 InstInfo.hasSideEffects_Unset = false;
2965 // Get the primary instruction pattern.
2966 const TreePattern *Pattern = getInstruction(InstInfo.TheDef).getPattern();
2968 if (InstInfo.hasUndefFlags())
2969 Revisit.push_back(&InstInfo);
2972 InstAnalyzer PatInfo(*this);
2973 PatInfo.Analyze(Pattern);
2974 Errors += InferFromPattern(InstInfo, PatInfo, InstInfo.TheDef);
2977 // Second, look for single-instruction patterns defined outside the
2979 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
2980 const PatternToMatch &PTM = *I;
2982 // We can only infer from single-instruction patterns, otherwise we won't
2983 // know which instruction should get the flags.
2984 SmallVector<Record*, 8> PatInstrs;
2985 getInstructionsInTree(PTM.getDstPattern(), PatInstrs);
2986 if (PatInstrs.size() != 1)
2989 // Get the single instruction.
2990 CodeGenInstruction &InstInfo = Target.getInstruction(PatInstrs.front());
2992 // Only infer properties from the first pattern. We'll verify the others.
2993 if (InstInfo.InferredFrom)
2996 InstAnalyzer PatInfo(*this);
2997 PatInfo.Analyze(&PTM);
2998 Errors += InferFromPattern(InstInfo, PatInfo, PTM.getSrcRecord());
3002 PrintFatalError("pattern conflicts");
3004 // Revisit instructions with undefined flags and no pattern.
3005 if (Target.guessInstructionProperties()) {
3006 for (unsigned i = 0, e = Revisit.size(); i != e; ++i) {
3007 CodeGenInstruction &InstInfo = *Revisit[i];
3008 if (InstInfo.InferredFrom)
3010 // The mayLoad and mayStore flags default to false.
3011 // Conservatively assume hasSideEffects if it wasn't explicit.
3012 if (InstInfo.hasSideEffects_Unset)
3013 InstInfo.hasSideEffects = true;
3018 // Complain about any flags that are still undefined.
3019 for (unsigned i = 0, e = Revisit.size(); i != e; ++i) {
3020 CodeGenInstruction &InstInfo = *Revisit[i];
3021 if (InstInfo.InferredFrom)
3023 if (InstInfo.hasSideEffects_Unset)
3024 PrintError(InstInfo.TheDef->getLoc(),
3025 "Can't infer hasSideEffects from patterns");
3026 if (InstInfo.mayStore_Unset)
3027 PrintError(InstInfo.TheDef->getLoc(),
3028 "Can't infer mayStore from patterns");
3029 if (InstInfo.mayLoad_Unset)
3030 PrintError(InstInfo.TheDef->getLoc(),
3031 "Can't infer mayLoad from patterns");
3036 /// Verify instruction flags against pattern node properties.
3037 void CodeGenDAGPatterns::VerifyInstructionFlags() {
3038 unsigned Errors = 0;
3039 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3040 const PatternToMatch &PTM = *I;
3041 SmallVector<Record*, 8> Instrs;
3042 getInstructionsInTree(PTM.getDstPattern(), Instrs);
3046 // Count the number of instructions with each flag set.
3047 unsigned NumSideEffects = 0;
3048 unsigned NumStores = 0;
3049 unsigned NumLoads = 0;
3050 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
3051 const CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
3052 NumSideEffects += InstInfo.hasSideEffects;
3053 NumStores += InstInfo.mayStore;
3054 NumLoads += InstInfo.mayLoad;
3057 // Analyze the source pattern.
3058 InstAnalyzer PatInfo(*this);
3059 PatInfo.Analyze(&PTM);
3061 // Collect error messages.
3062 SmallVector<std::string, 4> Msgs;
3064 // Check for missing flags in the output.
3065 // Permit extra flags for now at least.
3066 if (PatInfo.hasSideEffects && !NumSideEffects)
3067 Msgs.push_back("pattern has side effects, but hasSideEffects isn't set");
3069 // Don't verify store flags on instructions with side effects. At least for
3070 // intrinsics, side effects implies mayStore.
3071 if (!PatInfo.hasSideEffects && PatInfo.mayStore && !NumStores)
3072 Msgs.push_back("pattern may store, but mayStore isn't set");
3074 // Similarly, mayStore implies mayLoad on intrinsics.
3075 if (!PatInfo.mayStore && PatInfo.mayLoad && !NumLoads)
3076 Msgs.push_back("pattern may load, but mayLoad isn't set");
3078 // Print error messages.
3083 for (unsigned i = 0, e = Msgs.size(); i != e; ++i)
3084 PrintError(PTM.getSrcRecord()->getLoc(), Twine(Msgs[i]) + " on the " +
3085 (Instrs.size() == 1 ?
3086 "instruction" : "output instructions"));
3087 // Provide the location of the relevant instruction definitions.
3088 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
3089 if (Instrs[i] != PTM.getSrcRecord())
3090 PrintError(Instrs[i]->getLoc(), "defined here");
3091 const CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
3092 if (InstInfo.InferredFrom &&
3093 InstInfo.InferredFrom != InstInfo.TheDef &&
3094 InstInfo.InferredFrom != PTM.getSrcRecord())
3095 PrintError(InstInfo.InferredFrom->getLoc(), "inferred from patttern");
3099 PrintFatalError("Errors in DAG patterns");
3102 /// Given a pattern result with an unresolved type, see if we can find one
3103 /// instruction with an unresolved result type. Force this result type to an
3104 /// arbitrary element if it's possible types to converge results.
3105 static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
3109 // Analyze children.
3110 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3111 if (ForceArbitraryInstResultType(N->getChild(i), TP))
3114 if (!N->getOperator()->isSubClassOf("Instruction"))
3117 // If this type is already concrete or completely unknown we can't do
3119 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
3120 if (N->getExtType(i).isCompletelyUnknown() || N->getExtType(i).isConcrete())
3123 // Otherwise, force its type to the first possibility (an arbitrary choice).
3124 if (N->getExtType(i).MergeInTypeInfo(N->getExtType(i).getTypeList()[0], TP))
3131 void CodeGenDAGPatterns::ParsePatterns() {
3132 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
3134 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
3135 Record *CurPattern = Patterns[i];
3136 DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
3138 // If the pattern references the null_frag, there's nothing to do.
3139 if (hasNullFragReference(Tree))
3142 TreePattern *Pattern = new TreePattern(CurPattern, Tree, true, *this);
3144 // Inline pattern fragments into it.
3145 Pattern->InlinePatternFragments();
3147 ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
3148 if (LI->getSize() == 0) continue; // no pattern.
3150 // Parse the instruction.
3151 TreePattern *Result = new TreePattern(CurPattern, LI, false, *this);
3153 // Inline pattern fragments into it.
3154 Result->InlinePatternFragments();
3156 if (Result->getNumTrees() != 1)
3157 Result->error("Cannot handle instructions producing instructions "
3158 "with temporaries yet!");
3160 bool IterateInference;
3161 bool InferredAllPatternTypes, InferredAllResultTypes;
3163 // Infer as many types as possible. If we cannot infer all of them, we
3164 // can never do anything with this pattern: report it to the user.
3165 InferredAllPatternTypes =
3166 Pattern->InferAllTypes(&Pattern->getNamedNodesMap());
3168 // Infer as many types as possible. If we cannot infer all of them, we
3169 // can never do anything with this pattern: report it to the user.
3170 InferredAllResultTypes =
3171 Result->InferAllTypes(&Pattern->getNamedNodesMap());
3173 IterateInference = false;
3175 // Apply the type of the result to the source pattern. This helps us
3176 // resolve cases where the input type is known to be a pointer type (which
3177 // is considered resolved), but the result knows it needs to be 32- or
3178 // 64-bits. Infer the other way for good measure.
3179 for (unsigned i = 0, e = std::min(Result->getTree(0)->getNumTypes(),
3180 Pattern->getTree(0)->getNumTypes());
3182 IterateInference = Pattern->getTree(0)->
3183 UpdateNodeType(i, Result->getTree(0)->getExtType(i), *Result);
3184 IterateInference |= Result->getTree(0)->
3185 UpdateNodeType(i, Pattern->getTree(0)->getExtType(i), *Result);
3188 // If our iteration has converged and the input pattern's types are fully
3189 // resolved but the result pattern is not fully resolved, we may have a
3190 // situation where we have two instructions in the result pattern and
3191 // the instructions require a common register class, but don't care about
3192 // what actual MVT is used. This is actually a bug in our modelling:
3193 // output patterns should have register classes, not MVTs.
3195 // In any case, to handle this, we just go through and disambiguate some
3196 // arbitrary types to the result pattern's nodes.
3197 if (!IterateInference && InferredAllPatternTypes &&
3198 !InferredAllResultTypes)
3199 IterateInference = ForceArbitraryInstResultType(Result->getTree(0),
3201 } while (IterateInference);
3203 // Verify that we inferred enough types that we can do something with the
3204 // pattern and result. If these fire the user has to add type casts.
3205 if (!InferredAllPatternTypes)
3206 Pattern->error("Could not infer all types in pattern!");
3207 if (!InferredAllResultTypes) {
3209 Result->error("Could not infer all types in pattern result!");
3212 // Validate that the input pattern is correct.
3213 std::map<std::string, TreePatternNode*> InstInputs;
3214 std::map<std::string, TreePatternNode*> InstResults;
3215 std::vector<Record*> InstImpResults;
3216 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
3217 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
3218 InstInputs, InstResults,
3221 // Promote the xform function to be an explicit node if set.
3222 TreePatternNode *DstPattern = Result->getOnlyTree();
3223 std::vector<TreePatternNode*> ResultNodeOperands;
3224 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
3225 TreePatternNode *OpNode = DstPattern->getChild(ii);
3226 if (Record *Xform = OpNode->getTransformFn()) {
3227 OpNode->setTransformFn(0);
3228 std::vector<TreePatternNode*> Children;
3229 Children.push_back(OpNode);
3230 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
3232 ResultNodeOperands.push_back(OpNode);
3234 DstPattern = Result->getOnlyTree();
3235 if (!DstPattern->isLeaf())
3236 DstPattern = new TreePatternNode(DstPattern->getOperator(),
3238 DstPattern->getNumTypes());
3240 for (unsigned i = 0, e = Result->getOnlyTree()->getNumTypes(); i != e; ++i)
3241 DstPattern->setType(i, Result->getOnlyTree()->getExtType(i));
3243 TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
3244 Temp.InferAllTypes();
3247 AddPatternToMatch(Pattern,
3248 PatternToMatch(CurPattern,
3249 CurPattern->getValueAsListInit("Predicates"),
3250 Pattern->getTree(0),
3251 Temp.getOnlyTree(), InstImpResults,
3252 CurPattern->getValueAsInt("AddedComplexity"),
3253 CurPattern->getID()));
3257 /// CombineChildVariants - Given a bunch of permutations of each child of the
3258 /// 'operator' node, put them together in all possible ways.
3259 static void CombineChildVariants(TreePatternNode *Orig,
3260 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
3261 std::vector<TreePatternNode*> &OutVariants,
3262 CodeGenDAGPatterns &CDP,
3263 const MultipleUseVarSet &DepVars) {
3264 // Make sure that each operand has at least one variant to choose from.
3265 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
3266 if (ChildVariants[i].empty())
3269 // The end result is an all-pairs construction of the resultant pattern.
3270 std::vector<unsigned> Idxs;
3271 Idxs.resize(ChildVariants.size());
3275 DEBUG(if (!Idxs.empty()) {
3276 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
3277 for (unsigned i = 0; i < Idxs.size(); ++i) {
3278 errs() << Idxs[i] << " ";
3283 // Create the variant and add it to the output list.
3284 std::vector<TreePatternNode*> NewChildren;
3285 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
3286 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
3287 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren,
3288 Orig->getNumTypes());
3290 // Copy over properties.
3291 R->setName(Orig->getName());
3292 R->setPredicateFns(Orig->getPredicateFns());
3293 R->setTransformFn(Orig->getTransformFn());
3294 for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
3295 R->setType(i, Orig->getExtType(i));
3297 // If this pattern cannot match, do not include it as a variant.
3298 std::string ErrString;
3299 if (!R->canPatternMatch(ErrString, CDP)) {
3302 bool AlreadyExists = false;
3304 // Scan to see if this pattern has already been emitted. We can get
3305 // duplication due to things like commuting:
3306 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
3307 // which are the same pattern. Ignore the dups.
3308 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
3309 if (R->isIsomorphicTo(OutVariants[i], DepVars)) {
3310 AlreadyExists = true;
3317 OutVariants.push_back(R);
3320 // Increment indices to the next permutation by incrementing the
3321 // indicies from last index backward, e.g., generate the sequence
3322 // [0, 0], [0, 1], [1, 0], [1, 1].
3324 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
3325 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
3330 NotDone = (IdxsIdx >= 0);
3334 /// CombineChildVariants - A helper function for binary operators.
3336 static void CombineChildVariants(TreePatternNode *Orig,
3337 const std::vector<TreePatternNode*> &LHS,
3338 const std::vector<TreePatternNode*> &RHS,
3339 std::vector<TreePatternNode*> &OutVariants,
3340 CodeGenDAGPatterns &CDP,
3341 const MultipleUseVarSet &DepVars) {
3342 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3343 ChildVariants.push_back(LHS);
3344 ChildVariants.push_back(RHS);
3345 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
3349 static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
3350 std::vector<TreePatternNode *> &Children) {
3351 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
3352 Record *Operator = N->getOperator();
3354 // Only permit raw nodes.
3355 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
3356 N->getTransformFn()) {
3357 Children.push_back(N);
3361 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
3362 Children.push_back(N->getChild(0));
3364 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
3366 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
3367 Children.push_back(N->getChild(1));
3369 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
3372 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
3373 /// the (potentially recursive) pattern by using algebraic laws.
3375 static void GenerateVariantsOf(TreePatternNode *N,
3376 std::vector<TreePatternNode*> &OutVariants,
3377 CodeGenDAGPatterns &CDP,
3378 const MultipleUseVarSet &DepVars) {
3379 // We cannot permute leaves.
3381 OutVariants.push_back(N);
3385 // Look up interesting info about the node.
3386 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
3388 // If this node is associative, re-associate.
3389 if (NodeInfo.hasProperty(SDNPAssociative)) {
3390 // Re-associate by pulling together all of the linked operators
3391 std::vector<TreePatternNode*> MaximalChildren;
3392 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
3394 // Only handle child sizes of 3. Otherwise we'll end up trying too many
3396 if (MaximalChildren.size() == 3) {
3397 // Find the variants of all of our maximal children.
3398 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
3399 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
3400 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
3401 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
3403 // There are only two ways we can permute the tree:
3404 // (A op B) op C and A op (B op C)
3405 // Within these forms, we can also permute A/B/C.
3407 // Generate legal pair permutations of A/B/C.
3408 std::vector<TreePatternNode*> ABVariants;
3409 std::vector<TreePatternNode*> BAVariants;
3410 std::vector<TreePatternNode*> ACVariants;
3411 std::vector<TreePatternNode*> CAVariants;
3412 std::vector<TreePatternNode*> BCVariants;
3413 std::vector<TreePatternNode*> CBVariants;
3414 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
3415 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
3416 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
3417 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
3418 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
3419 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
3421 // Combine those into the result: (x op x) op x
3422 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
3423 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
3424 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
3425 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
3426 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
3427 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
3429 // Combine those into the result: x op (x op x)
3430 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
3431 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
3432 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
3433 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
3434 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
3435 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
3440 // Compute permutations of all children.
3441 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3442 ChildVariants.resize(N->getNumChildren());
3443 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3444 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
3446 // Build all permutations based on how the children were formed.
3447 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
3449 // If this node is commutative, consider the commuted order.
3450 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
3451 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
3452 assert((N->getNumChildren()==2 || isCommIntrinsic) &&
3453 "Commutative but doesn't have 2 children!");
3454 // Don't count children which are actually register references.
3456 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
3457 TreePatternNode *Child = N->getChild(i);
3458 if (Child->isLeaf())
3459 if (DefInit *DI = dyn_cast<DefInit>(Child->getLeafValue())) {
3460 Record *RR = DI->getDef();
3461 if (RR->isSubClassOf("Register"))
3466 // Consider the commuted order.
3467 if (isCommIntrinsic) {
3468 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
3469 // operands are the commutative operands, and there might be more operands
3472 "Commutative intrinsic should have at least 3 childrean!");
3473 std::vector<std::vector<TreePatternNode*> > Variants;
3474 Variants.push_back(ChildVariants[0]); // Intrinsic id.
3475 Variants.push_back(ChildVariants[2]);
3476 Variants.push_back(ChildVariants[1]);
3477 for (unsigned i = 3; i != NC; ++i)
3478 Variants.push_back(ChildVariants[i]);
3479 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
3481 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
3482 OutVariants, CDP, DepVars);
3487 // GenerateVariants - Generate variants. For example, commutative patterns can
3488 // match multiple ways. Add them to PatternsToMatch as well.
3489 void CodeGenDAGPatterns::GenerateVariants() {
3490 DEBUG(errs() << "Generating instruction variants.\n");
3492 // Loop over all of the patterns we've collected, checking to see if we can
3493 // generate variants of the instruction, through the exploitation of
3494 // identities. This permits the target to provide aggressive matching without
3495 // the .td file having to contain tons of variants of instructions.
3497 // Note that this loop adds new patterns to the PatternsToMatch list, but we
3498 // intentionally do not reconsider these. Any variants of added patterns have
3499 // already been added.
3501 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
3502 MultipleUseVarSet DepVars;
3503 std::vector<TreePatternNode*> Variants;
3504 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
3505 DEBUG(errs() << "Dependent/multiply used variables: ");
3506 DEBUG(DumpDepVars(DepVars));
3507 DEBUG(errs() << "\n");
3508 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this,
3511 assert(!Variants.empty() && "Must create at least original variant!");
3512 Variants.erase(Variants.begin()); // Remove the original pattern.
3514 if (Variants.empty()) // No variants for this pattern.
3517 DEBUG(errs() << "FOUND VARIANTS OF: ";
3518 PatternsToMatch[i].getSrcPattern()->dump();
3521 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
3522 TreePatternNode *Variant = Variants[v];
3524 DEBUG(errs() << " VAR#" << v << ": ";
3528 // Scan to see if an instruction or explicit pattern already matches this.
3529 bool AlreadyExists = false;
3530 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
3531 // Skip if the top level predicates do not match.
3532 if (PatternsToMatch[i].getPredicates() !=
3533 PatternsToMatch[p].getPredicates())
3535 // Check to see if this variant already exists.
3536 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),
3538 DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
3539 AlreadyExists = true;
3543 // If we already have it, ignore the variant.
3544 if (AlreadyExists) continue;
3546 // Otherwise, add it to the list of patterns we have.
3548 push_back(PatternToMatch(PatternsToMatch[i].getSrcRecord(),
3549 PatternsToMatch[i].getPredicates(),
3550 Variant, PatternsToMatch[i].getDstPattern(),
3551 PatternsToMatch[i].getDstRegs(),
3552 PatternsToMatch[i].getAddedComplexity(),
3553 Record::getNewUID()));
3556 DEBUG(errs() << "\n");