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/SmallString.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/ADT/Twine.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/ErrorHandling.h"
22 #include "llvm/TableGen/Error.h"
23 #include "llvm/TableGen/Record.h"
29 #define DEBUG_TYPE "dag-patterns"
31 //===----------------------------------------------------------------------===//
32 // EEVT::TypeSet Implementation
33 //===----------------------------------------------------------------------===//
35 static inline bool isInteger(MVT::SimpleValueType VT) {
36 return MVT(VT).isInteger();
38 static inline bool isFloatingPoint(MVT::SimpleValueType VT) {
39 return MVT(VT).isFloatingPoint();
41 static inline bool isVector(MVT::SimpleValueType VT) {
42 return MVT(VT).isVector();
44 static inline bool isScalar(MVT::SimpleValueType VT) {
45 return !MVT(VT).isVector();
48 EEVT::TypeSet::TypeSet(MVT::SimpleValueType VT, TreePattern &TP) {
51 else if (VT == MVT::fAny)
52 EnforceFloatingPoint(TP);
53 else if (VT == MVT::vAny)
56 assert((VT < MVT::LAST_VALUETYPE || VT == MVT::iPTR ||
57 VT == MVT::iPTRAny || VT == MVT::Any) && "Not a concrete type!");
58 TypeVec.push_back(VT);
63 EEVT::TypeSet::TypeSet(ArrayRef<MVT::SimpleValueType> VTList) {
64 assert(!VTList.empty() && "empty list?");
65 TypeVec.append(VTList.begin(), VTList.end());
68 assert(VTList[0] != MVT::iAny && VTList[0] != MVT::vAny &&
69 VTList[0] != MVT::fAny);
71 // Verify no duplicates.
72 array_pod_sort(TypeVec.begin(), TypeVec.end());
73 assert(std::unique(TypeVec.begin(), TypeVec.end()) == TypeVec.end());
76 /// FillWithPossibleTypes - Set to all legal types and return true, only valid
77 /// on completely unknown type sets.
78 bool EEVT::TypeSet::FillWithPossibleTypes(TreePattern &TP,
79 bool (*Pred)(MVT::SimpleValueType),
80 const char *PredicateName) {
81 assert(isCompletelyUnknown());
82 ArrayRef<MVT::SimpleValueType> LegalTypes =
83 TP.getDAGPatterns().getTargetInfo().getLegalValueTypes();
88 for (MVT::SimpleValueType VT : LegalTypes)
89 if (!Pred || Pred(VT))
90 TypeVec.push_back(VT);
92 // If we have nothing that matches the predicate, bail out.
93 if (TypeVec.empty()) {
94 TP.error("Type inference contradiction found, no " +
95 std::string(PredicateName) + " types found");
98 // No need to sort with one element.
99 if (TypeVec.size() == 1) return true;
101 // Remove duplicates.
102 array_pod_sort(TypeVec.begin(), TypeVec.end());
103 TypeVec.erase(std::unique(TypeVec.begin(), TypeVec.end()), TypeVec.end());
108 /// hasIntegerTypes - Return true if this TypeSet contains iAny or an
109 /// integer value type.
110 bool EEVT::TypeSet::hasIntegerTypes() const {
111 return any_of(TypeVec, isInteger);
114 /// hasFloatingPointTypes - Return true if this TypeSet contains an fAny or
115 /// a floating point value type.
116 bool EEVT::TypeSet::hasFloatingPointTypes() const {
117 return any_of(TypeVec, isFloatingPoint);
120 /// hasScalarTypes - Return true if this TypeSet contains a scalar value type.
121 bool EEVT::TypeSet::hasScalarTypes() const {
122 return any_of(TypeVec, isScalar);
125 /// hasVectorTypes - Return true if this TypeSet contains a vAny or a vector
127 bool EEVT::TypeSet::hasVectorTypes() const {
128 return any_of(TypeVec, isVector);
132 std::string EEVT::TypeSet::getName() const {
133 if (TypeVec.empty()) return "<empty>";
137 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i) {
138 std::string VTName = llvm::getEnumName(TypeVec[i]);
139 // Strip off MVT:: prefix if present.
140 if (VTName.substr(0,5) == "MVT::")
141 VTName = VTName.substr(5);
142 if (i) Result += ':';
146 if (TypeVec.size() == 1)
148 return "{" + Result + "}";
151 /// MergeInTypeInfo - This merges in type information from the specified
152 /// argument. If 'this' changes, it returns true. If the two types are
153 /// contradictory (e.g. merge f32 into i32) then this flags an error.
154 bool EEVT::TypeSet::MergeInTypeInfo(const EEVT::TypeSet &InVT, TreePattern &TP){
155 if (InVT.isCompletelyUnknown() || *this == InVT || TP.hasError())
158 if (isCompletelyUnknown()) {
163 assert(!TypeVec.empty() && !InVT.TypeVec.empty() && "No unknowns");
165 // Handle the abstract cases, seeing if we can resolve them better.
166 switch (TypeVec[0]) {
170 if (InVT.hasIntegerTypes()) {
171 EEVT::TypeSet InCopy(InVT);
172 InCopy.EnforceInteger(TP);
173 InCopy.EnforceScalar(TP);
175 if (InCopy.isConcrete()) {
176 // If the RHS has one integer type, upgrade iPTR to i32.
177 TypeVec[0] = InVT.TypeVec[0];
181 // If the input has multiple scalar integers, this doesn't add any info.
182 if (!InCopy.isCompletelyUnknown())
188 // If the input constraint is iAny/iPTR and this is an integer type list,
189 // remove non-integer types from the list.
190 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
192 bool MadeChange = EnforceInteger(TP);
194 // If we're merging in iPTR/iPTRAny and the node currently has a list of
195 // multiple different integer types, replace them with a single iPTR.
196 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
197 TypeVec.size() != 1) {
198 TypeVec.assign(1, InVT.TypeVec[0]);
205 // If this is a type list and the RHS is a typelist as well, eliminate entries
206 // from this list that aren't in the other one.
207 TypeSet InputSet(*this);
210 std::set_intersection(InputSet.TypeVec.begin(), InputSet.TypeVec.end(),
211 InVT.TypeVec.begin(), InVT.TypeVec.end(),
212 std::back_inserter(TypeVec));
214 // If the intersection is the same size as the original set then we're done.
215 if (TypeVec.size() == InputSet.TypeVec.size())
218 // If we removed all of our types, we have a type contradiction.
219 if (!TypeVec.empty())
222 // FIXME: Really want an SMLoc here!
223 TP.error("Type inference contradiction found, merging '" +
224 InVT.getName() + "' into '" + InputSet.getName() + "'");
228 /// EnforceInteger - Remove all non-integer types from this set.
229 bool EEVT::TypeSet::EnforceInteger(TreePattern &TP) {
232 // If we know nothing, then get the full set.
234 return FillWithPossibleTypes(TP, isInteger, "integer");
236 if (!hasFloatingPointTypes())
239 TypeSet InputSet(*this);
241 // Filter out all the fp types.
242 TypeVec.erase(remove_if(TypeVec, 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(remove_if(TypeVec, std::not1(std::ptr_fun(isFloatingPoint))),
270 if (TypeVec.empty()) {
271 TP.error("Type inference contradiction found, '" +
272 InputSet.getName() + "' needs to be floating point");
278 /// EnforceScalar - Remove all vector types from this.
279 bool EEVT::TypeSet::EnforceScalar(TreePattern &TP) {
283 // If we know nothing, then get the full set.
285 return FillWithPossibleTypes(TP, isScalar, "scalar");
287 if (!hasVectorTypes())
290 TypeSet InputSet(*this);
292 // Filter out all the vector types.
293 TypeVec.erase(remove_if(TypeVec, std::not1(std::ptr_fun(isScalar))),
296 if (TypeVec.empty()) {
297 TP.error("Type inference contradiction found, '" +
298 InputSet.getName() + "' needs to be scalar");
304 /// EnforceVector - Remove all vector types from this.
305 bool EEVT::TypeSet::EnforceVector(TreePattern &TP) {
309 // If we know nothing, then get the full set.
311 return FillWithPossibleTypes(TP, isVector, "vector");
313 TypeSet InputSet(*this);
314 bool MadeChange = false;
316 // Filter out all the scalar types.
317 TypeVec.erase(remove_if(TypeVec, std::not1(std::ptr_fun(isVector))),
320 if (TypeVec.empty()) {
321 TP.error("Type inference contradiction found, '" +
322 InputSet.getName() + "' needs to be a vector");
330 /// EnforceSmallerThan - 'this' must be a smaller VT than Other. For vectors
331 /// this should be based on the element type. Update this and other based on
332 /// this information.
333 bool EEVT::TypeSet::EnforceSmallerThan(EEVT::TypeSet &Other, TreePattern &TP) {
337 // Both operands must be integer or FP, but we don't care which.
338 bool MadeChange = false;
340 if (isCompletelyUnknown())
341 MadeChange = FillWithPossibleTypes(TP);
343 if (Other.isCompletelyUnknown())
344 MadeChange = Other.FillWithPossibleTypes(TP);
346 // If one side is known to be integer or known to be FP but the other side has
347 // no information, get at least the type integrality info in there.
348 if (!hasFloatingPointTypes())
349 MadeChange |= Other.EnforceInteger(TP);
350 else if (!hasIntegerTypes())
351 MadeChange |= Other.EnforceFloatingPoint(TP);
352 if (!Other.hasFloatingPointTypes())
353 MadeChange |= EnforceInteger(TP);
354 else if (!Other.hasIntegerTypes())
355 MadeChange |= EnforceFloatingPoint(TP);
357 assert(!isCompletelyUnknown() && !Other.isCompletelyUnknown() &&
358 "Should have a type list now");
360 // If one contains vectors but the other doesn't pull vectors out.
361 if (!hasVectorTypes())
362 MadeChange |= Other.EnforceScalar(TP);
363 else if (!hasScalarTypes())
364 MadeChange |= Other.EnforceVector(TP);
365 if (!Other.hasVectorTypes())
366 MadeChange |= EnforceScalar(TP);
367 else if (!Other.hasScalarTypes())
368 MadeChange |= EnforceVector(TP);
370 // This code does not currently handle nodes which have multiple types,
371 // where some types are integer, and some are fp. Assert that this is not
373 assert(!(hasIntegerTypes() && hasFloatingPointTypes()) &&
374 !(Other.hasIntegerTypes() && Other.hasFloatingPointTypes()) &&
375 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
380 // Okay, find the smallest type from current set and remove anything the
381 // same or smaller from the other set. We need to ensure that the scalar
382 // type size is smaller than the scalar size of the smallest type. For
383 // vectors, we also need to make sure that the total size is no larger than
384 // the size of the smallest type.
386 TypeSet InputSet(Other);
387 MVT Smallest = *std::min_element(TypeVec.begin(), TypeVec.end(),
389 return A.getScalarSizeInBits() < B.getScalarSizeInBits() ||
390 (A.getScalarSizeInBits() == B.getScalarSizeInBits() &&
391 A.getSizeInBits() < B.getSizeInBits());
394 auto I = remove_if(Other.TypeVec, [Smallest](MVT OtherVT) {
395 // Don't compare vector and non-vector types.
396 if (OtherVT.isVector() != Smallest.isVector())
398 // The getSizeInBits() check here is only needed for vectors, but is
399 // a subset of the scalar check for scalars so no need to qualify.
400 return OtherVT.getScalarSizeInBits() <= Smallest.getScalarSizeInBits() ||
401 OtherVT.getSizeInBits() < Smallest.getSizeInBits();
403 MadeChange |= I != Other.TypeVec.end(); // If we're about to remove types.
404 Other.TypeVec.erase(I, Other.TypeVec.end());
406 if (Other.TypeVec.empty()) {
407 TP.error("Type inference contradiction found, '" + InputSet.getName() +
408 "' has nothing larger than '" + getName() +"'!");
413 // Okay, find the largest type from the other set and remove anything the
414 // same or smaller from the current set. We need to ensure that the scalar
415 // type size is larger than the scalar size of the largest type. For
416 // vectors, we also need to make sure that the total size is no smaller than
417 // the size of the largest type.
419 TypeSet InputSet(*this);
420 MVT Largest = *std::max_element(Other.TypeVec.begin(), Other.TypeVec.end(),
422 return A.getScalarSizeInBits() < B.getScalarSizeInBits() ||
423 (A.getScalarSizeInBits() == B.getScalarSizeInBits() &&
424 A.getSizeInBits() < B.getSizeInBits());
426 auto I = remove_if(TypeVec, [Largest](MVT OtherVT) {
427 // Don't compare vector and non-vector types.
428 if (OtherVT.isVector() != Largest.isVector())
430 return OtherVT.getScalarSizeInBits() >= Largest.getScalarSizeInBits() ||
431 OtherVT.getSizeInBits() > Largest.getSizeInBits();
433 MadeChange |= I != TypeVec.end(); // If we're about to remove types.
434 TypeVec.erase(I, TypeVec.end());
436 if (TypeVec.empty()) {
437 TP.error("Type inference contradiction found, '" + InputSet.getName() +
438 "' has nothing smaller than '" + Other.getName() +"'!");
446 /// EnforceVectorEltTypeIs - 'this' is now constrained to be a vector type
447 /// whose element is specified by VTOperand.
448 bool EEVT::TypeSet::EnforceVectorEltTypeIs(MVT::SimpleValueType VT,
450 bool MadeChange = false;
452 MadeChange |= EnforceVector(TP);
454 TypeSet InputSet(*this);
456 // Filter out all the types which don't have the right element type.
457 auto I = remove_if(TypeVec, [VT](MVT VVT) {
458 return VVT.getVectorElementType().SimpleTy != VT;
460 MadeChange |= I != TypeVec.end();
461 TypeVec.erase(I, TypeVec.end());
463 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
464 TP.error("Type inference contradiction found, forcing '" +
465 InputSet.getName() + "' to have a vector element of type " +
473 /// EnforceVectorEltTypeIs - 'this' is now constrained to be a vector type
474 /// whose element is specified by VTOperand.
475 bool EEVT::TypeSet::EnforceVectorEltTypeIs(EEVT::TypeSet &VTOperand,
480 // "This" must be a vector and "VTOperand" must be a scalar.
481 bool MadeChange = false;
482 MadeChange |= EnforceVector(TP);
483 MadeChange |= VTOperand.EnforceScalar(TP);
485 // If we know the vector type, it forces the scalar to agree.
487 MVT IVT = getConcrete();
488 IVT = IVT.getVectorElementType();
489 return MadeChange || VTOperand.MergeInTypeInfo(IVT.SimpleTy, TP);
492 // If the scalar type is known, filter out vector types whose element types
494 if (!VTOperand.isConcrete())
497 MVT::SimpleValueType VT = VTOperand.getConcrete();
499 MadeChange |= EnforceVectorEltTypeIs(VT, TP);
504 /// EnforceVectorSubVectorTypeIs - 'this' is now constrained to be a
505 /// vector type specified by VTOperand.
506 bool EEVT::TypeSet::EnforceVectorSubVectorTypeIs(EEVT::TypeSet &VTOperand,
511 // "This" must be a vector and "VTOperand" must be a vector.
512 bool MadeChange = false;
513 MadeChange |= EnforceVector(TP);
514 MadeChange |= VTOperand.EnforceVector(TP);
516 // If one side is known to be integer or known to be FP but the other side has
517 // no information, get at least the type integrality info in there.
518 if (!hasFloatingPointTypes())
519 MadeChange |= VTOperand.EnforceInteger(TP);
520 else if (!hasIntegerTypes())
521 MadeChange |= VTOperand.EnforceFloatingPoint(TP);
522 if (!VTOperand.hasFloatingPointTypes())
523 MadeChange |= EnforceInteger(TP);
524 else if (!VTOperand.hasIntegerTypes())
525 MadeChange |= EnforceFloatingPoint(TP);
527 assert(!isCompletelyUnknown() && !VTOperand.isCompletelyUnknown() &&
528 "Should have a type list now");
530 // If we know the vector type, it forces the scalar types to agree.
531 // Also force one vector to have more elements than the other.
533 MVT IVT = getConcrete();
534 unsigned NumElems = IVT.getVectorNumElements();
535 IVT = IVT.getVectorElementType();
537 EEVT::TypeSet EltTypeSet(IVT.SimpleTy, TP);
538 MadeChange |= VTOperand.EnforceVectorEltTypeIs(EltTypeSet, TP);
540 // Only keep types that have less elements than VTOperand.
541 TypeSet InputSet(VTOperand);
543 auto I = remove_if(VTOperand.TypeVec, [NumElems](MVT VVT) {
544 return VVT.getVectorNumElements() >= NumElems;
546 MadeChange |= I != VTOperand.TypeVec.end();
547 VTOperand.TypeVec.erase(I, VTOperand.TypeVec.end());
549 if (VTOperand.TypeVec.empty()) { // FIXME: Really want an SMLoc here!
550 TP.error("Type inference contradiction found, forcing '" +
551 InputSet.getName() + "' to have less vector elements than '" +
555 } else if (VTOperand.isConcrete()) {
556 MVT IVT = VTOperand.getConcrete();
557 unsigned NumElems = IVT.getVectorNumElements();
558 IVT = IVT.getVectorElementType();
560 EEVT::TypeSet EltTypeSet(IVT.SimpleTy, TP);
561 MadeChange |= EnforceVectorEltTypeIs(EltTypeSet, TP);
563 // Only keep types that have more elements than 'this'.
564 TypeSet InputSet(*this);
566 auto I = remove_if(TypeVec, [NumElems](MVT VVT) {
567 return VVT.getVectorNumElements() <= NumElems;
569 MadeChange |= I != TypeVec.end();
570 TypeVec.erase(I, TypeVec.end());
572 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
573 TP.error("Type inference contradiction found, forcing '" +
574 InputSet.getName() + "' to have more vector elements than '" +
575 VTOperand.getName() + "'");
583 /// EnforceameNumElts - If VTOperand is a scalar, then 'this' is a scalar. If
584 /// VTOperand is a vector, then 'this' must have the same number of elements.
585 bool EEVT::TypeSet::EnforceSameNumElts(EEVT::TypeSet &VTOperand,
590 bool MadeChange = false;
592 if (isCompletelyUnknown())
593 MadeChange = FillWithPossibleTypes(TP);
595 if (VTOperand.isCompletelyUnknown())
596 MadeChange = VTOperand.FillWithPossibleTypes(TP);
598 // If one contains vectors but the other doesn't pull vectors out.
599 if (!hasVectorTypes())
600 MadeChange |= VTOperand.EnforceScalar(TP);
601 else if (!hasScalarTypes())
602 MadeChange |= VTOperand.EnforceVector(TP);
603 if (!VTOperand.hasVectorTypes())
604 MadeChange |= EnforceScalar(TP);
605 else if (!VTOperand.hasScalarTypes())
606 MadeChange |= EnforceVector(TP);
608 // If one type is a vector, make sure the other has the same element count.
609 // If this a scalar, then we are already done with the above.
611 MVT IVT = getConcrete();
612 if (IVT.isVector()) {
613 unsigned NumElems = IVT.getVectorNumElements();
615 // Only keep types that have same elements as 'this'.
616 TypeSet InputSet(VTOperand);
618 auto I = remove_if(VTOperand.TypeVec, [NumElems](MVT VVT) {
619 return VVT.getVectorNumElements() != NumElems;
621 MadeChange |= I != VTOperand.TypeVec.end();
622 VTOperand.TypeVec.erase(I, VTOperand.TypeVec.end());
624 if (VTOperand.TypeVec.empty()) { // FIXME: Really want an SMLoc here!
625 TP.error("Type inference contradiction found, forcing '" +
626 InputSet.getName() + "' to have same number elements as '" +
631 } else if (VTOperand.isConcrete()) {
632 MVT IVT = VTOperand.getConcrete();
633 if (IVT.isVector()) {
634 unsigned NumElems = IVT.getVectorNumElements();
636 // Only keep types that have same elements as VTOperand.
637 TypeSet InputSet(*this);
639 auto I = remove_if(TypeVec, [NumElems](MVT VVT) {
640 return VVT.getVectorNumElements() != NumElems;
642 MadeChange |= I != TypeVec.end();
643 TypeVec.erase(I, TypeVec.end());
645 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
646 TP.error("Type inference contradiction found, forcing '" +
647 InputSet.getName() + "' to have same number elements than '" +
648 VTOperand.getName() + "'");
657 /// EnforceSameSize - 'this' is now constrained to be same size as VTOperand.
658 bool EEVT::TypeSet::EnforceSameSize(EEVT::TypeSet &VTOperand,
663 bool MadeChange = false;
665 if (isCompletelyUnknown())
666 MadeChange = FillWithPossibleTypes(TP);
668 if (VTOperand.isCompletelyUnknown())
669 MadeChange = VTOperand.FillWithPossibleTypes(TP);
671 // If we know one of the types, it forces the other type agree.
673 MVT IVT = getConcrete();
674 unsigned Size = IVT.getSizeInBits();
676 // Only keep types that have the same size as 'this'.
677 TypeSet InputSet(VTOperand);
679 auto I = remove_if(VTOperand.TypeVec,
680 [&](MVT VT) { return VT.getSizeInBits() != Size; });
681 MadeChange |= I != VTOperand.TypeVec.end();
682 VTOperand.TypeVec.erase(I, VTOperand.TypeVec.end());
684 if (VTOperand.TypeVec.empty()) { // FIXME: Really want an SMLoc here!
685 TP.error("Type inference contradiction found, forcing '" +
686 InputSet.getName() + "' to have same size as '" +
690 } else if (VTOperand.isConcrete()) {
691 MVT IVT = VTOperand.getConcrete();
692 unsigned Size = IVT.getSizeInBits();
694 // Only keep types that have the same size as VTOperand.
695 TypeSet InputSet(*this);
698 remove_if(TypeVec, [&](MVT VT) { return VT.getSizeInBits() != Size; });
699 MadeChange |= I != TypeVec.end();
700 TypeVec.erase(I, TypeVec.end());
702 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
703 TP.error("Type inference contradiction found, forcing '" +
704 InputSet.getName() + "' to have same size as '" +
705 VTOperand.getName() + "'");
713 //===----------------------------------------------------------------------===//
714 // Helpers for working with extended types.
716 /// Dependent variable map for CodeGenDAGPattern variant generation
717 typedef std::map<std::string, int> DepVarMap;
719 static void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
721 if (isa<DefInit>(N->getLeafValue()))
722 DepMap[N->getName()]++;
724 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
725 FindDepVarsOf(N->getChild(i), DepMap);
729 /// Find dependent variables within child patterns
730 static void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
732 FindDepVarsOf(N, depcounts);
733 for (const std::pair<std::string, int> &Pair : depcounts) {
735 DepVars.insert(Pair.first);
740 /// Dump the dependent variable set:
741 static void DumpDepVars(MultipleUseVarSet &DepVars) {
742 if (DepVars.empty()) {
743 DEBUG(errs() << "<empty set>");
745 DEBUG(errs() << "[ ");
746 for (const std::string &DepVar : DepVars) {
747 DEBUG(errs() << DepVar << " ");
749 DEBUG(errs() << "]");
755 //===----------------------------------------------------------------------===//
756 // TreePredicateFn Implementation
757 //===----------------------------------------------------------------------===//
759 /// TreePredicateFn constructor. Here 'N' is a subclass of PatFrag.
760 TreePredicateFn::TreePredicateFn(TreePattern *N) : PatFragRec(N) {
761 assert((getPredCode().empty() || getImmCode().empty()) &&
762 ".td file corrupt: can't have a node predicate *and* an imm predicate");
765 std::string TreePredicateFn::getPredCode() const {
766 return PatFragRec->getRecord()->getValueAsString("PredicateCode");
769 std::string TreePredicateFn::getImmCode() const {
770 return PatFragRec->getRecord()->getValueAsString("ImmediateCode");
774 /// isAlwaysTrue - Return true if this is a noop predicate.
775 bool TreePredicateFn::isAlwaysTrue() const {
776 return getPredCode().empty() && getImmCode().empty();
779 /// Return the name to use in the generated code to reference this, this is
780 /// "Predicate_foo" if from a pattern fragment "foo".
781 std::string TreePredicateFn::getFnName() const {
782 return "Predicate_" + PatFragRec->getRecord()->getName().str();
785 /// getCodeToRunOnSDNode - Return the code for the function body that
786 /// evaluates this predicate. The argument is expected to be in "Node",
787 /// not N. This handles casting and conversion to a concrete node type as
789 std::string TreePredicateFn::getCodeToRunOnSDNode() const {
790 // Handle immediate predicates first.
791 std::string ImmCode = getImmCode();
792 if (!ImmCode.empty()) {
794 " int64_t Imm = cast<ConstantSDNode>(Node)->getSExtValue();\n";
795 return Result + ImmCode;
798 // Handle arbitrary node predicates.
799 assert(!getPredCode().empty() && "Don't have any predicate code!");
800 std::string ClassName;
801 if (PatFragRec->getOnlyTree()->isLeaf())
802 ClassName = "SDNode";
804 Record *Op = PatFragRec->getOnlyTree()->getOperator();
805 ClassName = PatFragRec->getDAGPatterns().getSDNodeInfo(Op).getSDClassName();
808 if (ClassName == "SDNode")
809 Result = " SDNode *N = Node;\n";
811 Result = " auto *N = cast<" + ClassName + ">(Node);\n";
813 return Result + getPredCode();
816 //===----------------------------------------------------------------------===//
817 // PatternToMatch implementation
821 /// getPatternSize - Return the 'size' of this pattern. We want to match large
822 /// patterns before small ones. This is used to determine the size of a
824 static unsigned getPatternSize(const TreePatternNode *P,
825 const CodeGenDAGPatterns &CGP) {
826 unsigned Size = 3; // The node itself.
827 // If the root node is a ConstantSDNode, increases its size.
828 // e.g. (set R32:$dst, 0).
829 if (P->isLeaf() && isa<IntInit>(P->getLeafValue()))
832 const ComplexPattern *AM = P->getComplexPatternInfo(CGP);
834 Size += AM->getComplexity();
836 // We don't want to count any children twice, so return early.
840 // If this node has some predicate function that must match, it adds to the
841 // complexity of this node.
842 if (!P->getPredicateFns().empty())
845 // Count children in the count if they are also nodes.
846 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
847 TreePatternNode *Child = P->getChild(i);
848 if (!Child->isLeaf() && Child->getNumTypes() &&
849 Child->getType(0) != MVT::Other)
850 Size += getPatternSize(Child, CGP);
851 else if (Child->isLeaf()) {
852 if (isa<IntInit>(Child->getLeafValue()))
853 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
854 else if (Child->getComplexPatternInfo(CGP))
855 Size += getPatternSize(Child, CGP);
856 else if (!Child->getPredicateFns().empty())
864 /// Compute the complexity metric for the input pattern. This roughly
865 /// corresponds to the number of nodes that are covered.
867 getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
868 return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();
872 /// getPredicateCheck - Return a single string containing all of this
873 /// pattern's predicates concatenated with "&&" operators.
875 std::string PatternToMatch::getPredicateCheck() const {
876 SmallVector<Record *, 4> PredicateRecs;
877 for (Init *I : Predicates->getValues()) {
878 if (DefInit *Pred = dyn_cast<DefInit>(I)) {
879 Record *Def = Pred->getDef();
880 if (!Def->isSubClassOf("Predicate")) {
884 llvm_unreachable("Unknown predicate type!");
886 PredicateRecs.push_back(Def);
889 // Sort so that different orders get canonicalized to the same string.
890 std::sort(PredicateRecs.begin(), PredicateRecs.end(), LessRecord());
892 SmallString<128> PredicateCheck;
893 for (Record *Pred : PredicateRecs) {
894 if (!PredicateCheck.empty())
895 PredicateCheck += " && ";
896 PredicateCheck += "(";
897 PredicateCheck += Pred->getValueAsString("CondString");
898 PredicateCheck += ")";
901 return PredicateCheck.str();
904 //===----------------------------------------------------------------------===//
905 // SDTypeConstraint implementation
908 SDTypeConstraint::SDTypeConstraint(Record *R) {
909 OperandNo = R->getValueAsInt("OperandNum");
911 if (R->isSubClassOf("SDTCisVT")) {
912 ConstraintType = SDTCisVT;
913 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
914 if (x.SDTCisVT_Info.VT == MVT::isVoid)
915 PrintFatalError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
917 } else if (R->isSubClassOf("SDTCisPtrTy")) {
918 ConstraintType = SDTCisPtrTy;
919 } else if (R->isSubClassOf("SDTCisInt")) {
920 ConstraintType = SDTCisInt;
921 } else if (R->isSubClassOf("SDTCisFP")) {
922 ConstraintType = SDTCisFP;
923 } else if (R->isSubClassOf("SDTCisVec")) {
924 ConstraintType = SDTCisVec;
925 } else if (R->isSubClassOf("SDTCisSameAs")) {
926 ConstraintType = SDTCisSameAs;
927 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
928 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
929 ConstraintType = SDTCisVTSmallerThanOp;
930 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
931 R->getValueAsInt("OtherOperandNum");
932 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
933 ConstraintType = SDTCisOpSmallerThanOp;
934 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
935 R->getValueAsInt("BigOperandNum");
936 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
937 ConstraintType = SDTCisEltOfVec;
938 x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
939 } else if (R->isSubClassOf("SDTCisSubVecOfVec")) {
940 ConstraintType = SDTCisSubVecOfVec;
941 x.SDTCisSubVecOfVec_Info.OtherOperandNum =
942 R->getValueAsInt("OtherOpNum");
943 } else if (R->isSubClassOf("SDTCVecEltisVT")) {
944 ConstraintType = SDTCVecEltisVT;
945 x.SDTCVecEltisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
946 if (MVT(x.SDTCVecEltisVT_Info.VT).isVector())
947 PrintFatalError(R->getLoc(), "Cannot use vector type as SDTCVecEltisVT");
948 if (!MVT(x.SDTCVecEltisVT_Info.VT).isInteger() &&
949 !MVT(x.SDTCVecEltisVT_Info.VT).isFloatingPoint())
950 PrintFatalError(R->getLoc(), "Must use integer or floating point type "
951 "as SDTCVecEltisVT");
952 } else if (R->isSubClassOf("SDTCisSameNumEltsAs")) {
953 ConstraintType = SDTCisSameNumEltsAs;
954 x.SDTCisSameNumEltsAs_Info.OtherOperandNum =
955 R->getValueAsInt("OtherOperandNum");
956 } else if (R->isSubClassOf("SDTCisSameSizeAs")) {
957 ConstraintType = SDTCisSameSizeAs;
958 x.SDTCisSameSizeAs_Info.OtherOperandNum =
959 R->getValueAsInt("OtherOperandNum");
961 PrintFatalError("Unrecognized SDTypeConstraint '" + R->getName() + "'!\n");
965 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
966 /// N, and the result number in ResNo.
967 static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
968 const SDNodeInfo &NodeInfo,
970 unsigned NumResults = NodeInfo.getNumResults();
971 if (OpNo < NumResults) {
978 if (OpNo >= N->getNumChildren()) {
980 raw_string_ostream OS(S);
981 OS << "Invalid operand number in type constraint "
982 << (OpNo+NumResults) << " ";
984 PrintFatalError(OS.str());
987 return N->getChild(OpNo);
990 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
991 /// constraint to the nodes operands. This returns true if it makes a
992 /// change, false otherwise. If a type contradiction is found, flag an error.
993 bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
994 const SDNodeInfo &NodeInfo,
995 TreePattern &TP) const {
999 unsigned ResNo = 0; // The result number being referenced.
1000 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
1002 switch (ConstraintType) {
1004 // Operand must be a particular type.
1005 return NodeToApply->UpdateNodeType(ResNo, x.SDTCisVT_Info.VT, TP);
1007 // Operand must be same as target pointer type.
1008 return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
1010 // Require it to be one of the legal integer VTs.
1011 return NodeToApply->getExtType(ResNo).EnforceInteger(TP);
1013 // Require it to be one of the legal fp VTs.
1014 return NodeToApply->getExtType(ResNo).EnforceFloatingPoint(TP);
1016 // Require it to be one of the legal vector VTs.
1017 return NodeToApply->getExtType(ResNo).EnforceVector(TP);
1018 case SDTCisSameAs: {
1019 unsigned OResNo = 0;
1020 TreePatternNode *OtherNode =
1021 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
1022 return NodeToApply->UpdateNodeType(ResNo, OtherNode->getExtType(OResNo),TP)|
1023 OtherNode->UpdateNodeType(OResNo,NodeToApply->getExtType(ResNo),TP);
1025 case SDTCisVTSmallerThanOp: {
1026 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
1027 // have an integer type that is smaller than the VT.
1028 if (!NodeToApply->isLeaf() ||
1029 !isa<DefInit>(NodeToApply->getLeafValue()) ||
1030 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
1031 ->isSubClassOf("ValueType")) {
1032 TP.error(N->getOperator()->getName() + " expects a VT operand!");
1035 MVT::SimpleValueType VT =
1036 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
1038 EEVT::TypeSet TypeListTmp(VT, TP);
1040 unsigned OResNo = 0;
1041 TreePatternNode *OtherNode =
1042 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
1045 return TypeListTmp.EnforceSmallerThan(OtherNode->getExtType(OResNo), TP);
1047 case SDTCisOpSmallerThanOp: {
1048 unsigned BResNo = 0;
1049 TreePatternNode *BigOperand =
1050 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
1052 return NodeToApply->getExtType(ResNo).
1053 EnforceSmallerThan(BigOperand->getExtType(BResNo), TP);
1055 case SDTCisEltOfVec: {
1056 unsigned VResNo = 0;
1057 TreePatternNode *VecOperand =
1058 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
1061 // Filter vector types out of VecOperand that don't have the right element
1063 return VecOperand->getExtType(VResNo).
1064 EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), TP);
1066 case SDTCisSubVecOfVec: {
1067 unsigned VResNo = 0;
1068 TreePatternNode *BigVecOperand =
1069 getOperandNum(x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo,
1072 // Filter vector types out of BigVecOperand that don't have the
1073 // right subvector type.
1074 return BigVecOperand->getExtType(VResNo).
1075 EnforceVectorSubVectorTypeIs(NodeToApply->getExtType(ResNo), TP);
1077 case SDTCVecEltisVT: {
1078 return NodeToApply->getExtType(ResNo).
1079 EnforceVectorEltTypeIs(x.SDTCVecEltisVT_Info.VT, TP);
1081 case SDTCisSameNumEltsAs: {
1082 unsigned OResNo = 0;
1083 TreePatternNode *OtherNode =
1084 getOperandNum(x.SDTCisSameNumEltsAs_Info.OtherOperandNum,
1085 N, NodeInfo, OResNo);
1086 return OtherNode->getExtType(OResNo).
1087 EnforceSameNumElts(NodeToApply->getExtType(ResNo), TP);
1089 case SDTCisSameSizeAs: {
1090 unsigned OResNo = 0;
1091 TreePatternNode *OtherNode =
1092 getOperandNum(x.SDTCisSameSizeAs_Info.OtherOperandNum,
1093 N, NodeInfo, OResNo);
1094 return OtherNode->getExtType(OResNo).
1095 EnforceSameSize(NodeToApply->getExtType(ResNo), TP);
1098 llvm_unreachable("Invalid ConstraintType!");
1101 // Update the node type to match an instruction operand or result as specified
1102 // in the ins or outs lists on the instruction definition. Return true if the
1103 // type was actually changed.
1104 bool TreePatternNode::UpdateNodeTypeFromInst(unsigned ResNo,
1107 // The 'unknown' operand indicates that types should be inferred from the
1109 if (Operand->isSubClassOf("unknown_class"))
1112 // The Operand class specifies a type directly.
1113 if (Operand->isSubClassOf("Operand"))
1114 return UpdateNodeType(ResNo, getValueType(Operand->getValueAsDef("Type")),
1117 // PointerLikeRegClass has a type that is determined at runtime.
1118 if (Operand->isSubClassOf("PointerLikeRegClass"))
1119 return UpdateNodeType(ResNo, MVT::iPTR, TP);
1121 // Both RegisterClass and RegisterOperand operands derive their types from a
1122 // register class def.
1123 Record *RC = nullptr;
1124 if (Operand->isSubClassOf("RegisterClass"))
1126 else if (Operand->isSubClassOf("RegisterOperand"))
1127 RC = Operand->getValueAsDef("RegClass");
1129 assert(RC && "Unknown operand type");
1130 CodeGenTarget &Tgt = TP.getDAGPatterns().getTargetInfo();
1131 return UpdateNodeType(ResNo, Tgt.getRegisterClass(RC).getValueTypes(), TP);
1135 //===----------------------------------------------------------------------===//
1136 // SDNodeInfo implementation
1138 SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
1139 EnumName = R->getValueAsString("Opcode");
1140 SDClassName = R->getValueAsString("SDClass");
1141 Record *TypeProfile = R->getValueAsDef("TypeProfile");
1142 NumResults = TypeProfile->getValueAsInt("NumResults");
1143 NumOperands = TypeProfile->getValueAsInt("NumOperands");
1145 // Parse the properties.
1147 for (Record *Property : R->getValueAsListOfDefs("Properties")) {
1148 if (Property->getName() == "SDNPCommutative") {
1149 Properties |= 1 << SDNPCommutative;
1150 } else if (Property->getName() == "SDNPAssociative") {
1151 Properties |= 1 << SDNPAssociative;
1152 } else if (Property->getName() == "SDNPHasChain") {
1153 Properties |= 1 << SDNPHasChain;
1154 } else if (Property->getName() == "SDNPOutGlue") {
1155 Properties |= 1 << SDNPOutGlue;
1156 } else if (Property->getName() == "SDNPInGlue") {
1157 Properties |= 1 << SDNPInGlue;
1158 } else if (Property->getName() == "SDNPOptInGlue") {
1159 Properties |= 1 << SDNPOptInGlue;
1160 } else if (Property->getName() == "SDNPMayStore") {
1161 Properties |= 1 << SDNPMayStore;
1162 } else if (Property->getName() == "SDNPMayLoad") {
1163 Properties |= 1 << SDNPMayLoad;
1164 } else if (Property->getName() == "SDNPSideEffect") {
1165 Properties |= 1 << SDNPSideEffect;
1166 } else if (Property->getName() == "SDNPMemOperand") {
1167 Properties |= 1 << SDNPMemOperand;
1168 } else if (Property->getName() == "SDNPVariadic") {
1169 Properties |= 1 << SDNPVariadic;
1171 PrintFatalError("Unknown SD Node property '" +
1172 Property->getName() + "' on node '" +
1173 R->getName() + "'!");
1178 // Parse the type constraints.
1179 std::vector<Record*> ConstraintList =
1180 TypeProfile->getValueAsListOfDefs("Constraints");
1181 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
1184 /// getKnownType - If the type constraints on this node imply a fixed type
1185 /// (e.g. all stores return void, etc), then return it as an
1186 /// MVT::SimpleValueType. Otherwise, return EEVT::Other.
1187 MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
1188 unsigned NumResults = getNumResults();
1189 assert(NumResults <= 1 &&
1190 "We only work with nodes with zero or one result so far!");
1191 assert(ResNo == 0 && "Only handles single result nodes so far");
1193 for (const SDTypeConstraint &Constraint : TypeConstraints) {
1194 // Make sure that this applies to the correct node result.
1195 if (Constraint.OperandNo >= NumResults) // FIXME: need value #
1198 switch (Constraint.ConstraintType) {
1200 case SDTypeConstraint::SDTCisVT:
1201 return Constraint.x.SDTCisVT_Info.VT;
1202 case SDTypeConstraint::SDTCisPtrTy:
1209 //===----------------------------------------------------------------------===//
1210 // TreePatternNode implementation
1213 TreePatternNode::~TreePatternNode() {
1214 #if 0 // FIXME: implement refcounted tree nodes!
1215 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1220 static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
1221 if (Operator->getName() == "set" ||
1222 Operator->getName() == "implicit")
1223 return 0; // All return nothing.
1225 if (Operator->isSubClassOf("Intrinsic"))
1226 return CDP.getIntrinsic(Operator).IS.RetVTs.size();
1228 if (Operator->isSubClassOf("SDNode"))
1229 return CDP.getSDNodeInfo(Operator).getNumResults();
1231 if (Operator->isSubClassOf("PatFrag")) {
1232 // If we've already parsed this pattern fragment, get it. Otherwise, handle
1233 // the forward reference case where one pattern fragment references another
1234 // before it is processed.
1235 if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator))
1236 return PFRec->getOnlyTree()->getNumTypes();
1238 // Get the result tree.
1239 DagInit *Tree = Operator->getValueAsDag("Fragment");
1240 Record *Op = nullptr;
1242 if (DefInit *DI = dyn_cast<DefInit>(Tree->getOperator()))
1244 assert(Op && "Invalid Fragment");
1245 return GetNumNodeResults(Op, CDP);
1248 if (Operator->isSubClassOf("Instruction")) {
1249 CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
1251 unsigned NumDefsToAdd = InstInfo.Operands.NumDefs;
1253 // Subtract any defaulted outputs.
1254 for (unsigned i = 0; i != InstInfo.Operands.NumDefs; ++i) {
1255 Record *OperandNode = InstInfo.Operands[i].Rec;
1257 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
1258 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1262 // Add on one implicit def if it has a resolvable type.
1263 if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
1265 return NumDefsToAdd;
1268 if (Operator->isSubClassOf("SDNodeXForm"))
1269 return 1; // FIXME: Generalize SDNodeXForm
1271 if (Operator->isSubClassOf("ValueType"))
1272 return 1; // A type-cast of one result.
1274 if (Operator->isSubClassOf("ComplexPattern"))
1277 errs() << *Operator;
1278 PrintFatalError("Unhandled node in GetNumNodeResults");
1281 void TreePatternNode::print(raw_ostream &OS) const {
1283 OS << *getLeafValue();
1285 OS << '(' << getOperator()->getName();
1287 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1288 OS << ':' << getExtType(i).getName();
1291 if (getNumChildren() != 0) {
1293 getChild(0)->print(OS);
1294 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
1296 getChild(i)->print(OS);
1302 for (const TreePredicateFn &Pred : PredicateFns)
1303 OS << "<<P:" << Pred.getFnName() << ">>";
1305 OS << "<<X:" << TransformFn->getName() << ">>";
1306 if (!getName().empty())
1307 OS << ":$" << getName();
1310 void TreePatternNode::dump() const {
1314 /// isIsomorphicTo - Return true if this node is recursively
1315 /// isomorphic to the specified node. For this comparison, the node's
1316 /// entire state is considered. The assigned name is ignored, since
1317 /// nodes with differing names are considered isomorphic. However, if
1318 /// the assigned name is present in the dependent variable set, then
1319 /// the assigned name is considered significant and the node is
1320 /// isomorphic if the names match.
1321 bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
1322 const MultipleUseVarSet &DepVars) const {
1323 if (N == this) return true;
1324 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
1325 getPredicateFns() != N->getPredicateFns() ||
1326 getTransformFn() != N->getTransformFn())
1330 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
1331 if (DefInit *NDI = dyn_cast<DefInit>(N->getLeafValue())) {
1332 return ((DI->getDef() == NDI->getDef())
1333 && (DepVars.find(getName()) == DepVars.end()
1334 || getName() == N->getName()));
1337 return getLeafValue() == N->getLeafValue();
1340 if (N->getOperator() != getOperator() ||
1341 N->getNumChildren() != getNumChildren()) return false;
1342 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1343 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
1348 /// clone - Make a copy of this tree and all of its children.
1350 TreePatternNode *TreePatternNode::clone() const {
1351 TreePatternNode *New;
1353 New = new TreePatternNode(getLeafValue(), getNumTypes());
1355 std::vector<TreePatternNode*> CChildren;
1356 CChildren.reserve(Children.size());
1357 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1358 CChildren.push_back(getChild(i)->clone());
1359 New = new TreePatternNode(getOperator(), CChildren, getNumTypes());
1361 New->setName(getName());
1363 New->setPredicateFns(getPredicateFns());
1364 New->setTransformFn(getTransformFn());
1368 /// RemoveAllTypes - Recursively strip all the types of this tree.
1369 void TreePatternNode::RemoveAllTypes() {
1370 // Reset to unknown type.
1371 std::fill(Types.begin(), Types.end(), EEVT::TypeSet());
1372 if (isLeaf()) return;
1373 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1374 getChild(i)->RemoveAllTypes();
1378 /// SubstituteFormalArguments - Replace the formal arguments in this tree
1379 /// with actual values specified by ArgMap.
1380 void TreePatternNode::
1381 SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
1382 if (isLeaf()) return;
1384 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1385 TreePatternNode *Child = getChild(i);
1386 if (Child->isLeaf()) {
1387 Init *Val = Child->getLeafValue();
1388 // Note that, when substituting into an output pattern, Val might be an
1390 if (isa<UnsetInit>(Val) || (isa<DefInit>(Val) &&
1391 cast<DefInit>(Val)->getDef()->getName() == "node")) {
1392 // We found a use of a formal argument, replace it with its value.
1393 TreePatternNode *NewChild = ArgMap[Child->getName()];
1394 assert(NewChild && "Couldn't find formal argument!");
1395 assert((Child->getPredicateFns().empty() ||
1396 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1397 "Non-empty child predicate clobbered!");
1398 setChild(i, NewChild);
1401 getChild(i)->SubstituteFormalArguments(ArgMap);
1407 /// InlinePatternFragments - If this pattern refers to any pattern
1408 /// fragments, inline them into place, giving us a pattern without any
1409 /// PatFrag references.
1410 TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
1415 return this; // nothing to do.
1416 Record *Op = getOperator();
1418 if (!Op->isSubClassOf("PatFrag")) {
1419 // Just recursively inline children nodes.
1420 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1421 TreePatternNode *Child = getChild(i);
1422 TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
1424 assert((Child->getPredicateFns().empty() ||
1425 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1426 "Non-empty child predicate clobbered!");
1428 setChild(i, NewChild);
1433 // Otherwise, we found a reference to a fragment. First, look up its
1434 // TreePattern record.
1435 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
1437 // Verify that we are passing the right number of operands.
1438 if (Frag->getNumArgs() != Children.size()) {
1439 TP.error("'" + Op->getName() + "' fragment requires " +
1440 utostr(Frag->getNumArgs()) + " operands!");
1444 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
1446 TreePredicateFn PredFn(Frag);
1447 if (!PredFn.isAlwaysTrue())
1448 FragTree->addPredicateFn(PredFn);
1450 // Resolve formal arguments to their actual value.
1451 if (Frag->getNumArgs()) {
1452 // Compute the map of formal to actual arguments.
1453 std::map<std::string, TreePatternNode*> ArgMap;
1454 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
1455 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
1457 FragTree->SubstituteFormalArguments(ArgMap);
1460 FragTree->setName(getName());
1461 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1462 FragTree->UpdateNodeType(i, getExtType(i), TP);
1464 // Transfer in the old predicates.
1465 for (const TreePredicateFn &Pred : getPredicateFns())
1466 FragTree->addPredicateFn(Pred);
1468 // Get a new copy of this fragment to stitch into here.
1469 //delete this; // FIXME: implement refcounting!
1471 // The fragment we inlined could have recursive inlining that is needed. See
1472 // if there are any pattern fragments in it and inline them as needed.
1473 return FragTree->InlinePatternFragments(TP);
1476 /// getImplicitType - Check to see if the specified record has an implicit
1477 /// type which should be applied to it. This will infer the type of register
1478 /// references from the register file information, for example.
1480 /// When Unnamed is set, return the type of a DAG operand with no name, such as
1481 /// the F8RC register class argument in:
1483 /// (COPY_TO_REGCLASS GPR:$src, F8RC)
1485 /// When Unnamed is false, return the type of a named DAG operand such as the
1486 /// GPR:$src operand above.
1488 static EEVT::TypeSet getImplicitType(Record *R, unsigned ResNo,
1492 // Check to see if this is a register operand.
1493 if (R->isSubClassOf("RegisterOperand")) {
1494 assert(ResNo == 0 && "Regoperand ref only has one result!");
1496 return EEVT::TypeSet(); // Unknown.
1497 Record *RegClass = R->getValueAsDef("RegClass");
1498 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1499 return EEVT::TypeSet(T.getRegisterClass(RegClass).getValueTypes());
1502 // Check to see if this is a register or a register class.
1503 if (R->isSubClassOf("RegisterClass")) {
1504 assert(ResNo == 0 && "Regclass ref only has one result!");
1505 // An unnamed register class represents itself as an i32 immediate, for
1506 // example on a COPY_TO_REGCLASS instruction.
1508 return EEVT::TypeSet(MVT::i32, TP);
1510 // In a named operand, the register class provides the possible set of
1513 return EEVT::TypeSet(); // Unknown.
1514 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1515 return EEVT::TypeSet(T.getRegisterClass(R).getValueTypes());
1518 if (R->isSubClassOf("PatFrag")) {
1519 assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
1520 // Pattern fragment types will be resolved when they are inlined.
1521 return EEVT::TypeSet(); // Unknown.
1524 if (R->isSubClassOf("Register")) {
1525 assert(ResNo == 0 && "Registers only produce one result!");
1527 return EEVT::TypeSet(); // Unknown.
1528 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1529 return EEVT::TypeSet(T.getRegisterVTs(R));
1532 if (R->isSubClassOf("SubRegIndex")) {
1533 assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
1534 return EEVT::TypeSet(MVT::i32, TP);
1537 if (R->isSubClassOf("ValueType")) {
1538 assert(ResNo == 0 && "This node only has one result!");
1539 // An unnamed VTSDNode represents itself as an MVT::Other immediate.
1541 // (sext_inreg GPR:$src, i16)
1544 return EEVT::TypeSet(MVT::Other, TP);
1545 // With a name, the ValueType simply provides the type of the named
1548 // (sext_inreg i32:$src, i16)
1551 return EEVT::TypeSet(); // Unknown.
1552 return EEVT::TypeSet(getValueType(R), TP);
1555 if (R->isSubClassOf("CondCode")) {
1556 assert(ResNo == 0 && "This node only has one result!");
1557 // Using a CondCodeSDNode.
1558 return EEVT::TypeSet(MVT::Other, TP);
1561 if (R->isSubClassOf("ComplexPattern")) {
1562 assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
1564 return EEVT::TypeSet(); // Unknown.
1565 return EEVT::TypeSet(TP.getDAGPatterns().getComplexPattern(R).getValueType(),
1568 if (R->isSubClassOf("PointerLikeRegClass")) {
1569 assert(ResNo == 0 && "Regclass can only have one result!");
1570 return EEVT::TypeSet(MVT::iPTR, TP);
1573 if (R->getName() == "node" || R->getName() == "srcvalue" ||
1574 R->getName() == "zero_reg") {
1576 return EEVT::TypeSet(); // Unknown.
1579 if (R->isSubClassOf("Operand"))
1580 return EEVT::TypeSet(getValueType(R->getValueAsDef("Type")));
1582 TP.error("Unknown node flavor used in pattern: " + R->getName());
1583 return EEVT::TypeSet(MVT::Other, TP);
1587 /// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
1588 /// CodeGenIntrinsic information for it, otherwise return a null pointer.
1589 const CodeGenIntrinsic *TreePatternNode::
1590 getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
1591 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
1592 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
1593 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
1596 unsigned IID = cast<IntInit>(getChild(0)->getLeafValue())->getValue();
1597 return &CDP.getIntrinsicInfo(IID);
1600 /// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
1601 /// return the ComplexPattern information, otherwise return null.
1602 const ComplexPattern *
1603 TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
1606 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
1611 Rec = getOperator();
1613 if (!Rec->isSubClassOf("ComplexPattern"))
1615 return &CGP.getComplexPattern(Rec);
1618 unsigned TreePatternNode::getNumMIResults(const CodeGenDAGPatterns &CGP) const {
1619 // A ComplexPattern specifically declares how many results it fills in.
1620 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1621 return CP->getNumOperands();
1623 // If MIOperandInfo is specified, that gives the count.
1625 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
1626 if (DI && DI->getDef()->isSubClassOf("Operand")) {
1627 DagInit *MIOps = DI->getDef()->getValueAsDag("MIOperandInfo");
1628 if (MIOps->getNumArgs())
1629 return MIOps->getNumArgs();
1633 // Otherwise there is just one result.
1637 /// NodeHasProperty - Return true if this node has the specified property.
1638 bool TreePatternNode::NodeHasProperty(SDNP Property,
1639 const CodeGenDAGPatterns &CGP) const {
1641 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1642 return CP->hasProperty(Property);
1646 Record *Operator = getOperator();
1647 if (!Operator->isSubClassOf("SDNode")) return false;
1649 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
1655 /// TreeHasProperty - Return true if any node in this tree has the specified
1657 bool TreePatternNode::TreeHasProperty(SDNP Property,
1658 const CodeGenDAGPatterns &CGP) const {
1659 if (NodeHasProperty(Property, CGP))
1661 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1662 if (getChild(i)->TreeHasProperty(Property, CGP))
1667 /// isCommutativeIntrinsic - Return true if the node corresponds to a
1668 /// commutative intrinsic.
1670 TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
1671 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
1672 return Int->isCommutative;
1676 static bool isOperandClass(const TreePatternNode *N, StringRef Class) {
1678 return N->getOperator()->isSubClassOf(Class);
1680 DefInit *DI = dyn_cast<DefInit>(N->getLeafValue());
1681 if (DI && DI->getDef()->isSubClassOf(Class))
1687 static void emitTooManyOperandsError(TreePattern &TP,
1691 TP.error("Instruction '" + InstName + "' was provided " + Twine(Actual) +
1692 " operands but expected only " + Twine(Expected) + "!");
1695 static void emitTooFewOperandsError(TreePattern &TP,
1698 TP.error("Instruction '" + InstName +
1699 "' expects more than the provided " + Twine(Actual) + " operands!");
1702 /// ApplyTypeConstraints - Apply all of the type constraints relevant to
1703 /// this node and its children in the tree. This returns true if it makes a
1704 /// change, false otherwise. If a type contradiction is found, flag an error.
1705 bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
1709 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
1711 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
1712 // If it's a regclass or something else known, include the type.
1713 bool MadeChange = false;
1714 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1715 MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
1717 !hasName(), TP), TP);
1721 if (IntInit *II = dyn_cast<IntInit>(getLeafValue())) {
1722 assert(Types.size() == 1 && "Invalid IntInit");
1724 // Int inits are always integers. :)
1725 bool MadeChange = Types[0].EnforceInteger(TP);
1727 if (!Types[0].isConcrete())
1730 MVT::SimpleValueType VT = getType(0);
1731 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
1734 unsigned Size = MVT(VT).getSizeInBits();
1735 // Make sure that the value is representable for this type.
1736 if (Size >= 32) return MadeChange;
1738 // Check that the value doesn't use more bits than we have. It must either
1739 // be a sign- or zero-extended equivalent of the original.
1740 int64_t SignBitAndAbove = II->getValue() >> (Size - 1);
1741 if (SignBitAndAbove == -1 || SignBitAndAbove == 0 || SignBitAndAbove == 1)
1744 TP.error("Integer value '" + itostr(II->getValue()) +
1745 "' is out of range for type '" + getEnumName(getType(0)) + "'!");
1751 // special handling for set, which isn't really an SDNode.
1752 if (getOperator()->getName() == "set") {
1753 assert(getNumTypes() == 0 && "Set doesn't produce a value");
1754 assert(getNumChildren() >= 2 && "Missing RHS of a set?");
1755 unsigned NC = getNumChildren();
1757 TreePatternNode *SetVal = getChild(NC-1);
1758 bool MadeChange = SetVal->ApplyTypeConstraints(TP, NotRegisters);
1760 for (unsigned i = 0; i < NC-1; ++i) {
1761 TreePatternNode *Child = getChild(i);
1762 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
1764 // Types of operands must match.
1765 MadeChange |= Child->UpdateNodeType(0, SetVal->getExtType(i), TP);
1766 MadeChange |= SetVal->UpdateNodeType(i, Child->getExtType(0), TP);
1771 if (getOperator()->getName() == "implicit") {
1772 assert(getNumTypes() == 0 && "Node doesn't produce a value");
1774 bool MadeChange = false;
1775 for (unsigned i = 0; i < getNumChildren(); ++i)
1776 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1780 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
1781 bool MadeChange = false;
1783 // Apply the result type to the node.
1784 unsigned NumRetVTs = Int->IS.RetVTs.size();
1785 unsigned NumParamVTs = Int->IS.ParamVTs.size();
1787 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
1788 MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
1790 if (getNumChildren() != NumParamVTs + 1) {
1791 TP.error("Intrinsic '" + Int->Name + "' expects " +
1792 utostr(NumParamVTs) + " operands, not " +
1793 utostr(getNumChildren() - 1) + " operands!");
1797 // Apply type info to the intrinsic ID.
1798 MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
1800 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
1801 MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
1803 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
1804 assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
1805 MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
1810 if (getOperator()->isSubClassOf("SDNode")) {
1811 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
1813 // Check that the number of operands is sane. Negative operands -> varargs.
1814 if (NI.getNumOperands() >= 0 &&
1815 getNumChildren() != (unsigned)NI.getNumOperands()) {
1816 TP.error(getOperator()->getName() + " node requires exactly " +
1817 itostr(NI.getNumOperands()) + " operands!");
1821 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
1822 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1823 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1827 if (getOperator()->isSubClassOf("Instruction")) {
1828 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
1829 CodeGenInstruction &InstInfo =
1830 CDP.getTargetInfo().getInstruction(getOperator());
1832 bool MadeChange = false;
1834 // Apply the result types to the node, these come from the things in the
1835 // (outs) list of the instruction.
1836 unsigned NumResultsToAdd = std::min(InstInfo.Operands.NumDefs,
1837 Inst.getNumResults());
1838 for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo)
1839 MadeChange |= UpdateNodeTypeFromInst(ResNo, Inst.getResult(ResNo), TP);
1841 // If the instruction has implicit defs, we apply the first one as a result.
1842 // FIXME: This sucks, it should apply all implicit defs.
1843 if (!InstInfo.ImplicitDefs.empty()) {
1844 unsigned ResNo = NumResultsToAdd;
1846 // FIXME: Generalize to multiple possible types and multiple possible
1848 MVT::SimpleValueType VT =
1849 InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
1851 if (VT != MVT::Other)
1852 MadeChange |= UpdateNodeType(ResNo, VT, TP);
1855 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
1857 if (getOperator()->getName() == "INSERT_SUBREG") {
1858 assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
1859 MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
1860 MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
1861 } else if (getOperator()->getName() == "REG_SEQUENCE") {
1862 // We need to do extra, custom typechecking for REG_SEQUENCE since it is
1865 unsigned NChild = getNumChildren();
1867 TP.error("REG_SEQUENCE requires at least 3 operands!");
1871 if (NChild % 2 == 0) {
1872 TP.error("REG_SEQUENCE requires an odd number of operands!");
1876 if (!isOperandClass(getChild(0), "RegisterClass")) {
1877 TP.error("REG_SEQUENCE requires a RegisterClass for first operand!");
1881 for (unsigned I = 1; I < NChild; I += 2) {
1882 TreePatternNode *SubIdxChild = getChild(I + 1);
1883 if (!isOperandClass(SubIdxChild, "SubRegIndex")) {
1884 TP.error("REG_SEQUENCE requires a SubRegIndex for operand " +
1885 itostr(I + 1) + "!");
1891 unsigned ChildNo = 0;
1892 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
1893 Record *OperandNode = Inst.getOperand(i);
1895 // If the instruction expects a predicate or optional def operand, we
1896 // codegen this by setting the operand to it's default value if it has a
1897 // non-empty DefaultOps field.
1898 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
1899 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1902 // Verify that we didn't run out of provided operands.
1903 if (ChildNo >= getNumChildren()) {
1904 emitTooFewOperandsError(TP, getOperator()->getName(), getNumChildren());
1908 TreePatternNode *Child = getChild(ChildNo++);
1909 unsigned ChildResNo = 0; // Instructions always use res #0 of their op.
1911 // If the operand has sub-operands, they may be provided by distinct
1912 // child patterns, so attempt to match each sub-operand separately.
1913 if (OperandNode->isSubClassOf("Operand")) {
1914 DagInit *MIOpInfo = OperandNode->getValueAsDag("MIOperandInfo");
1915 if (unsigned NumArgs = MIOpInfo->getNumArgs()) {
1916 // But don't do that if the whole operand is being provided by
1917 // a single ComplexPattern-related Operand.
1919 if (Child->getNumMIResults(CDP) < NumArgs) {
1920 // Match first sub-operand against the child we already have.
1921 Record *SubRec = cast<DefInit>(MIOpInfo->getArg(0))->getDef();
1923 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
1925 // And the remaining sub-operands against subsequent children.
1926 for (unsigned Arg = 1; Arg < NumArgs; ++Arg) {
1927 if (ChildNo >= getNumChildren()) {
1928 emitTooFewOperandsError(TP, getOperator()->getName(),
1932 Child = getChild(ChildNo++);
1934 SubRec = cast<DefInit>(MIOpInfo->getArg(Arg))->getDef();
1936 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
1943 // If we didn't match by pieces above, attempt to match the whole
1945 MadeChange |= Child->UpdateNodeTypeFromInst(ChildResNo, OperandNode, TP);
1948 if (!InstInfo.Operands.isVariadic && ChildNo != getNumChildren()) {
1949 emitTooManyOperandsError(TP, getOperator()->getName(),
1950 ChildNo, getNumChildren());
1954 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1955 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1959 if (getOperator()->isSubClassOf("ComplexPattern")) {
1960 bool MadeChange = false;
1962 for (unsigned i = 0; i < getNumChildren(); ++i)
1963 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1968 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
1970 // Node transforms always take one operand.
1971 if (getNumChildren() != 1) {
1972 TP.error("Node transform '" + getOperator()->getName() +
1973 "' requires one operand!");
1977 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1980 // If either the output or input of the xform does not have exact
1981 // type info. We assume they must be the same. Otherwise, it is perfectly
1982 // legal to transform from one type to a completely different type.
1984 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
1985 bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
1986 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
1993 /// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
1994 /// RHS of a commutative operation, not the on LHS.
1995 static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
1996 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
1998 if (N->isLeaf() && isa<IntInit>(N->getLeafValue()))
2004 /// canPatternMatch - If it is impossible for this pattern to match on this
2005 /// target, fill in Reason and return false. Otherwise, return true. This is
2006 /// used as a sanity check for .td files (to prevent people from writing stuff
2007 /// that can never possibly work), and to prevent the pattern permuter from
2008 /// generating stuff that is useless.
2009 bool TreePatternNode::canPatternMatch(std::string &Reason,
2010 const CodeGenDAGPatterns &CDP) {
2011 if (isLeaf()) return true;
2013 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
2014 if (!getChild(i)->canPatternMatch(Reason, CDP))
2017 // If this is an intrinsic, handle cases that would make it not match. For
2018 // example, if an operand is required to be an immediate.
2019 if (getOperator()->isSubClassOf("Intrinsic")) {
2024 if (getOperator()->isSubClassOf("ComplexPattern"))
2027 // If this node is a commutative operator, check that the LHS isn't an
2029 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
2030 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
2031 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
2032 // Scan all of the operands of the node and make sure that only the last one
2033 // is a constant node, unless the RHS also is.
2034 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
2035 unsigned Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
2036 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
2037 if (OnlyOnRHSOfCommutative(getChild(i))) {
2038 Reason="Immediate value must be on the RHS of commutative operators!";
2047 //===----------------------------------------------------------------------===//
2048 // TreePattern implementation
2051 TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
2052 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
2053 isInputPattern(isInput), HasError(false) {
2054 for (Init *I : RawPat->getValues())
2055 Trees.push_back(ParseTreePattern(I, ""));
2058 TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
2059 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
2060 isInputPattern(isInput), HasError(false) {
2061 Trees.push_back(ParseTreePattern(Pat, ""));
2064 TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
2065 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
2066 isInputPattern(isInput), HasError(false) {
2067 Trees.push_back(Pat);
2070 void TreePattern::error(const Twine &Msg) {
2074 PrintError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
2078 void TreePattern::ComputeNamedNodes() {
2079 for (TreePatternNode *Tree : Trees)
2080 ComputeNamedNodes(Tree);
2083 void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
2084 if (!N->getName().empty())
2085 NamedNodes[N->getName()].push_back(N);
2087 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2088 ComputeNamedNodes(N->getChild(i));
2092 TreePatternNode *TreePattern::ParseTreePattern(Init *TheInit, StringRef OpName){
2093 if (DefInit *DI = dyn_cast<DefInit>(TheInit)) {
2094 Record *R = DI->getDef();
2096 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
2097 // TreePatternNode of its own. For example:
2098 /// (foo GPR, imm) -> (foo GPR, (imm))
2099 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag"))
2100 return ParseTreePattern(
2101 DagInit::get(DI, nullptr,
2102 std::vector<std::pair<Init*, StringInit*> >()),
2106 TreePatternNode *Res = new TreePatternNode(DI, 1);
2107 if (R->getName() == "node" && !OpName.empty()) {
2109 error("'node' argument requires a name to match with operand list");
2110 Args.push_back(OpName);
2113 Res->setName(OpName);
2117 // ?:$name or just $name.
2118 if (isa<UnsetInit>(TheInit)) {
2120 error("'?' argument requires a name to match with operand list");
2121 TreePatternNode *Res = new TreePatternNode(TheInit, 1);
2122 Args.push_back(OpName);
2123 Res->setName(OpName);
2127 if (IntInit *II = dyn_cast<IntInit>(TheInit)) {
2128 if (!OpName.empty())
2129 error("Constant int argument should not have a name!");
2130 return new TreePatternNode(II, 1);
2133 if (BitsInit *BI = dyn_cast<BitsInit>(TheInit)) {
2134 // Turn this into an IntInit.
2135 Init *II = BI->convertInitializerTo(IntRecTy::get());
2136 if (!II || !isa<IntInit>(II))
2137 error("Bits value must be constants!");
2138 return ParseTreePattern(II, OpName);
2141 DagInit *Dag = dyn_cast<DagInit>(TheInit);
2143 TheInit->print(errs());
2144 error("Pattern has unexpected init kind!");
2146 DefInit *OpDef = dyn_cast<DefInit>(Dag->getOperator());
2147 if (!OpDef) error("Pattern has unexpected operator type!");
2148 Record *Operator = OpDef->getDef();
2150 if (Operator->isSubClassOf("ValueType")) {
2151 // If the operator is a ValueType, then this must be "type cast" of a leaf
2153 if (Dag->getNumArgs() != 1)
2154 error("Type cast only takes one operand!");
2156 TreePatternNode *New = ParseTreePattern(Dag->getArg(0),
2157 Dag->getArgNameStr(0));
2159 // Apply the type cast.
2160 assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
2161 New->UpdateNodeType(0, getValueType(Operator), *this);
2163 if (!OpName.empty())
2164 error("ValueType cast should not have a name!");
2168 // Verify that this is something that makes sense for an operator.
2169 if (!Operator->isSubClassOf("PatFrag") &&
2170 !Operator->isSubClassOf("SDNode") &&
2171 !Operator->isSubClassOf("Instruction") &&
2172 !Operator->isSubClassOf("SDNodeXForm") &&
2173 !Operator->isSubClassOf("Intrinsic") &&
2174 !Operator->isSubClassOf("ComplexPattern") &&
2175 Operator->getName() != "set" &&
2176 Operator->getName() != "implicit")
2177 error("Unrecognized node '" + Operator->getName() + "'!");
2179 // Check to see if this is something that is illegal in an input pattern.
2180 if (isInputPattern) {
2181 if (Operator->isSubClassOf("Instruction") ||
2182 Operator->isSubClassOf("SDNodeXForm"))
2183 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
2185 if (Operator->isSubClassOf("Intrinsic"))
2186 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
2188 if (Operator->isSubClassOf("SDNode") &&
2189 Operator->getName() != "imm" &&
2190 Operator->getName() != "fpimm" &&
2191 Operator->getName() != "tglobaltlsaddr" &&
2192 Operator->getName() != "tconstpool" &&
2193 Operator->getName() != "tjumptable" &&
2194 Operator->getName() != "tframeindex" &&
2195 Operator->getName() != "texternalsym" &&
2196 Operator->getName() != "tblockaddress" &&
2197 Operator->getName() != "tglobaladdr" &&
2198 Operator->getName() != "bb" &&
2199 Operator->getName() != "vt" &&
2200 Operator->getName() != "mcsym")
2201 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
2204 std::vector<TreePatternNode*> Children;
2206 // Parse all the operands.
2207 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
2208 Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgNameStr(i)));
2210 // If the operator is an intrinsic, then this is just syntactic sugar for for
2211 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
2212 // convert the intrinsic name to a number.
2213 if (Operator->isSubClassOf("Intrinsic")) {
2214 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
2215 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
2217 // If this intrinsic returns void, it must have side-effects and thus a
2219 if (Int.IS.RetVTs.empty())
2220 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
2221 else if (Int.ModRef != CodeGenIntrinsic::NoMem)
2222 // Has side-effects, requires chain.
2223 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
2224 else // Otherwise, no chain.
2225 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
2227 TreePatternNode *IIDNode = new TreePatternNode(IntInit::get(IID), 1);
2228 Children.insert(Children.begin(), IIDNode);
2231 if (Operator->isSubClassOf("ComplexPattern")) {
2232 for (unsigned i = 0; i < Children.size(); ++i) {
2233 TreePatternNode *Child = Children[i];
2235 if (Child->getName().empty())
2236 error("All arguments to a ComplexPattern must be named");
2238 // Check that the ComplexPattern uses are consistent: "(MY_PAT $a, $b)"
2239 // and "(MY_PAT $b, $a)" should not be allowed in the same pattern;
2240 // neither should "(MY_PAT_1 $a, $b)" and "(MY_PAT_2 $a, $b)".
2241 auto OperandId = std::make_pair(Operator, i);
2242 auto PrevOp = ComplexPatternOperands.find(Child->getName());
2243 if (PrevOp != ComplexPatternOperands.end()) {
2244 if (PrevOp->getValue() != OperandId)
2245 error("All ComplexPattern operands must appear consistently: "
2246 "in the same order in just one ComplexPattern instance.");
2248 ComplexPatternOperands[Child->getName()] = OperandId;
2252 unsigned NumResults = GetNumNodeResults(Operator, CDP);
2253 TreePatternNode *Result = new TreePatternNode(Operator, Children, NumResults);
2254 Result->setName(OpName);
2256 if (Dag->getName()) {
2257 assert(Result->getName().empty());
2258 Result->setName(Dag->getNameStr());
2263 /// SimplifyTree - See if we can simplify this tree to eliminate something that
2264 /// will never match in favor of something obvious that will. This is here
2265 /// strictly as a convenience to target authors because it allows them to write
2266 /// more type generic things and have useless type casts fold away.
2268 /// This returns true if any change is made.
2269 static bool SimplifyTree(TreePatternNode *&N) {
2273 // If we have a bitconvert with a resolved type and if the source and
2274 // destination types are the same, then the bitconvert is useless, remove it.
2275 if (N->getOperator()->getName() == "bitconvert" &&
2276 N->getExtType(0).isConcrete() &&
2277 N->getExtType(0) == N->getChild(0)->getExtType(0) &&
2278 N->getName().empty()) {
2284 // Walk all children.
2285 bool MadeChange = false;
2286 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2287 TreePatternNode *Child = N->getChild(i);
2288 MadeChange |= SimplifyTree(Child);
2289 N->setChild(i, Child);
2296 /// InferAllTypes - Infer/propagate as many types throughout the expression
2297 /// patterns as possible. Return true if all types are inferred, false
2298 /// otherwise. Flags an error if a type contradiction is found.
2300 InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
2301 if (NamedNodes.empty())
2302 ComputeNamedNodes();
2304 bool MadeChange = true;
2305 while (MadeChange) {
2307 for (TreePatternNode *Tree : Trees) {
2308 MadeChange |= Tree->ApplyTypeConstraints(*this, false);
2309 MadeChange |= SimplifyTree(Tree);
2312 // If there are constraints on our named nodes, apply them.
2313 for (auto &Entry : NamedNodes) {
2314 SmallVectorImpl<TreePatternNode*> &Nodes = Entry.second;
2316 // If we have input named node types, propagate their types to the named
2319 if (!InNamedTypes->count(Entry.getKey())) {
2320 error("Node '" + std::string(Entry.getKey()) +
2321 "' in output pattern but not input pattern");
2325 const SmallVectorImpl<TreePatternNode*> &InNodes =
2326 InNamedTypes->find(Entry.getKey())->second;
2328 // The input types should be fully resolved by now.
2329 for (TreePatternNode *Node : Nodes) {
2330 // If this node is a register class, and it is the root of the pattern
2331 // then we're mapping something onto an input register. We allow
2332 // changing the type of the input register in this case. This allows
2333 // us to match things like:
2334 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
2335 if (Node == Trees[0] && Node->isLeaf()) {
2336 DefInit *DI = dyn_cast<DefInit>(Node->getLeafValue());
2337 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2338 DI->getDef()->isSubClassOf("RegisterOperand")))
2342 assert(Node->getNumTypes() == 1 &&
2343 InNodes[0]->getNumTypes() == 1 &&
2344 "FIXME: cannot name multiple result nodes yet");
2345 MadeChange |= Node->UpdateNodeType(0, InNodes[0]->getExtType(0),
2350 // If there are multiple nodes with the same name, they must all have the
2352 if (Entry.second.size() > 1) {
2353 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
2354 TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
2355 assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
2356 "FIXME: cannot name multiple result nodes yet");
2358 MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
2359 MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
2365 bool HasUnresolvedTypes = false;
2366 for (const TreePatternNode *Tree : Trees)
2367 HasUnresolvedTypes |= Tree->ContainsUnresolvedType();
2368 return !HasUnresolvedTypes;
2371 void TreePattern::print(raw_ostream &OS) const {
2372 OS << getRecord()->getName();
2373 if (!Args.empty()) {
2374 OS << "(" << Args[0];
2375 for (unsigned i = 1, e = Args.size(); i != e; ++i)
2376 OS << ", " << Args[i];
2381 if (Trees.size() > 1)
2383 for (const TreePatternNode *Tree : Trees) {
2389 if (Trees.size() > 1)
2393 void TreePattern::dump() const { print(errs()); }
2395 //===----------------------------------------------------------------------===//
2396 // CodeGenDAGPatterns implementation
2399 CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) :
2400 Records(R), Target(R) {
2402 Intrinsics = CodeGenIntrinsicTable(Records, false);
2403 TgtIntrinsics = CodeGenIntrinsicTable(Records, true);
2405 ParseNodeTransforms();
2406 ParseComplexPatterns();
2407 ParsePatternFragments();
2408 ParseDefaultOperands();
2409 ParseInstructions();
2410 ParsePatternFragments(/*OutFrags*/true);
2413 // Generate variants. For example, commutative patterns can match
2414 // multiple ways. Add them to PatternsToMatch as well.
2417 // Infer instruction flags. For example, we can detect loads,
2418 // stores, and side effects in many cases by examining an
2419 // instruction's pattern.
2420 InferInstructionFlags();
2422 // Verify that instruction flags match the patterns.
2423 VerifyInstructionFlags();
2426 Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
2427 Record *N = Records.getDef(Name);
2428 if (!N || !N->isSubClassOf("SDNode"))
2429 PrintFatalError("Error getting SDNode '" + Name + "'!");
2434 // Parse all of the SDNode definitions for the target, populating SDNodes.
2435 void CodeGenDAGPatterns::ParseNodeInfo() {
2436 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
2437 while (!Nodes.empty()) {
2438 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
2442 // Get the builtin intrinsic nodes.
2443 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
2444 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
2445 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
2448 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
2449 /// map, and emit them to the file as functions.
2450 void CodeGenDAGPatterns::ParseNodeTransforms() {
2451 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
2452 while (!Xforms.empty()) {
2453 Record *XFormNode = Xforms.back();
2454 Record *SDNode = XFormNode->getValueAsDef("Opcode");
2455 StringRef Code = XFormNode->getValueAsString("XFormFunction");
2456 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
2462 void CodeGenDAGPatterns::ParseComplexPatterns() {
2463 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
2464 while (!AMs.empty()) {
2465 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
2471 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
2472 /// file, building up the PatternFragments map. After we've collected them all,
2473 /// inline fragments together as necessary, so that there are no references left
2474 /// inside a pattern fragment to a pattern fragment.
2476 void CodeGenDAGPatterns::ParsePatternFragments(bool OutFrags) {
2477 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
2479 // First step, parse all of the fragments.
2480 for (Record *Frag : Fragments) {
2481 if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
2484 DagInit *Tree = Frag->getValueAsDag("Fragment");
2486 (PatternFragments[Frag] = llvm::make_unique<TreePattern>(
2487 Frag, Tree, !Frag->isSubClassOf("OutPatFrag"),
2490 // Validate the argument list, converting it to set, to discard duplicates.
2491 std::vector<std::string> &Args = P->getArgList();
2492 std::set<std::string> OperandsSet(Args.begin(), Args.end());
2494 if (OperandsSet.count(""))
2495 P->error("Cannot have unnamed 'node' values in pattern fragment!");
2497 // Parse the operands list.
2498 DagInit *OpsList = Frag->getValueAsDag("Operands");
2499 DefInit *OpsOp = dyn_cast<DefInit>(OpsList->getOperator());
2500 // Special cases: ops == outs == ins. Different names are used to
2501 // improve readability.
2503 (OpsOp->getDef()->getName() != "ops" &&
2504 OpsOp->getDef()->getName() != "outs" &&
2505 OpsOp->getDef()->getName() != "ins"))
2506 P->error("Operands list should start with '(ops ... '!");
2508 // Copy over the arguments.
2510 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
2511 if (!isa<DefInit>(OpsList->getArg(j)) ||
2512 cast<DefInit>(OpsList->getArg(j))->getDef()->getName() != "node")
2513 P->error("Operands list should all be 'node' values.");
2514 if (!OpsList->getArgName(j))
2515 P->error("Operands list should have names for each operand!");
2516 StringRef ArgNameStr = OpsList->getArgNameStr(j);
2517 if (!OperandsSet.count(ArgNameStr))
2518 P->error("'" + ArgNameStr +
2519 "' does not occur in pattern or was multiply specified!");
2520 OperandsSet.erase(ArgNameStr);
2521 Args.push_back(ArgNameStr);
2524 if (!OperandsSet.empty())
2525 P->error("Operands list does not contain an entry for operand '" +
2526 *OperandsSet.begin() + "'!");
2528 // If there is a code init for this fragment, keep track of the fact that
2529 // this fragment uses it.
2530 TreePredicateFn PredFn(P);
2531 if (!PredFn.isAlwaysTrue())
2532 P->getOnlyTree()->addPredicateFn(PredFn);
2534 // If there is a node transformation corresponding to this, keep track of
2536 Record *Transform = Frag->getValueAsDef("OperandTransform");
2537 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
2538 P->getOnlyTree()->setTransformFn(Transform);
2541 // Now that we've parsed all of the tree fragments, do a closure on them so
2542 // that there are not references to PatFrags left inside of them.
2543 for (Record *Frag : Fragments) {
2544 if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
2547 TreePattern &ThePat = *PatternFragments[Frag];
2548 ThePat.InlinePatternFragments();
2550 // Infer as many types as possible. Don't worry about it if we don't infer
2551 // all of them, some may depend on the inputs of the pattern.
2552 ThePat.InferAllTypes();
2553 ThePat.resetError();
2555 // If debugging, print out the pattern fragment result.
2556 DEBUG(ThePat.dump());
2560 void CodeGenDAGPatterns::ParseDefaultOperands() {
2561 std::vector<Record*> DefaultOps;
2562 DefaultOps = Records.getAllDerivedDefinitions("OperandWithDefaultOps");
2564 // Find some SDNode.
2565 assert(!SDNodes.empty() && "No SDNodes parsed?");
2566 Init *SomeSDNode = DefInit::get(SDNodes.begin()->first);
2568 for (unsigned i = 0, e = DefaultOps.size(); i != e; ++i) {
2569 DagInit *DefaultInfo = DefaultOps[i]->getValueAsDag("DefaultOps");
2571 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
2572 // SomeSDnode so that we can parse this.
2573 std::vector<std::pair<Init*, StringInit*> > Ops;
2574 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
2575 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
2576 DefaultInfo->getArgName(op)));
2577 DagInit *DI = DagInit::get(SomeSDNode, nullptr, Ops);
2579 // Create a TreePattern to parse this.
2580 TreePattern P(DefaultOps[i], DI, false, *this);
2581 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
2583 // Copy the operands over into a DAGDefaultOperand.
2584 DAGDefaultOperand DefaultOpInfo;
2586 TreePatternNode *T = P.getTree(0);
2587 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
2588 TreePatternNode *TPN = T->getChild(op);
2589 while (TPN->ApplyTypeConstraints(P, false))
2590 /* Resolve all types */;
2592 if (TPN->ContainsUnresolvedType()) {
2593 PrintFatalError("Value #" + Twine(i) + " of OperandWithDefaultOps '" +
2594 DefaultOps[i]->getName() +
2595 "' doesn't have a concrete type!");
2597 DefaultOpInfo.DefaultOps.push_back(TPN);
2600 // Insert it into the DefaultOperands map so we can find it later.
2601 DefaultOperands[DefaultOps[i]] = DefaultOpInfo;
2605 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
2606 /// instruction input. Return true if this is a real use.
2607 static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
2608 std::map<std::string, TreePatternNode*> &InstInputs) {
2609 // No name -> not interesting.
2610 if (Pat->getName().empty()) {
2611 if (Pat->isLeaf()) {
2612 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
2613 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2614 DI->getDef()->isSubClassOf("RegisterOperand")))
2615 I->error("Input " + DI->getDef()->getName() + " must be named!");
2621 if (Pat->isLeaf()) {
2622 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
2623 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
2626 Rec = Pat->getOperator();
2629 // SRCVALUE nodes are ignored.
2630 if (Rec->getName() == "srcvalue")
2633 TreePatternNode *&Slot = InstInputs[Pat->getName()];
2639 if (Slot->isLeaf()) {
2640 SlotRec = cast<DefInit>(Slot->getLeafValue())->getDef();
2642 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
2643 SlotRec = Slot->getOperator();
2646 // Ensure that the inputs agree if we've already seen this input.
2648 I->error("All $" + Pat->getName() + " inputs must agree with each other");
2649 if (Slot->getExtTypes() != Pat->getExtTypes())
2650 I->error("All $" + Pat->getName() + " inputs must agree with each other");
2654 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
2655 /// part of "I", the instruction), computing the set of inputs and outputs of
2656 /// the pattern. Report errors if we see anything naughty.
2657 void CodeGenDAGPatterns::
2658 FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
2659 std::map<std::string, TreePatternNode*> &InstInputs,
2660 std::map<std::string, TreePatternNode*>&InstResults,
2661 std::vector<Record*> &InstImpResults) {
2662 if (Pat->isLeaf()) {
2663 bool isUse = HandleUse(I, Pat, InstInputs);
2664 if (!isUse && Pat->getTransformFn())
2665 I->error("Cannot specify a transform function for a non-input value!");
2669 if (Pat->getOperator()->getName() == "implicit") {
2670 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2671 TreePatternNode *Dest = Pat->getChild(i);
2672 if (!Dest->isLeaf())
2673 I->error("implicitly defined value should be a register!");
2675 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
2676 if (!Val || !Val->getDef()->isSubClassOf("Register"))
2677 I->error("implicitly defined value should be a register!");
2678 InstImpResults.push_back(Val->getDef());
2683 if (Pat->getOperator()->getName() != "set") {
2684 // If this is not a set, verify that the children nodes are not void typed,
2686 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2687 if (Pat->getChild(i)->getNumTypes() == 0)
2688 I->error("Cannot have void nodes inside of patterns!");
2689 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
2693 // If this is a non-leaf node with no children, treat it basically as if
2694 // it were a leaf. This handles nodes like (imm).
2695 bool isUse = HandleUse(I, Pat, InstInputs);
2697 if (!isUse && Pat->getTransformFn())
2698 I->error("Cannot specify a transform function for a non-input value!");
2702 // Otherwise, this is a set, validate and collect instruction results.
2703 if (Pat->getNumChildren() == 0)
2704 I->error("set requires operands!");
2706 if (Pat->getTransformFn())
2707 I->error("Cannot specify a transform function on a set node!");
2709 // Check the set destinations.
2710 unsigned NumDests = Pat->getNumChildren()-1;
2711 for (unsigned i = 0; i != NumDests; ++i) {
2712 TreePatternNode *Dest = Pat->getChild(i);
2713 if (!Dest->isLeaf())
2714 I->error("set destination should be a register!");
2716 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
2718 I->error("set destination should be a register!");
2722 if (Val->getDef()->isSubClassOf("RegisterClass") ||
2723 Val->getDef()->isSubClassOf("ValueType") ||
2724 Val->getDef()->isSubClassOf("RegisterOperand") ||
2725 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
2726 if (Dest->getName().empty())
2727 I->error("set destination must have a name!");
2728 if (InstResults.count(Dest->getName()))
2729 I->error("cannot set '" + Dest->getName() +"' multiple times");
2730 InstResults[Dest->getName()] = Dest;
2731 } else if (Val->getDef()->isSubClassOf("Register")) {
2732 InstImpResults.push_back(Val->getDef());
2734 I->error("set destination should be a register!");
2738 // Verify and collect info from the computation.
2739 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
2740 InstInputs, InstResults, InstImpResults);
2743 //===----------------------------------------------------------------------===//
2744 // Instruction Analysis
2745 //===----------------------------------------------------------------------===//
2747 class InstAnalyzer {
2748 const CodeGenDAGPatterns &CDP;
2750 bool hasSideEffects;
2756 InstAnalyzer(const CodeGenDAGPatterns &cdp)
2757 : CDP(cdp), hasSideEffects(false), mayStore(false), mayLoad(false),
2758 isBitcast(false), isVariadic(false) {}
2760 void Analyze(const TreePattern *Pat) {
2761 // Assume only the first tree is the pattern. The others are clobber nodes.
2762 AnalyzeNode(Pat->getTree(0));
2765 void Analyze(const PatternToMatch &Pat) {
2766 AnalyzeNode(Pat.getSrcPattern());
2770 bool IsNodeBitcast(const TreePatternNode *N) const {
2771 if (hasSideEffects || mayLoad || mayStore || isVariadic)
2774 if (N->getNumChildren() != 2)
2777 const TreePatternNode *N0 = N->getChild(0);
2778 if (!N0->isLeaf() || !isa<DefInit>(N0->getLeafValue()))
2781 const TreePatternNode *N1 = N->getChild(1);
2784 if (N1->getNumChildren() != 1 || !N1->getChild(0)->isLeaf())
2787 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N1->getOperator());
2788 if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1)
2790 return OpInfo.getEnumName() == "ISD::BITCAST";
2794 void AnalyzeNode(const TreePatternNode *N) {
2796 if (DefInit *DI = dyn_cast<DefInit>(N->getLeafValue())) {
2797 Record *LeafRec = DI->getDef();
2798 // Handle ComplexPattern leaves.
2799 if (LeafRec->isSubClassOf("ComplexPattern")) {
2800 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
2801 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
2802 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
2803 if (CP.hasProperty(SDNPSideEffect)) hasSideEffects = true;
2809 // Analyze children.
2810 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2811 AnalyzeNode(N->getChild(i));
2813 // Ignore set nodes, which are not SDNodes.
2814 if (N->getOperator()->getName() == "set") {
2815 isBitcast = IsNodeBitcast(N);
2819 // Notice properties of the node.
2820 if (N->NodeHasProperty(SDNPMayStore, CDP)) mayStore = true;
2821 if (N->NodeHasProperty(SDNPMayLoad, CDP)) mayLoad = true;
2822 if (N->NodeHasProperty(SDNPSideEffect, CDP)) hasSideEffects = true;
2823 if (N->NodeHasProperty(SDNPVariadic, CDP)) isVariadic = true;
2825 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
2826 // If this is an intrinsic, analyze it.
2827 if (IntInfo->ModRef & CodeGenIntrinsic::MR_Ref)
2828 mayLoad = true;// These may load memory.
2830 if (IntInfo->ModRef & CodeGenIntrinsic::MR_Mod)
2831 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
2833 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem ||
2834 IntInfo->hasSideEffects)
2835 // ReadWriteMem intrinsics can have other strange effects.
2836 hasSideEffects = true;
2842 static bool InferFromPattern(CodeGenInstruction &InstInfo,
2843 const InstAnalyzer &PatInfo,
2847 // Remember where InstInfo got its flags.
2848 if (InstInfo.hasUndefFlags())
2849 InstInfo.InferredFrom = PatDef;
2851 // Check explicitly set flags for consistency.
2852 if (InstInfo.hasSideEffects != PatInfo.hasSideEffects &&
2853 !InstInfo.hasSideEffects_Unset) {
2854 // Allow explicitly setting hasSideEffects = 1 on instructions, even when
2855 // the pattern has no side effects. That could be useful for div/rem
2856 // instructions that may trap.
2857 if (!InstInfo.hasSideEffects) {
2859 PrintError(PatDef->getLoc(), "Pattern doesn't match hasSideEffects = " +
2860 Twine(InstInfo.hasSideEffects));
2864 if (InstInfo.mayStore != PatInfo.mayStore && !InstInfo.mayStore_Unset) {
2866 PrintError(PatDef->getLoc(), "Pattern doesn't match mayStore = " +
2867 Twine(InstInfo.mayStore));
2870 if (InstInfo.mayLoad != PatInfo.mayLoad && !InstInfo.mayLoad_Unset) {
2871 // Allow explicitly setting mayLoad = 1, even when the pattern has no loads.
2872 // Some targets translate immediates to loads.
2873 if (!InstInfo.mayLoad) {
2875 PrintError(PatDef->getLoc(), "Pattern doesn't match mayLoad = " +
2876 Twine(InstInfo.mayLoad));
2880 // Transfer inferred flags.
2881 InstInfo.hasSideEffects |= PatInfo.hasSideEffects;
2882 InstInfo.mayStore |= PatInfo.mayStore;
2883 InstInfo.mayLoad |= PatInfo.mayLoad;
2885 // These flags are silently added without any verification.
2886 InstInfo.isBitcast |= PatInfo.isBitcast;
2888 // Don't infer isVariadic. This flag means something different on SDNodes and
2889 // instructions. For example, a CALL SDNode is variadic because it has the
2890 // call arguments as operands, but a CALL instruction is not variadic - it
2891 // has argument registers as implicit, not explicit uses.
2896 /// hasNullFragReference - Return true if the DAG has any reference to the
2897 /// null_frag operator.
2898 static bool hasNullFragReference(DagInit *DI) {
2899 DefInit *OpDef = dyn_cast<DefInit>(DI->getOperator());
2900 if (!OpDef) return false;
2901 Record *Operator = OpDef->getDef();
2903 // If this is the null fragment, return true.
2904 if (Operator->getName() == "null_frag") return true;
2905 // If any of the arguments reference the null fragment, return true.
2906 for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {
2907 DagInit *Arg = dyn_cast<DagInit>(DI->getArg(i));
2908 if (Arg && hasNullFragReference(Arg))
2915 /// hasNullFragReference - Return true if any DAG in the list references
2916 /// the null_frag operator.
2917 static bool hasNullFragReference(ListInit *LI) {
2918 for (Init *I : LI->getValues()) {
2919 DagInit *DI = dyn_cast<DagInit>(I);
2920 assert(DI && "non-dag in an instruction Pattern list?!");
2921 if (hasNullFragReference(DI))
2927 /// Get all the instructions in a tree.
2929 getInstructionsInTree(TreePatternNode *Tree, SmallVectorImpl<Record*> &Instrs) {
2932 if (Tree->getOperator()->isSubClassOf("Instruction"))
2933 Instrs.push_back(Tree->getOperator());
2934 for (unsigned i = 0, e = Tree->getNumChildren(); i != e; ++i)
2935 getInstructionsInTree(Tree->getChild(i), Instrs);
2938 /// Check the class of a pattern leaf node against the instruction operand it
2940 static bool checkOperandClass(CGIOperandList::OperandInfo &OI,
2945 // Allow direct value types to be used in instruction set patterns.
2946 // The type will be checked later.
2947 if (Leaf->isSubClassOf("ValueType"))
2950 // Patterns can also be ComplexPattern instances.
2951 if (Leaf->isSubClassOf("ComplexPattern"))
2957 const DAGInstruction &CodeGenDAGPatterns::parseInstructionPattern(
2958 CodeGenInstruction &CGI, ListInit *Pat, DAGInstMap &DAGInsts) {
2960 assert(!DAGInsts.count(CGI.TheDef) && "Instruction already parsed!");
2962 // Parse the instruction.
2963 TreePattern *I = new TreePattern(CGI.TheDef, Pat, true, *this);
2964 // Inline pattern fragments into it.
2965 I->InlinePatternFragments();
2967 // Infer as many types as possible. If we cannot infer all of them, we can
2968 // never do anything with this instruction pattern: report it to the user.
2969 if (!I->InferAllTypes())
2970 I->error("Could not infer all types in pattern!");
2972 // InstInputs - Keep track of all of the inputs of the instruction, along
2973 // with the record they are declared as.
2974 std::map<std::string, TreePatternNode*> InstInputs;
2976 // InstResults - Keep track of all the virtual registers that are 'set'
2977 // in the instruction, including what reg class they are.
2978 std::map<std::string, TreePatternNode*> InstResults;
2980 std::vector<Record*> InstImpResults;
2982 // Verify that the top-level forms in the instruction are of void type, and
2983 // fill in the InstResults map.
2984 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
2985 TreePatternNode *Pat = I->getTree(j);
2986 if (Pat->getNumTypes() != 0) {
2988 for (unsigned k = 0, ke = Pat->getNumTypes(); k != ke; ++k) {
2991 Types += Pat->getExtType(k).getName();
2993 I->error("Top-level forms in instruction pattern should have"
2994 " void types, has types " + Types);
2997 // Find inputs and outputs, and verify the structure of the uses/defs.
2998 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
3002 // Now that we have inputs and outputs of the pattern, inspect the operands
3003 // list for the instruction. This determines the order that operands are
3004 // added to the machine instruction the node corresponds to.
3005 unsigned NumResults = InstResults.size();
3007 // Parse the operands list from the (ops) list, validating it.
3008 assert(I->getArgList().empty() && "Args list should still be empty here!");
3010 // Check that all of the results occur first in the list.
3011 std::vector<Record*> Results;
3012 SmallVector<TreePatternNode *, 2> ResNodes;
3013 for (unsigned i = 0; i != NumResults; ++i) {
3014 if (i == CGI.Operands.size())
3015 I->error("'" + InstResults.begin()->first +
3016 "' set but does not appear in operand list!");
3017 const std::string &OpName = CGI.Operands[i].Name;
3019 // Check that it exists in InstResults.
3020 TreePatternNode *RNode = InstResults[OpName];
3022 I->error("Operand $" + OpName + " does not exist in operand list!");
3024 ResNodes.push_back(RNode);
3026 Record *R = cast<DefInit>(RNode->getLeafValue())->getDef();
3028 I->error("Operand $" + OpName + " should be a set destination: all "
3029 "outputs must occur before inputs in operand list!");
3031 if (!checkOperandClass(CGI.Operands[i], R))
3032 I->error("Operand $" + OpName + " class mismatch!");
3034 // Remember the return type.
3035 Results.push_back(CGI.Operands[i].Rec);
3037 // Okay, this one checks out.
3038 InstResults.erase(OpName);
3041 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
3042 // the copy while we're checking the inputs.
3043 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
3045 std::vector<TreePatternNode*> ResultNodeOperands;
3046 std::vector<Record*> Operands;
3047 for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
3048 CGIOperandList::OperandInfo &Op = CGI.Operands[i];
3049 const std::string &OpName = Op.Name;
3051 I->error("Operand #" + utostr(i) + " in operands list has no name!");
3053 if (!InstInputsCheck.count(OpName)) {
3054 // If this is an operand with a DefaultOps set filled in, we can ignore
3055 // this. When we codegen it, we will do so as always executed.
3056 if (Op.Rec->isSubClassOf("OperandWithDefaultOps")) {
3057 // Does it have a non-empty DefaultOps field? If so, ignore this
3059 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
3062 I->error("Operand $" + OpName +
3063 " does not appear in the instruction pattern");
3065 TreePatternNode *InVal = InstInputsCheck[OpName];
3066 InstInputsCheck.erase(OpName); // It occurred, remove from map.
3068 if (InVal->isLeaf() && isa<DefInit>(InVal->getLeafValue())) {
3069 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
3070 if (!checkOperandClass(Op, InRec))
3071 I->error("Operand $" + OpName + "'s register class disagrees"
3072 " between the operand and pattern");
3074 Operands.push_back(Op.Rec);
3076 // Construct the result for the dest-pattern operand list.
3077 TreePatternNode *OpNode = InVal->clone();
3079 // No predicate is useful on the result.
3080 OpNode->clearPredicateFns();
3082 // Promote the xform function to be an explicit node if set.
3083 if (Record *Xform = OpNode->getTransformFn()) {
3084 OpNode->setTransformFn(nullptr);
3085 std::vector<TreePatternNode*> Children;
3086 Children.push_back(OpNode);
3087 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
3090 ResultNodeOperands.push_back(OpNode);
3093 if (!InstInputsCheck.empty())
3094 I->error("Input operand $" + InstInputsCheck.begin()->first +
3095 " occurs in pattern but not in operands list!");
3097 TreePatternNode *ResultPattern =
3098 new TreePatternNode(I->getRecord(), ResultNodeOperands,
3099 GetNumNodeResults(I->getRecord(), *this));
3100 // Copy fully inferred output node types to instruction result pattern.
3101 for (unsigned i = 0; i != NumResults; ++i) {
3102 assert(ResNodes[i]->getNumTypes() == 1 && "FIXME: Unhandled");
3103 ResultPattern->setType(i, ResNodes[i]->getExtType(0));
3106 // Create and insert the instruction.
3107 // FIXME: InstImpResults should not be part of DAGInstruction.
3108 DAGInstruction TheInst(I, Results, Operands, InstImpResults);
3109 DAGInsts.insert(std::make_pair(I->getRecord(), TheInst));
3111 // Use a temporary tree pattern to infer all types and make sure that the
3112 // constructed result is correct. This depends on the instruction already
3113 // being inserted into the DAGInsts map.
3114 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
3115 Temp.InferAllTypes(&I->getNamedNodesMap());
3117 DAGInstruction &TheInsertedInst = DAGInsts.find(I->getRecord())->second;
3118 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
3120 return TheInsertedInst;
3123 /// ParseInstructions - Parse all of the instructions, inlining and resolving
3124 /// any fragments involved. This populates the Instructions list with fully
3125 /// resolved instructions.
3126 void CodeGenDAGPatterns::ParseInstructions() {
3127 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
3129 for (Record *Instr : Instrs) {
3130 ListInit *LI = nullptr;
3132 if (isa<ListInit>(Instr->getValueInit("Pattern")))
3133 LI = Instr->getValueAsListInit("Pattern");
3135 // If there is no pattern, only collect minimal information about the
3136 // instruction for its operand list. We have to assume that there is one
3137 // result, as we have no detailed info. A pattern which references the
3138 // null_frag operator is as-if no pattern were specified. Normally this
3139 // is from a multiclass expansion w/ a SDPatternOperator passed in as
3141 if (!LI || LI->empty() || hasNullFragReference(LI)) {
3142 std::vector<Record*> Results;
3143 std::vector<Record*> Operands;
3145 CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
3147 if (InstInfo.Operands.size() != 0) {
3148 for (unsigned j = 0, e = InstInfo.Operands.NumDefs; j < e; ++j)
3149 Results.push_back(InstInfo.Operands[j].Rec);
3151 // The rest are inputs.
3152 for (unsigned j = InstInfo.Operands.NumDefs,
3153 e = InstInfo.Operands.size(); j < e; ++j)
3154 Operands.push_back(InstInfo.Operands[j].Rec);
3157 // Create and insert the instruction.
3158 std::vector<Record*> ImpResults;
3159 Instructions.insert(std::make_pair(Instr,
3160 DAGInstruction(nullptr, Results, Operands, ImpResults)));
3161 continue; // no pattern.
3164 CodeGenInstruction &CGI = Target.getInstruction(Instr);
3165 const DAGInstruction &DI = parseInstructionPattern(CGI, LI, Instructions);
3168 DEBUG(DI.getPattern()->dump());
3171 // If we can, convert the instructions to be patterns that are matched!
3172 for (auto &Entry : Instructions) {
3173 DAGInstruction &TheInst = Entry.second;
3174 TreePattern *I = TheInst.getPattern();
3175 if (!I) continue; // No pattern.
3177 // FIXME: Assume only the first tree is the pattern. The others are clobber
3179 TreePatternNode *Pattern = I->getTree(0);
3180 TreePatternNode *SrcPattern;
3181 if (Pattern->getOperator()->getName() == "set") {
3182 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
3184 // Not a set (store or something?)
3185 SrcPattern = Pattern;
3188 Record *Instr = Entry.first;
3189 AddPatternToMatch(I,
3190 PatternToMatch(Instr,
3191 Instr->getValueAsListInit("Predicates"),
3193 TheInst.getResultPattern(),
3194 TheInst.getImpResults(),
3195 Instr->getValueAsInt("AddedComplexity"),
3201 typedef std::pair<const TreePatternNode*, unsigned> NameRecord;
3203 static void FindNames(const TreePatternNode *P,
3204 std::map<std::string, NameRecord> &Names,
3205 TreePattern *PatternTop) {
3206 if (!P->getName().empty()) {
3207 NameRecord &Rec = Names[P->getName()];
3208 // If this is the first instance of the name, remember the node.
3209 if (Rec.second++ == 0)
3211 else if (Rec.first->getExtTypes() != P->getExtTypes())
3212 PatternTop->error("repetition of value: $" + P->getName() +
3213 " where different uses have different types!");
3217 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
3218 FindNames(P->getChild(i), Names, PatternTop);
3222 void CodeGenDAGPatterns::AddPatternToMatch(TreePattern *Pattern,
3223 PatternToMatch &&PTM) {
3224 // Do some sanity checking on the pattern we're about to match.
3226 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this)) {
3227 PrintWarning(Pattern->getRecord()->getLoc(),
3228 Twine("Pattern can never match: ") + Reason);
3232 // If the source pattern's root is a complex pattern, that complex pattern
3233 // must specify the nodes it can potentially match.
3234 if (const ComplexPattern *CP =
3235 PTM.getSrcPattern()->getComplexPatternInfo(*this))
3236 if (CP->getRootNodes().empty())
3237 Pattern->error("ComplexPattern at root must specify list of opcodes it"
3241 // Find all of the named values in the input and output, ensure they have the
3243 std::map<std::string, NameRecord> SrcNames, DstNames;
3244 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
3245 FindNames(PTM.getDstPattern(), DstNames, Pattern);
3247 // Scan all of the named values in the destination pattern, rejecting them if
3248 // they don't exist in the input pattern.
3249 for (const auto &Entry : DstNames) {
3250 if (SrcNames[Entry.first].first == nullptr)
3251 Pattern->error("Pattern has input without matching name in output: $" +
3255 // Scan all of the named values in the source pattern, rejecting them if the
3256 // name isn't used in the dest, and isn't used to tie two values together.
3257 for (const auto &Entry : SrcNames)
3258 if (DstNames[Entry.first].first == nullptr &&
3259 SrcNames[Entry.first].second == 1)
3260 Pattern->error("Pattern has dead named input: $" + Entry.first);
3262 PatternsToMatch.push_back(std::move(PTM));
3267 void CodeGenDAGPatterns::InferInstructionFlags() {
3268 ArrayRef<const CodeGenInstruction*> Instructions =
3269 Target.getInstructionsByEnumValue();
3271 // First try to infer flags from the primary instruction pattern, if any.
3272 SmallVector<CodeGenInstruction*, 8> Revisit;
3273 unsigned Errors = 0;
3274 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
3275 CodeGenInstruction &InstInfo =
3276 const_cast<CodeGenInstruction &>(*Instructions[i]);
3278 // Get the primary instruction pattern.
3279 const TreePattern *Pattern = getInstruction(InstInfo.TheDef).getPattern();
3281 if (InstInfo.hasUndefFlags())
3282 Revisit.push_back(&InstInfo);
3285 InstAnalyzer PatInfo(*this);
3286 PatInfo.Analyze(Pattern);
3287 Errors += InferFromPattern(InstInfo, PatInfo, InstInfo.TheDef);
3290 // Second, look for single-instruction patterns defined outside the
3292 for (const PatternToMatch &PTM : ptms()) {
3293 // We can only infer from single-instruction patterns, otherwise we won't
3294 // know which instruction should get the flags.
3295 SmallVector<Record*, 8> PatInstrs;
3296 getInstructionsInTree(PTM.getDstPattern(), PatInstrs);
3297 if (PatInstrs.size() != 1)
3300 // Get the single instruction.
3301 CodeGenInstruction &InstInfo = Target.getInstruction(PatInstrs.front());
3303 // Only infer properties from the first pattern. We'll verify the others.
3304 if (InstInfo.InferredFrom)
3307 InstAnalyzer PatInfo(*this);
3308 PatInfo.Analyze(PTM);
3309 Errors += InferFromPattern(InstInfo, PatInfo, PTM.getSrcRecord());
3313 PrintFatalError("pattern conflicts");
3315 // Revisit instructions with undefined flags and no pattern.
3316 if (Target.guessInstructionProperties()) {
3317 for (CodeGenInstruction *InstInfo : Revisit) {
3318 if (InstInfo->InferredFrom)
3320 // The mayLoad and mayStore flags default to false.
3321 // Conservatively assume hasSideEffects if it wasn't explicit.
3322 if (InstInfo->hasSideEffects_Unset)
3323 InstInfo->hasSideEffects = true;
3328 // Complain about any flags that are still undefined.
3329 for (CodeGenInstruction *InstInfo : Revisit) {
3330 if (InstInfo->InferredFrom)
3332 if (InstInfo->hasSideEffects_Unset)
3333 PrintError(InstInfo->TheDef->getLoc(),
3334 "Can't infer hasSideEffects from patterns");
3335 if (InstInfo->mayStore_Unset)
3336 PrintError(InstInfo->TheDef->getLoc(),
3337 "Can't infer mayStore from patterns");
3338 if (InstInfo->mayLoad_Unset)
3339 PrintError(InstInfo->TheDef->getLoc(),
3340 "Can't infer mayLoad from patterns");
3345 /// Verify instruction flags against pattern node properties.
3346 void CodeGenDAGPatterns::VerifyInstructionFlags() {
3347 unsigned Errors = 0;
3348 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3349 const PatternToMatch &PTM = *I;
3350 SmallVector<Record*, 8> Instrs;
3351 getInstructionsInTree(PTM.getDstPattern(), Instrs);
3355 // Count the number of instructions with each flag set.
3356 unsigned NumSideEffects = 0;
3357 unsigned NumStores = 0;
3358 unsigned NumLoads = 0;
3359 for (const Record *Instr : Instrs) {
3360 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
3361 NumSideEffects += InstInfo.hasSideEffects;
3362 NumStores += InstInfo.mayStore;
3363 NumLoads += InstInfo.mayLoad;
3366 // Analyze the source pattern.
3367 InstAnalyzer PatInfo(*this);
3368 PatInfo.Analyze(PTM);
3370 // Collect error messages.
3371 SmallVector<std::string, 4> Msgs;
3373 // Check for missing flags in the output.
3374 // Permit extra flags for now at least.
3375 if (PatInfo.hasSideEffects && !NumSideEffects)
3376 Msgs.push_back("pattern has side effects, but hasSideEffects isn't set");
3378 // Don't verify store flags on instructions with side effects. At least for
3379 // intrinsics, side effects implies mayStore.
3380 if (!PatInfo.hasSideEffects && PatInfo.mayStore && !NumStores)
3381 Msgs.push_back("pattern may store, but mayStore isn't set");
3383 // Similarly, mayStore implies mayLoad on intrinsics.
3384 if (!PatInfo.mayStore && PatInfo.mayLoad && !NumLoads)
3385 Msgs.push_back("pattern may load, but mayLoad isn't set");
3387 // Print error messages.
3392 for (const std::string &Msg : Msgs)
3393 PrintError(PTM.getSrcRecord()->getLoc(), Twine(Msg) + " on the " +
3394 (Instrs.size() == 1 ?
3395 "instruction" : "output instructions"));
3396 // Provide the location of the relevant instruction definitions.
3397 for (const Record *Instr : Instrs) {
3398 if (Instr != PTM.getSrcRecord())
3399 PrintError(Instr->getLoc(), "defined here");
3400 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
3401 if (InstInfo.InferredFrom &&
3402 InstInfo.InferredFrom != InstInfo.TheDef &&
3403 InstInfo.InferredFrom != PTM.getSrcRecord())
3404 PrintError(InstInfo.InferredFrom->getLoc(), "inferred from pattern");
3408 PrintFatalError("Errors in DAG patterns");
3411 /// Given a pattern result with an unresolved type, see if we can find one
3412 /// instruction with an unresolved result type. Force this result type to an
3413 /// arbitrary element if it's possible types to converge results.
3414 static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
3418 // Analyze children.
3419 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3420 if (ForceArbitraryInstResultType(N->getChild(i), TP))
3423 if (!N->getOperator()->isSubClassOf("Instruction"))
3426 // If this type is already concrete or completely unknown we can't do
3428 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
3429 if (N->getExtType(i).isCompletelyUnknown() || N->getExtType(i).isConcrete())
3432 // Otherwise, force its type to the first possibility (an arbitrary choice).
3433 if (N->getExtType(i).MergeInTypeInfo(N->getExtType(i).getTypeList()[0], TP))
3440 void CodeGenDAGPatterns::ParsePatterns() {
3441 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
3443 for (Record *CurPattern : Patterns) {
3444 DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
3446 // If the pattern references the null_frag, there's nothing to do.
3447 if (hasNullFragReference(Tree))
3450 TreePattern *Pattern = new TreePattern(CurPattern, Tree, true, *this);
3452 // Inline pattern fragments into it.
3453 Pattern->InlinePatternFragments();
3455 ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
3456 if (LI->empty()) continue; // no pattern.
3458 // Parse the instruction.
3459 TreePattern Result(CurPattern, LI, false, *this);
3461 // Inline pattern fragments into it.
3462 Result.InlinePatternFragments();
3464 if (Result.getNumTrees() != 1)
3465 Result.error("Cannot handle instructions producing instructions "
3466 "with temporaries yet!");
3468 bool IterateInference;
3469 bool InferredAllPatternTypes, InferredAllResultTypes;
3471 // Infer as many types as possible. If we cannot infer all of them, we
3472 // can never do anything with this pattern: report it to the user.
3473 InferredAllPatternTypes =
3474 Pattern->InferAllTypes(&Pattern->getNamedNodesMap());
3476 // Infer as many types as possible. If we cannot infer all of them, we
3477 // can never do anything with this pattern: report it to the user.
3478 InferredAllResultTypes =
3479 Result.InferAllTypes(&Pattern->getNamedNodesMap());
3481 IterateInference = false;
3483 // Apply the type of the result to the source pattern. This helps us
3484 // resolve cases where the input type is known to be a pointer type (which
3485 // is considered resolved), but the result knows it needs to be 32- or
3486 // 64-bits. Infer the other way for good measure.
3487 for (unsigned i = 0, e = std::min(Result.getTree(0)->getNumTypes(),
3488 Pattern->getTree(0)->getNumTypes());
3490 IterateInference = Pattern->getTree(0)->UpdateNodeType(
3491 i, Result.getTree(0)->getExtType(i), Result);
3492 IterateInference |= Result.getTree(0)->UpdateNodeType(
3493 i, Pattern->getTree(0)->getExtType(i), Result);
3496 // If our iteration has converged and the input pattern's types are fully
3497 // resolved but the result pattern is not fully resolved, we may have a
3498 // situation where we have two instructions in the result pattern and
3499 // the instructions require a common register class, but don't care about
3500 // what actual MVT is used. This is actually a bug in our modelling:
3501 // output patterns should have register classes, not MVTs.
3503 // In any case, to handle this, we just go through and disambiguate some
3504 // arbitrary types to the result pattern's nodes.
3505 if (!IterateInference && InferredAllPatternTypes &&
3506 !InferredAllResultTypes)
3508 ForceArbitraryInstResultType(Result.getTree(0), Result);
3509 } while (IterateInference);
3511 // Verify that we inferred enough types that we can do something with the
3512 // pattern and result. If these fire the user has to add type casts.
3513 if (!InferredAllPatternTypes)
3514 Pattern->error("Could not infer all types in pattern!");
3515 if (!InferredAllResultTypes) {
3517 Result.error("Could not infer all types in pattern result!");
3520 // Validate that the input pattern is correct.
3521 std::map<std::string, TreePatternNode*> InstInputs;
3522 std::map<std::string, TreePatternNode*> InstResults;
3523 std::vector<Record*> InstImpResults;
3524 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
3525 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
3526 InstInputs, InstResults,
3529 // Promote the xform function to be an explicit node if set.
3530 TreePatternNode *DstPattern = Result.getOnlyTree();
3531 std::vector<TreePatternNode*> ResultNodeOperands;
3532 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
3533 TreePatternNode *OpNode = DstPattern->getChild(ii);
3534 if (Record *Xform = OpNode->getTransformFn()) {
3535 OpNode->setTransformFn(nullptr);
3536 std::vector<TreePatternNode*> Children;
3537 Children.push_back(OpNode);
3538 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
3540 ResultNodeOperands.push_back(OpNode);
3542 DstPattern = Result.getOnlyTree();
3543 if (!DstPattern->isLeaf())
3544 DstPattern = new TreePatternNode(DstPattern->getOperator(),
3546 DstPattern->getNumTypes());
3548 for (unsigned i = 0, e = Result.getOnlyTree()->getNumTypes(); i != e; ++i)
3549 DstPattern->setType(i, Result.getOnlyTree()->getExtType(i));
3551 TreePattern Temp(Result.getRecord(), DstPattern, false, *this);
3552 Temp.InferAllTypes();
3557 CurPattern, CurPattern->getValueAsListInit("Predicates"),
3558 Pattern->getTree(0), Temp.getOnlyTree(), std::move(InstImpResults),
3559 CurPattern->getValueAsInt("AddedComplexity"), CurPattern->getID()));
3563 /// CombineChildVariants - Given a bunch of permutations of each child of the
3564 /// 'operator' node, put them together in all possible ways.
3565 static void CombineChildVariants(TreePatternNode *Orig,
3566 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
3567 std::vector<TreePatternNode*> &OutVariants,
3568 CodeGenDAGPatterns &CDP,
3569 const MultipleUseVarSet &DepVars) {
3570 // Make sure that each operand has at least one variant to choose from.
3571 for (const auto &Variants : ChildVariants)
3572 if (Variants.empty())
3575 // The end result is an all-pairs construction of the resultant pattern.
3576 std::vector<unsigned> Idxs;
3577 Idxs.resize(ChildVariants.size());
3581 DEBUG(if (!Idxs.empty()) {
3582 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
3583 for (unsigned Idx : Idxs) {
3584 errs() << Idx << " ";
3589 // Create the variant and add it to the output list.
3590 std::vector<TreePatternNode*> NewChildren;
3591 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
3592 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
3593 auto R = llvm::make_unique<TreePatternNode>(
3594 Orig->getOperator(), NewChildren, Orig->getNumTypes());
3596 // Copy over properties.
3597 R->setName(Orig->getName());
3598 R->setPredicateFns(Orig->getPredicateFns());
3599 R->setTransformFn(Orig->getTransformFn());
3600 for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
3601 R->setType(i, Orig->getExtType(i));
3603 // If this pattern cannot match, do not include it as a variant.
3604 std::string ErrString;
3605 // Scan to see if this pattern has already been emitted. We can get
3606 // duplication due to things like commuting:
3607 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
3608 // which are the same pattern. Ignore the dups.
3609 if (R->canPatternMatch(ErrString, CDP) &&
3610 none_of(OutVariants, [&](TreePatternNode *Variant) {
3611 return R->isIsomorphicTo(Variant, DepVars);
3613 OutVariants.push_back(R.release());
3615 // Increment indices to the next permutation by incrementing the
3616 // indices from last index backward, e.g., generate the sequence
3617 // [0, 0], [0, 1], [1, 0], [1, 1].
3619 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
3620 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
3625 NotDone = (IdxsIdx >= 0);
3629 /// CombineChildVariants - A helper function for binary operators.
3631 static void CombineChildVariants(TreePatternNode *Orig,
3632 const std::vector<TreePatternNode*> &LHS,
3633 const std::vector<TreePatternNode*> &RHS,
3634 std::vector<TreePatternNode*> &OutVariants,
3635 CodeGenDAGPatterns &CDP,
3636 const MultipleUseVarSet &DepVars) {
3637 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3638 ChildVariants.push_back(LHS);
3639 ChildVariants.push_back(RHS);
3640 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
3644 static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
3645 std::vector<TreePatternNode *> &Children) {
3646 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
3647 Record *Operator = N->getOperator();
3649 // Only permit raw nodes.
3650 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
3651 N->getTransformFn()) {
3652 Children.push_back(N);
3656 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
3657 Children.push_back(N->getChild(0));
3659 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
3661 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
3662 Children.push_back(N->getChild(1));
3664 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
3667 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
3668 /// the (potentially recursive) pattern by using algebraic laws.
3670 static void GenerateVariantsOf(TreePatternNode *N,
3671 std::vector<TreePatternNode*> &OutVariants,
3672 CodeGenDAGPatterns &CDP,
3673 const MultipleUseVarSet &DepVars) {
3674 // We cannot permute leaves or ComplexPattern uses.
3675 if (N->isLeaf() || N->getOperator()->isSubClassOf("ComplexPattern")) {
3676 OutVariants.push_back(N);
3680 // Look up interesting info about the node.
3681 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
3683 // If this node is associative, re-associate.
3684 if (NodeInfo.hasProperty(SDNPAssociative)) {
3685 // Re-associate by pulling together all of the linked operators
3686 std::vector<TreePatternNode*> MaximalChildren;
3687 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
3689 // Only handle child sizes of 3. Otherwise we'll end up trying too many
3691 if (MaximalChildren.size() == 3) {
3692 // Find the variants of all of our maximal children.
3693 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
3694 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
3695 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
3696 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
3698 // There are only two ways we can permute the tree:
3699 // (A op B) op C and A op (B op C)
3700 // Within these forms, we can also permute A/B/C.
3702 // Generate legal pair permutations of A/B/C.
3703 std::vector<TreePatternNode*> ABVariants;
3704 std::vector<TreePatternNode*> BAVariants;
3705 std::vector<TreePatternNode*> ACVariants;
3706 std::vector<TreePatternNode*> CAVariants;
3707 std::vector<TreePatternNode*> BCVariants;
3708 std::vector<TreePatternNode*> CBVariants;
3709 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
3710 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
3711 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
3712 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
3713 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
3714 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
3716 // Combine those into the result: (x op x) op x
3717 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
3718 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
3719 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
3720 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
3721 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
3722 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
3724 // Combine those into the result: x op (x op x)
3725 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
3726 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
3727 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
3728 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
3729 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
3730 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
3735 // Compute permutations of all children.
3736 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3737 ChildVariants.resize(N->getNumChildren());
3738 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3739 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
3741 // Build all permutations based on how the children were formed.
3742 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
3744 // If this node is commutative, consider the commuted order.
3745 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
3746 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
3747 assert((N->getNumChildren()==2 || isCommIntrinsic) &&
3748 "Commutative but doesn't have 2 children!");
3749 // Don't count children which are actually register references.
3751 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
3752 TreePatternNode *Child = N->getChild(i);
3753 if (Child->isLeaf())
3754 if (DefInit *DI = dyn_cast<DefInit>(Child->getLeafValue())) {
3755 Record *RR = DI->getDef();
3756 if (RR->isSubClassOf("Register"))
3761 // Consider the commuted order.
3762 if (isCommIntrinsic) {
3763 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
3764 // operands are the commutative operands, and there might be more operands
3767 "Commutative intrinsic should have at least 3 children!");
3768 std::vector<std::vector<TreePatternNode*> > Variants;
3769 Variants.push_back(ChildVariants[0]); // Intrinsic id.
3770 Variants.push_back(ChildVariants[2]);
3771 Variants.push_back(ChildVariants[1]);
3772 for (unsigned i = 3; i != NC; ++i)
3773 Variants.push_back(ChildVariants[i]);
3774 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
3776 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
3777 OutVariants, CDP, DepVars);
3782 // GenerateVariants - Generate variants. For example, commutative patterns can
3783 // match multiple ways. Add them to PatternsToMatch as well.
3784 void CodeGenDAGPatterns::GenerateVariants() {
3785 DEBUG(errs() << "Generating instruction variants.\n");
3787 // Loop over all of the patterns we've collected, checking to see if we can
3788 // generate variants of the instruction, through the exploitation of
3789 // identities. This permits the target to provide aggressive matching without
3790 // the .td file having to contain tons of variants of instructions.
3792 // Note that this loop adds new patterns to the PatternsToMatch list, but we
3793 // intentionally do not reconsider these. Any variants of added patterns have
3794 // already been added.
3796 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
3797 MultipleUseVarSet DepVars;
3798 std::vector<TreePatternNode*> Variants;
3799 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
3800 DEBUG(errs() << "Dependent/multiply used variables: ");
3801 DEBUG(DumpDepVars(DepVars));
3802 DEBUG(errs() << "\n");
3803 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this,
3806 assert(!Variants.empty() && "Must create at least original variant!");
3807 if (Variants.size() == 1) // No additional variants for this pattern.
3810 DEBUG(errs() << "FOUND VARIANTS OF: ";
3811 PatternsToMatch[i].getSrcPattern()->dump();
3814 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
3815 TreePatternNode *Variant = Variants[v];
3817 DEBUG(errs() << " VAR#" << v << ": ";
3821 // Scan to see if an instruction or explicit pattern already matches this.
3822 bool AlreadyExists = false;
3823 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
3824 // Skip if the top level predicates do not match.
3825 if (PatternsToMatch[i].getPredicates() !=
3826 PatternsToMatch[p].getPredicates())
3828 // Check to see if this variant already exists.
3829 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),
3831 DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
3832 AlreadyExists = true;
3836 // If we already have it, ignore the variant.
3837 if (AlreadyExists) continue;
3839 // Otherwise, add it to the list of patterns we have.
3840 PatternsToMatch.push_back(PatternToMatch(
3841 PatternsToMatch[i].getSrcRecord(), PatternsToMatch[i].getPredicates(),
3842 Variant, PatternsToMatch[i].getDstPattern(),
3843 PatternsToMatch[i].getDstRegs(),
3844 PatternsToMatch[i].getAddedComplexity(), Record::getNewUID()));
3847 DEBUG(errs() << "\n");