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 #define DEBUG_TYPE "dag-patterns"
30 //===----------------------------------------------------------------------===//
31 // EEVT::TypeSet Implementation
32 //===----------------------------------------------------------------------===//
34 static inline bool isInteger(MVT::SimpleValueType VT) {
35 return MVT(VT).isInteger();
37 static inline bool isFloatingPoint(MVT::SimpleValueType VT) {
38 return MVT(VT).isFloatingPoint();
40 static inline bool isVector(MVT::SimpleValueType VT) {
41 return MVT(VT).isVector();
43 static inline bool isScalar(MVT::SimpleValueType VT) {
44 return !MVT(VT).isVector();
47 EEVT::TypeSet::TypeSet(MVT::SimpleValueType VT, TreePattern &TP) {
50 else if (VT == MVT::fAny)
51 EnforceFloatingPoint(TP);
52 else if (VT == MVT::vAny)
55 assert((VT < MVT::LAST_VALUETYPE || VT == MVT::iPTR ||
56 VT == MVT::iPTRAny || VT == MVT::Any) && "Not a concrete type!");
57 TypeVec.push_back(VT);
62 EEVT::TypeSet::TypeSet(ArrayRef<MVT::SimpleValueType> VTList) {
63 assert(!VTList.empty() && "empty list?");
64 TypeVec.append(VTList.begin(), VTList.end());
67 assert(VTList[0] != MVT::iAny && VTList[0] != MVT::vAny &&
68 VTList[0] != MVT::fAny);
70 // Verify no duplicates.
71 array_pod_sort(TypeVec.begin(), TypeVec.end());
72 assert(std::unique(TypeVec.begin(), TypeVec.end()) == TypeVec.end());
75 /// FillWithPossibleTypes - Set to all legal types and return true, only valid
76 /// on completely unknown type sets.
77 bool EEVT::TypeSet::FillWithPossibleTypes(TreePattern &TP,
78 bool (*Pred)(MVT::SimpleValueType),
79 const char *PredicateName) {
80 assert(isCompletelyUnknown());
81 ArrayRef<MVT::SimpleValueType> LegalTypes =
82 TP.getDAGPatterns().getTargetInfo().getLegalValueTypes();
87 for (unsigned i = 0, e = LegalTypes.size(); i != e; ++i)
88 if (!Pred || Pred(LegalTypes[i]))
89 TypeVec.push_back(LegalTypes[i]);
91 // If we have nothing that matches the predicate, bail out.
92 if (TypeVec.empty()) {
93 TP.error("Type inference contradiction found, no " +
94 std::string(PredicateName) + " types found");
97 // No need to sort with one element.
98 if (TypeVec.size() == 1) return true;
100 // Remove duplicates.
101 array_pod_sort(TypeVec.begin(), TypeVec.end());
102 TypeVec.erase(std::unique(TypeVec.begin(), TypeVec.end()), TypeVec.end());
107 /// hasIntegerTypes - Return true if this TypeSet contains iAny or an
108 /// integer value type.
109 bool EEVT::TypeSet::hasIntegerTypes() const {
110 return std::any_of(TypeVec.begin(), TypeVec.end(),
111 [](MVT::SimpleValueType VT) {
112 return isInteger(VT);
116 /// hasFloatingPointTypes - Return true if this TypeSet contains an fAny or
117 /// a floating point value type.
118 bool EEVT::TypeSet::hasFloatingPointTypes() const {
119 return std::any_of(TypeVec.begin(), TypeVec.end(),
120 [](MVT::SimpleValueType VT) {
121 return isFloatingPoint(VT);
125 /// hasScalarTypes - Return true if this TypeSet contains a scalar value type.
126 bool EEVT::TypeSet::hasScalarTypes() const {
127 return std::any_of(TypeVec.begin(), TypeVec.end(),
128 [](MVT::SimpleValueType VT) {
133 /// hasVectorTypes - Return true if this TypeSet contains a vAny or a vector
135 bool EEVT::TypeSet::hasVectorTypes() const {
136 return std::any_of(TypeVec.begin(), TypeVec.end(),
137 [](MVT::SimpleValueType VT) {
143 std::string EEVT::TypeSet::getName() const {
144 if (TypeVec.empty()) return "<empty>";
148 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i) {
149 std::string VTName = llvm::getEnumName(TypeVec[i]);
150 // Strip off MVT:: prefix if present.
151 if (VTName.substr(0,5) == "MVT::")
152 VTName = VTName.substr(5);
153 if (i) Result += ':';
157 if (TypeVec.size() == 1)
159 return "{" + Result + "}";
162 /// MergeInTypeInfo - This merges in type information from the specified
163 /// argument. If 'this' changes, it returns true. If the two types are
164 /// contradictory (e.g. merge f32 into i32) then this flags an error.
165 bool EEVT::TypeSet::MergeInTypeInfo(const EEVT::TypeSet &InVT, TreePattern &TP){
166 if (InVT.isCompletelyUnknown() || *this == InVT || TP.hasError())
169 if (isCompletelyUnknown()) {
174 assert(TypeVec.size() >= 1 && InVT.TypeVec.size() >= 1 && "No unknowns");
176 // Handle the abstract cases, seeing if we can resolve them better.
177 switch (TypeVec[0]) {
181 if (InVT.hasIntegerTypes()) {
182 EEVT::TypeSet InCopy(InVT);
183 InCopy.EnforceInteger(TP);
184 InCopy.EnforceScalar(TP);
186 if (InCopy.isConcrete()) {
187 // If the RHS has one integer type, upgrade iPTR to i32.
188 TypeVec[0] = InVT.TypeVec[0];
192 // If the input has multiple scalar integers, this doesn't add any info.
193 if (!InCopy.isCompletelyUnknown())
199 // If the input constraint is iAny/iPTR and this is an integer type list,
200 // remove non-integer types from the list.
201 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
203 bool MadeChange = EnforceInteger(TP);
205 // If we're merging in iPTR/iPTRAny and the node currently has a list of
206 // multiple different integer types, replace them with a single iPTR.
207 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
208 TypeVec.size() != 1) {
210 TypeVec[0] = InVT.TypeVec[0];
217 // If this is a type list and the RHS is a typelist as well, eliminate entries
218 // from this list that aren't in the other one.
219 bool MadeChange = false;
220 TypeSet InputSet(*this);
222 for (unsigned i = 0; i != TypeVec.size(); ++i) {
223 if (std::find(InVT.TypeVec.begin(), InVT.TypeVec.end(), TypeVec[i]) !=
227 TypeVec.erase(TypeVec.begin()+i--);
231 // If we removed all of our types, we have a type contradiction.
232 if (!TypeVec.empty())
235 // FIXME: Really want an SMLoc here!
236 TP.error("Type inference contradiction found, merging '" +
237 InVT.getName() + "' into '" + InputSet.getName() + "'");
241 /// EnforceInteger - Remove all non-integer types from this set.
242 bool EEVT::TypeSet::EnforceInteger(TreePattern &TP) {
245 // If we know nothing, then get the full set.
247 return FillWithPossibleTypes(TP, isInteger, "integer");
248 if (!hasFloatingPointTypes())
251 TypeSet InputSet(*this);
253 // Filter out all the fp types.
254 for (unsigned i = 0; i != TypeVec.size(); ++i)
255 if (!isInteger(TypeVec[i]))
256 TypeVec.erase(TypeVec.begin()+i--);
258 if (TypeVec.empty()) {
259 TP.error("Type inference contradiction found, '" +
260 InputSet.getName() + "' needs to be integer");
266 /// EnforceFloatingPoint - Remove all integer types from this set.
267 bool EEVT::TypeSet::EnforceFloatingPoint(TreePattern &TP) {
270 // If we know nothing, then get the full set.
272 return FillWithPossibleTypes(TP, isFloatingPoint, "floating point");
274 if (!hasIntegerTypes())
277 TypeSet InputSet(*this);
279 // Filter out all the fp types.
280 for (unsigned i = 0; i != TypeVec.size(); ++i)
281 if (!isFloatingPoint(TypeVec[i]))
282 TypeVec.erase(TypeVec.begin()+i--);
284 if (TypeVec.empty()) {
285 TP.error("Type inference contradiction found, '" +
286 InputSet.getName() + "' needs to be floating point");
292 /// EnforceScalar - Remove all vector types from this.
293 bool EEVT::TypeSet::EnforceScalar(TreePattern &TP) {
297 // If we know nothing, then get the full set.
299 return FillWithPossibleTypes(TP, isScalar, "scalar");
301 if (!hasVectorTypes())
304 TypeSet InputSet(*this);
306 // Filter out all the vector types.
307 for (unsigned i = 0; i != TypeVec.size(); ++i)
308 if (!isScalar(TypeVec[i]))
309 TypeVec.erase(TypeVec.begin()+i--);
311 if (TypeVec.empty()) {
312 TP.error("Type inference contradiction found, '" +
313 InputSet.getName() + "' needs to be scalar");
319 /// EnforceVector - Remove all vector types from this.
320 bool EEVT::TypeSet::EnforceVector(TreePattern &TP) {
324 // If we know nothing, then get the full set.
326 return FillWithPossibleTypes(TP, isVector, "vector");
328 TypeSet InputSet(*this);
329 bool MadeChange = false;
331 // Filter out all the scalar types.
332 for (unsigned i = 0; i != TypeVec.size(); ++i)
333 if (!isVector(TypeVec[i])) {
334 TypeVec.erase(TypeVec.begin()+i--);
338 if (TypeVec.empty()) {
339 TP.error("Type inference contradiction found, '" +
340 InputSet.getName() + "' needs to be a vector");
348 /// EnforceSmallerThan - 'this' must be a smaller VT than Other. For vectors
349 /// this should be based on the element type. Update this and other based on
350 /// this information.
351 bool EEVT::TypeSet::EnforceSmallerThan(EEVT::TypeSet &Other, TreePattern &TP) {
355 // Both operands must be integer or FP, but we don't care which.
356 bool MadeChange = false;
358 if (isCompletelyUnknown())
359 MadeChange = FillWithPossibleTypes(TP);
361 if (Other.isCompletelyUnknown())
362 MadeChange = Other.FillWithPossibleTypes(TP);
364 // If one side is known to be integer or known to be FP but the other side has
365 // no information, get at least the type integrality info in there.
366 if (!hasFloatingPointTypes())
367 MadeChange |= Other.EnforceInteger(TP);
368 else if (!hasIntegerTypes())
369 MadeChange |= Other.EnforceFloatingPoint(TP);
370 if (!Other.hasFloatingPointTypes())
371 MadeChange |= EnforceInteger(TP);
372 else if (!Other.hasIntegerTypes())
373 MadeChange |= EnforceFloatingPoint(TP);
375 assert(!isCompletelyUnknown() && !Other.isCompletelyUnknown() &&
376 "Should have a type list now");
378 // If one contains vectors but the other doesn't pull vectors out.
379 if (!hasVectorTypes())
380 MadeChange |= Other.EnforceScalar(TP);
381 else if (!hasScalarTypes())
382 MadeChange |= Other.EnforceVector(TP);
383 if (!Other.hasVectorTypes())
384 MadeChange |= EnforceScalar(TP);
385 else if (!Other.hasScalarTypes())
386 MadeChange |= EnforceVector(TP);
388 // This code does not currently handle nodes which have multiple types,
389 // where some types are integer, and some are fp. Assert that this is not
391 assert(!(hasIntegerTypes() && hasFloatingPointTypes()) &&
392 !(Other.hasIntegerTypes() && Other.hasFloatingPointTypes()) &&
393 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
398 // Okay, find the smallest type from current set and remove anything the
399 // same or smaller from the other set. We need to ensure that the scalar
400 // type size is smaller than the scalar size of the smallest type. For
401 // vectors, we also need to make sure that the total size is no larger than
402 // the size of the smallest type.
403 TypeSet InputSet(Other);
404 MVT Smallest = TypeVec[0];
405 for (unsigned i = 0; i != Other.TypeVec.size(); ++i) {
406 MVT OtherVT = Other.TypeVec[i];
407 // Don't compare vector and non-vector types.
408 if (OtherVT.isVector() != Smallest.isVector())
410 // The getSizeInBits() check here is only needed for vectors, but is
411 // a subset of the scalar check for scalars so no need to qualify.
412 if (OtherVT.getScalarSizeInBits() <= Smallest.getScalarSizeInBits() ||
413 OtherVT.getSizeInBits() < Smallest.getSizeInBits()) {
414 Other.TypeVec.erase(Other.TypeVec.begin()+i--);
419 if (Other.TypeVec.empty()) {
420 TP.error("Type inference contradiction found, '" + InputSet.getName() +
421 "' has nothing larger than '" + getName() +"'!");
425 // Okay, find the largest type from the other set and remove anything the
426 // same or smaller from the current set. We need to ensure that the scalar
427 // type size is larger than the scalar size of the largest type. For
428 // vectors, we also need to make sure that the total size is no smaller than
429 // the size of the largest type.
430 InputSet = TypeSet(*this);
431 MVT Largest = Other.TypeVec[Other.TypeVec.size()-1];
432 for (unsigned i = 0; i != TypeVec.size(); ++i) {
433 MVT OtherVT = TypeVec[i];
434 // Don't compare vector and non-vector types.
435 if (OtherVT.isVector() != Largest.isVector())
437 // The getSizeInBits() check here is only needed for vectors, but is
438 // a subset of the scalar check for scalars so no need to qualify.
439 if (OtherVT.getScalarSizeInBits() >= Largest.getScalarSizeInBits() ||
440 OtherVT.getSizeInBits() > Largest.getSizeInBits()) {
441 TypeVec.erase(TypeVec.begin()+i--);
446 if (TypeVec.empty()) {
447 TP.error("Type inference contradiction found, '" + InputSet.getName() +
448 "' has nothing smaller than '" + Other.getName() +"'!");
455 /// EnforceVectorEltTypeIs - 'this' is now constrained to be a vector type
456 /// whose element is specified by VTOperand.
457 bool EEVT::TypeSet::EnforceVectorEltTypeIs(MVT::SimpleValueType VT,
459 bool MadeChange = false;
461 MadeChange |= EnforceVector(TP);
463 TypeSet InputSet(*this);
465 // Filter out all the types which don't have the right element type.
466 for (unsigned i = 0; i != TypeVec.size(); ++i) {
467 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
468 if (MVT(TypeVec[i]).getVectorElementType().SimpleTy != VT) {
469 TypeVec.erase(TypeVec.begin()+i--);
474 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
475 TP.error("Type inference contradiction found, forcing '" +
476 InputSet.getName() + "' to have a vector element");
483 /// EnforceVectorEltTypeIs - 'this' is now constrained to be a vector type
484 /// whose element is specified by VTOperand.
485 bool EEVT::TypeSet::EnforceVectorEltTypeIs(EEVT::TypeSet &VTOperand,
490 // "This" must be a vector and "VTOperand" must be a scalar.
491 bool MadeChange = false;
492 MadeChange |= EnforceVector(TP);
493 MadeChange |= VTOperand.EnforceScalar(TP);
495 // If we know the vector type, it forces the scalar to agree.
497 MVT IVT = getConcrete();
498 IVT = IVT.getVectorElementType();
500 VTOperand.MergeInTypeInfo(IVT.SimpleTy, TP);
503 // If the scalar type is known, filter out vector types whose element types
505 if (!VTOperand.isConcrete())
508 MVT::SimpleValueType VT = VTOperand.getConcrete();
510 TypeSet InputSet(*this);
512 // Filter out all the types which don't have the right element type.
513 for (unsigned i = 0; i != TypeVec.size(); ++i) {
514 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
515 if (MVT(TypeVec[i]).getVectorElementType().SimpleTy != VT) {
516 TypeVec.erase(TypeVec.begin()+i--);
521 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
522 TP.error("Type inference contradiction found, forcing '" +
523 InputSet.getName() + "' to have a vector element");
529 /// EnforceVectorSubVectorTypeIs - 'this' is now constrained to be a
530 /// vector type specified by VTOperand.
531 bool EEVT::TypeSet::EnforceVectorSubVectorTypeIs(EEVT::TypeSet &VTOperand,
536 // "This" must be a vector and "VTOperand" must be a vector.
537 bool MadeChange = false;
538 MadeChange |= EnforceVector(TP);
539 MadeChange |= VTOperand.EnforceVector(TP);
541 // If one side is known to be integer or known to be FP but the other side has
542 // no information, get at least the type integrality info in there.
543 if (!hasFloatingPointTypes())
544 MadeChange |= VTOperand.EnforceInteger(TP);
545 else if (!hasIntegerTypes())
546 MadeChange |= VTOperand.EnforceFloatingPoint(TP);
547 if (!VTOperand.hasFloatingPointTypes())
548 MadeChange |= EnforceInteger(TP);
549 else if (!VTOperand.hasIntegerTypes())
550 MadeChange |= EnforceFloatingPoint(TP);
552 assert(!isCompletelyUnknown() && !VTOperand.isCompletelyUnknown() &&
553 "Should have a type list now");
555 // If we know the vector type, it forces the scalar types to agree.
556 // Also force one vector to have more elements than the other.
558 MVT IVT = getConcrete();
559 unsigned NumElems = IVT.getVectorNumElements();
560 IVT = IVT.getVectorElementType();
562 EEVT::TypeSet EltTypeSet(IVT.SimpleTy, TP);
563 MadeChange |= VTOperand.EnforceVectorEltTypeIs(EltTypeSet, TP);
565 // Only keep types that have less elements than VTOperand.
566 TypeSet InputSet(VTOperand);
568 for (unsigned i = 0; i != VTOperand.TypeVec.size(); ++i) {
569 assert(isVector(VTOperand.TypeVec[i]) && "EnforceVector didn't work");
570 if (MVT(VTOperand.TypeVec[i]).getVectorNumElements() >= NumElems) {
571 VTOperand.TypeVec.erase(VTOperand.TypeVec.begin()+i--);
575 if (VTOperand.TypeVec.empty()) { // FIXME: Really want an SMLoc here!
576 TP.error("Type inference contradiction found, forcing '" +
577 InputSet.getName() + "' to have less vector elements than '" +
581 } else if (VTOperand.isConcrete()) {
582 MVT IVT = VTOperand.getConcrete();
583 unsigned NumElems = IVT.getVectorNumElements();
584 IVT = IVT.getVectorElementType();
586 EEVT::TypeSet EltTypeSet(IVT.SimpleTy, TP);
587 MadeChange |= EnforceVectorEltTypeIs(EltTypeSet, TP);
589 // Only keep types that have more elements than 'this'.
590 TypeSet InputSet(*this);
592 for (unsigned i = 0; i != TypeVec.size(); ++i) {
593 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
594 if (MVT(TypeVec[i]).getVectorNumElements() <= NumElems) {
595 TypeVec.erase(TypeVec.begin()+i--);
599 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
600 TP.error("Type inference contradiction found, forcing '" +
601 InputSet.getName() + "' to have more vector elements than '" +
602 VTOperand.getName() + "'");
610 /// EnforceVectorSameNumElts - 'this' is now constrained to
611 /// be a vector with same num elements as VTOperand.
612 bool EEVT::TypeSet::EnforceVectorSameNumElts(EEVT::TypeSet &VTOperand,
617 // "This" must be a vector and "VTOperand" must be a vector.
618 bool MadeChange = false;
619 MadeChange |= EnforceVector(TP);
620 MadeChange |= VTOperand.EnforceVector(TP);
622 // If we know one of the vector types, it forces the other type to agree.
624 MVT IVT = getConcrete();
625 unsigned NumElems = IVT.getVectorNumElements();
627 // Only keep types that have same elements as VTOperand.
628 TypeSet InputSet(VTOperand);
630 for (unsigned i = 0; i != VTOperand.TypeVec.size(); ++i) {
631 assert(isVector(VTOperand.TypeVec[i]) && "EnforceVector didn't work");
632 if (MVT(VTOperand.TypeVec[i]).getVectorNumElements() != NumElems) {
633 VTOperand.TypeVec.erase(VTOperand.TypeVec.begin()+i--);
637 if (VTOperand.TypeVec.empty()) { // FIXME: Really want an SMLoc here!
638 TP.error("Type inference contradiction found, forcing '" +
639 InputSet.getName() + "' to have same number elements as '" +
643 } else if (VTOperand.isConcrete()) {
644 MVT IVT = VTOperand.getConcrete();
645 unsigned NumElems = IVT.getVectorNumElements();
647 // Only keep types that have same elements as 'this'.
648 TypeSet InputSet(*this);
650 for (unsigned i = 0; i != TypeVec.size(); ++i) {
651 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
652 if (MVT(TypeVec[i]).getVectorNumElements() != NumElems) {
653 TypeVec.erase(TypeVec.begin()+i--);
657 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
658 TP.error("Type inference contradiction found, forcing '" +
659 InputSet.getName() + "' to have same number elements than '" +
660 VTOperand.getName() + "'");
668 //===----------------------------------------------------------------------===//
669 // Helpers for working with extended types.
671 /// Dependent variable map for CodeGenDAGPattern variant generation
672 typedef std::map<std::string, int> DepVarMap;
674 /// Const iterator shorthand for DepVarMap
675 typedef DepVarMap::const_iterator DepVarMap_citer;
677 static void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
679 if (isa<DefInit>(N->getLeafValue()))
680 DepMap[N->getName()]++;
682 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
683 FindDepVarsOf(N->getChild(i), DepMap);
687 /// Find dependent variables within child patterns
688 static void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
690 FindDepVarsOf(N, depcounts);
691 for (DepVarMap_citer i = depcounts.begin(); i != depcounts.end(); ++i) {
692 if (i->second > 1) // std::pair<std::string, int>
693 DepVars.insert(i->first);
698 /// Dump the dependent variable set:
699 static void DumpDepVars(MultipleUseVarSet &DepVars) {
700 if (DepVars.empty()) {
701 DEBUG(errs() << "<empty set>");
703 DEBUG(errs() << "[ ");
704 for (MultipleUseVarSet::const_iterator i = DepVars.begin(),
705 e = DepVars.end(); i != e; ++i) {
706 DEBUG(errs() << (*i) << " ");
708 DEBUG(errs() << "]");
714 //===----------------------------------------------------------------------===//
715 // TreePredicateFn Implementation
716 //===----------------------------------------------------------------------===//
718 /// TreePredicateFn constructor. Here 'N' is a subclass of PatFrag.
719 TreePredicateFn::TreePredicateFn(TreePattern *N) : PatFragRec(N) {
720 assert((getPredCode().empty() || getImmCode().empty()) &&
721 ".td file corrupt: can't have a node predicate *and* an imm predicate");
724 std::string TreePredicateFn::getPredCode() const {
725 return PatFragRec->getRecord()->getValueAsString("PredicateCode");
728 std::string TreePredicateFn::getImmCode() const {
729 return PatFragRec->getRecord()->getValueAsString("ImmediateCode");
733 /// isAlwaysTrue - Return true if this is a noop predicate.
734 bool TreePredicateFn::isAlwaysTrue() const {
735 return getPredCode().empty() && getImmCode().empty();
738 /// Return the name to use in the generated code to reference this, this is
739 /// "Predicate_foo" if from a pattern fragment "foo".
740 std::string TreePredicateFn::getFnName() const {
741 return "Predicate_" + PatFragRec->getRecord()->getName();
744 /// getCodeToRunOnSDNode - Return the code for the function body that
745 /// evaluates this predicate. The argument is expected to be in "Node",
746 /// not N. This handles casting and conversion to a concrete node type as
748 std::string TreePredicateFn::getCodeToRunOnSDNode() const {
749 // Handle immediate predicates first.
750 std::string ImmCode = getImmCode();
751 if (!ImmCode.empty()) {
753 " int64_t Imm = cast<ConstantSDNode>(Node)->getSExtValue();\n";
754 return Result + ImmCode;
757 // Handle arbitrary node predicates.
758 assert(!getPredCode().empty() && "Don't have any predicate code!");
759 std::string ClassName;
760 if (PatFragRec->getOnlyTree()->isLeaf())
761 ClassName = "SDNode";
763 Record *Op = PatFragRec->getOnlyTree()->getOperator();
764 ClassName = PatFragRec->getDAGPatterns().getSDNodeInfo(Op).getSDClassName();
767 if (ClassName == "SDNode")
768 Result = " SDNode *N = Node;\n";
770 Result = " auto *N = cast<" + ClassName + ">(Node);\n";
772 return Result + getPredCode();
775 //===----------------------------------------------------------------------===//
776 // PatternToMatch implementation
780 /// getPatternSize - Return the 'size' of this pattern. We want to match large
781 /// patterns before small ones. This is used to determine the size of a
783 static unsigned getPatternSize(const TreePatternNode *P,
784 const CodeGenDAGPatterns &CGP) {
785 unsigned Size = 3; // The node itself.
786 // If the root node is a ConstantSDNode, increases its size.
787 // e.g. (set R32:$dst, 0).
788 if (P->isLeaf() && isa<IntInit>(P->getLeafValue()))
791 // FIXME: This is a hack to statically increase the priority of patterns
792 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
793 // Later we can allow complexity / cost for each pattern to be (optionally)
794 // specified. To get best possible pattern match we'll need to dynamically
795 // calculate the complexity of all patterns a dag can potentially map to.
796 const ComplexPattern *AM = P->getComplexPatternInfo(CGP);
798 Size += AM->getNumOperands() * 3;
800 // We don't want to count any children twice, so return early.
804 // If this node has some predicate function that must match, it adds to the
805 // complexity of this node.
806 if (!P->getPredicateFns().empty())
809 // Count children in the count if they are also nodes.
810 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
811 TreePatternNode *Child = P->getChild(i);
812 if (!Child->isLeaf() && Child->getNumTypes() &&
813 Child->getType(0) != MVT::Other)
814 Size += getPatternSize(Child, CGP);
815 else if (Child->isLeaf()) {
816 if (isa<IntInit>(Child->getLeafValue()))
817 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
818 else if (Child->getComplexPatternInfo(CGP))
819 Size += getPatternSize(Child, CGP);
820 else if (!Child->getPredicateFns().empty())
828 /// Compute the complexity metric for the input pattern. This roughly
829 /// corresponds to the number of nodes that are covered.
831 getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
832 return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();
836 /// getPredicateCheck - Return a single string containing all of this
837 /// pattern's predicates concatenated with "&&" operators.
839 std::string PatternToMatch::getPredicateCheck() const {
840 std::string PredicateCheck;
841 for (Init *I : Predicates->getValues()) {
842 if (DefInit *Pred = dyn_cast<DefInit>(I)) {
843 Record *Def = Pred->getDef();
844 if (!Def->isSubClassOf("Predicate")) {
848 llvm_unreachable("Unknown predicate type!");
850 if (!PredicateCheck.empty())
851 PredicateCheck += " && ";
852 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
856 return PredicateCheck;
859 //===----------------------------------------------------------------------===//
860 // SDTypeConstraint implementation
863 SDTypeConstraint::SDTypeConstraint(Record *R) {
864 OperandNo = R->getValueAsInt("OperandNum");
866 if (R->isSubClassOf("SDTCisVT")) {
867 ConstraintType = SDTCisVT;
868 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
869 if (x.SDTCisVT_Info.VT == MVT::isVoid)
870 PrintFatalError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
872 } else if (R->isSubClassOf("SDTCisPtrTy")) {
873 ConstraintType = SDTCisPtrTy;
874 } else if (R->isSubClassOf("SDTCisInt")) {
875 ConstraintType = SDTCisInt;
876 } else if (R->isSubClassOf("SDTCisFP")) {
877 ConstraintType = SDTCisFP;
878 } else if (R->isSubClassOf("SDTCisVec")) {
879 ConstraintType = SDTCisVec;
880 } else if (R->isSubClassOf("SDTCisSameAs")) {
881 ConstraintType = SDTCisSameAs;
882 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
883 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
884 ConstraintType = SDTCisVTSmallerThanOp;
885 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
886 R->getValueAsInt("OtherOperandNum");
887 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
888 ConstraintType = SDTCisOpSmallerThanOp;
889 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
890 R->getValueAsInt("BigOperandNum");
891 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
892 ConstraintType = SDTCisEltOfVec;
893 x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
894 } else if (R->isSubClassOf("SDTCisSubVecOfVec")) {
895 ConstraintType = SDTCisSubVecOfVec;
896 x.SDTCisSubVecOfVec_Info.OtherOperandNum =
897 R->getValueAsInt("OtherOpNum");
898 } else if (R->isSubClassOf("SDTCVecEltisVT")) {
899 ConstraintType = SDTCVecEltisVT;
900 x.SDTCVecEltisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
901 if (MVT(x.SDTCVecEltisVT_Info.VT).isVector())
902 PrintFatalError(R->getLoc(), "Cannot use vector type as SDTCVecEltisVT");
903 if (!MVT(x.SDTCVecEltisVT_Info.VT).isInteger() &&
904 !MVT(x.SDTCVecEltisVT_Info.VT).isFloatingPoint())
905 PrintFatalError(R->getLoc(), "Must use integer or floating point type "
906 "as SDTCVecEltisVT");
907 } else if (R->isSubClassOf("SDTCisSameNumEltsAs")) {
908 ConstraintType = SDTCisSameNumEltsAs;
909 x.SDTCisSameNumEltsAs_Info.OtherOperandNum =
910 R->getValueAsInt("OtherOperandNum");
912 PrintFatalError("Unrecognized SDTypeConstraint '" + R->getName() + "'!\n");
916 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
917 /// N, and the result number in ResNo.
918 static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
919 const SDNodeInfo &NodeInfo,
921 unsigned NumResults = NodeInfo.getNumResults();
922 if (OpNo < NumResults) {
929 if (OpNo >= N->getNumChildren()) {
931 raw_string_ostream OS(S);
932 OS << "Invalid operand number in type constraint "
933 << (OpNo+NumResults) << " ";
935 PrintFatalError(OS.str());
938 return N->getChild(OpNo);
941 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
942 /// constraint to the nodes operands. This returns true if it makes a
943 /// change, false otherwise. If a type contradiction is found, flag an error.
944 bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
945 const SDNodeInfo &NodeInfo,
946 TreePattern &TP) const {
950 unsigned ResNo = 0; // The result number being referenced.
951 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
953 switch (ConstraintType) {
955 // Operand must be a particular type.
956 return NodeToApply->UpdateNodeType(ResNo, x.SDTCisVT_Info.VT, TP);
958 // Operand must be same as target pointer type.
959 return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
961 // Require it to be one of the legal integer VTs.
962 return NodeToApply->getExtType(ResNo).EnforceInteger(TP);
964 // Require it to be one of the legal fp VTs.
965 return NodeToApply->getExtType(ResNo).EnforceFloatingPoint(TP);
967 // Require it to be one of the legal vector VTs.
968 return NodeToApply->getExtType(ResNo).EnforceVector(TP);
971 TreePatternNode *OtherNode =
972 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
973 return NodeToApply->UpdateNodeType(ResNo, OtherNode->getExtType(OResNo),TP)|
974 OtherNode->UpdateNodeType(OResNo,NodeToApply->getExtType(ResNo),TP);
976 case SDTCisVTSmallerThanOp: {
977 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
978 // have an integer type that is smaller than the VT.
979 if (!NodeToApply->isLeaf() ||
980 !isa<DefInit>(NodeToApply->getLeafValue()) ||
981 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
982 ->isSubClassOf("ValueType")) {
983 TP.error(N->getOperator()->getName() + " expects a VT operand!");
986 MVT::SimpleValueType VT =
987 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
989 EEVT::TypeSet TypeListTmp(VT, TP);
992 TreePatternNode *OtherNode =
993 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
996 return TypeListTmp.EnforceSmallerThan(OtherNode->getExtType(OResNo), TP);
998 case SDTCisOpSmallerThanOp: {
1000 TreePatternNode *BigOperand =
1001 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
1003 return NodeToApply->getExtType(ResNo).
1004 EnforceSmallerThan(BigOperand->getExtType(BResNo), TP);
1006 case SDTCisEltOfVec: {
1007 unsigned VResNo = 0;
1008 TreePatternNode *VecOperand =
1009 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
1012 // Filter vector types out of VecOperand that don't have the right element
1014 return VecOperand->getExtType(VResNo).
1015 EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), TP);
1017 case SDTCisSubVecOfVec: {
1018 unsigned VResNo = 0;
1019 TreePatternNode *BigVecOperand =
1020 getOperandNum(x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo,
1023 // Filter vector types out of BigVecOperand that don't have the
1024 // right subvector type.
1025 return BigVecOperand->getExtType(VResNo).
1026 EnforceVectorSubVectorTypeIs(NodeToApply->getExtType(ResNo), TP);
1028 case SDTCVecEltisVT: {
1029 return NodeToApply->getExtType(ResNo).
1030 EnforceVectorEltTypeIs(x.SDTCVecEltisVT_Info.VT, TP);
1032 case SDTCisSameNumEltsAs: {
1033 unsigned OResNo = 0;
1034 TreePatternNode *OtherNode =
1035 getOperandNum(x.SDTCisSameNumEltsAs_Info.OtherOperandNum,
1036 N, NodeInfo, OResNo);
1037 return OtherNode->getExtType(OResNo).
1038 EnforceVectorSameNumElts(NodeToApply->getExtType(ResNo), TP);
1041 llvm_unreachable("Invalid ConstraintType!");
1044 // Update the node type to match an instruction operand or result as specified
1045 // in the ins or outs lists on the instruction definition. Return true if the
1046 // type was actually changed.
1047 bool TreePatternNode::UpdateNodeTypeFromInst(unsigned ResNo,
1050 // The 'unknown' operand indicates that types should be inferred from the
1052 if (Operand->isSubClassOf("unknown_class"))
1055 // The Operand class specifies a type directly.
1056 if (Operand->isSubClassOf("Operand"))
1057 return UpdateNodeType(ResNo, getValueType(Operand->getValueAsDef("Type")),
1060 // PointerLikeRegClass has a type that is determined at runtime.
1061 if (Operand->isSubClassOf("PointerLikeRegClass"))
1062 return UpdateNodeType(ResNo, MVT::iPTR, TP);
1064 // Both RegisterClass and RegisterOperand operands derive their types from a
1065 // register class def.
1066 Record *RC = nullptr;
1067 if (Operand->isSubClassOf("RegisterClass"))
1069 else if (Operand->isSubClassOf("RegisterOperand"))
1070 RC = Operand->getValueAsDef("RegClass");
1072 assert(RC && "Unknown operand type");
1073 CodeGenTarget &Tgt = TP.getDAGPatterns().getTargetInfo();
1074 return UpdateNodeType(ResNo, Tgt.getRegisterClass(RC).getValueTypes(), TP);
1078 //===----------------------------------------------------------------------===//
1079 // SDNodeInfo implementation
1081 SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
1082 EnumName = R->getValueAsString("Opcode");
1083 SDClassName = R->getValueAsString("SDClass");
1084 Record *TypeProfile = R->getValueAsDef("TypeProfile");
1085 NumResults = TypeProfile->getValueAsInt("NumResults");
1086 NumOperands = TypeProfile->getValueAsInt("NumOperands");
1088 // Parse the properties.
1090 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
1091 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
1092 if (PropList[i]->getName() == "SDNPCommutative") {
1093 Properties |= 1 << SDNPCommutative;
1094 } else if (PropList[i]->getName() == "SDNPAssociative") {
1095 Properties |= 1 << SDNPAssociative;
1096 } else if (PropList[i]->getName() == "SDNPHasChain") {
1097 Properties |= 1 << SDNPHasChain;
1098 } else if (PropList[i]->getName() == "SDNPOutGlue") {
1099 Properties |= 1 << SDNPOutGlue;
1100 } else if (PropList[i]->getName() == "SDNPInGlue") {
1101 Properties |= 1 << SDNPInGlue;
1102 } else if (PropList[i]->getName() == "SDNPOptInGlue") {
1103 Properties |= 1 << SDNPOptInGlue;
1104 } else if (PropList[i]->getName() == "SDNPMayStore") {
1105 Properties |= 1 << SDNPMayStore;
1106 } else if (PropList[i]->getName() == "SDNPMayLoad") {
1107 Properties |= 1 << SDNPMayLoad;
1108 } else if (PropList[i]->getName() == "SDNPSideEffect") {
1109 Properties |= 1 << SDNPSideEffect;
1110 } else if (PropList[i]->getName() == "SDNPMemOperand") {
1111 Properties |= 1 << SDNPMemOperand;
1112 } else if (PropList[i]->getName() == "SDNPVariadic") {
1113 Properties |= 1 << SDNPVariadic;
1115 PrintFatalError("Unknown SD Node property '" +
1116 PropList[i]->getName() + "' on node '" +
1117 R->getName() + "'!");
1122 // Parse the type constraints.
1123 std::vector<Record*> ConstraintList =
1124 TypeProfile->getValueAsListOfDefs("Constraints");
1125 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
1128 /// getKnownType - If the type constraints on this node imply a fixed type
1129 /// (e.g. all stores return void, etc), then return it as an
1130 /// MVT::SimpleValueType. Otherwise, return EEVT::Other.
1131 MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
1132 unsigned NumResults = getNumResults();
1133 assert(NumResults <= 1 &&
1134 "We only work with nodes with zero or one result so far!");
1135 assert(ResNo == 0 && "Only handles single result nodes so far");
1137 for (unsigned i = 0, e = TypeConstraints.size(); i != e; ++i) {
1138 // Make sure that this applies to the correct node result.
1139 if (TypeConstraints[i].OperandNo >= NumResults) // FIXME: need value #
1142 switch (TypeConstraints[i].ConstraintType) {
1144 case SDTypeConstraint::SDTCisVT:
1145 return TypeConstraints[i].x.SDTCisVT_Info.VT;
1146 case SDTypeConstraint::SDTCisPtrTy:
1153 //===----------------------------------------------------------------------===//
1154 // TreePatternNode implementation
1157 TreePatternNode::~TreePatternNode() {
1158 #if 0 // FIXME: implement refcounted tree nodes!
1159 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1164 static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
1165 if (Operator->getName() == "set" ||
1166 Operator->getName() == "implicit")
1167 return 0; // All return nothing.
1169 if (Operator->isSubClassOf("Intrinsic"))
1170 return CDP.getIntrinsic(Operator).IS.RetVTs.size();
1172 if (Operator->isSubClassOf("SDNode"))
1173 return CDP.getSDNodeInfo(Operator).getNumResults();
1175 if (Operator->isSubClassOf("PatFrag")) {
1176 // If we've already parsed this pattern fragment, get it. Otherwise, handle
1177 // the forward reference case where one pattern fragment references another
1178 // before it is processed.
1179 if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator))
1180 return PFRec->getOnlyTree()->getNumTypes();
1182 // Get the result tree.
1183 DagInit *Tree = Operator->getValueAsDag("Fragment");
1184 Record *Op = nullptr;
1186 if (DefInit *DI = dyn_cast<DefInit>(Tree->getOperator()))
1188 assert(Op && "Invalid Fragment");
1189 return GetNumNodeResults(Op, CDP);
1192 if (Operator->isSubClassOf("Instruction")) {
1193 CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
1195 unsigned NumDefsToAdd = InstInfo.Operands.NumDefs;
1197 // Subtract any defaulted outputs.
1198 for (unsigned i = 0; i != InstInfo.Operands.NumDefs; ++i) {
1199 Record *OperandNode = InstInfo.Operands[i].Rec;
1201 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
1202 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1206 // Add on one implicit def if it has a resolvable type.
1207 if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
1209 return NumDefsToAdd;
1212 if (Operator->isSubClassOf("SDNodeXForm"))
1213 return 1; // FIXME: Generalize SDNodeXForm
1215 if (Operator->isSubClassOf("ValueType"))
1216 return 1; // A type-cast of one result.
1218 if (Operator->isSubClassOf("ComplexPattern"))
1222 PrintFatalError("Unhandled node in GetNumNodeResults");
1225 void TreePatternNode::print(raw_ostream &OS) const {
1227 OS << *getLeafValue();
1229 OS << '(' << getOperator()->getName();
1231 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1232 OS << ':' << getExtType(i).getName();
1235 if (getNumChildren() != 0) {
1237 getChild(0)->print(OS);
1238 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
1240 getChild(i)->print(OS);
1246 for (unsigned i = 0, e = PredicateFns.size(); i != e; ++i)
1247 OS << "<<P:" << PredicateFns[i].getFnName() << ">>";
1249 OS << "<<X:" << TransformFn->getName() << ">>";
1250 if (!getName().empty())
1251 OS << ":$" << getName();
1254 void TreePatternNode::dump() const {
1258 /// isIsomorphicTo - Return true if this node is recursively
1259 /// isomorphic to the specified node. For this comparison, the node's
1260 /// entire state is considered. The assigned name is ignored, since
1261 /// nodes with differing names are considered isomorphic. However, if
1262 /// the assigned name is present in the dependent variable set, then
1263 /// the assigned name is considered significant and the node is
1264 /// isomorphic if the names match.
1265 bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
1266 const MultipleUseVarSet &DepVars) const {
1267 if (N == this) return true;
1268 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
1269 getPredicateFns() != N->getPredicateFns() ||
1270 getTransformFn() != N->getTransformFn())
1274 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
1275 if (DefInit *NDI = dyn_cast<DefInit>(N->getLeafValue())) {
1276 return ((DI->getDef() == NDI->getDef())
1277 && (DepVars.find(getName()) == DepVars.end()
1278 || getName() == N->getName()));
1281 return getLeafValue() == N->getLeafValue();
1284 if (N->getOperator() != getOperator() ||
1285 N->getNumChildren() != getNumChildren()) return false;
1286 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1287 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
1292 /// clone - Make a copy of this tree and all of its children.
1294 TreePatternNode *TreePatternNode::clone() const {
1295 TreePatternNode *New;
1297 New = new TreePatternNode(getLeafValue(), getNumTypes());
1299 std::vector<TreePatternNode*> CChildren;
1300 CChildren.reserve(Children.size());
1301 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1302 CChildren.push_back(getChild(i)->clone());
1303 New = new TreePatternNode(getOperator(), CChildren, getNumTypes());
1305 New->setName(getName());
1307 New->setPredicateFns(getPredicateFns());
1308 New->setTransformFn(getTransformFn());
1312 /// RemoveAllTypes - Recursively strip all the types of this tree.
1313 void TreePatternNode::RemoveAllTypes() {
1314 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1315 Types[i] = EEVT::TypeSet(); // Reset to unknown type.
1316 if (isLeaf()) return;
1317 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1318 getChild(i)->RemoveAllTypes();
1322 /// SubstituteFormalArguments - Replace the formal arguments in this tree
1323 /// with actual values specified by ArgMap.
1324 void TreePatternNode::
1325 SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
1326 if (isLeaf()) return;
1328 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1329 TreePatternNode *Child = getChild(i);
1330 if (Child->isLeaf()) {
1331 Init *Val = Child->getLeafValue();
1332 // Note that, when substituting into an output pattern, Val might be an
1334 if (isa<UnsetInit>(Val) || (isa<DefInit>(Val) &&
1335 cast<DefInit>(Val)->getDef()->getName() == "node")) {
1336 // We found a use of a formal argument, replace it with its value.
1337 TreePatternNode *NewChild = ArgMap[Child->getName()];
1338 assert(NewChild && "Couldn't find formal argument!");
1339 assert((Child->getPredicateFns().empty() ||
1340 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1341 "Non-empty child predicate clobbered!");
1342 setChild(i, NewChild);
1345 getChild(i)->SubstituteFormalArguments(ArgMap);
1351 /// InlinePatternFragments - If this pattern refers to any pattern
1352 /// fragments, inline them into place, giving us a pattern without any
1353 /// PatFrag references.
1354 TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
1359 return this; // nothing to do.
1360 Record *Op = getOperator();
1362 if (!Op->isSubClassOf("PatFrag")) {
1363 // Just recursively inline children nodes.
1364 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1365 TreePatternNode *Child = getChild(i);
1366 TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
1368 assert((Child->getPredicateFns().empty() ||
1369 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1370 "Non-empty child predicate clobbered!");
1372 setChild(i, NewChild);
1377 // Otherwise, we found a reference to a fragment. First, look up its
1378 // TreePattern record.
1379 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
1381 // Verify that we are passing the right number of operands.
1382 if (Frag->getNumArgs() != Children.size()) {
1383 TP.error("'" + Op->getName() + "' fragment requires " +
1384 utostr(Frag->getNumArgs()) + " operands!");
1388 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
1390 TreePredicateFn PredFn(Frag);
1391 if (!PredFn.isAlwaysTrue())
1392 FragTree->addPredicateFn(PredFn);
1394 // Resolve formal arguments to their actual value.
1395 if (Frag->getNumArgs()) {
1396 // Compute the map of formal to actual arguments.
1397 std::map<std::string, TreePatternNode*> ArgMap;
1398 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
1399 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
1401 FragTree->SubstituteFormalArguments(ArgMap);
1404 FragTree->setName(getName());
1405 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1406 FragTree->UpdateNodeType(i, getExtType(i), TP);
1408 // Transfer in the old predicates.
1409 for (unsigned i = 0, e = getPredicateFns().size(); i != e; ++i)
1410 FragTree->addPredicateFn(getPredicateFns()[i]);
1412 // Get a new copy of this fragment to stitch into here.
1413 //delete this; // FIXME: implement refcounting!
1415 // The fragment we inlined could have recursive inlining that is needed. See
1416 // if there are any pattern fragments in it and inline them as needed.
1417 return FragTree->InlinePatternFragments(TP);
1420 /// getImplicitType - Check to see if the specified record has an implicit
1421 /// type which should be applied to it. This will infer the type of register
1422 /// references from the register file information, for example.
1424 /// When Unnamed is set, return the type of a DAG operand with no name, such as
1425 /// the F8RC register class argument in:
1427 /// (COPY_TO_REGCLASS GPR:$src, F8RC)
1429 /// When Unnamed is false, return the type of a named DAG operand such as the
1430 /// GPR:$src operand above.
1432 static EEVT::TypeSet getImplicitType(Record *R, unsigned ResNo,
1436 // Check to see if this is a register operand.
1437 if (R->isSubClassOf("RegisterOperand")) {
1438 assert(ResNo == 0 && "Regoperand ref only has one result!");
1440 return EEVT::TypeSet(); // Unknown.
1441 Record *RegClass = R->getValueAsDef("RegClass");
1442 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1443 return EEVT::TypeSet(T.getRegisterClass(RegClass).getValueTypes());
1446 // Check to see if this is a register or a register class.
1447 if (R->isSubClassOf("RegisterClass")) {
1448 assert(ResNo == 0 && "Regclass ref only has one result!");
1449 // An unnamed register class represents itself as an i32 immediate, for
1450 // example on a COPY_TO_REGCLASS instruction.
1452 return EEVT::TypeSet(MVT::i32, TP);
1454 // In a named operand, the register class provides the possible set of
1457 return EEVT::TypeSet(); // Unknown.
1458 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1459 return EEVT::TypeSet(T.getRegisterClass(R).getValueTypes());
1462 if (R->isSubClassOf("PatFrag")) {
1463 assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
1464 // Pattern fragment types will be resolved when they are inlined.
1465 return EEVT::TypeSet(); // Unknown.
1468 if (R->isSubClassOf("Register")) {
1469 assert(ResNo == 0 && "Registers only produce one result!");
1471 return EEVT::TypeSet(); // Unknown.
1472 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1473 return EEVT::TypeSet(T.getRegisterVTs(R));
1476 if (R->isSubClassOf("SubRegIndex")) {
1477 assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
1478 return EEVT::TypeSet(MVT::i32, TP);
1481 if (R->isSubClassOf("ValueType")) {
1482 assert(ResNo == 0 && "This node only has one result!");
1483 // An unnamed VTSDNode represents itself as an MVT::Other immediate.
1485 // (sext_inreg GPR:$src, i16)
1488 return EEVT::TypeSet(MVT::Other, TP);
1489 // With a name, the ValueType simply provides the type of the named
1492 // (sext_inreg i32:$src, i16)
1495 return EEVT::TypeSet(); // Unknown.
1496 return EEVT::TypeSet(getValueType(R), TP);
1499 if (R->isSubClassOf("CondCode")) {
1500 assert(ResNo == 0 && "This node only has one result!");
1501 // Using a CondCodeSDNode.
1502 return EEVT::TypeSet(MVT::Other, TP);
1505 if (R->isSubClassOf("ComplexPattern")) {
1506 assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
1508 return EEVT::TypeSet(); // Unknown.
1509 return EEVT::TypeSet(TP.getDAGPatterns().getComplexPattern(R).getValueType(),
1512 if (R->isSubClassOf("PointerLikeRegClass")) {
1513 assert(ResNo == 0 && "Regclass can only have one result!");
1514 return EEVT::TypeSet(MVT::iPTR, TP);
1517 if (R->getName() == "node" || R->getName() == "srcvalue" ||
1518 R->getName() == "zero_reg") {
1520 return EEVT::TypeSet(); // Unknown.
1523 if (R->isSubClassOf("Operand"))
1524 return EEVT::TypeSet(getValueType(R->getValueAsDef("Type")));
1526 TP.error("Unknown node flavor used in pattern: " + R->getName());
1527 return EEVT::TypeSet(MVT::Other, TP);
1531 /// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
1532 /// CodeGenIntrinsic information for it, otherwise return a null pointer.
1533 const CodeGenIntrinsic *TreePatternNode::
1534 getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
1535 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
1536 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
1537 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
1540 unsigned IID = cast<IntInit>(getChild(0)->getLeafValue())->getValue();
1541 return &CDP.getIntrinsicInfo(IID);
1544 /// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
1545 /// return the ComplexPattern information, otherwise return null.
1546 const ComplexPattern *
1547 TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
1550 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
1555 Rec = getOperator();
1557 if (!Rec->isSubClassOf("ComplexPattern"))
1559 return &CGP.getComplexPattern(Rec);
1562 unsigned TreePatternNode::getNumMIResults(const CodeGenDAGPatterns &CGP) const {
1563 // A ComplexPattern specifically declares how many results it fills in.
1564 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1565 return CP->getNumOperands();
1567 // If MIOperandInfo is specified, that gives the count.
1569 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
1570 if (DI && DI->getDef()->isSubClassOf("Operand")) {
1571 DagInit *MIOps = DI->getDef()->getValueAsDag("MIOperandInfo");
1572 if (MIOps->getNumArgs())
1573 return MIOps->getNumArgs();
1577 // Otherwise there is just one result.
1581 /// NodeHasProperty - Return true if this node has the specified property.
1582 bool TreePatternNode::NodeHasProperty(SDNP Property,
1583 const CodeGenDAGPatterns &CGP) const {
1585 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1586 return CP->hasProperty(Property);
1590 Record *Operator = getOperator();
1591 if (!Operator->isSubClassOf("SDNode")) return false;
1593 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
1599 /// TreeHasProperty - Return true if any node in this tree has the specified
1601 bool TreePatternNode::TreeHasProperty(SDNP Property,
1602 const CodeGenDAGPatterns &CGP) const {
1603 if (NodeHasProperty(Property, CGP))
1605 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1606 if (getChild(i)->TreeHasProperty(Property, CGP))
1611 /// isCommutativeIntrinsic - Return true if the node corresponds to a
1612 /// commutative intrinsic.
1614 TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
1615 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
1616 return Int->isCommutative;
1620 static bool isOperandClass(const TreePatternNode *N, StringRef Class) {
1622 return N->getOperator()->isSubClassOf(Class);
1624 DefInit *DI = dyn_cast<DefInit>(N->getLeafValue());
1625 if (DI && DI->getDef()->isSubClassOf(Class))
1631 static void emitTooManyOperandsError(TreePattern &TP,
1635 TP.error("Instruction '" + InstName + "' was provided " + Twine(Actual) +
1636 " operands but expected only " + Twine(Expected) + "!");
1639 static void emitTooFewOperandsError(TreePattern &TP,
1642 TP.error("Instruction '" + InstName +
1643 "' expects more than the provided " + Twine(Actual) + " operands!");
1646 /// ApplyTypeConstraints - Apply all of the type constraints relevant to
1647 /// this node and its children in the tree. This returns true if it makes a
1648 /// change, false otherwise. If a type contradiction is found, flag an error.
1649 bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
1653 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
1655 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
1656 // If it's a regclass or something else known, include the type.
1657 bool MadeChange = false;
1658 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1659 MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
1661 !hasName(), TP), TP);
1665 if (IntInit *II = dyn_cast<IntInit>(getLeafValue())) {
1666 assert(Types.size() == 1 && "Invalid IntInit");
1668 // Int inits are always integers. :)
1669 bool MadeChange = Types[0].EnforceInteger(TP);
1671 if (!Types[0].isConcrete())
1674 MVT::SimpleValueType VT = getType(0);
1675 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
1678 unsigned Size = MVT(VT).getSizeInBits();
1679 // Make sure that the value is representable for this type.
1680 if (Size >= 32) return MadeChange;
1682 // Check that the value doesn't use more bits than we have. It must either
1683 // be a sign- or zero-extended equivalent of the original.
1684 int64_t SignBitAndAbove = II->getValue() >> (Size - 1);
1685 if (SignBitAndAbove == -1 || SignBitAndAbove == 0 || SignBitAndAbove == 1)
1688 TP.error("Integer value '" + itostr(II->getValue()) +
1689 "' is out of range for type '" + getEnumName(getType(0)) + "'!");
1695 // special handling for set, which isn't really an SDNode.
1696 if (getOperator()->getName() == "set") {
1697 assert(getNumTypes() == 0 && "Set doesn't produce a value");
1698 assert(getNumChildren() >= 2 && "Missing RHS of a set?");
1699 unsigned NC = getNumChildren();
1701 TreePatternNode *SetVal = getChild(NC-1);
1702 bool MadeChange = SetVal->ApplyTypeConstraints(TP, NotRegisters);
1704 for (unsigned i = 0; i < NC-1; ++i) {
1705 TreePatternNode *Child = getChild(i);
1706 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
1708 // Types of operands must match.
1709 MadeChange |= Child->UpdateNodeType(0, SetVal->getExtType(i), TP);
1710 MadeChange |= SetVal->UpdateNodeType(i, Child->getExtType(0), TP);
1715 if (getOperator()->getName() == "implicit") {
1716 assert(getNumTypes() == 0 && "Node doesn't produce a value");
1718 bool MadeChange = false;
1719 for (unsigned i = 0; i < getNumChildren(); ++i)
1720 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1724 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
1725 bool MadeChange = false;
1727 // Apply the result type to the node.
1728 unsigned NumRetVTs = Int->IS.RetVTs.size();
1729 unsigned NumParamVTs = Int->IS.ParamVTs.size();
1731 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
1732 MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
1734 if (getNumChildren() != NumParamVTs + 1) {
1735 TP.error("Intrinsic '" + Int->Name + "' expects " +
1736 utostr(NumParamVTs) + " operands, not " +
1737 utostr(getNumChildren() - 1) + " operands!");
1741 // Apply type info to the intrinsic ID.
1742 MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
1744 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
1745 MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
1747 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
1748 assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
1749 MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
1754 if (getOperator()->isSubClassOf("SDNode")) {
1755 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
1757 // Check that the number of operands is sane. Negative operands -> varargs.
1758 if (NI.getNumOperands() >= 0 &&
1759 getNumChildren() != (unsigned)NI.getNumOperands()) {
1760 TP.error(getOperator()->getName() + " node requires exactly " +
1761 itostr(NI.getNumOperands()) + " operands!");
1765 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
1766 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1767 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1771 if (getOperator()->isSubClassOf("Instruction")) {
1772 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
1773 CodeGenInstruction &InstInfo =
1774 CDP.getTargetInfo().getInstruction(getOperator());
1776 bool MadeChange = false;
1778 // Apply the result types to the node, these come from the things in the
1779 // (outs) list of the instruction.
1780 unsigned NumResultsToAdd = std::min(InstInfo.Operands.NumDefs,
1781 Inst.getNumResults());
1782 for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo)
1783 MadeChange |= UpdateNodeTypeFromInst(ResNo, Inst.getResult(ResNo), TP);
1785 // If the instruction has implicit defs, we apply the first one as a result.
1786 // FIXME: This sucks, it should apply all implicit defs.
1787 if (!InstInfo.ImplicitDefs.empty()) {
1788 unsigned ResNo = NumResultsToAdd;
1790 // FIXME: Generalize to multiple possible types and multiple possible
1792 MVT::SimpleValueType VT =
1793 InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
1795 if (VT != MVT::Other)
1796 MadeChange |= UpdateNodeType(ResNo, VT, TP);
1799 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
1801 if (getOperator()->getName() == "INSERT_SUBREG") {
1802 assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
1803 MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
1804 MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
1805 } else if (getOperator()->getName() == "REG_SEQUENCE") {
1806 // We need to do extra, custom typechecking for REG_SEQUENCE since it is
1809 unsigned NChild = getNumChildren();
1811 TP.error("REG_SEQUENCE requires at least 3 operands!");
1815 if (NChild % 2 == 0) {
1816 TP.error("REG_SEQUENCE requires an odd number of operands!");
1820 if (!isOperandClass(getChild(0), "RegisterClass")) {
1821 TP.error("REG_SEQUENCE requires a RegisterClass for first operand!");
1825 for (unsigned I = 1; I < NChild; I += 2) {
1826 TreePatternNode *SubIdxChild = getChild(I + 1);
1827 if (!isOperandClass(SubIdxChild, "SubRegIndex")) {
1828 TP.error("REG_SEQUENCE requires a SubRegIndex for operand " +
1829 itostr(I + 1) + "!");
1835 unsigned ChildNo = 0;
1836 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
1837 Record *OperandNode = Inst.getOperand(i);
1839 // If the instruction expects a predicate or optional def operand, we
1840 // codegen this by setting the operand to it's default value if it has a
1841 // non-empty DefaultOps field.
1842 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
1843 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1846 // Verify that we didn't run out of provided operands.
1847 if (ChildNo >= getNumChildren()) {
1848 emitTooFewOperandsError(TP, getOperator()->getName(), getNumChildren());
1852 TreePatternNode *Child = getChild(ChildNo++);
1853 unsigned ChildResNo = 0; // Instructions always use res #0 of their op.
1855 // If the operand has sub-operands, they may be provided by distinct
1856 // child patterns, so attempt to match each sub-operand separately.
1857 if (OperandNode->isSubClassOf("Operand")) {
1858 DagInit *MIOpInfo = OperandNode->getValueAsDag("MIOperandInfo");
1859 if (unsigned NumArgs = MIOpInfo->getNumArgs()) {
1860 // But don't do that if the whole operand is being provided by
1861 // a single ComplexPattern-related Operand.
1863 if (Child->getNumMIResults(CDP) < NumArgs) {
1864 // Match first sub-operand against the child we already have.
1865 Record *SubRec = cast<DefInit>(MIOpInfo->getArg(0))->getDef();
1867 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
1869 // And the remaining sub-operands against subsequent children.
1870 for (unsigned Arg = 1; Arg < NumArgs; ++Arg) {
1871 if (ChildNo >= getNumChildren()) {
1872 emitTooFewOperandsError(TP, getOperator()->getName(),
1876 Child = getChild(ChildNo++);
1878 SubRec = cast<DefInit>(MIOpInfo->getArg(Arg))->getDef();
1880 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
1887 // If we didn't match by pieces above, attempt to match the whole
1889 MadeChange |= Child->UpdateNodeTypeFromInst(ChildResNo, OperandNode, TP);
1892 if (!InstInfo.Operands.isVariadic && ChildNo != getNumChildren()) {
1893 emitTooManyOperandsError(TP, getOperator()->getName(),
1894 ChildNo, getNumChildren());
1898 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1899 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1903 if (getOperator()->isSubClassOf("ComplexPattern")) {
1904 bool MadeChange = false;
1906 for (unsigned i = 0; i < getNumChildren(); ++i)
1907 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1912 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
1914 // Node transforms always take one operand.
1915 if (getNumChildren() != 1) {
1916 TP.error("Node transform '" + getOperator()->getName() +
1917 "' requires one operand!");
1921 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1924 // If either the output or input of the xform does not have exact
1925 // type info. We assume they must be the same. Otherwise, it is perfectly
1926 // legal to transform from one type to a completely different type.
1928 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
1929 bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
1930 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
1937 /// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
1938 /// RHS of a commutative operation, not the on LHS.
1939 static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
1940 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
1942 if (N->isLeaf() && isa<IntInit>(N->getLeafValue()))
1948 /// canPatternMatch - If it is impossible for this pattern to match on this
1949 /// target, fill in Reason and return false. Otherwise, return true. This is
1950 /// used as a sanity check for .td files (to prevent people from writing stuff
1951 /// that can never possibly work), and to prevent the pattern permuter from
1952 /// generating stuff that is useless.
1953 bool TreePatternNode::canPatternMatch(std::string &Reason,
1954 const CodeGenDAGPatterns &CDP) {
1955 if (isLeaf()) return true;
1957 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1958 if (!getChild(i)->canPatternMatch(Reason, CDP))
1961 // If this is an intrinsic, handle cases that would make it not match. For
1962 // example, if an operand is required to be an immediate.
1963 if (getOperator()->isSubClassOf("Intrinsic")) {
1968 if (getOperator()->isSubClassOf("ComplexPattern"))
1971 // If this node is a commutative operator, check that the LHS isn't an
1973 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
1974 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
1975 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
1976 // Scan all of the operands of the node and make sure that only the last one
1977 // is a constant node, unless the RHS also is.
1978 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
1979 bool Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
1980 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
1981 if (OnlyOnRHSOfCommutative(getChild(i))) {
1982 Reason="Immediate value must be on the RHS of commutative operators!";
1991 //===----------------------------------------------------------------------===//
1992 // TreePattern implementation
1995 TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
1996 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
1997 isInputPattern(isInput), HasError(false) {
1998 for (Init *I : RawPat->getValues())
1999 Trees.push_back(ParseTreePattern(I, ""));
2002 TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
2003 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
2004 isInputPattern(isInput), HasError(false) {
2005 Trees.push_back(ParseTreePattern(Pat, ""));
2008 TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
2009 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
2010 isInputPattern(isInput), HasError(false) {
2011 Trees.push_back(Pat);
2014 void TreePattern::error(const Twine &Msg) {
2018 PrintError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
2022 void TreePattern::ComputeNamedNodes() {
2023 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
2024 ComputeNamedNodes(Trees[i]);
2027 void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
2028 if (!N->getName().empty())
2029 NamedNodes[N->getName()].push_back(N);
2031 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2032 ComputeNamedNodes(N->getChild(i));
2036 TreePatternNode *TreePattern::ParseTreePattern(Init *TheInit, StringRef OpName){
2037 if (DefInit *DI = dyn_cast<DefInit>(TheInit)) {
2038 Record *R = DI->getDef();
2040 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
2041 // TreePatternNode of its own. For example:
2042 /// (foo GPR, imm) -> (foo GPR, (imm))
2043 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag"))
2044 return ParseTreePattern(
2045 DagInit::get(DI, "",
2046 std::vector<std::pair<Init*, std::string> >()),
2050 TreePatternNode *Res = new TreePatternNode(DI, 1);
2051 if (R->getName() == "node" && !OpName.empty()) {
2053 error("'node' argument requires a name to match with operand list");
2054 Args.push_back(OpName);
2057 Res->setName(OpName);
2061 // ?:$name or just $name.
2062 if (isa<UnsetInit>(TheInit)) {
2064 error("'?' argument requires a name to match with operand list");
2065 TreePatternNode *Res = new TreePatternNode(TheInit, 1);
2066 Args.push_back(OpName);
2067 Res->setName(OpName);
2071 if (IntInit *II = dyn_cast<IntInit>(TheInit)) {
2072 if (!OpName.empty())
2073 error("Constant int argument should not have a name!");
2074 return new TreePatternNode(II, 1);
2077 if (BitsInit *BI = dyn_cast<BitsInit>(TheInit)) {
2078 // Turn this into an IntInit.
2079 Init *II = BI->convertInitializerTo(IntRecTy::get());
2080 if (!II || !isa<IntInit>(II))
2081 error("Bits value must be constants!");
2082 return ParseTreePattern(II, OpName);
2085 DagInit *Dag = dyn_cast<DagInit>(TheInit);
2088 error("Pattern has unexpected init kind!");
2090 DefInit *OpDef = dyn_cast<DefInit>(Dag->getOperator());
2091 if (!OpDef) error("Pattern has unexpected operator type!");
2092 Record *Operator = OpDef->getDef();
2094 if (Operator->isSubClassOf("ValueType")) {
2095 // If the operator is a ValueType, then this must be "type cast" of a leaf
2097 if (Dag->getNumArgs() != 1)
2098 error("Type cast only takes one operand!");
2100 TreePatternNode *New = ParseTreePattern(Dag->getArg(0), Dag->getArgName(0));
2102 // Apply the type cast.
2103 assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
2104 New->UpdateNodeType(0, getValueType(Operator), *this);
2106 if (!OpName.empty())
2107 error("ValueType cast should not have a name!");
2111 // Verify that this is something that makes sense for an operator.
2112 if (!Operator->isSubClassOf("PatFrag") &&
2113 !Operator->isSubClassOf("SDNode") &&
2114 !Operator->isSubClassOf("Instruction") &&
2115 !Operator->isSubClassOf("SDNodeXForm") &&
2116 !Operator->isSubClassOf("Intrinsic") &&
2117 !Operator->isSubClassOf("ComplexPattern") &&
2118 Operator->getName() != "set" &&
2119 Operator->getName() != "implicit")
2120 error("Unrecognized node '" + Operator->getName() + "'!");
2122 // Check to see if this is something that is illegal in an input pattern.
2123 if (isInputPattern) {
2124 if (Operator->isSubClassOf("Instruction") ||
2125 Operator->isSubClassOf("SDNodeXForm"))
2126 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
2128 if (Operator->isSubClassOf("Intrinsic"))
2129 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
2131 if (Operator->isSubClassOf("SDNode") &&
2132 Operator->getName() != "imm" &&
2133 Operator->getName() != "fpimm" &&
2134 Operator->getName() != "tglobaltlsaddr" &&
2135 Operator->getName() != "tconstpool" &&
2136 Operator->getName() != "tjumptable" &&
2137 Operator->getName() != "tframeindex" &&
2138 Operator->getName() != "texternalsym" &&
2139 Operator->getName() != "tblockaddress" &&
2140 Operator->getName() != "tglobaladdr" &&
2141 Operator->getName() != "bb" &&
2142 Operator->getName() != "vt" &&
2143 Operator->getName() != "mcsym")
2144 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
2147 std::vector<TreePatternNode*> Children;
2149 // Parse all the operands.
2150 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
2151 Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgName(i)));
2153 // If the operator is an intrinsic, then this is just syntactic sugar for for
2154 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
2155 // convert the intrinsic name to a number.
2156 if (Operator->isSubClassOf("Intrinsic")) {
2157 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
2158 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
2160 // If this intrinsic returns void, it must have side-effects and thus a
2162 if (Int.IS.RetVTs.empty())
2163 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
2164 else if (Int.ModRef != CodeGenIntrinsic::NoMem)
2165 // Has side-effects, requires chain.
2166 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
2167 else // Otherwise, no chain.
2168 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
2170 TreePatternNode *IIDNode = new TreePatternNode(IntInit::get(IID), 1);
2171 Children.insert(Children.begin(), IIDNode);
2174 if (Operator->isSubClassOf("ComplexPattern")) {
2175 for (unsigned i = 0; i < Children.size(); ++i) {
2176 TreePatternNode *Child = Children[i];
2178 if (Child->getName().empty())
2179 error("All arguments to a ComplexPattern must be named");
2181 // Check that the ComplexPattern uses are consistent: "(MY_PAT $a, $b)"
2182 // and "(MY_PAT $b, $a)" should not be allowed in the same pattern;
2183 // neither should "(MY_PAT_1 $a, $b)" and "(MY_PAT_2 $a, $b)".
2184 auto OperandId = std::make_pair(Operator, i);
2185 auto PrevOp = ComplexPatternOperands.find(Child->getName());
2186 if (PrevOp != ComplexPatternOperands.end()) {
2187 if (PrevOp->getValue() != OperandId)
2188 error("All ComplexPattern operands must appear consistently: "
2189 "in the same order in just one ComplexPattern instance.");
2191 ComplexPatternOperands[Child->getName()] = OperandId;
2195 unsigned NumResults = GetNumNodeResults(Operator, CDP);
2196 TreePatternNode *Result = new TreePatternNode(Operator, Children, NumResults);
2197 Result->setName(OpName);
2199 if (!Dag->getName().empty()) {
2200 assert(Result->getName().empty());
2201 Result->setName(Dag->getName());
2206 /// SimplifyTree - See if we can simplify this tree to eliminate something that
2207 /// will never match in favor of something obvious that will. This is here
2208 /// strictly as a convenience to target authors because it allows them to write
2209 /// more type generic things and have useless type casts fold away.
2211 /// This returns true if any change is made.
2212 static bool SimplifyTree(TreePatternNode *&N) {
2216 // If we have a bitconvert with a resolved type and if the source and
2217 // destination types are the same, then the bitconvert is useless, remove it.
2218 if (N->getOperator()->getName() == "bitconvert" &&
2219 N->getExtType(0).isConcrete() &&
2220 N->getExtType(0) == N->getChild(0)->getExtType(0) &&
2221 N->getName().empty()) {
2227 // Walk all children.
2228 bool MadeChange = false;
2229 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2230 TreePatternNode *Child = N->getChild(i);
2231 MadeChange |= SimplifyTree(Child);
2232 N->setChild(i, Child);
2239 /// InferAllTypes - Infer/propagate as many types throughout the expression
2240 /// patterns as possible. Return true if all types are inferred, false
2241 /// otherwise. Flags an error if a type contradiction is found.
2243 InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
2244 if (NamedNodes.empty())
2245 ComputeNamedNodes();
2247 bool MadeChange = true;
2248 while (MadeChange) {
2250 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
2251 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
2252 MadeChange |= SimplifyTree(Trees[i]);
2255 // If there are constraints on our named nodes, apply them.
2256 for (StringMap<SmallVector<TreePatternNode*,1> >::iterator
2257 I = NamedNodes.begin(), E = NamedNodes.end(); I != E; ++I) {
2258 SmallVectorImpl<TreePatternNode*> &Nodes = I->second;
2260 // If we have input named node types, propagate their types to the named
2263 if (!InNamedTypes->count(I->getKey())) {
2264 error("Node '" + std::string(I->getKey()) +
2265 "' in output pattern but not input pattern");
2269 const SmallVectorImpl<TreePatternNode*> &InNodes =
2270 InNamedTypes->find(I->getKey())->second;
2272 // The input types should be fully resolved by now.
2273 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
2274 // If this node is a register class, and it is the root of the pattern
2275 // then we're mapping something onto an input register. We allow
2276 // changing the type of the input register in this case. This allows
2277 // us to match things like:
2278 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
2279 if (Nodes[i] == Trees[0] && Nodes[i]->isLeaf()) {
2280 DefInit *DI = dyn_cast<DefInit>(Nodes[i]->getLeafValue());
2281 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2282 DI->getDef()->isSubClassOf("RegisterOperand")))
2286 assert(Nodes[i]->getNumTypes() == 1 &&
2287 InNodes[0]->getNumTypes() == 1 &&
2288 "FIXME: cannot name multiple result nodes yet");
2289 MadeChange |= Nodes[i]->UpdateNodeType(0, InNodes[0]->getExtType(0),
2294 // If there are multiple nodes with the same name, they must all have the
2296 if (I->second.size() > 1) {
2297 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
2298 TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
2299 assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
2300 "FIXME: cannot name multiple result nodes yet");
2302 MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
2303 MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
2309 bool HasUnresolvedTypes = false;
2310 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
2311 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
2312 return !HasUnresolvedTypes;
2315 void TreePattern::print(raw_ostream &OS) const {
2316 OS << getRecord()->getName();
2317 if (!Args.empty()) {
2318 OS << "(" << Args[0];
2319 for (unsigned i = 1, e = Args.size(); i != e; ++i)
2320 OS << ", " << Args[i];
2325 if (Trees.size() > 1)
2327 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
2329 Trees[i]->print(OS);
2333 if (Trees.size() > 1)
2337 void TreePattern::dump() const { print(errs()); }
2339 //===----------------------------------------------------------------------===//
2340 // CodeGenDAGPatterns implementation
2343 CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) :
2344 Records(R), Target(R) {
2346 Intrinsics = LoadIntrinsics(Records, false);
2347 TgtIntrinsics = LoadIntrinsics(Records, true);
2349 ParseNodeTransforms();
2350 ParseComplexPatterns();
2351 ParsePatternFragments();
2352 ParseDefaultOperands();
2353 ParseInstructions();
2354 ParsePatternFragments(/*OutFrags*/true);
2357 // Generate variants. For example, commutative patterns can match
2358 // multiple ways. Add them to PatternsToMatch as well.
2361 // Infer instruction flags. For example, we can detect loads,
2362 // stores, and side effects in many cases by examining an
2363 // instruction's pattern.
2364 InferInstructionFlags();
2366 // Verify that instruction flags match the patterns.
2367 VerifyInstructionFlags();
2370 Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
2371 Record *N = Records.getDef(Name);
2372 if (!N || !N->isSubClassOf("SDNode"))
2373 PrintFatalError("Error getting SDNode '" + Name + "'!");
2378 // Parse all of the SDNode definitions for the target, populating SDNodes.
2379 void CodeGenDAGPatterns::ParseNodeInfo() {
2380 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
2381 while (!Nodes.empty()) {
2382 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
2386 // Get the builtin intrinsic nodes.
2387 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
2388 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
2389 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
2392 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
2393 /// map, and emit them to the file as functions.
2394 void CodeGenDAGPatterns::ParseNodeTransforms() {
2395 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
2396 while (!Xforms.empty()) {
2397 Record *XFormNode = Xforms.back();
2398 Record *SDNode = XFormNode->getValueAsDef("Opcode");
2399 std::string Code = XFormNode->getValueAsString("XFormFunction");
2400 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
2406 void CodeGenDAGPatterns::ParseComplexPatterns() {
2407 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
2408 while (!AMs.empty()) {
2409 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
2415 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
2416 /// file, building up the PatternFragments map. After we've collected them all,
2417 /// inline fragments together as necessary, so that there are no references left
2418 /// inside a pattern fragment to a pattern fragment.
2420 void CodeGenDAGPatterns::ParsePatternFragments(bool OutFrags) {
2421 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
2423 // First step, parse all of the fragments.
2424 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
2425 if (OutFrags != Fragments[i]->isSubClassOf("OutPatFrag"))
2428 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
2430 (PatternFragments[Fragments[i]] = llvm::make_unique<TreePattern>(
2431 Fragments[i], Tree, !Fragments[i]->isSubClassOf("OutPatFrag"),
2434 // Validate the argument list, converting it to set, to discard duplicates.
2435 std::vector<std::string> &Args = P->getArgList();
2436 std::set<std::string> OperandsSet(Args.begin(), Args.end());
2438 if (OperandsSet.count(""))
2439 P->error("Cannot have unnamed 'node' values in pattern fragment!");
2441 // Parse the operands list.
2442 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
2443 DefInit *OpsOp = dyn_cast<DefInit>(OpsList->getOperator());
2444 // Special cases: ops == outs == ins. Different names are used to
2445 // improve readability.
2447 (OpsOp->getDef()->getName() != "ops" &&
2448 OpsOp->getDef()->getName() != "outs" &&
2449 OpsOp->getDef()->getName() != "ins"))
2450 P->error("Operands list should start with '(ops ... '!");
2452 // Copy over the arguments.
2454 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
2455 if (!isa<DefInit>(OpsList->getArg(j)) ||
2456 cast<DefInit>(OpsList->getArg(j))->getDef()->getName() != "node")
2457 P->error("Operands list should all be 'node' values.");
2458 if (OpsList->getArgName(j).empty())
2459 P->error("Operands list should have names for each operand!");
2460 if (!OperandsSet.count(OpsList->getArgName(j)))
2461 P->error("'" + OpsList->getArgName(j) +
2462 "' does not occur in pattern or was multiply specified!");
2463 OperandsSet.erase(OpsList->getArgName(j));
2464 Args.push_back(OpsList->getArgName(j));
2467 if (!OperandsSet.empty())
2468 P->error("Operands list does not contain an entry for operand '" +
2469 *OperandsSet.begin() + "'!");
2471 // If there is a code init for this fragment, keep track of the fact that
2472 // this fragment uses it.
2473 TreePredicateFn PredFn(P);
2474 if (!PredFn.isAlwaysTrue())
2475 P->getOnlyTree()->addPredicateFn(PredFn);
2477 // If there is a node transformation corresponding to this, keep track of
2479 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
2480 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
2481 P->getOnlyTree()->setTransformFn(Transform);
2484 // Now that we've parsed all of the tree fragments, do a closure on them so
2485 // that there are not references to PatFrags left inside of them.
2486 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
2487 if (OutFrags != Fragments[i]->isSubClassOf("OutPatFrag"))
2490 TreePattern &ThePat = *PatternFragments[Fragments[i]];
2491 ThePat.InlinePatternFragments();
2493 // Infer as many types as possible. Don't worry about it if we don't infer
2494 // all of them, some may depend on the inputs of the pattern.
2495 ThePat.InferAllTypes();
2496 ThePat.resetError();
2498 // If debugging, print out the pattern fragment result.
2499 DEBUG(ThePat.dump());
2503 void CodeGenDAGPatterns::ParseDefaultOperands() {
2504 std::vector<Record*> DefaultOps;
2505 DefaultOps = Records.getAllDerivedDefinitions("OperandWithDefaultOps");
2507 // Find some SDNode.
2508 assert(!SDNodes.empty() && "No SDNodes parsed?");
2509 Init *SomeSDNode = DefInit::get(SDNodes.begin()->first);
2511 for (unsigned i = 0, e = DefaultOps.size(); i != e; ++i) {
2512 DagInit *DefaultInfo = DefaultOps[i]->getValueAsDag("DefaultOps");
2514 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
2515 // SomeSDnode so that we can parse this.
2516 std::vector<std::pair<Init*, std::string> > Ops;
2517 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
2518 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
2519 DefaultInfo->getArgName(op)));
2520 DagInit *DI = DagInit::get(SomeSDNode, "", Ops);
2522 // Create a TreePattern to parse this.
2523 TreePattern P(DefaultOps[i], DI, false, *this);
2524 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
2526 // Copy the operands over into a DAGDefaultOperand.
2527 DAGDefaultOperand DefaultOpInfo;
2529 TreePatternNode *T = P.getTree(0);
2530 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
2531 TreePatternNode *TPN = T->getChild(op);
2532 while (TPN->ApplyTypeConstraints(P, false))
2533 /* Resolve all types */;
2535 if (TPN->ContainsUnresolvedType()) {
2536 PrintFatalError("Value #" + Twine(i) + " of OperandWithDefaultOps '" +
2537 DefaultOps[i]->getName() +
2538 "' doesn't have a concrete type!");
2540 DefaultOpInfo.DefaultOps.push_back(TPN);
2543 // Insert it into the DefaultOperands map so we can find it later.
2544 DefaultOperands[DefaultOps[i]] = DefaultOpInfo;
2548 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
2549 /// instruction input. Return true if this is a real use.
2550 static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
2551 std::map<std::string, TreePatternNode*> &InstInputs) {
2552 // No name -> not interesting.
2553 if (Pat->getName().empty()) {
2554 if (Pat->isLeaf()) {
2555 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
2556 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2557 DI->getDef()->isSubClassOf("RegisterOperand")))
2558 I->error("Input " + DI->getDef()->getName() + " must be named!");
2564 if (Pat->isLeaf()) {
2565 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
2566 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
2569 Rec = Pat->getOperator();
2572 // SRCVALUE nodes are ignored.
2573 if (Rec->getName() == "srcvalue")
2576 TreePatternNode *&Slot = InstInputs[Pat->getName()];
2582 if (Slot->isLeaf()) {
2583 SlotRec = cast<DefInit>(Slot->getLeafValue())->getDef();
2585 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
2586 SlotRec = Slot->getOperator();
2589 // Ensure that the inputs agree if we've already seen this input.
2591 I->error("All $" + Pat->getName() + " inputs must agree with each other");
2592 if (Slot->getExtTypes() != Pat->getExtTypes())
2593 I->error("All $" + Pat->getName() + " inputs must agree with each other");
2597 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
2598 /// part of "I", the instruction), computing the set of inputs and outputs of
2599 /// the pattern. Report errors if we see anything naughty.
2600 void CodeGenDAGPatterns::
2601 FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
2602 std::map<std::string, TreePatternNode*> &InstInputs,
2603 std::map<std::string, TreePatternNode*>&InstResults,
2604 std::vector<Record*> &InstImpResults) {
2605 if (Pat->isLeaf()) {
2606 bool isUse = HandleUse(I, Pat, InstInputs);
2607 if (!isUse && Pat->getTransformFn())
2608 I->error("Cannot specify a transform function for a non-input value!");
2612 if (Pat->getOperator()->getName() == "implicit") {
2613 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2614 TreePatternNode *Dest = Pat->getChild(i);
2615 if (!Dest->isLeaf())
2616 I->error("implicitly defined value should be a register!");
2618 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
2619 if (!Val || !Val->getDef()->isSubClassOf("Register"))
2620 I->error("implicitly defined value should be a register!");
2621 InstImpResults.push_back(Val->getDef());
2626 if (Pat->getOperator()->getName() != "set") {
2627 // If this is not a set, verify that the children nodes are not void typed,
2629 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2630 if (Pat->getChild(i)->getNumTypes() == 0)
2631 I->error("Cannot have void nodes inside of patterns!");
2632 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
2636 // If this is a non-leaf node with no children, treat it basically as if
2637 // it were a leaf. This handles nodes like (imm).
2638 bool isUse = HandleUse(I, Pat, InstInputs);
2640 if (!isUse && Pat->getTransformFn())
2641 I->error("Cannot specify a transform function for a non-input value!");
2645 // Otherwise, this is a set, validate and collect instruction results.
2646 if (Pat->getNumChildren() == 0)
2647 I->error("set requires operands!");
2649 if (Pat->getTransformFn())
2650 I->error("Cannot specify a transform function on a set node!");
2652 // Check the set destinations.
2653 unsigned NumDests = Pat->getNumChildren()-1;
2654 for (unsigned i = 0; i != NumDests; ++i) {
2655 TreePatternNode *Dest = Pat->getChild(i);
2656 if (!Dest->isLeaf())
2657 I->error("set destination should be a register!");
2659 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
2661 I->error("set destination should be a register!");
2665 if (Val->getDef()->isSubClassOf("RegisterClass") ||
2666 Val->getDef()->isSubClassOf("ValueType") ||
2667 Val->getDef()->isSubClassOf("RegisterOperand") ||
2668 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
2669 if (Dest->getName().empty())
2670 I->error("set destination must have a name!");
2671 if (InstResults.count(Dest->getName()))
2672 I->error("cannot set '" + Dest->getName() +"' multiple times");
2673 InstResults[Dest->getName()] = Dest;
2674 } else if (Val->getDef()->isSubClassOf("Register")) {
2675 InstImpResults.push_back(Val->getDef());
2677 I->error("set destination should be a register!");
2681 // Verify and collect info from the computation.
2682 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
2683 InstInputs, InstResults, InstImpResults);
2686 //===----------------------------------------------------------------------===//
2687 // Instruction Analysis
2688 //===----------------------------------------------------------------------===//
2690 class InstAnalyzer {
2691 const CodeGenDAGPatterns &CDP;
2693 bool hasSideEffects;
2699 InstAnalyzer(const CodeGenDAGPatterns &cdp)
2700 : CDP(cdp), hasSideEffects(false), mayStore(false), mayLoad(false),
2701 isBitcast(false), isVariadic(false) {}
2703 void Analyze(const TreePattern *Pat) {
2704 // Assume only the first tree is the pattern. The others are clobber nodes.
2705 AnalyzeNode(Pat->getTree(0));
2708 void Analyze(const PatternToMatch *Pat) {
2709 AnalyzeNode(Pat->getSrcPattern());
2713 bool IsNodeBitcast(const TreePatternNode *N) const {
2714 if (hasSideEffects || mayLoad || mayStore || isVariadic)
2717 if (N->getNumChildren() != 2)
2720 const TreePatternNode *N0 = N->getChild(0);
2721 if (!N0->isLeaf() || !isa<DefInit>(N0->getLeafValue()))
2724 const TreePatternNode *N1 = N->getChild(1);
2727 if (N1->getNumChildren() != 1 || !N1->getChild(0)->isLeaf())
2730 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N1->getOperator());
2731 if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1)
2733 return OpInfo.getEnumName() == "ISD::BITCAST";
2737 void AnalyzeNode(const TreePatternNode *N) {
2739 if (DefInit *DI = dyn_cast<DefInit>(N->getLeafValue())) {
2740 Record *LeafRec = DI->getDef();
2741 // Handle ComplexPattern leaves.
2742 if (LeafRec->isSubClassOf("ComplexPattern")) {
2743 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
2744 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
2745 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
2746 if (CP.hasProperty(SDNPSideEffect)) hasSideEffects = true;
2752 // Analyze children.
2753 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2754 AnalyzeNode(N->getChild(i));
2756 // Ignore set nodes, which are not SDNodes.
2757 if (N->getOperator()->getName() == "set") {
2758 isBitcast = IsNodeBitcast(N);
2762 // Notice properties of the node.
2763 if (N->NodeHasProperty(SDNPMayStore, CDP)) mayStore = true;
2764 if (N->NodeHasProperty(SDNPMayLoad, CDP)) mayLoad = true;
2765 if (N->NodeHasProperty(SDNPSideEffect, CDP)) hasSideEffects = true;
2766 if (N->NodeHasProperty(SDNPVariadic, CDP)) isVariadic = true;
2768 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
2769 // If this is an intrinsic, analyze it.
2770 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
2771 mayLoad = true;// These may load memory.
2773 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteArgMem)
2774 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
2776 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem)
2777 // WriteMem intrinsics can have other strange effects.
2778 hasSideEffects = true;
2784 static bool InferFromPattern(CodeGenInstruction &InstInfo,
2785 const InstAnalyzer &PatInfo,
2789 // Remember where InstInfo got its flags.
2790 if (InstInfo.hasUndefFlags())
2791 InstInfo.InferredFrom = PatDef;
2793 // Check explicitly set flags for consistency.
2794 if (InstInfo.hasSideEffects != PatInfo.hasSideEffects &&
2795 !InstInfo.hasSideEffects_Unset) {
2796 // Allow explicitly setting hasSideEffects = 1 on instructions, even when
2797 // the pattern has no side effects. That could be useful for div/rem
2798 // instructions that may trap.
2799 if (!InstInfo.hasSideEffects) {
2801 PrintError(PatDef->getLoc(), "Pattern doesn't match hasSideEffects = " +
2802 Twine(InstInfo.hasSideEffects));
2806 if (InstInfo.mayStore != PatInfo.mayStore && !InstInfo.mayStore_Unset) {
2808 PrintError(PatDef->getLoc(), "Pattern doesn't match mayStore = " +
2809 Twine(InstInfo.mayStore));
2812 if (InstInfo.mayLoad != PatInfo.mayLoad && !InstInfo.mayLoad_Unset) {
2813 // Allow explicitly setting mayLoad = 1, even when the pattern has no loads.
2814 // Some targets translate immediates to loads.
2815 if (!InstInfo.mayLoad) {
2817 PrintError(PatDef->getLoc(), "Pattern doesn't match mayLoad = " +
2818 Twine(InstInfo.mayLoad));
2822 // Transfer inferred flags.
2823 InstInfo.hasSideEffects |= PatInfo.hasSideEffects;
2824 InstInfo.mayStore |= PatInfo.mayStore;
2825 InstInfo.mayLoad |= PatInfo.mayLoad;
2827 // These flags are silently added without any verification.
2828 InstInfo.isBitcast |= PatInfo.isBitcast;
2830 // Don't infer isVariadic. This flag means something different on SDNodes and
2831 // instructions. For example, a CALL SDNode is variadic because it has the
2832 // call arguments as operands, but a CALL instruction is not variadic - it
2833 // has argument registers as implicit, not explicit uses.
2838 /// hasNullFragReference - Return true if the DAG has any reference to the
2839 /// null_frag operator.
2840 static bool hasNullFragReference(DagInit *DI) {
2841 DefInit *OpDef = dyn_cast<DefInit>(DI->getOperator());
2842 if (!OpDef) return false;
2843 Record *Operator = OpDef->getDef();
2845 // If this is the null fragment, return true.
2846 if (Operator->getName() == "null_frag") return true;
2847 // If any of the arguments reference the null fragment, return true.
2848 for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {
2849 DagInit *Arg = dyn_cast<DagInit>(DI->getArg(i));
2850 if (Arg && hasNullFragReference(Arg))
2857 /// hasNullFragReference - Return true if any DAG in the list references
2858 /// the null_frag operator.
2859 static bool hasNullFragReference(ListInit *LI) {
2860 for (Init *I : LI->getValues()) {
2861 DagInit *DI = dyn_cast<DagInit>(I);
2862 assert(DI && "non-dag in an instruction Pattern list?!");
2863 if (hasNullFragReference(DI))
2869 /// Get all the instructions in a tree.
2871 getInstructionsInTree(TreePatternNode *Tree, SmallVectorImpl<Record*> &Instrs) {
2874 if (Tree->getOperator()->isSubClassOf("Instruction"))
2875 Instrs.push_back(Tree->getOperator());
2876 for (unsigned i = 0, e = Tree->getNumChildren(); i != e; ++i)
2877 getInstructionsInTree(Tree->getChild(i), Instrs);
2880 /// Check the class of a pattern leaf node against the instruction operand it
2882 static bool checkOperandClass(CGIOperandList::OperandInfo &OI,
2887 // Allow direct value types to be used in instruction set patterns.
2888 // The type will be checked later.
2889 if (Leaf->isSubClassOf("ValueType"))
2892 // Patterns can also be ComplexPattern instances.
2893 if (Leaf->isSubClassOf("ComplexPattern"))
2899 const DAGInstruction &CodeGenDAGPatterns::parseInstructionPattern(
2900 CodeGenInstruction &CGI, ListInit *Pat, DAGInstMap &DAGInsts) {
2902 assert(!DAGInsts.count(CGI.TheDef) && "Instruction already parsed!");
2904 // Parse the instruction.
2905 TreePattern *I = new TreePattern(CGI.TheDef, Pat, true, *this);
2906 // Inline pattern fragments into it.
2907 I->InlinePatternFragments();
2909 // Infer as many types as possible. If we cannot infer all of them, we can
2910 // never do anything with this instruction pattern: report it to the user.
2911 if (!I->InferAllTypes())
2912 I->error("Could not infer all types in pattern!");
2914 // InstInputs - Keep track of all of the inputs of the instruction, along
2915 // with the record they are declared as.
2916 std::map<std::string, TreePatternNode*> InstInputs;
2918 // InstResults - Keep track of all the virtual registers that are 'set'
2919 // in the instruction, including what reg class they are.
2920 std::map<std::string, TreePatternNode*> InstResults;
2922 std::vector<Record*> InstImpResults;
2924 // Verify that the top-level forms in the instruction are of void type, and
2925 // fill in the InstResults map.
2926 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
2927 TreePatternNode *Pat = I->getTree(j);
2928 if (Pat->getNumTypes() != 0)
2929 I->error("Top-level forms in instruction pattern should have"
2932 // Find inputs and outputs, and verify the structure of the uses/defs.
2933 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
2937 // Now that we have inputs and outputs of the pattern, inspect the operands
2938 // list for the instruction. This determines the order that operands are
2939 // added to the machine instruction the node corresponds to.
2940 unsigned NumResults = InstResults.size();
2942 // Parse the operands list from the (ops) list, validating it.
2943 assert(I->getArgList().empty() && "Args list should still be empty here!");
2945 // Check that all of the results occur first in the list.
2946 std::vector<Record*> Results;
2947 SmallVector<TreePatternNode *, 2> ResNodes;
2948 for (unsigned i = 0; i != NumResults; ++i) {
2949 if (i == CGI.Operands.size())
2950 I->error("'" + InstResults.begin()->first +
2951 "' set but does not appear in operand list!");
2952 const std::string &OpName = CGI.Operands[i].Name;
2954 // Check that it exists in InstResults.
2955 TreePatternNode *RNode = InstResults[OpName];
2957 I->error("Operand $" + OpName + " does not exist in operand list!");
2959 ResNodes.push_back(RNode);
2961 Record *R = cast<DefInit>(RNode->getLeafValue())->getDef();
2963 I->error("Operand $" + OpName + " should be a set destination: all "
2964 "outputs must occur before inputs in operand list!");
2966 if (!checkOperandClass(CGI.Operands[i], R))
2967 I->error("Operand $" + OpName + " class mismatch!");
2969 // Remember the return type.
2970 Results.push_back(CGI.Operands[i].Rec);
2972 // Okay, this one checks out.
2973 InstResults.erase(OpName);
2976 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
2977 // the copy while we're checking the inputs.
2978 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
2980 std::vector<TreePatternNode*> ResultNodeOperands;
2981 std::vector<Record*> Operands;
2982 for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
2983 CGIOperandList::OperandInfo &Op = CGI.Operands[i];
2984 const std::string &OpName = Op.Name;
2986 I->error("Operand #" + utostr(i) + " in operands list has no name!");
2988 if (!InstInputsCheck.count(OpName)) {
2989 // If this is an operand with a DefaultOps set filled in, we can ignore
2990 // this. When we codegen it, we will do so as always executed.
2991 if (Op.Rec->isSubClassOf("OperandWithDefaultOps")) {
2992 // Does it have a non-empty DefaultOps field? If so, ignore this
2994 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
2997 I->error("Operand $" + OpName +
2998 " does not appear in the instruction pattern");
3000 TreePatternNode *InVal = InstInputsCheck[OpName];
3001 InstInputsCheck.erase(OpName); // It occurred, remove from map.
3003 if (InVal->isLeaf() && isa<DefInit>(InVal->getLeafValue())) {
3004 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
3005 if (!checkOperandClass(Op, InRec))
3006 I->error("Operand $" + OpName + "'s register class disagrees"
3007 " between the operand and pattern");
3009 Operands.push_back(Op.Rec);
3011 // Construct the result for the dest-pattern operand list.
3012 TreePatternNode *OpNode = InVal->clone();
3014 // No predicate is useful on the result.
3015 OpNode->clearPredicateFns();
3017 // Promote the xform function to be an explicit node if set.
3018 if (Record *Xform = OpNode->getTransformFn()) {
3019 OpNode->setTransformFn(nullptr);
3020 std::vector<TreePatternNode*> Children;
3021 Children.push_back(OpNode);
3022 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
3025 ResultNodeOperands.push_back(OpNode);
3028 if (!InstInputsCheck.empty())
3029 I->error("Input operand $" + InstInputsCheck.begin()->first +
3030 " occurs in pattern but not in operands list!");
3032 TreePatternNode *ResultPattern =
3033 new TreePatternNode(I->getRecord(), ResultNodeOperands,
3034 GetNumNodeResults(I->getRecord(), *this));
3035 // Copy fully inferred output node types to instruction result pattern.
3036 for (unsigned i = 0; i != NumResults; ++i) {
3037 assert(ResNodes[i]->getNumTypes() == 1 && "FIXME: Unhandled");
3038 ResultPattern->setType(i, ResNodes[i]->getExtType(0));
3041 // Create and insert the instruction.
3042 // FIXME: InstImpResults should not be part of DAGInstruction.
3043 DAGInstruction TheInst(I, Results, Operands, InstImpResults);
3044 DAGInsts.insert(std::make_pair(I->getRecord(), TheInst));
3046 // Use a temporary tree pattern to infer all types and make sure that the
3047 // constructed result is correct. This depends on the instruction already
3048 // being inserted into the DAGInsts map.
3049 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
3050 Temp.InferAllTypes(&I->getNamedNodesMap());
3052 DAGInstruction &TheInsertedInst = DAGInsts.find(I->getRecord())->second;
3053 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
3055 return TheInsertedInst;
3058 /// ParseInstructions - Parse all of the instructions, inlining and resolving
3059 /// any fragments involved. This populates the Instructions list with fully
3060 /// resolved instructions.
3061 void CodeGenDAGPatterns::ParseInstructions() {
3062 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
3064 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
3065 ListInit *LI = nullptr;
3067 if (isa<ListInit>(Instrs[i]->getValueInit("Pattern")))
3068 LI = Instrs[i]->getValueAsListInit("Pattern");
3070 // If there is no pattern, only collect minimal information about the
3071 // instruction for its operand list. We have to assume that there is one
3072 // result, as we have no detailed info. A pattern which references the
3073 // null_frag operator is as-if no pattern were specified. Normally this
3074 // is from a multiclass expansion w/ a SDPatternOperator passed in as
3076 if (!LI || LI->empty() || hasNullFragReference(LI)) {
3077 std::vector<Record*> Results;
3078 std::vector<Record*> Operands;
3080 CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
3082 if (InstInfo.Operands.size() != 0) {
3083 for (unsigned j = 0, e = InstInfo.Operands.NumDefs; j < e; ++j)
3084 Results.push_back(InstInfo.Operands[j].Rec);
3086 // The rest are inputs.
3087 for (unsigned j = InstInfo.Operands.NumDefs,
3088 e = InstInfo.Operands.size(); j < e; ++j)
3089 Operands.push_back(InstInfo.Operands[j].Rec);
3092 // Create and insert the instruction.
3093 std::vector<Record*> ImpResults;
3094 Instructions.insert(std::make_pair(Instrs[i],
3095 DAGInstruction(nullptr, Results, Operands, ImpResults)));
3096 continue; // no pattern.
3099 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]);
3100 const DAGInstruction &DI = parseInstructionPattern(CGI, LI, Instructions);
3103 DEBUG(DI.getPattern()->dump());
3106 // If we can, convert the instructions to be patterns that are matched!
3107 for (std::map<Record*, DAGInstruction, LessRecordByID>::iterator II =
3108 Instructions.begin(),
3109 E = Instructions.end(); II != E; ++II) {
3110 DAGInstruction &TheInst = II->second;
3111 TreePattern *I = TheInst.getPattern();
3112 if (!I) continue; // No pattern.
3114 // FIXME: Assume only the first tree is the pattern. The others are clobber
3116 TreePatternNode *Pattern = I->getTree(0);
3117 TreePatternNode *SrcPattern;
3118 if (Pattern->getOperator()->getName() == "set") {
3119 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
3121 // Not a set (store or something?)
3122 SrcPattern = Pattern;
3125 Record *Instr = II->first;
3126 AddPatternToMatch(I,
3127 PatternToMatch(Instr,
3128 Instr->getValueAsListInit("Predicates"),
3130 TheInst.getResultPattern(),
3131 TheInst.getImpResults(),
3132 Instr->getValueAsInt("AddedComplexity"),
3138 typedef std::pair<const TreePatternNode*, unsigned> NameRecord;
3140 static void FindNames(const TreePatternNode *P,
3141 std::map<std::string, NameRecord> &Names,
3142 TreePattern *PatternTop) {
3143 if (!P->getName().empty()) {
3144 NameRecord &Rec = Names[P->getName()];
3145 // If this is the first instance of the name, remember the node.
3146 if (Rec.second++ == 0)
3148 else if (Rec.first->getExtTypes() != P->getExtTypes())
3149 PatternTop->error("repetition of value: $" + P->getName() +
3150 " where different uses have different types!");
3154 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
3155 FindNames(P->getChild(i), Names, PatternTop);
3159 void CodeGenDAGPatterns::AddPatternToMatch(TreePattern *Pattern,
3160 const PatternToMatch &PTM) {
3161 // Do some sanity checking on the pattern we're about to match.
3163 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this)) {
3164 PrintWarning(Pattern->getRecord()->getLoc(),
3165 Twine("Pattern can never match: ") + Reason);
3169 // If the source pattern's root is a complex pattern, that complex pattern
3170 // must specify the nodes it can potentially match.
3171 if (const ComplexPattern *CP =
3172 PTM.getSrcPattern()->getComplexPatternInfo(*this))
3173 if (CP->getRootNodes().empty())
3174 Pattern->error("ComplexPattern at root must specify list of opcodes it"
3178 // Find all of the named values in the input and output, ensure they have the
3180 std::map<std::string, NameRecord> SrcNames, DstNames;
3181 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
3182 FindNames(PTM.getDstPattern(), DstNames, Pattern);
3184 // Scan all of the named values in the destination pattern, rejecting them if
3185 // they don't exist in the input pattern.
3186 for (std::map<std::string, NameRecord>::iterator
3187 I = DstNames.begin(), E = DstNames.end(); I != E; ++I) {
3188 if (SrcNames[I->first].first == nullptr)
3189 Pattern->error("Pattern has input without matching name in output: $" +
3193 // Scan all of the named values in the source pattern, rejecting them if the
3194 // name isn't used in the dest, and isn't used to tie two values together.
3195 for (std::map<std::string, NameRecord>::iterator
3196 I = SrcNames.begin(), E = SrcNames.end(); I != E; ++I)
3197 if (DstNames[I->first].first == nullptr && SrcNames[I->first].second == 1)
3198 Pattern->error("Pattern has dead named input: $" + I->first);
3200 PatternsToMatch.push_back(PTM);
3205 void CodeGenDAGPatterns::InferInstructionFlags() {
3206 const std::vector<const CodeGenInstruction*> &Instructions =
3207 Target.getInstructionsByEnumValue();
3209 // First try to infer flags from the primary instruction pattern, if any.
3210 SmallVector<CodeGenInstruction*, 8> Revisit;
3211 unsigned Errors = 0;
3212 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
3213 CodeGenInstruction &InstInfo =
3214 const_cast<CodeGenInstruction &>(*Instructions[i]);
3216 // Get the primary instruction pattern.
3217 const TreePattern *Pattern = getInstruction(InstInfo.TheDef).getPattern();
3219 if (InstInfo.hasUndefFlags())
3220 Revisit.push_back(&InstInfo);
3223 InstAnalyzer PatInfo(*this);
3224 PatInfo.Analyze(Pattern);
3225 Errors += InferFromPattern(InstInfo, PatInfo, InstInfo.TheDef);
3228 // Second, look for single-instruction patterns defined outside the
3230 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3231 const PatternToMatch &PTM = *I;
3233 // We can only infer from single-instruction patterns, otherwise we won't
3234 // know which instruction should get the flags.
3235 SmallVector<Record*, 8> PatInstrs;
3236 getInstructionsInTree(PTM.getDstPattern(), PatInstrs);
3237 if (PatInstrs.size() != 1)
3240 // Get the single instruction.
3241 CodeGenInstruction &InstInfo = Target.getInstruction(PatInstrs.front());
3243 // Only infer properties from the first pattern. We'll verify the others.
3244 if (InstInfo.InferredFrom)
3247 InstAnalyzer PatInfo(*this);
3248 PatInfo.Analyze(&PTM);
3249 Errors += InferFromPattern(InstInfo, PatInfo, PTM.getSrcRecord());
3253 PrintFatalError("pattern conflicts");
3255 // Revisit instructions with undefined flags and no pattern.
3256 if (Target.guessInstructionProperties()) {
3257 for (unsigned i = 0, e = Revisit.size(); i != e; ++i) {
3258 CodeGenInstruction &InstInfo = *Revisit[i];
3259 if (InstInfo.InferredFrom)
3261 // The mayLoad and mayStore flags default to false.
3262 // Conservatively assume hasSideEffects if it wasn't explicit.
3263 if (InstInfo.hasSideEffects_Unset)
3264 InstInfo.hasSideEffects = true;
3269 // Complain about any flags that are still undefined.
3270 for (unsigned i = 0, e = Revisit.size(); i != e; ++i) {
3271 CodeGenInstruction &InstInfo = *Revisit[i];
3272 if (InstInfo.InferredFrom)
3274 if (InstInfo.hasSideEffects_Unset)
3275 PrintError(InstInfo.TheDef->getLoc(),
3276 "Can't infer hasSideEffects from patterns");
3277 if (InstInfo.mayStore_Unset)
3278 PrintError(InstInfo.TheDef->getLoc(),
3279 "Can't infer mayStore from patterns");
3280 if (InstInfo.mayLoad_Unset)
3281 PrintError(InstInfo.TheDef->getLoc(),
3282 "Can't infer mayLoad from patterns");
3287 /// Verify instruction flags against pattern node properties.
3288 void CodeGenDAGPatterns::VerifyInstructionFlags() {
3289 unsigned Errors = 0;
3290 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3291 const PatternToMatch &PTM = *I;
3292 SmallVector<Record*, 8> Instrs;
3293 getInstructionsInTree(PTM.getDstPattern(), Instrs);
3297 // Count the number of instructions with each flag set.
3298 unsigned NumSideEffects = 0;
3299 unsigned NumStores = 0;
3300 unsigned NumLoads = 0;
3301 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
3302 const CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
3303 NumSideEffects += InstInfo.hasSideEffects;
3304 NumStores += InstInfo.mayStore;
3305 NumLoads += InstInfo.mayLoad;
3308 // Analyze the source pattern.
3309 InstAnalyzer PatInfo(*this);
3310 PatInfo.Analyze(&PTM);
3312 // Collect error messages.
3313 SmallVector<std::string, 4> Msgs;
3315 // Check for missing flags in the output.
3316 // Permit extra flags for now at least.
3317 if (PatInfo.hasSideEffects && !NumSideEffects)
3318 Msgs.push_back("pattern has side effects, but hasSideEffects isn't set");
3320 // Don't verify store flags on instructions with side effects. At least for
3321 // intrinsics, side effects implies mayStore.
3322 if (!PatInfo.hasSideEffects && PatInfo.mayStore && !NumStores)
3323 Msgs.push_back("pattern may store, but mayStore isn't set");
3325 // Similarly, mayStore implies mayLoad on intrinsics.
3326 if (!PatInfo.mayStore && PatInfo.mayLoad && !NumLoads)
3327 Msgs.push_back("pattern may load, but mayLoad isn't set");
3329 // Print error messages.
3334 for (unsigned i = 0, e = Msgs.size(); i != e; ++i)
3335 PrintError(PTM.getSrcRecord()->getLoc(), Twine(Msgs[i]) + " on the " +
3336 (Instrs.size() == 1 ?
3337 "instruction" : "output instructions"));
3338 // Provide the location of the relevant instruction definitions.
3339 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
3340 if (Instrs[i] != PTM.getSrcRecord())
3341 PrintError(Instrs[i]->getLoc(), "defined here");
3342 const CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
3343 if (InstInfo.InferredFrom &&
3344 InstInfo.InferredFrom != InstInfo.TheDef &&
3345 InstInfo.InferredFrom != PTM.getSrcRecord())
3346 PrintError(InstInfo.InferredFrom->getLoc(), "inferred from pattern");
3350 PrintFatalError("Errors in DAG patterns");
3353 /// Given a pattern result with an unresolved type, see if we can find one
3354 /// instruction with an unresolved result type. Force this result type to an
3355 /// arbitrary element if it's possible types to converge results.
3356 static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
3360 // Analyze children.
3361 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3362 if (ForceArbitraryInstResultType(N->getChild(i), TP))
3365 if (!N->getOperator()->isSubClassOf("Instruction"))
3368 // If this type is already concrete or completely unknown we can't do
3370 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
3371 if (N->getExtType(i).isCompletelyUnknown() || N->getExtType(i).isConcrete())
3374 // Otherwise, force its type to the first possibility (an arbitrary choice).
3375 if (N->getExtType(i).MergeInTypeInfo(N->getExtType(i).getTypeList()[0], TP))
3382 void CodeGenDAGPatterns::ParsePatterns() {
3383 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
3385 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
3386 Record *CurPattern = Patterns[i];
3387 DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
3389 // If the pattern references the null_frag, there's nothing to do.
3390 if (hasNullFragReference(Tree))
3393 TreePattern *Pattern = new TreePattern(CurPattern, Tree, true, *this);
3395 // Inline pattern fragments into it.
3396 Pattern->InlinePatternFragments();
3398 ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
3399 if (LI->empty()) continue; // no pattern.
3401 // Parse the instruction.
3402 TreePattern Result(CurPattern, LI, false, *this);
3404 // Inline pattern fragments into it.
3405 Result.InlinePatternFragments();
3407 if (Result.getNumTrees() != 1)
3408 Result.error("Cannot handle instructions producing instructions "
3409 "with temporaries yet!");
3411 bool IterateInference;
3412 bool InferredAllPatternTypes, InferredAllResultTypes;
3414 // Infer as many types as possible. If we cannot infer all of them, we
3415 // can never do anything with this pattern: report it to the user.
3416 InferredAllPatternTypes =
3417 Pattern->InferAllTypes(&Pattern->getNamedNodesMap());
3419 // Infer as many types as possible. If we cannot infer all of them, we
3420 // can never do anything with this pattern: report it to the user.
3421 InferredAllResultTypes =
3422 Result.InferAllTypes(&Pattern->getNamedNodesMap());
3424 IterateInference = false;
3426 // Apply the type of the result to the source pattern. This helps us
3427 // resolve cases where the input type is known to be a pointer type (which
3428 // is considered resolved), but the result knows it needs to be 32- or
3429 // 64-bits. Infer the other way for good measure.
3430 for (unsigned i = 0, e = std::min(Result.getTree(0)->getNumTypes(),
3431 Pattern->getTree(0)->getNumTypes());
3433 IterateInference = Pattern->getTree(0)->UpdateNodeType(
3434 i, Result.getTree(0)->getExtType(i), Result);
3435 IterateInference |= Result.getTree(0)->UpdateNodeType(
3436 i, Pattern->getTree(0)->getExtType(i), Result);
3439 // If our iteration has converged and the input pattern's types are fully
3440 // resolved but the result pattern is not fully resolved, we may have a
3441 // situation where we have two instructions in the result pattern and
3442 // the instructions require a common register class, but don't care about
3443 // what actual MVT is used. This is actually a bug in our modelling:
3444 // output patterns should have register classes, not MVTs.
3446 // In any case, to handle this, we just go through and disambiguate some
3447 // arbitrary types to the result pattern's nodes.
3448 if (!IterateInference && InferredAllPatternTypes &&
3449 !InferredAllResultTypes)
3451 ForceArbitraryInstResultType(Result.getTree(0), Result);
3452 } while (IterateInference);
3454 // Verify that we inferred enough types that we can do something with the
3455 // pattern and result. If these fire the user has to add type casts.
3456 if (!InferredAllPatternTypes)
3457 Pattern->error("Could not infer all types in pattern!");
3458 if (!InferredAllResultTypes) {
3460 Result.error("Could not infer all types in pattern result!");
3463 // Validate that the input pattern is correct.
3464 std::map<std::string, TreePatternNode*> InstInputs;
3465 std::map<std::string, TreePatternNode*> InstResults;
3466 std::vector<Record*> InstImpResults;
3467 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
3468 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
3469 InstInputs, InstResults,
3472 // Promote the xform function to be an explicit node if set.
3473 TreePatternNode *DstPattern = Result.getOnlyTree();
3474 std::vector<TreePatternNode*> ResultNodeOperands;
3475 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
3476 TreePatternNode *OpNode = DstPattern->getChild(ii);
3477 if (Record *Xform = OpNode->getTransformFn()) {
3478 OpNode->setTransformFn(nullptr);
3479 std::vector<TreePatternNode*> Children;
3480 Children.push_back(OpNode);
3481 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
3483 ResultNodeOperands.push_back(OpNode);
3485 DstPattern = Result.getOnlyTree();
3486 if (!DstPattern->isLeaf())
3487 DstPattern = new TreePatternNode(DstPattern->getOperator(),
3489 DstPattern->getNumTypes());
3491 for (unsigned i = 0, e = Result.getOnlyTree()->getNumTypes(); i != e; ++i)
3492 DstPattern->setType(i, Result.getOnlyTree()->getExtType(i));
3494 TreePattern Temp(Result.getRecord(), DstPattern, false, *this);
3495 Temp.InferAllTypes();
3498 AddPatternToMatch(Pattern,
3499 PatternToMatch(CurPattern,
3500 CurPattern->getValueAsListInit("Predicates"),
3501 Pattern->getTree(0),
3502 Temp.getOnlyTree(), InstImpResults,
3503 CurPattern->getValueAsInt("AddedComplexity"),
3504 CurPattern->getID()));
3508 /// CombineChildVariants - Given a bunch of permutations of each child of the
3509 /// 'operator' node, put them together in all possible ways.
3510 static void CombineChildVariants(TreePatternNode *Orig,
3511 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
3512 std::vector<TreePatternNode*> &OutVariants,
3513 CodeGenDAGPatterns &CDP,
3514 const MultipleUseVarSet &DepVars) {
3515 // Make sure that each operand has at least one variant to choose from.
3516 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
3517 if (ChildVariants[i].empty())
3520 // The end result is an all-pairs construction of the resultant pattern.
3521 std::vector<unsigned> Idxs;
3522 Idxs.resize(ChildVariants.size());
3526 DEBUG(if (!Idxs.empty()) {
3527 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
3528 for (unsigned i = 0; i < Idxs.size(); ++i) {
3529 errs() << Idxs[i] << " ";
3534 // Create the variant and add it to the output list.
3535 std::vector<TreePatternNode*> NewChildren;
3536 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
3537 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
3538 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren,
3539 Orig->getNumTypes());
3541 // Copy over properties.
3542 R->setName(Orig->getName());
3543 R->setPredicateFns(Orig->getPredicateFns());
3544 R->setTransformFn(Orig->getTransformFn());
3545 for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
3546 R->setType(i, Orig->getExtType(i));
3548 // If this pattern cannot match, do not include it as a variant.
3549 std::string ErrString;
3550 if (!R->canPatternMatch(ErrString, CDP)) {
3553 // Scan to see if this pattern has already been emitted. We can get
3554 // duplication due to things like commuting:
3555 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
3556 // which are the same pattern. Ignore the dups.
3557 if (std::any_of(OutVariants.begin(), OutVariants.end(),
3558 [=](TreePatternNode *Variant) {
3559 return R->isIsomorphicTo(Variant, DepVars);
3563 OutVariants.push_back(R);
3566 // Increment indices to the next permutation by incrementing the
3567 // indices from last index backward, e.g., generate the sequence
3568 // [0, 0], [0, 1], [1, 0], [1, 1].
3570 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
3571 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
3576 NotDone = (IdxsIdx >= 0);
3580 /// CombineChildVariants - A helper function for binary operators.
3582 static void CombineChildVariants(TreePatternNode *Orig,
3583 const std::vector<TreePatternNode*> &LHS,
3584 const std::vector<TreePatternNode*> &RHS,
3585 std::vector<TreePatternNode*> &OutVariants,
3586 CodeGenDAGPatterns &CDP,
3587 const MultipleUseVarSet &DepVars) {
3588 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3589 ChildVariants.push_back(LHS);
3590 ChildVariants.push_back(RHS);
3591 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
3595 static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
3596 std::vector<TreePatternNode *> &Children) {
3597 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
3598 Record *Operator = N->getOperator();
3600 // Only permit raw nodes.
3601 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
3602 N->getTransformFn()) {
3603 Children.push_back(N);
3607 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
3608 Children.push_back(N->getChild(0));
3610 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
3612 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
3613 Children.push_back(N->getChild(1));
3615 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
3618 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
3619 /// the (potentially recursive) pattern by using algebraic laws.
3621 static void GenerateVariantsOf(TreePatternNode *N,
3622 std::vector<TreePatternNode*> &OutVariants,
3623 CodeGenDAGPatterns &CDP,
3624 const MultipleUseVarSet &DepVars) {
3625 // We cannot permute leaves or ComplexPattern uses.
3626 if (N->isLeaf() || N->getOperator()->isSubClassOf("ComplexPattern")) {
3627 OutVariants.push_back(N);
3631 // Look up interesting info about the node.
3632 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
3634 // If this node is associative, re-associate.
3635 if (NodeInfo.hasProperty(SDNPAssociative)) {
3636 // Re-associate by pulling together all of the linked operators
3637 std::vector<TreePatternNode*> MaximalChildren;
3638 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
3640 // Only handle child sizes of 3. Otherwise we'll end up trying too many
3642 if (MaximalChildren.size() == 3) {
3643 // Find the variants of all of our maximal children.
3644 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
3645 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
3646 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
3647 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
3649 // There are only two ways we can permute the tree:
3650 // (A op B) op C and A op (B op C)
3651 // Within these forms, we can also permute A/B/C.
3653 // Generate legal pair permutations of A/B/C.
3654 std::vector<TreePatternNode*> ABVariants;
3655 std::vector<TreePatternNode*> BAVariants;
3656 std::vector<TreePatternNode*> ACVariants;
3657 std::vector<TreePatternNode*> CAVariants;
3658 std::vector<TreePatternNode*> BCVariants;
3659 std::vector<TreePatternNode*> CBVariants;
3660 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
3661 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
3662 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
3663 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
3664 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
3665 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
3667 // Combine those into the result: (x op x) op x
3668 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
3669 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
3670 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
3671 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
3672 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
3673 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
3675 // Combine those into the result: x op (x op x)
3676 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
3677 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
3678 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
3679 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
3680 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
3681 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
3686 // Compute permutations of all children.
3687 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3688 ChildVariants.resize(N->getNumChildren());
3689 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3690 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
3692 // Build all permutations based on how the children were formed.
3693 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
3695 // If this node is commutative, consider the commuted order.
3696 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
3697 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
3698 assert((N->getNumChildren()==2 || isCommIntrinsic) &&
3699 "Commutative but doesn't have 2 children!");
3700 // Don't count children which are actually register references.
3702 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
3703 TreePatternNode *Child = N->getChild(i);
3704 if (Child->isLeaf())
3705 if (DefInit *DI = dyn_cast<DefInit>(Child->getLeafValue())) {
3706 Record *RR = DI->getDef();
3707 if (RR->isSubClassOf("Register"))
3712 // Consider the commuted order.
3713 if (isCommIntrinsic) {
3714 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
3715 // operands are the commutative operands, and there might be more operands
3718 "Commutative intrinsic should have at least 3 children!");
3719 std::vector<std::vector<TreePatternNode*> > Variants;
3720 Variants.push_back(ChildVariants[0]); // Intrinsic id.
3721 Variants.push_back(ChildVariants[2]);
3722 Variants.push_back(ChildVariants[1]);
3723 for (unsigned i = 3; i != NC; ++i)
3724 Variants.push_back(ChildVariants[i]);
3725 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
3727 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
3728 OutVariants, CDP, DepVars);
3733 // GenerateVariants - Generate variants. For example, commutative patterns can
3734 // match multiple ways. Add them to PatternsToMatch as well.
3735 void CodeGenDAGPatterns::GenerateVariants() {
3736 DEBUG(errs() << "Generating instruction variants.\n");
3738 // Loop over all of the patterns we've collected, checking to see if we can
3739 // generate variants of the instruction, through the exploitation of
3740 // identities. This permits the target to provide aggressive matching without
3741 // the .td file having to contain tons of variants of instructions.
3743 // Note that this loop adds new patterns to the PatternsToMatch list, but we
3744 // intentionally do not reconsider these. Any variants of added patterns have
3745 // already been added.
3747 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
3748 MultipleUseVarSet DepVars;
3749 std::vector<TreePatternNode*> Variants;
3750 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
3751 DEBUG(errs() << "Dependent/multiply used variables: ");
3752 DEBUG(DumpDepVars(DepVars));
3753 DEBUG(errs() << "\n");
3754 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this,
3757 assert(!Variants.empty() && "Must create at least original variant!");
3758 Variants.erase(Variants.begin()); // Remove the original pattern.
3760 if (Variants.empty()) // No variants for this pattern.
3763 DEBUG(errs() << "FOUND VARIANTS OF: ";
3764 PatternsToMatch[i].getSrcPattern()->dump();
3767 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
3768 TreePatternNode *Variant = Variants[v];
3770 DEBUG(errs() << " VAR#" << v << ": ";
3774 // Scan to see if an instruction or explicit pattern already matches this.
3775 bool AlreadyExists = false;
3776 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
3777 // Skip if the top level predicates do not match.
3778 if (PatternsToMatch[i].getPredicates() !=
3779 PatternsToMatch[p].getPredicates())
3781 // Check to see if this variant already exists.
3782 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),
3784 DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
3785 AlreadyExists = true;
3789 // If we already have it, ignore the variant.
3790 if (AlreadyExists) continue;
3792 // Otherwise, add it to the list of patterns we have.
3793 PatternsToMatch.emplace_back(
3794 PatternsToMatch[i].getSrcRecord(), PatternsToMatch[i].getPredicates(),
3795 Variant, PatternsToMatch[i].getDstPattern(),
3796 PatternsToMatch[i].getDstRegs(),
3797 PatternsToMatch[i].getAddedComplexity(), Record::getNewUID());
3800 DEBUG(errs() << "\n");