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 (MVT::SimpleValueType VT : LegalTypes)
88 if (!Pred || Pred(VT))
89 TypeVec.push_back(VT);
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(), isInteger);
113 /// hasFloatingPointTypes - Return true if this TypeSet contains an fAny or
114 /// a floating point value type.
115 bool EEVT::TypeSet::hasFloatingPointTypes() const {
116 return std::any_of(TypeVec.begin(), TypeVec.end(), isFloatingPoint);
119 /// hasScalarTypes - Return true if this TypeSet contains a scalar value type.
120 bool EEVT::TypeSet::hasScalarTypes() const {
121 return std::any_of(TypeVec.begin(), TypeVec.end(), isScalar);
124 /// hasVectorTypes - Return true if this TypeSet contains a vAny or a vector
126 bool EEVT::TypeSet::hasVectorTypes() const {
127 return std::any_of(TypeVec.begin(), TypeVec.end(), isVector);
131 std::string EEVT::TypeSet::getName() const {
132 if (TypeVec.empty()) return "<empty>";
136 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i) {
137 std::string VTName = llvm::getEnumName(TypeVec[i]);
138 // Strip off MVT:: prefix if present.
139 if (VTName.substr(0,5) == "MVT::")
140 VTName = VTName.substr(5);
141 if (i) Result += ':';
145 if (TypeVec.size() == 1)
147 return "{" + Result + "}";
150 /// MergeInTypeInfo - This merges in type information from the specified
151 /// argument. If 'this' changes, it returns true. If the two types are
152 /// contradictory (e.g. merge f32 into i32) then this flags an error.
153 bool EEVT::TypeSet::MergeInTypeInfo(const EEVT::TypeSet &InVT, TreePattern &TP){
154 if (InVT.isCompletelyUnknown() || *this == InVT || TP.hasError())
157 if (isCompletelyUnknown()) {
162 assert(!TypeVec.empty() && !InVT.TypeVec.empty() && "No unknowns");
164 // Handle the abstract cases, seeing if we can resolve them better.
165 switch (TypeVec[0]) {
169 if (InVT.hasIntegerTypes()) {
170 EEVT::TypeSet InCopy(InVT);
171 InCopy.EnforceInteger(TP);
172 InCopy.EnforceScalar(TP);
174 if (InCopy.isConcrete()) {
175 // If the RHS has one integer type, upgrade iPTR to i32.
176 TypeVec[0] = InVT.TypeVec[0];
180 // If the input has multiple scalar integers, this doesn't add any info.
181 if (!InCopy.isCompletelyUnknown())
187 // If the input constraint is iAny/iPTR and this is an integer type list,
188 // remove non-integer types from the list.
189 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
191 bool MadeChange = EnforceInteger(TP);
193 // If we're merging in iPTR/iPTRAny and the node currently has a list of
194 // multiple different integer types, replace them with a single iPTR.
195 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
196 TypeVec.size() != 1) {
197 TypeVec.assign(1, InVT.TypeVec[0]);
204 // If this is a type list and the RHS is a typelist as well, eliminate entries
205 // from this list that aren't in the other one.
206 TypeSet InputSet(*this);
209 std::set_intersection(InputSet.TypeVec.begin(), InputSet.TypeVec.end(),
210 InVT.TypeVec.begin(), InVT.TypeVec.end(),
211 std::back_inserter(TypeVec));
213 // If the intersection is the same size as the original set then we're done.
214 if (TypeVec.size() == InputSet.TypeVec.size())
217 // If we removed all of our types, we have a type contradiction.
218 if (!TypeVec.empty())
221 // FIXME: Really want an SMLoc here!
222 TP.error("Type inference contradiction found, merging '" +
223 InVT.getName() + "' into '" + InputSet.getName() + "'");
227 /// EnforceInteger - Remove all non-integer types from this set.
228 bool EEVT::TypeSet::EnforceInteger(TreePattern &TP) {
231 // If we know nothing, then get the full set.
233 return FillWithPossibleTypes(TP, isInteger, "integer");
235 if (!hasFloatingPointTypes())
238 TypeSet InputSet(*this);
240 // Filter out all the fp types.
241 TypeVec.erase(std::remove_if(TypeVec.begin(), TypeVec.end(),
242 std::not1(std::ptr_fun(isInteger))),
245 if (TypeVec.empty()) {
246 TP.error("Type inference contradiction found, '" +
247 InputSet.getName() + "' needs to be integer");
253 /// EnforceFloatingPoint - Remove all integer types from this set.
254 bool EEVT::TypeSet::EnforceFloatingPoint(TreePattern &TP) {
257 // If we know nothing, then get the full set.
259 return FillWithPossibleTypes(TP, isFloatingPoint, "floating point");
261 if (!hasIntegerTypes())
264 TypeSet InputSet(*this);
266 // Filter out all the integer types.
267 TypeVec.erase(std::remove_if(TypeVec.begin(), TypeVec.end(),
268 std::not1(std::ptr_fun(isFloatingPoint))),
271 if (TypeVec.empty()) {
272 TP.error("Type inference contradiction found, '" +
273 InputSet.getName() + "' needs to be floating point");
279 /// EnforceScalar - Remove all vector types from this.
280 bool EEVT::TypeSet::EnforceScalar(TreePattern &TP) {
284 // If we know nothing, then get the full set.
286 return FillWithPossibleTypes(TP, isScalar, "scalar");
288 if (!hasVectorTypes())
291 TypeSet InputSet(*this);
293 // Filter out all the vector types.
294 TypeVec.erase(std::remove_if(TypeVec.begin(), TypeVec.end(),
295 std::not1(std::ptr_fun(isScalar))),
298 if (TypeVec.empty()) {
299 TP.error("Type inference contradiction found, '" +
300 InputSet.getName() + "' needs to be scalar");
306 /// EnforceVector - Remove all vector types from this.
307 bool EEVT::TypeSet::EnforceVector(TreePattern &TP) {
311 // If we know nothing, then get the full set.
313 return FillWithPossibleTypes(TP, isVector, "vector");
315 TypeSet InputSet(*this);
316 bool MadeChange = false;
318 // Filter out all the scalar types.
319 TypeVec.erase(std::remove_if(TypeVec.begin(), TypeVec.end(),
320 std::not1(std::ptr_fun(isVector))),
323 if (TypeVec.empty()) {
324 TP.error("Type inference contradiction found, '" +
325 InputSet.getName() + "' needs to be a vector");
333 /// EnforceSmallerThan - 'this' must be a smaller VT than Other. For vectors
334 /// this should be based on the element type. Update this and other based on
335 /// this information.
336 bool EEVT::TypeSet::EnforceSmallerThan(EEVT::TypeSet &Other, TreePattern &TP) {
340 // Both operands must be integer or FP, but we don't care which.
341 bool MadeChange = false;
343 if (isCompletelyUnknown())
344 MadeChange = FillWithPossibleTypes(TP);
346 if (Other.isCompletelyUnknown())
347 MadeChange = Other.FillWithPossibleTypes(TP);
349 // If one side is known to be integer or known to be FP but the other side has
350 // no information, get at least the type integrality info in there.
351 if (!hasFloatingPointTypes())
352 MadeChange |= Other.EnforceInteger(TP);
353 else if (!hasIntegerTypes())
354 MadeChange |= Other.EnforceFloatingPoint(TP);
355 if (!Other.hasFloatingPointTypes())
356 MadeChange |= EnforceInteger(TP);
357 else if (!Other.hasIntegerTypes())
358 MadeChange |= EnforceFloatingPoint(TP);
360 assert(!isCompletelyUnknown() && !Other.isCompletelyUnknown() &&
361 "Should have a type list now");
363 // If one contains vectors but the other doesn't pull vectors out.
364 if (!hasVectorTypes())
365 MadeChange |= Other.EnforceScalar(TP);
366 else if (!hasScalarTypes())
367 MadeChange |= Other.EnforceVector(TP);
368 if (!Other.hasVectorTypes())
369 MadeChange |= EnforceScalar(TP);
370 else if (!Other.hasScalarTypes())
371 MadeChange |= EnforceVector(TP);
373 // This code does not currently handle nodes which have multiple types,
374 // where some types are integer, and some are fp. Assert that this is not
376 assert(!(hasIntegerTypes() && hasFloatingPointTypes()) &&
377 !(Other.hasIntegerTypes() && Other.hasFloatingPointTypes()) &&
378 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
383 // Okay, find the smallest type from current set and remove anything the
384 // same or smaller from the other set. We need to ensure that the scalar
385 // type size is smaller than the scalar size of the smallest type. For
386 // vectors, we also need to make sure that the total size is no larger than
387 // the size of the smallest type.
389 TypeSet InputSet(Other);
390 MVT Smallest = TypeVec[0];
391 auto I = std::remove_if(Other.TypeVec.begin(), Other.TypeVec.end(),
392 [Smallest](MVT OtherVT) {
393 // Don't compare vector and non-vector types.
394 if (OtherVT.isVector() != Smallest.isVector())
396 // The getSizeInBits() check here is only needed for vectors, but is
397 // a subset of the scalar check for scalars so no need to qualify.
398 return OtherVT.getScalarSizeInBits() <= Smallest.getScalarSizeInBits()||
399 OtherVT.getSizeInBits() < Smallest.getSizeInBits();
401 MadeChange |= I != Other.TypeVec.end(); // If we're about to remove types.
402 Other.TypeVec.erase(I, Other.TypeVec.end());
404 if (Other.TypeVec.empty()) {
405 TP.error("Type inference contradiction found, '" + InputSet.getName() +
406 "' has nothing larger than '" + getName() +"'!");
411 // Okay, find the largest type from the other set and remove anything the
412 // same or smaller from the current set. We need to ensure that the scalar
413 // type size is larger than the scalar size of the largest type. For
414 // vectors, we also need to make sure that the total size is no smaller than
415 // the size of the largest type.
417 TypeSet InputSet(*this);
418 MVT Largest = Other.TypeVec[Other.TypeVec.size()-1];
419 auto I = std::remove_if(TypeVec.begin(), TypeVec.end(),
420 [Largest](MVT OtherVT) {
421 // Don't compare vector and non-vector types.
422 if (OtherVT.isVector() != Largest.isVector())
424 return OtherVT.getScalarSizeInBits() >= Largest.getScalarSizeInBits() ||
425 OtherVT.getSizeInBits() > Largest.getSizeInBits();
427 MadeChange |= I != TypeVec.end(); // If we're about to remove types.
428 TypeVec.erase(I, TypeVec.end());
430 if (TypeVec.empty()) {
431 TP.error("Type inference contradiction found, '" + InputSet.getName() +
432 "' has nothing smaller than '" + Other.getName() +"'!");
440 /// EnforceVectorEltTypeIs - 'this' is now constrained to be a vector type
441 /// whose element is specified by VTOperand.
442 bool EEVT::TypeSet::EnforceVectorEltTypeIs(MVT::SimpleValueType VT,
444 bool MadeChange = false;
446 MadeChange |= EnforceVector(TP);
448 TypeSet InputSet(*this);
450 // Filter out all the types which don't have the right element type.
451 auto I = std::remove_if(TypeVec.begin(), TypeVec.end(),
453 return VVT.getVectorElementType().SimpleTy != VT;
455 MadeChange |= I != TypeVec.end();
456 TypeVec.erase(I, TypeVec.end());
458 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
459 TP.error("Type inference contradiction found, forcing '" +
460 InputSet.getName() + "' to have a vector element of type " +
468 /// EnforceVectorEltTypeIs - 'this' is now constrained to be a vector type
469 /// whose element is specified by VTOperand.
470 bool EEVT::TypeSet::EnforceVectorEltTypeIs(EEVT::TypeSet &VTOperand,
475 // "This" must be a vector and "VTOperand" must be a scalar.
476 bool MadeChange = false;
477 MadeChange |= EnforceVector(TP);
478 MadeChange |= VTOperand.EnforceScalar(TP);
480 // If we know the vector type, it forces the scalar to agree.
482 MVT IVT = getConcrete();
483 IVT = IVT.getVectorElementType();
484 return MadeChange || VTOperand.MergeInTypeInfo(IVT.SimpleTy, TP);
487 // If the scalar type is known, filter out vector types whose element types
489 if (!VTOperand.isConcrete())
492 MVT::SimpleValueType VT = VTOperand.getConcrete();
494 MadeChange |= EnforceVectorEltTypeIs(VT, TP);
499 /// EnforceVectorSubVectorTypeIs - 'this' is now constrained to be a
500 /// vector type specified by VTOperand.
501 bool EEVT::TypeSet::EnforceVectorSubVectorTypeIs(EEVT::TypeSet &VTOperand,
506 // "This" must be a vector and "VTOperand" must be a vector.
507 bool MadeChange = false;
508 MadeChange |= EnforceVector(TP);
509 MadeChange |= VTOperand.EnforceVector(TP);
511 // If one side is known to be integer or known to be FP but the other side has
512 // no information, get at least the type integrality info in there.
513 if (!hasFloatingPointTypes())
514 MadeChange |= VTOperand.EnforceInteger(TP);
515 else if (!hasIntegerTypes())
516 MadeChange |= VTOperand.EnforceFloatingPoint(TP);
517 if (!VTOperand.hasFloatingPointTypes())
518 MadeChange |= EnforceInteger(TP);
519 else if (!VTOperand.hasIntegerTypes())
520 MadeChange |= EnforceFloatingPoint(TP);
522 assert(!isCompletelyUnknown() && !VTOperand.isCompletelyUnknown() &&
523 "Should have a type list now");
525 // If we know the vector type, it forces the scalar types to agree.
526 // Also force one vector to have more elements than the other.
528 MVT IVT = getConcrete();
529 unsigned NumElems = IVT.getVectorNumElements();
530 IVT = IVT.getVectorElementType();
532 EEVT::TypeSet EltTypeSet(IVT.SimpleTy, TP);
533 MadeChange |= VTOperand.EnforceVectorEltTypeIs(EltTypeSet, TP);
535 // Only keep types that have less elements than VTOperand.
536 TypeSet InputSet(VTOperand);
538 auto I = std::remove_if(VTOperand.TypeVec.begin(), VTOperand.TypeVec.end(),
539 [NumElems](MVT VVT) {
540 return VVT.getVectorNumElements() >= NumElems;
542 MadeChange |= I != VTOperand.TypeVec.end();
543 VTOperand.TypeVec.erase(I, VTOperand.TypeVec.end());
545 if (VTOperand.TypeVec.empty()) { // FIXME: Really want an SMLoc here!
546 TP.error("Type inference contradiction found, forcing '" +
547 InputSet.getName() + "' to have less vector elements than '" +
551 } else if (VTOperand.isConcrete()) {
552 MVT IVT = VTOperand.getConcrete();
553 unsigned NumElems = IVT.getVectorNumElements();
554 IVT = IVT.getVectorElementType();
556 EEVT::TypeSet EltTypeSet(IVT.SimpleTy, TP);
557 MadeChange |= EnforceVectorEltTypeIs(EltTypeSet, TP);
559 // Only keep types that have more elements than 'this'.
560 TypeSet InputSet(*this);
562 auto I = std::remove_if(TypeVec.begin(), TypeVec.end(),
563 [NumElems](MVT VVT) {
564 return VVT.getVectorNumElements() <= NumElems;
566 MadeChange |= I != TypeVec.end();
567 TypeVec.erase(I, TypeVec.end());
569 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
570 TP.error("Type inference contradiction found, forcing '" +
571 InputSet.getName() + "' to have more vector elements than '" +
572 VTOperand.getName() + "'");
580 /// EnforceVectorSameNumElts - 'this' is now constrained to
581 /// be a vector with same num elements as VTOperand.
582 bool EEVT::TypeSet::EnforceVectorSameNumElts(EEVT::TypeSet &VTOperand,
587 // "This" must be a vector and "VTOperand" must be a vector.
588 bool MadeChange = false;
589 MadeChange |= EnforceVector(TP);
590 MadeChange |= VTOperand.EnforceVector(TP);
592 // If we know one of the vector types, it forces the other type to agree.
594 MVT IVT = getConcrete();
595 unsigned NumElems = IVT.getVectorNumElements();
597 // Only keep types that have same elements as 'this'.
598 TypeSet InputSet(VTOperand);
600 auto I = std::remove_if(VTOperand.TypeVec.begin(), VTOperand.TypeVec.end(),
601 [NumElems](MVT VVT) {
602 return VVT.getVectorNumElements() != NumElems;
604 MadeChange |= I != VTOperand.TypeVec.end();
605 VTOperand.TypeVec.erase(I, VTOperand.TypeVec.end());
607 if (VTOperand.TypeVec.empty()) { // FIXME: Really want an SMLoc here!
608 TP.error("Type inference contradiction found, forcing '" +
609 InputSet.getName() + "' to have same number elements as '" +
613 } else if (VTOperand.isConcrete()) {
614 MVT IVT = VTOperand.getConcrete();
615 unsigned NumElems = IVT.getVectorNumElements();
617 // Only keep types that have same elements as VTOperand.
618 TypeSet InputSet(*this);
620 auto I = std::remove_if(TypeVec.begin(), TypeVec.end(),
621 [NumElems](MVT VVT) {
622 return VVT.getVectorNumElements() != NumElems;
624 MadeChange |= I != TypeVec.end();
625 TypeVec.erase(I, TypeVec.end());
627 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
628 TP.error("Type inference contradiction found, forcing '" +
629 InputSet.getName() + "' to have same number elements than '" +
630 VTOperand.getName() + "'");
638 /// EnforceSameSize - 'this' is now constrained to be same size as VTOperand.
639 bool EEVT::TypeSet::EnforceSameSize(EEVT::TypeSet &VTOperand,
644 bool MadeChange = false;
646 // If we know one of the types, it forces the other type agree.
648 MVT IVT = getConcrete();
649 unsigned Size = IVT.getSizeInBits();
651 // Only keep types that have the same size as 'this'.
652 TypeSet InputSet(VTOperand);
654 auto I = std::remove_if(VTOperand.TypeVec.begin(), VTOperand.TypeVec.end(),
656 return VT.getSizeInBits() != Size;
658 MadeChange |= I != VTOperand.TypeVec.end();
659 VTOperand.TypeVec.erase(I, VTOperand.TypeVec.end());
661 if (VTOperand.TypeVec.empty()) { // FIXME: Really want an SMLoc here!
662 TP.error("Type inference contradiction found, forcing '" +
663 InputSet.getName() + "' to have same size as '" +
667 } else if (VTOperand.isConcrete()) {
668 MVT IVT = VTOperand.getConcrete();
669 unsigned Size = IVT.getSizeInBits();
671 // Only keep types that have the same size as VTOperand.
672 TypeSet InputSet(*this);
674 auto I = std::remove_if(TypeVec.begin(), TypeVec.end(),
676 return VT.getSizeInBits() != Size;
678 MadeChange |= I != TypeVec.end();
679 TypeVec.erase(I, TypeVec.end());
681 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
682 TP.error("Type inference contradiction found, forcing '" +
683 InputSet.getName() + "' to have same size as '" +
684 VTOperand.getName() + "'");
692 //===----------------------------------------------------------------------===//
693 // Helpers for working with extended types.
695 /// Dependent variable map for CodeGenDAGPattern variant generation
696 typedef std::map<std::string, int> DepVarMap;
698 static void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
700 if (isa<DefInit>(N->getLeafValue()))
701 DepMap[N->getName()]++;
703 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
704 FindDepVarsOf(N->getChild(i), DepMap);
708 /// Find dependent variables within child patterns
709 static void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
711 FindDepVarsOf(N, depcounts);
712 for (const std::pair<std::string, int> &Pair : depcounts) {
714 DepVars.insert(Pair.first);
719 /// Dump the dependent variable set:
720 static void DumpDepVars(MultipleUseVarSet &DepVars) {
721 if (DepVars.empty()) {
722 DEBUG(errs() << "<empty set>");
724 DEBUG(errs() << "[ ");
725 for (const std::string &DepVar : DepVars) {
726 DEBUG(errs() << DepVar << " ");
728 DEBUG(errs() << "]");
734 //===----------------------------------------------------------------------===//
735 // TreePredicateFn Implementation
736 //===----------------------------------------------------------------------===//
738 /// TreePredicateFn constructor. Here 'N' is a subclass of PatFrag.
739 TreePredicateFn::TreePredicateFn(TreePattern *N) : PatFragRec(N) {
740 assert((getPredCode().empty() || getImmCode().empty()) &&
741 ".td file corrupt: can't have a node predicate *and* an imm predicate");
744 std::string TreePredicateFn::getPredCode() const {
745 return PatFragRec->getRecord()->getValueAsString("PredicateCode");
748 std::string TreePredicateFn::getImmCode() const {
749 return PatFragRec->getRecord()->getValueAsString("ImmediateCode");
753 /// isAlwaysTrue - Return true if this is a noop predicate.
754 bool TreePredicateFn::isAlwaysTrue() const {
755 return getPredCode().empty() && getImmCode().empty();
758 /// Return the name to use in the generated code to reference this, this is
759 /// "Predicate_foo" if from a pattern fragment "foo".
760 std::string TreePredicateFn::getFnName() const {
761 return "Predicate_" + PatFragRec->getRecord()->getName();
764 /// getCodeToRunOnSDNode - Return the code for the function body that
765 /// evaluates this predicate. The argument is expected to be in "Node",
766 /// not N. This handles casting and conversion to a concrete node type as
768 std::string TreePredicateFn::getCodeToRunOnSDNode() const {
769 // Handle immediate predicates first.
770 std::string ImmCode = getImmCode();
771 if (!ImmCode.empty()) {
773 " int64_t Imm = cast<ConstantSDNode>(Node)->getSExtValue();\n";
774 return Result + ImmCode;
777 // Handle arbitrary node predicates.
778 assert(!getPredCode().empty() && "Don't have any predicate code!");
779 std::string ClassName;
780 if (PatFragRec->getOnlyTree()->isLeaf())
781 ClassName = "SDNode";
783 Record *Op = PatFragRec->getOnlyTree()->getOperator();
784 ClassName = PatFragRec->getDAGPatterns().getSDNodeInfo(Op).getSDClassName();
787 if (ClassName == "SDNode")
788 Result = " SDNode *N = Node;\n";
790 Result = " auto *N = cast<" + ClassName + ">(Node);\n";
792 return Result + getPredCode();
795 //===----------------------------------------------------------------------===//
796 // PatternToMatch implementation
800 /// getPatternSize - Return the 'size' of this pattern. We want to match large
801 /// patterns before small ones. This is used to determine the size of a
803 static unsigned getPatternSize(const TreePatternNode *P,
804 const CodeGenDAGPatterns &CGP) {
805 unsigned Size = 3; // The node itself.
806 // If the root node is a ConstantSDNode, increases its size.
807 // e.g. (set R32:$dst, 0).
808 if (P->isLeaf() && isa<IntInit>(P->getLeafValue()))
811 // FIXME: This is a hack to statically increase the priority of patterns
812 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
813 // Later we can allow complexity / cost for each pattern to be (optionally)
814 // specified. To get best possible pattern match we'll need to dynamically
815 // calculate the complexity of all patterns a dag can potentially map to.
816 const ComplexPattern *AM = P->getComplexPatternInfo(CGP);
818 Size += AM->getNumOperands() * 3;
820 // We don't want to count any children twice, so return early.
824 // If this node has some predicate function that must match, it adds to the
825 // complexity of this node.
826 if (!P->getPredicateFns().empty())
829 // Count children in the count if they are also nodes.
830 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
831 TreePatternNode *Child = P->getChild(i);
832 if (!Child->isLeaf() && Child->getNumTypes() &&
833 Child->getType(0) != MVT::Other)
834 Size += getPatternSize(Child, CGP);
835 else if (Child->isLeaf()) {
836 if (isa<IntInit>(Child->getLeafValue()))
837 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
838 else if (Child->getComplexPatternInfo(CGP))
839 Size += getPatternSize(Child, CGP);
840 else if (!Child->getPredicateFns().empty())
848 /// Compute the complexity metric for the input pattern. This roughly
849 /// corresponds to the number of nodes that are covered.
851 getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
852 return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();
856 /// getPredicateCheck - Return a single string containing all of this
857 /// pattern's predicates concatenated with "&&" operators.
859 std::string PatternToMatch::getPredicateCheck() const {
860 SmallVector<Record *, 4> PredicateRecs;
861 for (Init *I : Predicates->getValues()) {
862 if (DefInit *Pred = dyn_cast<DefInit>(I)) {
863 Record *Def = Pred->getDef();
864 if (!Def->isSubClassOf("Predicate")) {
868 llvm_unreachable("Unknown predicate type!");
870 PredicateRecs.push_back(Def);
873 // Sort so that different orders get canonicalized to the same string.
874 std::sort(PredicateRecs.begin(), PredicateRecs.end(), LessRecord());
876 std::string PredicateCheck;
877 for (Record *Pred : PredicateRecs) {
878 if (!PredicateCheck.empty())
879 PredicateCheck += " && ";
880 PredicateCheck += "(" + Pred->getValueAsString("CondString") + ")";
883 return PredicateCheck;
886 //===----------------------------------------------------------------------===//
887 // SDTypeConstraint implementation
890 SDTypeConstraint::SDTypeConstraint(Record *R) {
891 OperandNo = R->getValueAsInt("OperandNum");
893 if (R->isSubClassOf("SDTCisVT")) {
894 ConstraintType = SDTCisVT;
895 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
896 if (x.SDTCisVT_Info.VT == MVT::isVoid)
897 PrintFatalError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
899 } else if (R->isSubClassOf("SDTCisPtrTy")) {
900 ConstraintType = SDTCisPtrTy;
901 } else if (R->isSubClassOf("SDTCisInt")) {
902 ConstraintType = SDTCisInt;
903 } else if (R->isSubClassOf("SDTCisFP")) {
904 ConstraintType = SDTCisFP;
905 } else if (R->isSubClassOf("SDTCisVec")) {
906 ConstraintType = SDTCisVec;
907 } else if (R->isSubClassOf("SDTCisSameAs")) {
908 ConstraintType = SDTCisSameAs;
909 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
910 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
911 ConstraintType = SDTCisVTSmallerThanOp;
912 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
913 R->getValueAsInt("OtherOperandNum");
914 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
915 ConstraintType = SDTCisOpSmallerThanOp;
916 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
917 R->getValueAsInt("BigOperandNum");
918 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
919 ConstraintType = SDTCisEltOfVec;
920 x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
921 } else if (R->isSubClassOf("SDTCisSubVecOfVec")) {
922 ConstraintType = SDTCisSubVecOfVec;
923 x.SDTCisSubVecOfVec_Info.OtherOperandNum =
924 R->getValueAsInt("OtherOpNum");
925 } else if (R->isSubClassOf("SDTCVecEltisVT")) {
926 ConstraintType = SDTCVecEltisVT;
927 x.SDTCVecEltisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
928 if (MVT(x.SDTCVecEltisVT_Info.VT).isVector())
929 PrintFatalError(R->getLoc(), "Cannot use vector type as SDTCVecEltisVT");
930 if (!MVT(x.SDTCVecEltisVT_Info.VT).isInteger() &&
931 !MVT(x.SDTCVecEltisVT_Info.VT).isFloatingPoint())
932 PrintFatalError(R->getLoc(), "Must use integer or floating point type "
933 "as SDTCVecEltisVT");
934 } else if (R->isSubClassOf("SDTCisSameNumEltsAs")) {
935 ConstraintType = SDTCisSameNumEltsAs;
936 x.SDTCisSameNumEltsAs_Info.OtherOperandNum =
937 R->getValueAsInt("OtherOperandNum");
938 } else if (R->isSubClassOf("SDTCisSameSizeAs")) {
939 ConstraintType = SDTCisSameSizeAs;
940 x.SDTCisSameSizeAs_Info.OtherOperandNum =
941 R->getValueAsInt("OtherOperandNum");
943 PrintFatalError("Unrecognized SDTypeConstraint '" + R->getName() + "'!\n");
947 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
948 /// N, and the result number in ResNo.
949 static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
950 const SDNodeInfo &NodeInfo,
952 unsigned NumResults = NodeInfo.getNumResults();
953 if (OpNo < NumResults) {
960 if (OpNo >= N->getNumChildren()) {
962 raw_string_ostream OS(S);
963 OS << "Invalid operand number in type constraint "
964 << (OpNo+NumResults) << " ";
966 PrintFatalError(OS.str());
969 return N->getChild(OpNo);
972 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
973 /// constraint to the nodes operands. This returns true if it makes a
974 /// change, false otherwise. If a type contradiction is found, flag an error.
975 bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
976 const SDNodeInfo &NodeInfo,
977 TreePattern &TP) const {
981 unsigned ResNo = 0; // The result number being referenced.
982 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
984 switch (ConstraintType) {
986 // Operand must be a particular type.
987 return NodeToApply->UpdateNodeType(ResNo, x.SDTCisVT_Info.VT, TP);
989 // Operand must be same as target pointer type.
990 return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
992 // Require it to be one of the legal integer VTs.
993 return NodeToApply->getExtType(ResNo).EnforceInteger(TP);
995 // Require it to be one of the legal fp VTs.
996 return NodeToApply->getExtType(ResNo).EnforceFloatingPoint(TP);
998 // Require it to be one of the legal vector VTs.
999 return NodeToApply->getExtType(ResNo).EnforceVector(TP);
1000 case SDTCisSameAs: {
1001 unsigned OResNo = 0;
1002 TreePatternNode *OtherNode =
1003 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
1004 return NodeToApply->UpdateNodeType(ResNo, OtherNode->getExtType(OResNo),TP)|
1005 OtherNode->UpdateNodeType(OResNo,NodeToApply->getExtType(ResNo),TP);
1007 case SDTCisVTSmallerThanOp: {
1008 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
1009 // have an integer type that is smaller than the VT.
1010 if (!NodeToApply->isLeaf() ||
1011 !isa<DefInit>(NodeToApply->getLeafValue()) ||
1012 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
1013 ->isSubClassOf("ValueType")) {
1014 TP.error(N->getOperator()->getName() + " expects a VT operand!");
1017 MVT::SimpleValueType VT =
1018 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
1020 EEVT::TypeSet TypeListTmp(VT, TP);
1022 unsigned OResNo = 0;
1023 TreePatternNode *OtherNode =
1024 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
1027 return TypeListTmp.EnforceSmallerThan(OtherNode->getExtType(OResNo), TP);
1029 case SDTCisOpSmallerThanOp: {
1030 unsigned BResNo = 0;
1031 TreePatternNode *BigOperand =
1032 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
1034 return NodeToApply->getExtType(ResNo).
1035 EnforceSmallerThan(BigOperand->getExtType(BResNo), TP);
1037 case SDTCisEltOfVec: {
1038 unsigned VResNo = 0;
1039 TreePatternNode *VecOperand =
1040 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
1043 // Filter vector types out of VecOperand that don't have the right element
1045 return VecOperand->getExtType(VResNo).
1046 EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), TP);
1048 case SDTCisSubVecOfVec: {
1049 unsigned VResNo = 0;
1050 TreePatternNode *BigVecOperand =
1051 getOperandNum(x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo,
1054 // Filter vector types out of BigVecOperand that don't have the
1055 // right subvector type.
1056 return BigVecOperand->getExtType(VResNo).
1057 EnforceVectorSubVectorTypeIs(NodeToApply->getExtType(ResNo), TP);
1059 case SDTCVecEltisVT: {
1060 return NodeToApply->getExtType(ResNo).
1061 EnforceVectorEltTypeIs(x.SDTCVecEltisVT_Info.VT, TP);
1063 case SDTCisSameNumEltsAs: {
1064 unsigned OResNo = 0;
1065 TreePatternNode *OtherNode =
1066 getOperandNum(x.SDTCisSameNumEltsAs_Info.OtherOperandNum,
1067 N, NodeInfo, OResNo);
1068 return OtherNode->getExtType(OResNo).
1069 EnforceVectorSameNumElts(NodeToApply->getExtType(ResNo), TP);
1071 case SDTCisSameSizeAs: {
1072 unsigned OResNo = 0;
1073 TreePatternNode *OtherNode =
1074 getOperandNum(x.SDTCisSameSizeAs_Info.OtherOperandNum,
1075 N, NodeInfo, OResNo);
1076 return OtherNode->getExtType(OResNo).
1077 EnforceSameSize(NodeToApply->getExtType(ResNo), TP);
1080 llvm_unreachable("Invalid ConstraintType!");
1083 // Update the node type to match an instruction operand or result as specified
1084 // in the ins or outs lists on the instruction definition. Return true if the
1085 // type was actually changed.
1086 bool TreePatternNode::UpdateNodeTypeFromInst(unsigned ResNo,
1089 // The 'unknown' operand indicates that types should be inferred from the
1091 if (Operand->isSubClassOf("unknown_class"))
1094 // The Operand class specifies a type directly.
1095 if (Operand->isSubClassOf("Operand"))
1096 return UpdateNodeType(ResNo, getValueType(Operand->getValueAsDef("Type")),
1099 // PointerLikeRegClass has a type that is determined at runtime.
1100 if (Operand->isSubClassOf("PointerLikeRegClass"))
1101 return UpdateNodeType(ResNo, MVT::iPTR, TP);
1103 // Both RegisterClass and RegisterOperand operands derive their types from a
1104 // register class def.
1105 Record *RC = nullptr;
1106 if (Operand->isSubClassOf("RegisterClass"))
1108 else if (Operand->isSubClassOf("RegisterOperand"))
1109 RC = Operand->getValueAsDef("RegClass");
1111 assert(RC && "Unknown operand type");
1112 CodeGenTarget &Tgt = TP.getDAGPatterns().getTargetInfo();
1113 return UpdateNodeType(ResNo, Tgt.getRegisterClass(RC).getValueTypes(), TP);
1117 //===----------------------------------------------------------------------===//
1118 // SDNodeInfo implementation
1120 SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
1121 EnumName = R->getValueAsString("Opcode");
1122 SDClassName = R->getValueAsString("SDClass");
1123 Record *TypeProfile = R->getValueAsDef("TypeProfile");
1124 NumResults = TypeProfile->getValueAsInt("NumResults");
1125 NumOperands = TypeProfile->getValueAsInt("NumOperands");
1127 // Parse the properties.
1129 for (Record *Property : R->getValueAsListOfDefs("Properties")) {
1130 if (Property->getName() == "SDNPCommutative") {
1131 Properties |= 1 << SDNPCommutative;
1132 } else if (Property->getName() == "SDNPAssociative") {
1133 Properties |= 1 << SDNPAssociative;
1134 } else if (Property->getName() == "SDNPHasChain") {
1135 Properties |= 1 << SDNPHasChain;
1136 } else if (Property->getName() == "SDNPOutGlue") {
1137 Properties |= 1 << SDNPOutGlue;
1138 } else if (Property->getName() == "SDNPInGlue") {
1139 Properties |= 1 << SDNPInGlue;
1140 } else if (Property->getName() == "SDNPOptInGlue") {
1141 Properties |= 1 << SDNPOptInGlue;
1142 } else if (Property->getName() == "SDNPMayStore") {
1143 Properties |= 1 << SDNPMayStore;
1144 } else if (Property->getName() == "SDNPMayLoad") {
1145 Properties |= 1 << SDNPMayLoad;
1146 } else if (Property->getName() == "SDNPSideEffect") {
1147 Properties |= 1 << SDNPSideEffect;
1148 } else if (Property->getName() == "SDNPMemOperand") {
1149 Properties |= 1 << SDNPMemOperand;
1150 } else if (Property->getName() == "SDNPVariadic") {
1151 Properties |= 1 << SDNPVariadic;
1153 PrintFatalError("Unknown SD Node property '" +
1154 Property->getName() + "' on node '" +
1155 R->getName() + "'!");
1160 // Parse the type constraints.
1161 std::vector<Record*> ConstraintList =
1162 TypeProfile->getValueAsListOfDefs("Constraints");
1163 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
1166 /// getKnownType - If the type constraints on this node imply a fixed type
1167 /// (e.g. all stores return void, etc), then return it as an
1168 /// MVT::SimpleValueType. Otherwise, return EEVT::Other.
1169 MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
1170 unsigned NumResults = getNumResults();
1171 assert(NumResults <= 1 &&
1172 "We only work with nodes with zero or one result so far!");
1173 assert(ResNo == 0 && "Only handles single result nodes so far");
1175 for (const SDTypeConstraint &Constraint : TypeConstraints) {
1176 // Make sure that this applies to the correct node result.
1177 if (Constraint.OperandNo >= NumResults) // FIXME: need value #
1180 switch (Constraint.ConstraintType) {
1182 case SDTypeConstraint::SDTCisVT:
1183 return Constraint.x.SDTCisVT_Info.VT;
1184 case SDTypeConstraint::SDTCisPtrTy:
1191 //===----------------------------------------------------------------------===//
1192 // TreePatternNode implementation
1195 TreePatternNode::~TreePatternNode() {
1196 #if 0 // FIXME: implement refcounted tree nodes!
1197 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1202 static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
1203 if (Operator->getName() == "set" ||
1204 Operator->getName() == "implicit")
1205 return 0; // All return nothing.
1207 if (Operator->isSubClassOf("Intrinsic"))
1208 return CDP.getIntrinsic(Operator).IS.RetVTs.size();
1210 if (Operator->isSubClassOf("SDNode"))
1211 return CDP.getSDNodeInfo(Operator).getNumResults();
1213 if (Operator->isSubClassOf("PatFrag")) {
1214 // If we've already parsed this pattern fragment, get it. Otherwise, handle
1215 // the forward reference case where one pattern fragment references another
1216 // before it is processed.
1217 if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator))
1218 return PFRec->getOnlyTree()->getNumTypes();
1220 // Get the result tree.
1221 DagInit *Tree = Operator->getValueAsDag("Fragment");
1222 Record *Op = nullptr;
1224 if (DefInit *DI = dyn_cast<DefInit>(Tree->getOperator()))
1226 assert(Op && "Invalid Fragment");
1227 return GetNumNodeResults(Op, CDP);
1230 if (Operator->isSubClassOf("Instruction")) {
1231 CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
1233 unsigned NumDefsToAdd = InstInfo.Operands.NumDefs;
1235 // Subtract any defaulted outputs.
1236 for (unsigned i = 0; i != InstInfo.Operands.NumDefs; ++i) {
1237 Record *OperandNode = InstInfo.Operands[i].Rec;
1239 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
1240 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1244 // Add on one implicit def if it has a resolvable type.
1245 if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
1247 return NumDefsToAdd;
1250 if (Operator->isSubClassOf("SDNodeXForm"))
1251 return 1; // FIXME: Generalize SDNodeXForm
1253 if (Operator->isSubClassOf("ValueType"))
1254 return 1; // A type-cast of one result.
1256 if (Operator->isSubClassOf("ComplexPattern"))
1260 PrintFatalError("Unhandled node in GetNumNodeResults");
1263 void TreePatternNode::print(raw_ostream &OS) const {
1265 OS << *getLeafValue();
1267 OS << '(' << getOperator()->getName();
1269 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1270 OS << ':' << getExtType(i).getName();
1273 if (getNumChildren() != 0) {
1275 getChild(0)->print(OS);
1276 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
1278 getChild(i)->print(OS);
1284 for (const TreePredicateFn &Pred : PredicateFns)
1285 OS << "<<P:" << Pred.getFnName() << ">>";
1287 OS << "<<X:" << TransformFn->getName() << ">>";
1288 if (!getName().empty())
1289 OS << ":$" << getName();
1292 void TreePatternNode::dump() const {
1296 /// isIsomorphicTo - Return true if this node is recursively
1297 /// isomorphic to the specified node. For this comparison, the node's
1298 /// entire state is considered. The assigned name is ignored, since
1299 /// nodes with differing names are considered isomorphic. However, if
1300 /// the assigned name is present in the dependent variable set, then
1301 /// the assigned name is considered significant and the node is
1302 /// isomorphic if the names match.
1303 bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
1304 const MultipleUseVarSet &DepVars) const {
1305 if (N == this) return true;
1306 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
1307 getPredicateFns() != N->getPredicateFns() ||
1308 getTransformFn() != N->getTransformFn())
1312 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
1313 if (DefInit *NDI = dyn_cast<DefInit>(N->getLeafValue())) {
1314 return ((DI->getDef() == NDI->getDef())
1315 && (DepVars.find(getName()) == DepVars.end()
1316 || getName() == N->getName()));
1319 return getLeafValue() == N->getLeafValue();
1322 if (N->getOperator() != getOperator() ||
1323 N->getNumChildren() != getNumChildren()) return false;
1324 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1325 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
1330 /// clone - Make a copy of this tree and all of its children.
1332 TreePatternNode *TreePatternNode::clone() const {
1333 TreePatternNode *New;
1335 New = new TreePatternNode(getLeafValue(), getNumTypes());
1337 std::vector<TreePatternNode*> CChildren;
1338 CChildren.reserve(Children.size());
1339 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1340 CChildren.push_back(getChild(i)->clone());
1341 New = new TreePatternNode(getOperator(), CChildren, getNumTypes());
1343 New->setName(getName());
1345 New->setPredicateFns(getPredicateFns());
1346 New->setTransformFn(getTransformFn());
1350 /// RemoveAllTypes - Recursively strip all the types of this tree.
1351 void TreePatternNode::RemoveAllTypes() {
1352 // Reset to unknown type.
1353 std::fill(Types.begin(), Types.end(), EEVT::TypeSet());
1354 if (isLeaf()) return;
1355 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1356 getChild(i)->RemoveAllTypes();
1360 /// SubstituteFormalArguments - Replace the formal arguments in this tree
1361 /// with actual values specified by ArgMap.
1362 void TreePatternNode::
1363 SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
1364 if (isLeaf()) return;
1366 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1367 TreePatternNode *Child = getChild(i);
1368 if (Child->isLeaf()) {
1369 Init *Val = Child->getLeafValue();
1370 // Note that, when substituting into an output pattern, Val might be an
1372 if (isa<UnsetInit>(Val) || (isa<DefInit>(Val) &&
1373 cast<DefInit>(Val)->getDef()->getName() == "node")) {
1374 // We found a use of a formal argument, replace it with its value.
1375 TreePatternNode *NewChild = ArgMap[Child->getName()];
1376 assert(NewChild && "Couldn't find formal argument!");
1377 assert((Child->getPredicateFns().empty() ||
1378 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1379 "Non-empty child predicate clobbered!");
1380 setChild(i, NewChild);
1383 getChild(i)->SubstituteFormalArguments(ArgMap);
1389 /// InlinePatternFragments - If this pattern refers to any pattern
1390 /// fragments, inline them into place, giving us a pattern without any
1391 /// PatFrag references.
1392 TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
1397 return this; // nothing to do.
1398 Record *Op = getOperator();
1400 if (!Op->isSubClassOf("PatFrag")) {
1401 // Just recursively inline children nodes.
1402 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1403 TreePatternNode *Child = getChild(i);
1404 TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
1406 assert((Child->getPredicateFns().empty() ||
1407 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1408 "Non-empty child predicate clobbered!");
1410 setChild(i, NewChild);
1415 // Otherwise, we found a reference to a fragment. First, look up its
1416 // TreePattern record.
1417 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
1419 // Verify that we are passing the right number of operands.
1420 if (Frag->getNumArgs() != Children.size()) {
1421 TP.error("'" + Op->getName() + "' fragment requires " +
1422 utostr(Frag->getNumArgs()) + " operands!");
1426 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
1428 TreePredicateFn PredFn(Frag);
1429 if (!PredFn.isAlwaysTrue())
1430 FragTree->addPredicateFn(PredFn);
1432 // Resolve formal arguments to their actual value.
1433 if (Frag->getNumArgs()) {
1434 // Compute the map of formal to actual arguments.
1435 std::map<std::string, TreePatternNode*> ArgMap;
1436 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
1437 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
1439 FragTree->SubstituteFormalArguments(ArgMap);
1442 FragTree->setName(getName());
1443 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1444 FragTree->UpdateNodeType(i, getExtType(i), TP);
1446 // Transfer in the old predicates.
1447 for (const TreePredicateFn &Pred : getPredicateFns())
1448 FragTree->addPredicateFn(Pred);
1450 // Get a new copy of this fragment to stitch into here.
1451 //delete this; // FIXME: implement refcounting!
1453 // The fragment we inlined could have recursive inlining that is needed. See
1454 // if there are any pattern fragments in it and inline them as needed.
1455 return FragTree->InlinePatternFragments(TP);
1458 /// getImplicitType - Check to see if the specified record has an implicit
1459 /// type which should be applied to it. This will infer the type of register
1460 /// references from the register file information, for example.
1462 /// When Unnamed is set, return the type of a DAG operand with no name, such as
1463 /// the F8RC register class argument in:
1465 /// (COPY_TO_REGCLASS GPR:$src, F8RC)
1467 /// When Unnamed is false, return the type of a named DAG operand such as the
1468 /// GPR:$src operand above.
1470 static EEVT::TypeSet getImplicitType(Record *R, unsigned ResNo,
1474 // Check to see if this is a register operand.
1475 if (R->isSubClassOf("RegisterOperand")) {
1476 assert(ResNo == 0 && "Regoperand ref only has one result!");
1478 return EEVT::TypeSet(); // Unknown.
1479 Record *RegClass = R->getValueAsDef("RegClass");
1480 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1481 return EEVT::TypeSet(T.getRegisterClass(RegClass).getValueTypes());
1484 // Check to see if this is a register or a register class.
1485 if (R->isSubClassOf("RegisterClass")) {
1486 assert(ResNo == 0 && "Regclass ref only has one result!");
1487 // An unnamed register class represents itself as an i32 immediate, for
1488 // example on a COPY_TO_REGCLASS instruction.
1490 return EEVT::TypeSet(MVT::i32, TP);
1492 // In a named operand, the register class provides the possible set of
1495 return EEVT::TypeSet(); // Unknown.
1496 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1497 return EEVT::TypeSet(T.getRegisterClass(R).getValueTypes());
1500 if (R->isSubClassOf("PatFrag")) {
1501 assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
1502 // Pattern fragment types will be resolved when they are inlined.
1503 return EEVT::TypeSet(); // Unknown.
1506 if (R->isSubClassOf("Register")) {
1507 assert(ResNo == 0 && "Registers only produce one result!");
1509 return EEVT::TypeSet(); // Unknown.
1510 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1511 return EEVT::TypeSet(T.getRegisterVTs(R));
1514 if (R->isSubClassOf("SubRegIndex")) {
1515 assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
1516 return EEVT::TypeSet(MVT::i32, TP);
1519 if (R->isSubClassOf("ValueType")) {
1520 assert(ResNo == 0 && "This node only has one result!");
1521 // An unnamed VTSDNode represents itself as an MVT::Other immediate.
1523 // (sext_inreg GPR:$src, i16)
1526 return EEVT::TypeSet(MVT::Other, TP);
1527 // With a name, the ValueType simply provides the type of the named
1530 // (sext_inreg i32:$src, i16)
1533 return EEVT::TypeSet(); // Unknown.
1534 return EEVT::TypeSet(getValueType(R), TP);
1537 if (R->isSubClassOf("CondCode")) {
1538 assert(ResNo == 0 && "This node only has one result!");
1539 // Using a CondCodeSDNode.
1540 return EEVT::TypeSet(MVT::Other, TP);
1543 if (R->isSubClassOf("ComplexPattern")) {
1544 assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
1546 return EEVT::TypeSet(); // Unknown.
1547 return EEVT::TypeSet(TP.getDAGPatterns().getComplexPattern(R).getValueType(),
1550 if (R->isSubClassOf("PointerLikeRegClass")) {
1551 assert(ResNo == 0 && "Regclass can only have one result!");
1552 return EEVT::TypeSet(MVT::iPTR, TP);
1555 if (R->getName() == "node" || R->getName() == "srcvalue" ||
1556 R->getName() == "zero_reg") {
1558 return EEVT::TypeSet(); // Unknown.
1561 if (R->isSubClassOf("Operand"))
1562 return EEVT::TypeSet(getValueType(R->getValueAsDef("Type")));
1564 TP.error("Unknown node flavor used in pattern: " + R->getName());
1565 return EEVT::TypeSet(MVT::Other, TP);
1569 /// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
1570 /// CodeGenIntrinsic information for it, otherwise return a null pointer.
1571 const CodeGenIntrinsic *TreePatternNode::
1572 getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
1573 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
1574 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
1575 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
1578 unsigned IID = cast<IntInit>(getChild(0)->getLeafValue())->getValue();
1579 return &CDP.getIntrinsicInfo(IID);
1582 /// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
1583 /// return the ComplexPattern information, otherwise return null.
1584 const ComplexPattern *
1585 TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
1588 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
1593 Rec = getOperator();
1595 if (!Rec->isSubClassOf("ComplexPattern"))
1597 return &CGP.getComplexPattern(Rec);
1600 unsigned TreePatternNode::getNumMIResults(const CodeGenDAGPatterns &CGP) const {
1601 // A ComplexPattern specifically declares how many results it fills in.
1602 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1603 return CP->getNumOperands();
1605 // If MIOperandInfo is specified, that gives the count.
1607 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
1608 if (DI && DI->getDef()->isSubClassOf("Operand")) {
1609 DagInit *MIOps = DI->getDef()->getValueAsDag("MIOperandInfo");
1610 if (MIOps->getNumArgs())
1611 return MIOps->getNumArgs();
1615 // Otherwise there is just one result.
1619 /// NodeHasProperty - Return true if this node has the specified property.
1620 bool TreePatternNode::NodeHasProperty(SDNP Property,
1621 const CodeGenDAGPatterns &CGP) const {
1623 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1624 return CP->hasProperty(Property);
1628 Record *Operator = getOperator();
1629 if (!Operator->isSubClassOf("SDNode")) return false;
1631 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
1637 /// TreeHasProperty - Return true if any node in this tree has the specified
1639 bool TreePatternNode::TreeHasProperty(SDNP Property,
1640 const CodeGenDAGPatterns &CGP) const {
1641 if (NodeHasProperty(Property, CGP))
1643 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1644 if (getChild(i)->TreeHasProperty(Property, CGP))
1649 /// isCommutativeIntrinsic - Return true if the node corresponds to a
1650 /// commutative intrinsic.
1652 TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
1653 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
1654 return Int->isCommutative;
1658 static bool isOperandClass(const TreePatternNode *N, StringRef Class) {
1660 return N->getOperator()->isSubClassOf(Class);
1662 DefInit *DI = dyn_cast<DefInit>(N->getLeafValue());
1663 if (DI && DI->getDef()->isSubClassOf(Class))
1669 static void emitTooManyOperandsError(TreePattern &TP,
1673 TP.error("Instruction '" + InstName + "' was provided " + Twine(Actual) +
1674 " operands but expected only " + Twine(Expected) + "!");
1677 static void emitTooFewOperandsError(TreePattern &TP,
1680 TP.error("Instruction '" + InstName +
1681 "' expects more than the provided " + Twine(Actual) + " operands!");
1684 /// ApplyTypeConstraints - Apply all of the type constraints relevant to
1685 /// this node and its children in the tree. This returns true if it makes a
1686 /// change, false otherwise. If a type contradiction is found, flag an error.
1687 bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
1691 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
1693 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
1694 // If it's a regclass or something else known, include the type.
1695 bool MadeChange = false;
1696 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1697 MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
1699 !hasName(), TP), TP);
1703 if (IntInit *II = dyn_cast<IntInit>(getLeafValue())) {
1704 assert(Types.size() == 1 && "Invalid IntInit");
1706 // Int inits are always integers. :)
1707 bool MadeChange = Types[0].EnforceInteger(TP);
1709 if (!Types[0].isConcrete())
1712 MVT::SimpleValueType VT = getType(0);
1713 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
1716 unsigned Size = MVT(VT).getSizeInBits();
1717 // Make sure that the value is representable for this type.
1718 if (Size >= 32) return MadeChange;
1720 // Check that the value doesn't use more bits than we have. It must either
1721 // be a sign- or zero-extended equivalent of the original.
1722 int64_t SignBitAndAbove = II->getValue() >> (Size - 1);
1723 if (SignBitAndAbove == -1 || SignBitAndAbove == 0 || SignBitAndAbove == 1)
1726 TP.error("Integer value '" + itostr(II->getValue()) +
1727 "' is out of range for type '" + getEnumName(getType(0)) + "'!");
1733 // special handling for set, which isn't really an SDNode.
1734 if (getOperator()->getName() == "set") {
1735 assert(getNumTypes() == 0 && "Set doesn't produce a value");
1736 assert(getNumChildren() >= 2 && "Missing RHS of a set?");
1737 unsigned NC = getNumChildren();
1739 TreePatternNode *SetVal = getChild(NC-1);
1740 bool MadeChange = SetVal->ApplyTypeConstraints(TP, NotRegisters);
1742 for (unsigned i = 0; i < NC-1; ++i) {
1743 TreePatternNode *Child = getChild(i);
1744 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
1746 // Types of operands must match.
1747 MadeChange |= Child->UpdateNodeType(0, SetVal->getExtType(i), TP);
1748 MadeChange |= SetVal->UpdateNodeType(i, Child->getExtType(0), TP);
1753 if (getOperator()->getName() == "implicit") {
1754 assert(getNumTypes() == 0 && "Node doesn't produce a value");
1756 bool MadeChange = false;
1757 for (unsigned i = 0; i < getNumChildren(); ++i)
1758 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1762 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
1763 bool MadeChange = false;
1765 // Apply the result type to the node.
1766 unsigned NumRetVTs = Int->IS.RetVTs.size();
1767 unsigned NumParamVTs = Int->IS.ParamVTs.size();
1769 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
1770 MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
1772 if (getNumChildren() != NumParamVTs + 1) {
1773 TP.error("Intrinsic '" + Int->Name + "' expects " +
1774 utostr(NumParamVTs) + " operands, not " +
1775 utostr(getNumChildren() - 1) + " operands!");
1779 // Apply type info to the intrinsic ID.
1780 MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
1782 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
1783 MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
1785 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
1786 assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
1787 MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
1792 if (getOperator()->isSubClassOf("SDNode")) {
1793 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
1795 // Check that the number of operands is sane. Negative operands -> varargs.
1796 if (NI.getNumOperands() >= 0 &&
1797 getNumChildren() != (unsigned)NI.getNumOperands()) {
1798 TP.error(getOperator()->getName() + " node requires exactly " +
1799 itostr(NI.getNumOperands()) + " operands!");
1803 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
1804 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1805 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1809 if (getOperator()->isSubClassOf("Instruction")) {
1810 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
1811 CodeGenInstruction &InstInfo =
1812 CDP.getTargetInfo().getInstruction(getOperator());
1814 bool MadeChange = false;
1816 // Apply the result types to the node, these come from the things in the
1817 // (outs) list of the instruction.
1818 unsigned NumResultsToAdd = std::min(InstInfo.Operands.NumDefs,
1819 Inst.getNumResults());
1820 for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo)
1821 MadeChange |= UpdateNodeTypeFromInst(ResNo, Inst.getResult(ResNo), TP);
1823 // If the instruction has implicit defs, we apply the first one as a result.
1824 // FIXME: This sucks, it should apply all implicit defs.
1825 if (!InstInfo.ImplicitDefs.empty()) {
1826 unsigned ResNo = NumResultsToAdd;
1828 // FIXME: Generalize to multiple possible types and multiple possible
1830 MVT::SimpleValueType VT =
1831 InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
1833 if (VT != MVT::Other)
1834 MadeChange |= UpdateNodeType(ResNo, VT, TP);
1837 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
1839 if (getOperator()->getName() == "INSERT_SUBREG") {
1840 assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
1841 MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
1842 MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
1843 } else if (getOperator()->getName() == "REG_SEQUENCE") {
1844 // We need to do extra, custom typechecking for REG_SEQUENCE since it is
1847 unsigned NChild = getNumChildren();
1849 TP.error("REG_SEQUENCE requires at least 3 operands!");
1853 if (NChild % 2 == 0) {
1854 TP.error("REG_SEQUENCE requires an odd number of operands!");
1858 if (!isOperandClass(getChild(0), "RegisterClass")) {
1859 TP.error("REG_SEQUENCE requires a RegisterClass for first operand!");
1863 for (unsigned I = 1; I < NChild; I += 2) {
1864 TreePatternNode *SubIdxChild = getChild(I + 1);
1865 if (!isOperandClass(SubIdxChild, "SubRegIndex")) {
1866 TP.error("REG_SEQUENCE requires a SubRegIndex for operand " +
1867 itostr(I + 1) + "!");
1873 unsigned ChildNo = 0;
1874 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
1875 Record *OperandNode = Inst.getOperand(i);
1877 // If the instruction expects a predicate or optional def operand, we
1878 // codegen this by setting the operand to it's default value if it has a
1879 // non-empty DefaultOps field.
1880 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
1881 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1884 // Verify that we didn't run out of provided operands.
1885 if (ChildNo >= getNumChildren()) {
1886 emitTooFewOperandsError(TP, getOperator()->getName(), getNumChildren());
1890 TreePatternNode *Child = getChild(ChildNo++);
1891 unsigned ChildResNo = 0; // Instructions always use res #0 of their op.
1893 // If the operand has sub-operands, they may be provided by distinct
1894 // child patterns, so attempt to match each sub-operand separately.
1895 if (OperandNode->isSubClassOf("Operand")) {
1896 DagInit *MIOpInfo = OperandNode->getValueAsDag("MIOperandInfo");
1897 if (unsigned NumArgs = MIOpInfo->getNumArgs()) {
1898 // But don't do that if the whole operand is being provided by
1899 // a single ComplexPattern-related Operand.
1901 if (Child->getNumMIResults(CDP) < NumArgs) {
1902 // Match first sub-operand against the child we already have.
1903 Record *SubRec = cast<DefInit>(MIOpInfo->getArg(0))->getDef();
1905 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
1907 // And the remaining sub-operands against subsequent children.
1908 for (unsigned Arg = 1; Arg < NumArgs; ++Arg) {
1909 if (ChildNo >= getNumChildren()) {
1910 emitTooFewOperandsError(TP, getOperator()->getName(),
1914 Child = getChild(ChildNo++);
1916 SubRec = cast<DefInit>(MIOpInfo->getArg(Arg))->getDef();
1918 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
1925 // If we didn't match by pieces above, attempt to match the whole
1927 MadeChange |= Child->UpdateNodeTypeFromInst(ChildResNo, OperandNode, TP);
1930 if (!InstInfo.Operands.isVariadic && ChildNo != getNumChildren()) {
1931 emitTooManyOperandsError(TP, getOperator()->getName(),
1932 ChildNo, getNumChildren());
1936 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1937 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1941 if (getOperator()->isSubClassOf("ComplexPattern")) {
1942 bool MadeChange = false;
1944 for (unsigned i = 0; i < getNumChildren(); ++i)
1945 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1950 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
1952 // Node transforms always take one operand.
1953 if (getNumChildren() != 1) {
1954 TP.error("Node transform '" + getOperator()->getName() +
1955 "' requires one operand!");
1959 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1962 // If either the output or input of the xform does not have exact
1963 // type info. We assume they must be the same. Otherwise, it is perfectly
1964 // legal to transform from one type to a completely different type.
1966 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
1967 bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
1968 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
1975 /// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
1976 /// RHS of a commutative operation, not the on LHS.
1977 static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
1978 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
1980 if (N->isLeaf() && isa<IntInit>(N->getLeafValue()))
1986 /// canPatternMatch - If it is impossible for this pattern to match on this
1987 /// target, fill in Reason and return false. Otherwise, return true. This is
1988 /// used as a sanity check for .td files (to prevent people from writing stuff
1989 /// that can never possibly work), and to prevent the pattern permuter from
1990 /// generating stuff that is useless.
1991 bool TreePatternNode::canPatternMatch(std::string &Reason,
1992 const CodeGenDAGPatterns &CDP) {
1993 if (isLeaf()) return true;
1995 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1996 if (!getChild(i)->canPatternMatch(Reason, CDP))
1999 // If this is an intrinsic, handle cases that would make it not match. For
2000 // example, if an operand is required to be an immediate.
2001 if (getOperator()->isSubClassOf("Intrinsic")) {
2006 if (getOperator()->isSubClassOf("ComplexPattern"))
2009 // If this node is a commutative operator, check that the LHS isn't an
2011 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
2012 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
2013 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
2014 // Scan all of the operands of the node and make sure that only the last one
2015 // is a constant node, unless the RHS also is.
2016 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
2017 bool Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
2018 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
2019 if (OnlyOnRHSOfCommutative(getChild(i))) {
2020 Reason="Immediate value must be on the RHS of commutative operators!";
2029 //===----------------------------------------------------------------------===//
2030 // TreePattern implementation
2033 TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
2034 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
2035 isInputPattern(isInput), HasError(false) {
2036 for (Init *I : RawPat->getValues())
2037 Trees.push_back(ParseTreePattern(I, ""));
2040 TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
2041 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
2042 isInputPattern(isInput), HasError(false) {
2043 Trees.push_back(ParseTreePattern(Pat, ""));
2046 TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
2047 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
2048 isInputPattern(isInput), HasError(false) {
2049 Trees.push_back(Pat);
2052 void TreePattern::error(const Twine &Msg) {
2056 PrintError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
2060 void TreePattern::ComputeNamedNodes() {
2061 for (TreePatternNode *Tree : Trees)
2062 ComputeNamedNodes(Tree);
2065 void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
2066 if (!N->getName().empty())
2067 NamedNodes[N->getName()].push_back(N);
2069 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2070 ComputeNamedNodes(N->getChild(i));
2074 TreePatternNode *TreePattern::ParseTreePattern(Init *TheInit, StringRef OpName){
2075 if (DefInit *DI = dyn_cast<DefInit>(TheInit)) {
2076 Record *R = DI->getDef();
2078 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
2079 // TreePatternNode of its own. For example:
2080 /// (foo GPR, imm) -> (foo GPR, (imm))
2081 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag"))
2082 return ParseTreePattern(
2083 DagInit::get(DI, "",
2084 std::vector<std::pair<Init*, std::string> >()),
2088 TreePatternNode *Res = new TreePatternNode(DI, 1);
2089 if (R->getName() == "node" && !OpName.empty()) {
2091 error("'node' argument requires a name to match with operand list");
2092 Args.push_back(OpName);
2095 Res->setName(OpName);
2099 // ?:$name or just $name.
2100 if (isa<UnsetInit>(TheInit)) {
2102 error("'?' argument requires a name to match with operand list");
2103 TreePatternNode *Res = new TreePatternNode(TheInit, 1);
2104 Args.push_back(OpName);
2105 Res->setName(OpName);
2109 if (IntInit *II = dyn_cast<IntInit>(TheInit)) {
2110 if (!OpName.empty())
2111 error("Constant int argument should not have a name!");
2112 return new TreePatternNode(II, 1);
2115 if (BitsInit *BI = dyn_cast<BitsInit>(TheInit)) {
2116 // Turn this into an IntInit.
2117 Init *II = BI->convertInitializerTo(IntRecTy::get());
2118 if (!II || !isa<IntInit>(II))
2119 error("Bits value must be constants!");
2120 return ParseTreePattern(II, OpName);
2123 DagInit *Dag = dyn_cast<DagInit>(TheInit);
2126 error("Pattern has unexpected init kind!");
2128 DefInit *OpDef = dyn_cast<DefInit>(Dag->getOperator());
2129 if (!OpDef) error("Pattern has unexpected operator type!");
2130 Record *Operator = OpDef->getDef();
2132 if (Operator->isSubClassOf("ValueType")) {
2133 // If the operator is a ValueType, then this must be "type cast" of a leaf
2135 if (Dag->getNumArgs() != 1)
2136 error("Type cast only takes one operand!");
2138 TreePatternNode *New = ParseTreePattern(Dag->getArg(0), Dag->getArgName(0));
2140 // Apply the type cast.
2141 assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
2142 New->UpdateNodeType(0, getValueType(Operator), *this);
2144 if (!OpName.empty())
2145 error("ValueType cast should not have a name!");
2149 // Verify that this is something that makes sense for an operator.
2150 if (!Operator->isSubClassOf("PatFrag") &&
2151 !Operator->isSubClassOf("SDNode") &&
2152 !Operator->isSubClassOf("Instruction") &&
2153 !Operator->isSubClassOf("SDNodeXForm") &&
2154 !Operator->isSubClassOf("Intrinsic") &&
2155 !Operator->isSubClassOf("ComplexPattern") &&
2156 Operator->getName() != "set" &&
2157 Operator->getName() != "implicit")
2158 error("Unrecognized node '" + Operator->getName() + "'!");
2160 // Check to see if this is something that is illegal in an input pattern.
2161 if (isInputPattern) {
2162 if (Operator->isSubClassOf("Instruction") ||
2163 Operator->isSubClassOf("SDNodeXForm"))
2164 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
2166 if (Operator->isSubClassOf("Intrinsic"))
2167 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
2169 if (Operator->isSubClassOf("SDNode") &&
2170 Operator->getName() != "imm" &&
2171 Operator->getName() != "fpimm" &&
2172 Operator->getName() != "tglobaltlsaddr" &&
2173 Operator->getName() != "tconstpool" &&
2174 Operator->getName() != "tjumptable" &&
2175 Operator->getName() != "tframeindex" &&
2176 Operator->getName() != "texternalsym" &&
2177 Operator->getName() != "tblockaddress" &&
2178 Operator->getName() != "tglobaladdr" &&
2179 Operator->getName() != "bb" &&
2180 Operator->getName() != "vt" &&
2181 Operator->getName() != "mcsym")
2182 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
2185 std::vector<TreePatternNode*> Children;
2187 // Parse all the operands.
2188 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
2189 Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgName(i)));
2191 // If the operator is an intrinsic, then this is just syntactic sugar for for
2192 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
2193 // convert the intrinsic name to a number.
2194 if (Operator->isSubClassOf("Intrinsic")) {
2195 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
2196 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
2198 // If this intrinsic returns void, it must have side-effects and thus a
2200 if (Int.IS.RetVTs.empty())
2201 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
2202 else if (Int.ModRef != CodeGenIntrinsic::NoMem)
2203 // Has side-effects, requires chain.
2204 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
2205 else // Otherwise, no chain.
2206 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
2208 TreePatternNode *IIDNode = new TreePatternNode(IntInit::get(IID), 1);
2209 Children.insert(Children.begin(), IIDNode);
2212 if (Operator->isSubClassOf("ComplexPattern")) {
2213 for (unsigned i = 0; i < Children.size(); ++i) {
2214 TreePatternNode *Child = Children[i];
2216 if (Child->getName().empty())
2217 error("All arguments to a ComplexPattern must be named");
2219 // Check that the ComplexPattern uses are consistent: "(MY_PAT $a, $b)"
2220 // and "(MY_PAT $b, $a)" should not be allowed in the same pattern;
2221 // neither should "(MY_PAT_1 $a, $b)" and "(MY_PAT_2 $a, $b)".
2222 auto OperandId = std::make_pair(Operator, i);
2223 auto PrevOp = ComplexPatternOperands.find(Child->getName());
2224 if (PrevOp != ComplexPatternOperands.end()) {
2225 if (PrevOp->getValue() != OperandId)
2226 error("All ComplexPattern operands must appear consistently: "
2227 "in the same order in just one ComplexPattern instance.");
2229 ComplexPatternOperands[Child->getName()] = OperandId;
2233 unsigned NumResults = GetNumNodeResults(Operator, CDP);
2234 TreePatternNode *Result = new TreePatternNode(Operator, Children, NumResults);
2235 Result->setName(OpName);
2237 if (!Dag->getName().empty()) {
2238 assert(Result->getName().empty());
2239 Result->setName(Dag->getName());
2244 /// SimplifyTree - See if we can simplify this tree to eliminate something that
2245 /// will never match in favor of something obvious that will. This is here
2246 /// strictly as a convenience to target authors because it allows them to write
2247 /// more type generic things and have useless type casts fold away.
2249 /// This returns true if any change is made.
2250 static bool SimplifyTree(TreePatternNode *&N) {
2254 // If we have a bitconvert with a resolved type and if the source and
2255 // destination types are the same, then the bitconvert is useless, remove it.
2256 if (N->getOperator()->getName() == "bitconvert" &&
2257 N->getExtType(0).isConcrete() &&
2258 N->getExtType(0) == N->getChild(0)->getExtType(0) &&
2259 N->getName().empty()) {
2265 // Walk all children.
2266 bool MadeChange = false;
2267 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2268 TreePatternNode *Child = N->getChild(i);
2269 MadeChange |= SimplifyTree(Child);
2270 N->setChild(i, Child);
2277 /// InferAllTypes - Infer/propagate as many types throughout the expression
2278 /// patterns as possible. Return true if all types are inferred, false
2279 /// otherwise. Flags an error if a type contradiction is found.
2281 InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
2282 if (NamedNodes.empty())
2283 ComputeNamedNodes();
2285 bool MadeChange = true;
2286 while (MadeChange) {
2288 for (TreePatternNode *Tree : Trees) {
2289 MadeChange |= Tree->ApplyTypeConstraints(*this, false);
2290 MadeChange |= SimplifyTree(Tree);
2293 // If there are constraints on our named nodes, apply them.
2294 for (auto &Entry : NamedNodes) {
2295 SmallVectorImpl<TreePatternNode*> &Nodes = Entry.second;
2297 // If we have input named node types, propagate their types to the named
2300 if (!InNamedTypes->count(Entry.getKey())) {
2301 error("Node '" + std::string(Entry.getKey()) +
2302 "' in output pattern but not input pattern");
2306 const SmallVectorImpl<TreePatternNode*> &InNodes =
2307 InNamedTypes->find(Entry.getKey())->second;
2309 // The input types should be fully resolved by now.
2310 for (TreePatternNode *Node : Nodes) {
2311 // If this node is a register class, and it is the root of the pattern
2312 // then we're mapping something onto an input register. We allow
2313 // changing the type of the input register in this case. This allows
2314 // us to match things like:
2315 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
2316 if (Node == Trees[0] && Node->isLeaf()) {
2317 DefInit *DI = dyn_cast<DefInit>(Node->getLeafValue());
2318 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2319 DI->getDef()->isSubClassOf("RegisterOperand")))
2323 assert(Node->getNumTypes() == 1 &&
2324 InNodes[0]->getNumTypes() == 1 &&
2325 "FIXME: cannot name multiple result nodes yet");
2326 MadeChange |= Node->UpdateNodeType(0, InNodes[0]->getExtType(0),
2331 // If there are multiple nodes with the same name, they must all have the
2333 if (Entry.second.size() > 1) {
2334 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
2335 TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
2336 assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
2337 "FIXME: cannot name multiple result nodes yet");
2339 MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
2340 MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
2346 bool HasUnresolvedTypes = false;
2347 for (const TreePatternNode *Tree : Trees)
2348 HasUnresolvedTypes |= Tree->ContainsUnresolvedType();
2349 return !HasUnresolvedTypes;
2352 void TreePattern::print(raw_ostream &OS) const {
2353 OS << getRecord()->getName();
2354 if (!Args.empty()) {
2355 OS << "(" << Args[0];
2356 for (unsigned i = 1, e = Args.size(); i != e; ++i)
2357 OS << ", " << Args[i];
2362 if (Trees.size() > 1)
2364 for (const TreePatternNode *Tree : Trees) {
2370 if (Trees.size() > 1)
2374 void TreePattern::dump() const { print(errs()); }
2376 //===----------------------------------------------------------------------===//
2377 // CodeGenDAGPatterns implementation
2380 CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) :
2381 Records(R), Target(R) {
2383 Intrinsics = LoadIntrinsics(Records, false);
2384 TgtIntrinsics = LoadIntrinsics(Records, true);
2386 ParseNodeTransforms();
2387 ParseComplexPatterns();
2388 ParsePatternFragments();
2389 ParseDefaultOperands();
2390 ParseInstructions();
2391 ParsePatternFragments(/*OutFrags*/true);
2394 // Generate variants. For example, commutative patterns can match
2395 // multiple ways. Add them to PatternsToMatch as well.
2398 // Infer instruction flags. For example, we can detect loads,
2399 // stores, and side effects in many cases by examining an
2400 // instruction's pattern.
2401 InferInstructionFlags();
2403 // Verify that instruction flags match the patterns.
2404 VerifyInstructionFlags();
2407 Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
2408 Record *N = Records.getDef(Name);
2409 if (!N || !N->isSubClassOf("SDNode"))
2410 PrintFatalError("Error getting SDNode '" + Name + "'!");
2415 // Parse all of the SDNode definitions for the target, populating SDNodes.
2416 void CodeGenDAGPatterns::ParseNodeInfo() {
2417 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
2418 while (!Nodes.empty()) {
2419 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
2423 // Get the builtin intrinsic nodes.
2424 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
2425 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
2426 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
2429 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
2430 /// map, and emit them to the file as functions.
2431 void CodeGenDAGPatterns::ParseNodeTransforms() {
2432 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
2433 while (!Xforms.empty()) {
2434 Record *XFormNode = Xforms.back();
2435 Record *SDNode = XFormNode->getValueAsDef("Opcode");
2436 std::string Code = XFormNode->getValueAsString("XFormFunction");
2437 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
2443 void CodeGenDAGPatterns::ParseComplexPatterns() {
2444 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
2445 while (!AMs.empty()) {
2446 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
2452 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
2453 /// file, building up the PatternFragments map. After we've collected them all,
2454 /// inline fragments together as necessary, so that there are no references left
2455 /// inside a pattern fragment to a pattern fragment.
2457 void CodeGenDAGPatterns::ParsePatternFragments(bool OutFrags) {
2458 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
2460 // First step, parse all of the fragments.
2461 for (Record *Frag : Fragments) {
2462 if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
2465 DagInit *Tree = Frag->getValueAsDag("Fragment");
2467 (PatternFragments[Frag] = llvm::make_unique<TreePattern>(
2468 Frag, Tree, !Frag->isSubClassOf("OutPatFrag"),
2471 // Validate the argument list, converting it to set, to discard duplicates.
2472 std::vector<std::string> &Args = P->getArgList();
2473 std::set<std::string> OperandsSet(Args.begin(), Args.end());
2475 if (OperandsSet.count(""))
2476 P->error("Cannot have unnamed 'node' values in pattern fragment!");
2478 // Parse the operands list.
2479 DagInit *OpsList = Frag->getValueAsDag("Operands");
2480 DefInit *OpsOp = dyn_cast<DefInit>(OpsList->getOperator());
2481 // Special cases: ops == outs == ins. Different names are used to
2482 // improve readability.
2484 (OpsOp->getDef()->getName() != "ops" &&
2485 OpsOp->getDef()->getName() != "outs" &&
2486 OpsOp->getDef()->getName() != "ins"))
2487 P->error("Operands list should start with '(ops ... '!");
2489 // Copy over the arguments.
2491 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
2492 if (!isa<DefInit>(OpsList->getArg(j)) ||
2493 cast<DefInit>(OpsList->getArg(j))->getDef()->getName() != "node")
2494 P->error("Operands list should all be 'node' values.");
2495 if (OpsList->getArgName(j).empty())
2496 P->error("Operands list should have names for each operand!");
2497 if (!OperandsSet.count(OpsList->getArgName(j)))
2498 P->error("'" + OpsList->getArgName(j) +
2499 "' does not occur in pattern or was multiply specified!");
2500 OperandsSet.erase(OpsList->getArgName(j));
2501 Args.push_back(OpsList->getArgName(j));
2504 if (!OperandsSet.empty())
2505 P->error("Operands list does not contain an entry for operand '" +
2506 *OperandsSet.begin() + "'!");
2508 // If there is a code init for this fragment, keep track of the fact that
2509 // this fragment uses it.
2510 TreePredicateFn PredFn(P);
2511 if (!PredFn.isAlwaysTrue())
2512 P->getOnlyTree()->addPredicateFn(PredFn);
2514 // If there is a node transformation corresponding to this, keep track of
2516 Record *Transform = Frag->getValueAsDef("OperandTransform");
2517 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
2518 P->getOnlyTree()->setTransformFn(Transform);
2521 // Now that we've parsed all of the tree fragments, do a closure on them so
2522 // that there are not references to PatFrags left inside of them.
2523 for (Record *Frag : Fragments) {
2524 if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
2527 TreePattern &ThePat = *PatternFragments[Frag];
2528 ThePat.InlinePatternFragments();
2530 // Infer as many types as possible. Don't worry about it if we don't infer
2531 // all of them, some may depend on the inputs of the pattern.
2532 ThePat.InferAllTypes();
2533 ThePat.resetError();
2535 // If debugging, print out the pattern fragment result.
2536 DEBUG(ThePat.dump());
2540 void CodeGenDAGPatterns::ParseDefaultOperands() {
2541 std::vector<Record*> DefaultOps;
2542 DefaultOps = Records.getAllDerivedDefinitions("OperandWithDefaultOps");
2544 // Find some SDNode.
2545 assert(!SDNodes.empty() && "No SDNodes parsed?");
2546 Init *SomeSDNode = DefInit::get(SDNodes.begin()->first);
2548 for (unsigned i = 0, e = DefaultOps.size(); i != e; ++i) {
2549 DagInit *DefaultInfo = DefaultOps[i]->getValueAsDag("DefaultOps");
2551 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
2552 // SomeSDnode so that we can parse this.
2553 std::vector<std::pair<Init*, std::string> > Ops;
2554 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
2555 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
2556 DefaultInfo->getArgName(op)));
2557 DagInit *DI = DagInit::get(SomeSDNode, "", Ops);
2559 // Create a TreePattern to parse this.
2560 TreePattern P(DefaultOps[i], DI, false, *this);
2561 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
2563 // Copy the operands over into a DAGDefaultOperand.
2564 DAGDefaultOperand DefaultOpInfo;
2566 TreePatternNode *T = P.getTree(0);
2567 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
2568 TreePatternNode *TPN = T->getChild(op);
2569 while (TPN->ApplyTypeConstraints(P, false))
2570 /* Resolve all types */;
2572 if (TPN->ContainsUnresolvedType()) {
2573 PrintFatalError("Value #" + Twine(i) + " of OperandWithDefaultOps '" +
2574 DefaultOps[i]->getName() +
2575 "' doesn't have a concrete type!");
2577 DefaultOpInfo.DefaultOps.push_back(TPN);
2580 // Insert it into the DefaultOperands map so we can find it later.
2581 DefaultOperands[DefaultOps[i]] = DefaultOpInfo;
2585 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
2586 /// instruction input. Return true if this is a real use.
2587 static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
2588 std::map<std::string, TreePatternNode*> &InstInputs) {
2589 // No name -> not interesting.
2590 if (Pat->getName().empty()) {
2591 if (Pat->isLeaf()) {
2592 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
2593 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2594 DI->getDef()->isSubClassOf("RegisterOperand")))
2595 I->error("Input " + DI->getDef()->getName() + " must be named!");
2601 if (Pat->isLeaf()) {
2602 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
2603 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
2606 Rec = Pat->getOperator();
2609 // SRCVALUE nodes are ignored.
2610 if (Rec->getName() == "srcvalue")
2613 TreePatternNode *&Slot = InstInputs[Pat->getName()];
2619 if (Slot->isLeaf()) {
2620 SlotRec = cast<DefInit>(Slot->getLeafValue())->getDef();
2622 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
2623 SlotRec = Slot->getOperator();
2626 // Ensure that the inputs agree if we've already seen this input.
2628 I->error("All $" + Pat->getName() + " inputs must agree with each other");
2629 if (Slot->getExtTypes() != Pat->getExtTypes())
2630 I->error("All $" + Pat->getName() + " inputs must agree with each other");
2634 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
2635 /// part of "I", the instruction), computing the set of inputs and outputs of
2636 /// the pattern. Report errors if we see anything naughty.
2637 void CodeGenDAGPatterns::
2638 FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
2639 std::map<std::string, TreePatternNode*> &InstInputs,
2640 std::map<std::string, TreePatternNode*>&InstResults,
2641 std::vector<Record*> &InstImpResults) {
2642 if (Pat->isLeaf()) {
2643 bool isUse = HandleUse(I, Pat, InstInputs);
2644 if (!isUse && Pat->getTransformFn())
2645 I->error("Cannot specify a transform function for a non-input value!");
2649 if (Pat->getOperator()->getName() == "implicit") {
2650 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2651 TreePatternNode *Dest = Pat->getChild(i);
2652 if (!Dest->isLeaf())
2653 I->error("implicitly defined value should be a register!");
2655 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
2656 if (!Val || !Val->getDef()->isSubClassOf("Register"))
2657 I->error("implicitly defined value should be a register!");
2658 InstImpResults.push_back(Val->getDef());
2663 if (Pat->getOperator()->getName() != "set") {
2664 // If this is not a set, verify that the children nodes are not void typed,
2666 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2667 if (Pat->getChild(i)->getNumTypes() == 0)
2668 I->error("Cannot have void nodes inside of patterns!");
2669 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
2673 // If this is a non-leaf node with no children, treat it basically as if
2674 // it were a leaf. This handles nodes like (imm).
2675 bool isUse = HandleUse(I, Pat, InstInputs);
2677 if (!isUse && Pat->getTransformFn())
2678 I->error("Cannot specify a transform function for a non-input value!");
2682 // Otherwise, this is a set, validate and collect instruction results.
2683 if (Pat->getNumChildren() == 0)
2684 I->error("set requires operands!");
2686 if (Pat->getTransformFn())
2687 I->error("Cannot specify a transform function on a set node!");
2689 // Check the set destinations.
2690 unsigned NumDests = Pat->getNumChildren()-1;
2691 for (unsigned i = 0; i != NumDests; ++i) {
2692 TreePatternNode *Dest = Pat->getChild(i);
2693 if (!Dest->isLeaf())
2694 I->error("set destination should be a register!");
2696 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
2698 I->error("set destination should be a register!");
2702 if (Val->getDef()->isSubClassOf("RegisterClass") ||
2703 Val->getDef()->isSubClassOf("ValueType") ||
2704 Val->getDef()->isSubClassOf("RegisterOperand") ||
2705 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
2706 if (Dest->getName().empty())
2707 I->error("set destination must have a name!");
2708 if (InstResults.count(Dest->getName()))
2709 I->error("cannot set '" + Dest->getName() +"' multiple times");
2710 InstResults[Dest->getName()] = Dest;
2711 } else if (Val->getDef()->isSubClassOf("Register")) {
2712 InstImpResults.push_back(Val->getDef());
2714 I->error("set destination should be a register!");
2718 // Verify and collect info from the computation.
2719 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
2720 InstInputs, InstResults, InstImpResults);
2723 //===----------------------------------------------------------------------===//
2724 // Instruction Analysis
2725 //===----------------------------------------------------------------------===//
2727 class InstAnalyzer {
2728 const CodeGenDAGPatterns &CDP;
2730 bool hasSideEffects;
2736 InstAnalyzer(const CodeGenDAGPatterns &cdp)
2737 : CDP(cdp), hasSideEffects(false), mayStore(false), mayLoad(false),
2738 isBitcast(false), isVariadic(false) {}
2740 void Analyze(const TreePattern *Pat) {
2741 // Assume only the first tree is the pattern. The others are clobber nodes.
2742 AnalyzeNode(Pat->getTree(0));
2745 void Analyze(const PatternToMatch *Pat) {
2746 AnalyzeNode(Pat->getSrcPattern());
2750 bool IsNodeBitcast(const TreePatternNode *N) const {
2751 if (hasSideEffects || mayLoad || mayStore || isVariadic)
2754 if (N->getNumChildren() != 2)
2757 const TreePatternNode *N0 = N->getChild(0);
2758 if (!N0->isLeaf() || !isa<DefInit>(N0->getLeafValue()))
2761 const TreePatternNode *N1 = N->getChild(1);
2764 if (N1->getNumChildren() != 1 || !N1->getChild(0)->isLeaf())
2767 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N1->getOperator());
2768 if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1)
2770 return OpInfo.getEnumName() == "ISD::BITCAST";
2774 void AnalyzeNode(const TreePatternNode *N) {
2776 if (DefInit *DI = dyn_cast<DefInit>(N->getLeafValue())) {
2777 Record *LeafRec = DI->getDef();
2778 // Handle ComplexPattern leaves.
2779 if (LeafRec->isSubClassOf("ComplexPattern")) {
2780 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
2781 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
2782 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
2783 if (CP.hasProperty(SDNPSideEffect)) hasSideEffects = true;
2789 // Analyze children.
2790 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2791 AnalyzeNode(N->getChild(i));
2793 // Ignore set nodes, which are not SDNodes.
2794 if (N->getOperator()->getName() == "set") {
2795 isBitcast = IsNodeBitcast(N);
2799 // Notice properties of the node.
2800 if (N->NodeHasProperty(SDNPMayStore, CDP)) mayStore = true;
2801 if (N->NodeHasProperty(SDNPMayLoad, CDP)) mayLoad = true;
2802 if (N->NodeHasProperty(SDNPSideEffect, CDP)) hasSideEffects = true;
2803 if (N->NodeHasProperty(SDNPVariadic, CDP)) isVariadic = true;
2805 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
2806 // If this is an intrinsic, analyze it.
2807 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
2808 mayLoad = true;// These may load memory.
2810 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteArgMem)
2811 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
2813 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem)
2814 // WriteMem intrinsics can have other strange effects.
2815 hasSideEffects = true;
2821 static bool InferFromPattern(CodeGenInstruction &InstInfo,
2822 const InstAnalyzer &PatInfo,
2826 // Remember where InstInfo got its flags.
2827 if (InstInfo.hasUndefFlags())
2828 InstInfo.InferredFrom = PatDef;
2830 // Check explicitly set flags for consistency.
2831 if (InstInfo.hasSideEffects != PatInfo.hasSideEffects &&
2832 !InstInfo.hasSideEffects_Unset) {
2833 // Allow explicitly setting hasSideEffects = 1 on instructions, even when
2834 // the pattern has no side effects. That could be useful for div/rem
2835 // instructions that may trap.
2836 if (!InstInfo.hasSideEffects) {
2838 PrintError(PatDef->getLoc(), "Pattern doesn't match hasSideEffects = " +
2839 Twine(InstInfo.hasSideEffects));
2843 if (InstInfo.mayStore != PatInfo.mayStore && !InstInfo.mayStore_Unset) {
2845 PrintError(PatDef->getLoc(), "Pattern doesn't match mayStore = " +
2846 Twine(InstInfo.mayStore));
2849 if (InstInfo.mayLoad != PatInfo.mayLoad && !InstInfo.mayLoad_Unset) {
2850 // Allow explicitly setting mayLoad = 1, even when the pattern has no loads.
2851 // Some targets translate immediates to loads.
2852 if (!InstInfo.mayLoad) {
2854 PrintError(PatDef->getLoc(), "Pattern doesn't match mayLoad = " +
2855 Twine(InstInfo.mayLoad));
2859 // Transfer inferred flags.
2860 InstInfo.hasSideEffects |= PatInfo.hasSideEffects;
2861 InstInfo.mayStore |= PatInfo.mayStore;
2862 InstInfo.mayLoad |= PatInfo.mayLoad;
2864 // These flags are silently added without any verification.
2865 InstInfo.isBitcast |= PatInfo.isBitcast;
2867 // Don't infer isVariadic. This flag means something different on SDNodes and
2868 // instructions. For example, a CALL SDNode is variadic because it has the
2869 // call arguments as operands, but a CALL instruction is not variadic - it
2870 // has argument registers as implicit, not explicit uses.
2875 /// hasNullFragReference - Return true if the DAG has any reference to the
2876 /// null_frag operator.
2877 static bool hasNullFragReference(DagInit *DI) {
2878 DefInit *OpDef = dyn_cast<DefInit>(DI->getOperator());
2879 if (!OpDef) return false;
2880 Record *Operator = OpDef->getDef();
2882 // If this is the null fragment, return true.
2883 if (Operator->getName() == "null_frag") return true;
2884 // If any of the arguments reference the null fragment, return true.
2885 for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {
2886 DagInit *Arg = dyn_cast<DagInit>(DI->getArg(i));
2887 if (Arg && hasNullFragReference(Arg))
2894 /// hasNullFragReference - Return true if any DAG in the list references
2895 /// the null_frag operator.
2896 static bool hasNullFragReference(ListInit *LI) {
2897 for (Init *I : LI->getValues()) {
2898 DagInit *DI = dyn_cast<DagInit>(I);
2899 assert(DI && "non-dag in an instruction Pattern list?!");
2900 if (hasNullFragReference(DI))
2906 /// Get all the instructions in a tree.
2908 getInstructionsInTree(TreePatternNode *Tree, SmallVectorImpl<Record*> &Instrs) {
2911 if (Tree->getOperator()->isSubClassOf("Instruction"))
2912 Instrs.push_back(Tree->getOperator());
2913 for (unsigned i = 0, e = Tree->getNumChildren(); i != e; ++i)
2914 getInstructionsInTree(Tree->getChild(i), Instrs);
2917 /// Check the class of a pattern leaf node against the instruction operand it
2919 static bool checkOperandClass(CGIOperandList::OperandInfo &OI,
2924 // Allow direct value types to be used in instruction set patterns.
2925 // The type will be checked later.
2926 if (Leaf->isSubClassOf("ValueType"))
2929 // Patterns can also be ComplexPattern instances.
2930 if (Leaf->isSubClassOf("ComplexPattern"))
2936 const DAGInstruction &CodeGenDAGPatterns::parseInstructionPattern(
2937 CodeGenInstruction &CGI, ListInit *Pat, DAGInstMap &DAGInsts) {
2939 assert(!DAGInsts.count(CGI.TheDef) && "Instruction already parsed!");
2941 // Parse the instruction.
2942 TreePattern *I = new TreePattern(CGI.TheDef, Pat, true, *this);
2943 // Inline pattern fragments into it.
2944 I->InlinePatternFragments();
2946 // Infer as many types as possible. If we cannot infer all of them, we can
2947 // never do anything with this instruction pattern: report it to the user.
2948 if (!I->InferAllTypes())
2949 I->error("Could not infer all types in pattern!");
2951 // InstInputs - Keep track of all of the inputs of the instruction, along
2952 // with the record they are declared as.
2953 std::map<std::string, TreePatternNode*> InstInputs;
2955 // InstResults - Keep track of all the virtual registers that are 'set'
2956 // in the instruction, including what reg class they are.
2957 std::map<std::string, TreePatternNode*> InstResults;
2959 std::vector<Record*> InstImpResults;
2961 // Verify that the top-level forms in the instruction are of void type, and
2962 // fill in the InstResults map.
2963 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
2964 TreePatternNode *Pat = I->getTree(j);
2965 if (Pat->getNumTypes() != 0)
2966 I->error("Top-level forms in instruction pattern should have"
2969 // Find inputs and outputs, and verify the structure of the uses/defs.
2970 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
2974 // Now that we have inputs and outputs of the pattern, inspect the operands
2975 // list for the instruction. This determines the order that operands are
2976 // added to the machine instruction the node corresponds to.
2977 unsigned NumResults = InstResults.size();
2979 // Parse the operands list from the (ops) list, validating it.
2980 assert(I->getArgList().empty() && "Args list should still be empty here!");
2982 // Check that all of the results occur first in the list.
2983 std::vector<Record*> Results;
2984 SmallVector<TreePatternNode *, 2> ResNodes;
2985 for (unsigned i = 0; i != NumResults; ++i) {
2986 if (i == CGI.Operands.size())
2987 I->error("'" + InstResults.begin()->first +
2988 "' set but does not appear in operand list!");
2989 const std::string &OpName = CGI.Operands[i].Name;
2991 // Check that it exists in InstResults.
2992 TreePatternNode *RNode = InstResults[OpName];
2994 I->error("Operand $" + OpName + " does not exist in operand list!");
2996 ResNodes.push_back(RNode);
2998 Record *R = cast<DefInit>(RNode->getLeafValue())->getDef();
3000 I->error("Operand $" + OpName + " should be a set destination: all "
3001 "outputs must occur before inputs in operand list!");
3003 if (!checkOperandClass(CGI.Operands[i], R))
3004 I->error("Operand $" + OpName + " class mismatch!");
3006 // Remember the return type.
3007 Results.push_back(CGI.Operands[i].Rec);
3009 // Okay, this one checks out.
3010 InstResults.erase(OpName);
3013 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
3014 // the copy while we're checking the inputs.
3015 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
3017 std::vector<TreePatternNode*> ResultNodeOperands;
3018 std::vector<Record*> Operands;
3019 for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
3020 CGIOperandList::OperandInfo &Op = CGI.Operands[i];
3021 const std::string &OpName = Op.Name;
3023 I->error("Operand #" + utostr(i) + " in operands list has no name!");
3025 if (!InstInputsCheck.count(OpName)) {
3026 // If this is an operand with a DefaultOps set filled in, we can ignore
3027 // this. When we codegen it, we will do so as always executed.
3028 if (Op.Rec->isSubClassOf("OperandWithDefaultOps")) {
3029 // Does it have a non-empty DefaultOps field? If so, ignore this
3031 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
3034 I->error("Operand $" + OpName +
3035 " does not appear in the instruction pattern");
3037 TreePatternNode *InVal = InstInputsCheck[OpName];
3038 InstInputsCheck.erase(OpName); // It occurred, remove from map.
3040 if (InVal->isLeaf() && isa<DefInit>(InVal->getLeafValue())) {
3041 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
3042 if (!checkOperandClass(Op, InRec))
3043 I->error("Operand $" + OpName + "'s register class disagrees"
3044 " between the operand and pattern");
3046 Operands.push_back(Op.Rec);
3048 // Construct the result for the dest-pattern operand list.
3049 TreePatternNode *OpNode = InVal->clone();
3051 // No predicate is useful on the result.
3052 OpNode->clearPredicateFns();
3054 // Promote the xform function to be an explicit node if set.
3055 if (Record *Xform = OpNode->getTransformFn()) {
3056 OpNode->setTransformFn(nullptr);
3057 std::vector<TreePatternNode*> Children;
3058 Children.push_back(OpNode);
3059 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
3062 ResultNodeOperands.push_back(OpNode);
3065 if (!InstInputsCheck.empty())
3066 I->error("Input operand $" + InstInputsCheck.begin()->first +
3067 " occurs in pattern but not in operands list!");
3069 TreePatternNode *ResultPattern =
3070 new TreePatternNode(I->getRecord(), ResultNodeOperands,
3071 GetNumNodeResults(I->getRecord(), *this));
3072 // Copy fully inferred output node types to instruction result pattern.
3073 for (unsigned i = 0; i != NumResults; ++i) {
3074 assert(ResNodes[i]->getNumTypes() == 1 && "FIXME: Unhandled");
3075 ResultPattern->setType(i, ResNodes[i]->getExtType(0));
3078 // Create and insert the instruction.
3079 // FIXME: InstImpResults should not be part of DAGInstruction.
3080 DAGInstruction TheInst(I, Results, Operands, InstImpResults);
3081 DAGInsts.insert(std::make_pair(I->getRecord(), TheInst));
3083 // Use a temporary tree pattern to infer all types and make sure that the
3084 // constructed result is correct. This depends on the instruction already
3085 // being inserted into the DAGInsts map.
3086 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
3087 Temp.InferAllTypes(&I->getNamedNodesMap());
3089 DAGInstruction &TheInsertedInst = DAGInsts.find(I->getRecord())->second;
3090 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
3092 return TheInsertedInst;
3095 /// ParseInstructions - Parse all of the instructions, inlining and resolving
3096 /// any fragments involved. This populates the Instructions list with fully
3097 /// resolved instructions.
3098 void CodeGenDAGPatterns::ParseInstructions() {
3099 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
3101 for (Record *Instr : Instrs) {
3102 ListInit *LI = nullptr;
3104 if (isa<ListInit>(Instr->getValueInit("Pattern")))
3105 LI = Instr->getValueAsListInit("Pattern");
3107 // If there is no pattern, only collect minimal information about the
3108 // instruction for its operand list. We have to assume that there is one
3109 // result, as we have no detailed info. A pattern which references the
3110 // null_frag operator is as-if no pattern were specified. Normally this
3111 // is from a multiclass expansion w/ a SDPatternOperator passed in as
3113 if (!LI || LI->empty() || hasNullFragReference(LI)) {
3114 std::vector<Record*> Results;
3115 std::vector<Record*> Operands;
3117 CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
3119 if (InstInfo.Operands.size() != 0) {
3120 for (unsigned j = 0, e = InstInfo.Operands.NumDefs; j < e; ++j)
3121 Results.push_back(InstInfo.Operands[j].Rec);
3123 // The rest are inputs.
3124 for (unsigned j = InstInfo.Operands.NumDefs,
3125 e = InstInfo.Operands.size(); j < e; ++j)
3126 Operands.push_back(InstInfo.Operands[j].Rec);
3129 // Create and insert the instruction.
3130 std::vector<Record*> ImpResults;
3131 Instructions.insert(std::make_pair(Instr,
3132 DAGInstruction(nullptr, Results, Operands, ImpResults)));
3133 continue; // no pattern.
3136 CodeGenInstruction &CGI = Target.getInstruction(Instr);
3137 const DAGInstruction &DI = parseInstructionPattern(CGI, LI, Instructions);
3140 DEBUG(DI.getPattern()->dump());
3143 // If we can, convert the instructions to be patterns that are matched!
3144 for (auto &Entry : Instructions) {
3145 DAGInstruction &TheInst = Entry.second;
3146 TreePattern *I = TheInst.getPattern();
3147 if (!I) continue; // No pattern.
3149 // FIXME: Assume only the first tree is the pattern. The others are clobber
3151 TreePatternNode *Pattern = I->getTree(0);
3152 TreePatternNode *SrcPattern;
3153 if (Pattern->getOperator()->getName() == "set") {
3154 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
3156 // Not a set (store or something?)
3157 SrcPattern = Pattern;
3160 Record *Instr = Entry.first;
3161 AddPatternToMatch(I,
3162 PatternToMatch(Instr,
3163 Instr->getValueAsListInit("Predicates"),
3165 TheInst.getResultPattern(),
3166 TheInst.getImpResults(),
3167 Instr->getValueAsInt("AddedComplexity"),
3173 typedef std::pair<const TreePatternNode*, unsigned> NameRecord;
3175 static void FindNames(const TreePatternNode *P,
3176 std::map<std::string, NameRecord> &Names,
3177 TreePattern *PatternTop) {
3178 if (!P->getName().empty()) {
3179 NameRecord &Rec = Names[P->getName()];
3180 // If this is the first instance of the name, remember the node.
3181 if (Rec.second++ == 0)
3183 else if (Rec.first->getExtTypes() != P->getExtTypes())
3184 PatternTop->error("repetition of value: $" + P->getName() +
3185 " where different uses have different types!");
3189 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
3190 FindNames(P->getChild(i), Names, PatternTop);
3194 void CodeGenDAGPatterns::AddPatternToMatch(TreePattern *Pattern,
3195 const PatternToMatch &PTM) {
3196 // Do some sanity checking on the pattern we're about to match.
3198 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this)) {
3199 PrintWarning(Pattern->getRecord()->getLoc(),
3200 Twine("Pattern can never match: ") + Reason);
3204 // If the source pattern's root is a complex pattern, that complex pattern
3205 // must specify the nodes it can potentially match.
3206 if (const ComplexPattern *CP =
3207 PTM.getSrcPattern()->getComplexPatternInfo(*this))
3208 if (CP->getRootNodes().empty())
3209 Pattern->error("ComplexPattern at root must specify list of opcodes it"
3213 // Find all of the named values in the input and output, ensure they have the
3215 std::map<std::string, NameRecord> SrcNames, DstNames;
3216 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
3217 FindNames(PTM.getDstPattern(), DstNames, Pattern);
3219 // Scan all of the named values in the destination pattern, rejecting them if
3220 // they don't exist in the input pattern.
3221 for (const auto &Entry : DstNames) {
3222 if (SrcNames[Entry.first].first == nullptr)
3223 Pattern->error("Pattern has input without matching name in output: $" +
3227 // Scan all of the named values in the source pattern, rejecting them if the
3228 // name isn't used in the dest, and isn't used to tie two values together.
3229 for (const auto &Entry : SrcNames)
3230 if (DstNames[Entry.first].first == nullptr &&
3231 SrcNames[Entry.first].second == 1)
3232 Pattern->error("Pattern has dead named input: $" + Entry.first);
3234 PatternsToMatch.push_back(PTM);
3239 void CodeGenDAGPatterns::InferInstructionFlags() {
3240 const std::vector<const CodeGenInstruction*> &Instructions =
3241 Target.getInstructionsByEnumValue();
3243 // First try to infer flags from the primary instruction pattern, if any.
3244 SmallVector<CodeGenInstruction*, 8> Revisit;
3245 unsigned Errors = 0;
3246 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
3247 CodeGenInstruction &InstInfo =
3248 const_cast<CodeGenInstruction &>(*Instructions[i]);
3250 // Get the primary instruction pattern.
3251 const TreePattern *Pattern = getInstruction(InstInfo.TheDef).getPattern();
3253 if (InstInfo.hasUndefFlags())
3254 Revisit.push_back(&InstInfo);
3257 InstAnalyzer PatInfo(*this);
3258 PatInfo.Analyze(Pattern);
3259 Errors += InferFromPattern(InstInfo, PatInfo, InstInfo.TheDef);
3262 // Second, look for single-instruction patterns defined outside the
3264 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3265 const PatternToMatch &PTM = *I;
3267 // We can only infer from single-instruction patterns, otherwise we won't
3268 // know which instruction should get the flags.
3269 SmallVector<Record*, 8> PatInstrs;
3270 getInstructionsInTree(PTM.getDstPattern(), PatInstrs);
3271 if (PatInstrs.size() != 1)
3274 // Get the single instruction.
3275 CodeGenInstruction &InstInfo = Target.getInstruction(PatInstrs.front());
3277 // Only infer properties from the first pattern. We'll verify the others.
3278 if (InstInfo.InferredFrom)
3281 InstAnalyzer PatInfo(*this);
3282 PatInfo.Analyze(&PTM);
3283 Errors += InferFromPattern(InstInfo, PatInfo, PTM.getSrcRecord());
3287 PrintFatalError("pattern conflicts");
3289 // Revisit instructions with undefined flags and no pattern.
3290 if (Target.guessInstructionProperties()) {
3291 for (CodeGenInstruction *InstInfo : Revisit) {
3292 if (InstInfo->InferredFrom)
3294 // The mayLoad and mayStore flags default to false.
3295 // Conservatively assume hasSideEffects if it wasn't explicit.
3296 if (InstInfo->hasSideEffects_Unset)
3297 InstInfo->hasSideEffects = true;
3302 // Complain about any flags that are still undefined.
3303 for (CodeGenInstruction *InstInfo : Revisit) {
3304 if (InstInfo->InferredFrom)
3306 if (InstInfo->hasSideEffects_Unset)
3307 PrintError(InstInfo->TheDef->getLoc(),
3308 "Can't infer hasSideEffects from patterns");
3309 if (InstInfo->mayStore_Unset)
3310 PrintError(InstInfo->TheDef->getLoc(),
3311 "Can't infer mayStore from patterns");
3312 if (InstInfo->mayLoad_Unset)
3313 PrintError(InstInfo->TheDef->getLoc(),
3314 "Can't infer mayLoad from patterns");
3319 /// Verify instruction flags against pattern node properties.
3320 void CodeGenDAGPatterns::VerifyInstructionFlags() {
3321 unsigned Errors = 0;
3322 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3323 const PatternToMatch &PTM = *I;
3324 SmallVector<Record*, 8> Instrs;
3325 getInstructionsInTree(PTM.getDstPattern(), Instrs);
3329 // Count the number of instructions with each flag set.
3330 unsigned NumSideEffects = 0;
3331 unsigned NumStores = 0;
3332 unsigned NumLoads = 0;
3333 for (const Record *Instr : Instrs) {
3334 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
3335 NumSideEffects += InstInfo.hasSideEffects;
3336 NumStores += InstInfo.mayStore;
3337 NumLoads += InstInfo.mayLoad;
3340 // Analyze the source pattern.
3341 InstAnalyzer PatInfo(*this);
3342 PatInfo.Analyze(&PTM);
3344 // Collect error messages.
3345 SmallVector<std::string, 4> Msgs;
3347 // Check for missing flags in the output.
3348 // Permit extra flags for now at least.
3349 if (PatInfo.hasSideEffects && !NumSideEffects)
3350 Msgs.push_back("pattern has side effects, but hasSideEffects isn't set");
3352 // Don't verify store flags on instructions with side effects. At least for
3353 // intrinsics, side effects implies mayStore.
3354 if (!PatInfo.hasSideEffects && PatInfo.mayStore && !NumStores)
3355 Msgs.push_back("pattern may store, but mayStore isn't set");
3357 // Similarly, mayStore implies mayLoad on intrinsics.
3358 if (!PatInfo.mayStore && PatInfo.mayLoad && !NumLoads)
3359 Msgs.push_back("pattern may load, but mayLoad isn't set");
3361 // Print error messages.
3366 for (const std::string &Msg : Msgs)
3367 PrintError(PTM.getSrcRecord()->getLoc(), Twine(Msg) + " on the " +
3368 (Instrs.size() == 1 ?
3369 "instruction" : "output instructions"));
3370 // Provide the location of the relevant instruction definitions.
3371 for (const Record *Instr : Instrs) {
3372 if (Instr != PTM.getSrcRecord())
3373 PrintError(Instr->getLoc(), "defined here");
3374 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
3375 if (InstInfo.InferredFrom &&
3376 InstInfo.InferredFrom != InstInfo.TheDef &&
3377 InstInfo.InferredFrom != PTM.getSrcRecord())
3378 PrintError(InstInfo.InferredFrom->getLoc(), "inferred from pattern");
3382 PrintFatalError("Errors in DAG patterns");
3385 /// Given a pattern result with an unresolved type, see if we can find one
3386 /// instruction with an unresolved result type. Force this result type to an
3387 /// arbitrary element if it's possible types to converge results.
3388 static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
3392 // Analyze children.
3393 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3394 if (ForceArbitraryInstResultType(N->getChild(i), TP))
3397 if (!N->getOperator()->isSubClassOf("Instruction"))
3400 // If this type is already concrete or completely unknown we can't do
3402 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
3403 if (N->getExtType(i).isCompletelyUnknown() || N->getExtType(i).isConcrete())
3406 // Otherwise, force its type to the first possibility (an arbitrary choice).
3407 if (N->getExtType(i).MergeInTypeInfo(N->getExtType(i).getTypeList()[0], TP))
3414 void CodeGenDAGPatterns::ParsePatterns() {
3415 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
3417 for (Record *CurPattern : Patterns) {
3418 DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
3420 // If the pattern references the null_frag, there's nothing to do.
3421 if (hasNullFragReference(Tree))
3424 TreePattern *Pattern = new TreePattern(CurPattern, Tree, true, *this);
3426 // Inline pattern fragments into it.
3427 Pattern->InlinePatternFragments();
3429 ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
3430 if (LI->empty()) continue; // no pattern.
3432 // Parse the instruction.
3433 TreePattern Result(CurPattern, LI, false, *this);
3435 // Inline pattern fragments into it.
3436 Result.InlinePatternFragments();
3438 if (Result.getNumTrees() != 1)
3439 Result.error("Cannot handle instructions producing instructions "
3440 "with temporaries yet!");
3442 bool IterateInference;
3443 bool InferredAllPatternTypes, InferredAllResultTypes;
3445 // Infer as many types as possible. If we cannot infer all of them, we
3446 // can never do anything with this pattern: report it to the user.
3447 InferredAllPatternTypes =
3448 Pattern->InferAllTypes(&Pattern->getNamedNodesMap());
3450 // Infer as many types as possible. If we cannot infer all of them, we
3451 // can never do anything with this pattern: report it to the user.
3452 InferredAllResultTypes =
3453 Result.InferAllTypes(&Pattern->getNamedNodesMap());
3455 IterateInference = false;
3457 // Apply the type of the result to the source pattern. This helps us
3458 // resolve cases where the input type is known to be a pointer type (which
3459 // is considered resolved), but the result knows it needs to be 32- or
3460 // 64-bits. Infer the other way for good measure.
3461 for (unsigned i = 0, e = std::min(Result.getTree(0)->getNumTypes(),
3462 Pattern->getTree(0)->getNumTypes());
3464 IterateInference = Pattern->getTree(0)->UpdateNodeType(
3465 i, Result.getTree(0)->getExtType(i), Result);
3466 IterateInference |= Result.getTree(0)->UpdateNodeType(
3467 i, Pattern->getTree(0)->getExtType(i), Result);
3470 // If our iteration has converged and the input pattern's types are fully
3471 // resolved but the result pattern is not fully resolved, we may have a
3472 // situation where we have two instructions in the result pattern and
3473 // the instructions require a common register class, but don't care about
3474 // what actual MVT is used. This is actually a bug in our modelling:
3475 // output patterns should have register classes, not MVTs.
3477 // In any case, to handle this, we just go through and disambiguate some
3478 // arbitrary types to the result pattern's nodes.
3479 if (!IterateInference && InferredAllPatternTypes &&
3480 !InferredAllResultTypes)
3482 ForceArbitraryInstResultType(Result.getTree(0), Result);
3483 } while (IterateInference);
3485 // Verify that we inferred enough types that we can do something with the
3486 // pattern and result. If these fire the user has to add type casts.
3487 if (!InferredAllPatternTypes)
3488 Pattern->error("Could not infer all types in pattern!");
3489 if (!InferredAllResultTypes) {
3491 Result.error("Could not infer all types in pattern result!");
3494 // Validate that the input pattern is correct.
3495 std::map<std::string, TreePatternNode*> InstInputs;
3496 std::map<std::string, TreePatternNode*> InstResults;
3497 std::vector<Record*> InstImpResults;
3498 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
3499 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
3500 InstInputs, InstResults,
3503 // Promote the xform function to be an explicit node if set.
3504 TreePatternNode *DstPattern = Result.getOnlyTree();
3505 std::vector<TreePatternNode*> ResultNodeOperands;
3506 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
3507 TreePatternNode *OpNode = DstPattern->getChild(ii);
3508 if (Record *Xform = OpNode->getTransformFn()) {
3509 OpNode->setTransformFn(nullptr);
3510 std::vector<TreePatternNode*> Children;
3511 Children.push_back(OpNode);
3512 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
3514 ResultNodeOperands.push_back(OpNode);
3516 DstPattern = Result.getOnlyTree();
3517 if (!DstPattern->isLeaf())
3518 DstPattern = new TreePatternNode(DstPattern->getOperator(),
3520 DstPattern->getNumTypes());
3522 for (unsigned i = 0, e = Result.getOnlyTree()->getNumTypes(); i != e; ++i)
3523 DstPattern->setType(i, Result.getOnlyTree()->getExtType(i));
3525 TreePattern Temp(Result.getRecord(), DstPattern, false, *this);
3526 Temp.InferAllTypes();
3529 AddPatternToMatch(Pattern,
3530 PatternToMatch(CurPattern,
3531 CurPattern->getValueAsListInit("Predicates"),
3532 Pattern->getTree(0),
3533 Temp.getOnlyTree(), InstImpResults,
3534 CurPattern->getValueAsInt("AddedComplexity"),
3535 CurPattern->getID()));
3539 /// CombineChildVariants - Given a bunch of permutations of each child of the
3540 /// 'operator' node, put them together in all possible ways.
3541 static void CombineChildVariants(TreePatternNode *Orig,
3542 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
3543 std::vector<TreePatternNode*> &OutVariants,
3544 CodeGenDAGPatterns &CDP,
3545 const MultipleUseVarSet &DepVars) {
3546 // Make sure that each operand has at least one variant to choose from.
3547 for (const auto &Variants : ChildVariants)
3548 if (Variants.empty())
3551 // The end result is an all-pairs construction of the resultant pattern.
3552 std::vector<unsigned> Idxs;
3553 Idxs.resize(ChildVariants.size());
3557 DEBUG(if (!Idxs.empty()) {
3558 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
3559 for (unsigned Idx : Idxs) {
3560 errs() << Idx << " ";
3565 // Create the variant and add it to the output list.
3566 std::vector<TreePatternNode*> NewChildren;
3567 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
3568 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
3569 auto R = llvm::make_unique<TreePatternNode>(
3570 Orig->getOperator(), NewChildren, Orig->getNumTypes());
3572 // Copy over properties.
3573 R->setName(Orig->getName());
3574 R->setPredicateFns(Orig->getPredicateFns());
3575 R->setTransformFn(Orig->getTransformFn());
3576 for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
3577 R->setType(i, Orig->getExtType(i));
3579 // If this pattern cannot match, do not include it as a variant.
3580 std::string ErrString;
3581 // Scan to see if this pattern has already been emitted. We can get
3582 // duplication due to things like commuting:
3583 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
3584 // which are the same pattern. Ignore the dups.
3585 if (R->canPatternMatch(ErrString, CDP) &&
3586 std::none_of(OutVariants.begin(), OutVariants.end(),
3587 [&](TreePatternNode *Variant) {
3588 return R->isIsomorphicTo(Variant, DepVars);
3590 OutVariants.push_back(R.release());
3592 // Increment indices to the next permutation by incrementing the
3593 // indices from last index backward, e.g., generate the sequence
3594 // [0, 0], [0, 1], [1, 0], [1, 1].
3596 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
3597 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
3602 NotDone = (IdxsIdx >= 0);
3606 /// CombineChildVariants - A helper function for binary operators.
3608 static void CombineChildVariants(TreePatternNode *Orig,
3609 const std::vector<TreePatternNode*> &LHS,
3610 const std::vector<TreePatternNode*> &RHS,
3611 std::vector<TreePatternNode*> &OutVariants,
3612 CodeGenDAGPatterns &CDP,
3613 const MultipleUseVarSet &DepVars) {
3614 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3615 ChildVariants.push_back(LHS);
3616 ChildVariants.push_back(RHS);
3617 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
3621 static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
3622 std::vector<TreePatternNode *> &Children) {
3623 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
3624 Record *Operator = N->getOperator();
3626 // Only permit raw nodes.
3627 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
3628 N->getTransformFn()) {
3629 Children.push_back(N);
3633 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
3634 Children.push_back(N->getChild(0));
3636 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
3638 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
3639 Children.push_back(N->getChild(1));
3641 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
3644 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
3645 /// the (potentially recursive) pattern by using algebraic laws.
3647 static void GenerateVariantsOf(TreePatternNode *N,
3648 std::vector<TreePatternNode*> &OutVariants,
3649 CodeGenDAGPatterns &CDP,
3650 const MultipleUseVarSet &DepVars) {
3651 // We cannot permute leaves or ComplexPattern uses.
3652 if (N->isLeaf() || N->getOperator()->isSubClassOf("ComplexPattern")) {
3653 OutVariants.push_back(N);
3657 // Look up interesting info about the node.
3658 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
3660 // If this node is associative, re-associate.
3661 if (NodeInfo.hasProperty(SDNPAssociative)) {
3662 // Re-associate by pulling together all of the linked operators
3663 std::vector<TreePatternNode*> MaximalChildren;
3664 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
3666 // Only handle child sizes of 3. Otherwise we'll end up trying too many
3668 if (MaximalChildren.size() == 3) {
3669 // Find the variants of all of our maximal children.
3670 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
3671 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
3672 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
3673 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
3675 // There are only two ways we can permute the tree:
3676 // (A op B) op C and A op (B op C)
3677 // Within these forms, we can also permute A/B/C.
3679 // Generate legal pair permutations of A/B/C.
3680 std::vector<TreePatternNode*> ABVariants;
3681 std::vector<TreePatternNode*> BAVariants;
3682 std::vector<TreePatternNode*> ACVariants;
3683 std::vector<TreePatternNode*> CAVariants;
3684 std::vector<TreePatternNode*> BCVariants;
3685 std::vector<TreePatternNode*> CBVariants;
3686 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
3687 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
3688 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
3689 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
3690 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
3691 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
3693 // Combine those into the result: (x op x) op x
3694 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
3695 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
3696 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
3697 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
3698 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
3699 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
3701 // Combine those into the result: x op (x op x)
3702 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
3703 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
3704 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
3705 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
3706 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
3707 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
3712 // Compute permutations of all children.
3713 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3714 ChildVariants.resize(N->getNumChildren());
3715 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3716 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
3718 // Build all permutations based on how the children were formed.
3719 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
3721 // If this node is commutative, consider the commuted order.
3722 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
3723 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
3724 assert((N->getNumChildren()==2 || isCommIntrinsic) &&
3725 "Commutative but doesn't have 2 children!");
3726 // Don't count children which are actually register references.
3728 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
3729 TreePatternNode *Child = N->getChild(i);
3730 if (Child->isLeaf())
3731 if (DefInit *DI = dyn_cast<DefInit>(Child->getLeafValue())) {
3732 Record *RR = DI->getDef();
3733 if (RR->isSubClassOf("Register"))
3738 // Consider the commuted order.
3739 if (isCommIntrinsic) {
3740 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
3741 // operands are the commutative operands, and there might be more operands
3744 "Commutative intrinsic should have at least 3 children!");
3745 std::vector<std::vector<TreePatternNode*> > Variants;
3746 Variants.push_back(ChildVariants[0]); // Intrinsic id.
3747 Variants.push_back(ChildVariants[2]);
3748 Variants.push_back(ChildVariants[1]);
3749 for (unsigned i = 3; i != NC; ++i)
3750 Variants.push_back(ChildVariants[i]);
3751 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
3753 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
3754 OutVariants, CDP, DepVars);
3759 // GenerateVariants - Generate variants. For example, commutative patterns can
3760 // match multiple ways. Add them to PatternsToMatch as well.
3761 void CodeGenDAGPatterns::GenerateVariants() {
3762 DEBUG(errs() << "Generating instruction variants.\n");
3764 // Loop over all of the patterns we've collected, checking to see if we can
3765 // generate variants of the instruction, through the exploitation of
3766 // identities. This permits the target to provide aggressive matching without
3767 // the .td file having to contain tons of variants of instructions.
3769 // Note that this loop adds new patterns to the PatternsToMatch list, but we
3770 // intentionally do not reconsider these. Any variants of added patterns have
3771 // already been added.
3773 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
3774 MultipleUseVarSet DepVars;
3775 std::vector<TreePatternNode*> Variants;
3776 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
3777 DEBUG(errs() << "Dependent/multiply used variables: ");
3778 DEBUG(DumpDepVars(DepVars));
3779 DEBUG(errs() << "\n");
3780 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this,
3783 assert(!Variants.empty() && "Must create at least original variant!");
3784 Variants.erase(Variants.begin()); // Remove the original pattern.
3786 if (Variants.empty()) // No variants for this pattern.
3789 DEBUG(errs() << "FOUND VARIANTS OF: ";
3790 PatternsToMatch[i].getSrcPattern()->dump();
3793 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
3794 TreePatternNode *Variant = Variants[v];
3796 DEBUG(errs() << " VAR#" << v << ": ";
3800 // Scan to see if an instruction or explicit pattern already matches this.
3801 bool AlreadyExists = false;
3802 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
3803 // Skip if the top level predicates do not match.
3804 if (PatternsToMatch[i].getPredicates() !=
3805 PatternsToMatch[p].getPredicates())
3807 // Check to see if this variant already exists.
3808 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),
3810 DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
3811 AlreadyExists = true;
3815 // If we already have it, ignore the variant.
3816 if (AlreadyExists) continue;
3818 // Otherwise, add it to the list of patterns we have.
3819 PatternsToMatch.emplace_back(
3820 PatternsToMatch[i].getSrcRecord(), PatternsToMatch[i].getPredicates(),
3821 Variant, PatternsToMatch[i].getDstPattern(),
3822 PatternsToMatch[i].getDstRegs(),
3823 PatternsToMatch[i].getAddedComplexity(), Record::getNewUID());
3826 DEBUG(errs() << "\n");