1 //===- CodeGenDAGPatterns.cpp - Read DAG patterns from .td file -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the CodeGenDAGPatterns class, which is used to read and
11 // represent the patterns present in a .td file for instructions.
13 //===----------------------------------------------------------------------===//
15 #include "CodeGenDAGPatterns.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/ADT/Twine.h"
19 #include "llvm/Support/Debug.h"
20 #include "llvm/Support/ErrorHandling.h"
21 #include "llvm/TableGen/Error.h"
22 #include "llvm/TableGen/Record.h"
28 #define DEBUG_TYPE "dag-patterns"
30 //===----------------------------------------------------------------------===//
31 // EEVT::TypeSet Implementation
32 //===----------------------------------------------------------------------===//
34 static inline bool isInteger(MVT::SimpleValueType VT) {
35 return MVT(VT).isInteger();
37 static inline bool isFloatingPoint(MVT::SimpleValueType VT) {
38 return MVT(VT).isFloatingPoint();
40 static inline bool isVector(MVT::SimpleValueType VT) {
41 return MVT(VT).isVector();
43 static inline bool isScalar(MVT::SimpleValueType VT) {
44 return !MVT(VT).isVector();
47 EEVT::TypeSet::TypeSet(MVT::SimpleValueType VT, TreePattern &TP) {
50 else if (VT == MVT::fAny)
51 EnforceFloatingPoint(TP);
52 else if (VT == MVT::vAny)
55 assert((VT < MVT::LAST_VALUETYPE || VT == MVT::iPTR ||
56 VT == MVT::iPTRAny || VT == MVT::Any) && "Not a concrete type!");
57 TypeVec.push_back(VT);
62 EEVT::TypeSet::TypeSet(ArrayRef<MVT::SimpleValueType> VTList) {
63 assert(!VTList.empty() && "empty list?");
64 TypeVec.append(VTList.begin(), VTList.end());
67 assert(VTList[0] != MVT::iAny && VTList[0] != MVT::vAny &&
68 VTList[0] != MVT::fAny);
70 // Verify no duplicates.
71 array_pod_sort(TypeVec.begin(), TypeVec.end());
72 assert(std::unique(TypeVec.begin(), TypeVec.end()) == TypeVec.end());
75 /// FillWithPossibleTypes - Set to all legal types and return true, only valid
76 /// on completely unknown type sets.
77 bool EEVT::TypeSet::FillWithPossibleTypes(TreePattern &TP,
78 bool (*Pred)(MVT::SimpleValueType),
79 const char *PredicateName) {
80 assert(isCompletelyUnknown());
81 ArrayRef<MVT::SimpleValueType> LegalTypes =
82 TP.getDAGPatterns().getTargetInfo().getLegalValueTypes();
87 for (MVT::SimpleValueType VT : LegalTypes)
88 if (!Pred || Pred(VT))
89 TypeVec.push_back(VT);
91 // If we have nothing that matches the predicate, bail out.
92 if (TypeVec.empty()) {
93 TP.error("Type inference contradiction found, no " +
94 std::string(PredicateName) + " types found");
97 // No need to sort with one element.
98 if (TypeVec.size() == 1) return true;
100 // Remove duplicates.
101 array_pod_sort(TypeVec.begin(), TypeVec.end());
102 TypeVec.erase(std::unique(TypeVec.begin(), TypeVec.end()), TypeVec.end());
107 /// hasIntegerTypes - Return true if this TypeSet contains iAny or an
108 /// integer value type.
109 bool EEVT::TypeSet::hasIntegerTypes() const {
110 return std::any_of(TypeVec.begin(), TypeVec.end(), isInteger);
113 /// hasFloatingPointTypes - Return true if this TypeSet contains an fAny or
114 /// a floating point value type.
115 bool EEVT::TypeSet::hasFloatingPointTypes() const {
116 return std::any_of(TypeVec.begin(), TypeVec.end(), isFloatingPoint);
119 /// hasScalarTypes - Return true if this TypeSet contains a scalar value type.
120 bool EEVT::TypeSet::hasScalarTypes() const {
121 return std::any_of(TypeVec.begin(), TypeVec.end(), isScalar);
124 /// hasVectorTypes - Return true if this TypeSet contains a vAny or a vector
126 bool EEVT::TypeSet::hasVectorTypes() const {
127 return std::any_of(TypeVec.begin(), TypeVec.end(), isVector);
131 std::string EEVT::TypeSet::getName() const {
132 if (TypeVec.empty()) return "<empty>";
136 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i) {
137 std::string VTName = llvm::getEnumName(TypeVec[i]);
138 // Strip off MVT:: prefix if present.
139 if (VTName.substr(0,5) == "MVT::")
140 VTName = VTName.substr(5);
141 if (i) Result += ':';
145 if (TypeVec.size() == 1)
147 return "{" + Result + "}";
150 /// MergeInTypeInfo - This merges in type information from the specified
151 /// argument. If 'this' changes, it returns true. If the two types are
152 /// contradictory (e.g. merge f32 into i32) then this flags an error.
153 bool EEVT::TypeSet::MergeInTypeInfo(const EEVT::TypeSet &InVT, TreePattern &TP){
154 if (InVT.isCompletelyUnknown() || *this == InVT || TP.hasError())
157 if (isCompletelyUnknown()) {
162 assert(TypeVec.size() >= 1 && InVT.TypeVec.size() >= 1 && "No unknowns");
164 // Handle the abstract cases, seeing if we can resolve them better.
165 switch (TypeVec[0]) {
169 if (InVT.hasIntegerTypes()) {
170 EEVT::TypeSet InCopy(InVT);
171 InCopy.EnforceInteger(TP);
172 InCopy.EnforceScalar(TP);
174 if (InCopy.isConcrete()) {
175 // If the RHS has one integer type, upgrade iPTR to i32.
176 TypeVec[0] = InVT.TypeVec[0];
180 // If the input has multiple scalar integers, this doesn't add any info.
181 if (!InCopy.isCompletelyUnknown())
187 // If the input constraint is iAny/iPTR and this is an integer type list,
188 // remove non-integer types from the list.
189 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
191 bool MadeChange = EnforceInteger(TP);
193 // If we're merging in iPTR/iPTRAny and the node currently has a list of
194 // multiple different integer types, replace them with a single iPTR.
195 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
196 TypeVec.size() != 1) {
198 TypeVec[0] = 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 bool MadeChange = false;
208 TypeSet InputSet(*this);
210 for (unsigned i = 0; i != TypeVec.size(); ++i) {
211 if (std::find(InVT.TypeVec.begin(), InVT.TypeVec.end(), TypeVec[i]) !=
215 TypeVec.erase(TypeVec.begin()+i--);
219 // If we removed all of our types, we have a type contradiction.
220 if (!TypeVec.empty())
223 // FIXME: Really want an SMLoc here!
224 TP.error("Type inference contradiction found, merging '" +
225 InVT.getName() + "' into '" + InputSet.getName() + "'");
229 /// EnforceInteger - Remove all non-integer types from this set.
230 bool EEVT::TypeSet::EnforceInteger(TreePattern &TP) {
233 // If we know nothing, then get the full set.
235 return FillWithPossibleTypes(TP, isInteger, "integer");
236 if (!hasFloatingPointTypes())
239 TypeSet InputSet(*this);
241 // Filter out all the fp types.
242 for (unsigned i = 0; i != TypeVec.size(); ++i)
243 if (!isInteger(TypeVec[i]))
244 TypeVec.erase(TypeVec.begin()+i--);
246 if (TypeVec.empty()) {
247 TP.error("Type inference contradiction found, '" +
248 InputSet.getName() + "' needs to be integer");
254 /// EnforceFloatingPoint - Remove all integer types from this set.
255 bool EEVT::TypeSet::EnforceFloatingPoint(TreePattern &TP) {
258 // If we know nothing, then get the full set.
260 return FillWithPossibleTypes(TP, isFloatingPoint, "floating point");
262 if (!hasIntegerTypes())
265 TypeSet InputSet(*this);
267 // Filter out all the fp types.
268 for (unsigned i = 0; i != TypeVec.size(); ++i)
269 if (!isFloatingPoint(TypeVec[i]))
270 TypeVec.erase(TypeVec.begin()+i--);
272 if (TypeVec.empty()) {
273 TP.error("Type inference contradiction found, '" +
274 InputSet.getName() + "' needs to be floating point");
280 /// EnforceScalar - Remove all vector types from this.
281 bool EEVT::TypeSet::EnforceScalar(TreePattern &TP) {
285 // If we know nothing, then get the full set.
287 return FillWithPossibleTypes(TP, isScalar, "scalar");
289 if (!hasVectorTypes())
292 TypeSet InputSet(*this);
294 // Filter out all the vector types.
295 for (unsigned i = 0; i != TypeVec.size(); ++i)
296 if (!isScalar(TypeVec[i]))
297 TypeVec.erase(TypeVec.begin()+i--);
299 if (TypeVec.empty()) {
300 TP.error("Type inference contradiction found, '" +
301 InputSet.getName() + "' needs to be scalar");
307 /// EnforceVector - Remove all vector types from this.
308 bool EEVT::TypeSet::EnforceVector(TreePattern &TP) {
312 // If we know nothing, then get the full set.
314 return FillWithPossibleTypes(TP, isVector, "vector");
316 TypeSet InputSet(*this);
317 bool MadeChange = false;
319 // Filter out all the scalar types.
320 for (unsigned i = 0; i != TypeVec.size(); ++i)
321 if (!isVector(TypeVec[i])) {
322 TypeVec.erase(TypeVec.begin()+i--);
326 if (TypeVec.empty()) {
327 TP.error("Type inference contradiction found, '" +
328 InputSet.getName() + "' needs to be a vector");
336 /// EnforceSmallerThan - 'this' must be a smaller VT than Other. For vectors
337 /// this should be based on the element type. Update this and other based on
338 /// this information.
339 bool EEVT::TypeSet::EnforceSmallerThan(EEVT::TypeSet &Other, TreePattern &TP) {
343 // Both operands must be integer or FP, but we don't care which.
344 bool MadeChange = false;
346 if (isCompletelyUnknown())
347 MadeChange = FillWithPossibleTypes(TP);
349 if (Other.isCompletelyUnknown())
350 MadeChange = Other.FillWithPossibleTypes(TP);
352 // If one side is known to be integer or known to be FP but the other side has
353 // no information, get at least the type integrality info in there.
354 if (!hasFloatingPointTypes())
355 MadeChange |= Other.EnforceInteger(TP);
356 else if (!hasIntegerTypes())
357 MadeChange |= Other.EnforceFloatingPoint(TP);
358 if (!Other.hasFloatingPointTypes())
359 MadeChange |= EnforceInteger(TP);
360 else if (!Other.hasIntegerTypes())
361 MadeChange |= EnforceFloatingPoint(TP);
363 assert(!isCompletelyUnknown() && !Other.isCompletelyUnknown() &&
364 "Should have a type list now");
366 // If one contains vectors but the other doesn't pull vectors out.
367 if (!hasVectorTypes())
368 MadeChange |= Other.EnforceScalar(TP);
369 else if (!hasScalarTypes())
370 MadeChange |= Other.EnforceVector(TP);
371 if (!Other.hasVectorTypes())
372 MadeChange |= EnforceScalar(TP);
373 else if (!Other.hasScalarTypes())
374 MadeChange |= EnforceVector(TP);
376 // This code does not currently handle nodes which have multiple types,
377 // where some types are integer, and some are fp. Assert that this is not
379 assert(!(hasIntegerTypes() && hasFloatingPointTypes()) &&
380 !(Other.hasIntegerTypes() && Other.hasFloatingPointTypes()) &&
381 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
386 // Okay, find the smallest type from current set and remove anything the
387 // same or smaller from the other set. We need to ensure that the scalar
388 // type size is smaller than the scalar size of the smallest type. For
389 // vectors, we also need to make sure that the total size is no larger than
390 // the size of the smallest type.
391 TypeSet InputSet(Other);
392 MVT Smallest = TypeVec[0];
393 for (unsigned i = 0; i != Other.TypeVec.size(); ++i) {
394 MVT OtherVT = Other.TypeVec[i];
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 if (OtherVT.getScalarSizeInBits() <= Smallest.getScalarSizeInBits() ||
401 OtherVT.getSizeInBits() < Smallest.getSizeInBits()) {
402 Other.TypeVec.erase(Other.TypeVec.begin()+i--);
407 if (Other.TypeVec.empty()) {
408 TP.error("Type inference contradiction found, '" + InputSet.getName() +
409 "' 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.
418 InputSet = TypeSet(*this);
419 MVT Largest = Other.TypeVec[Other.TypeVec.size()-1];
420 for (unsigned i = 0; i != TypeVec.size(); ++i) {
421 MVT OtherVT = TypeVec[i];
422 // Don't compare vector and non-vector types.
423 if (OtherVT.isVector() != Largest.isVector())
425 // The getSizeInBits() check here is only needed for vectors, but is
426 // a subset of the scalar check for scalars so no need to qualify.
427 if (OtherVT.getScalarSizeInBits() >= Largest.getScalarSizeInBits() ||
428 OtherVT.getSizeInBits() > Largest.getSizeInBits()) {
429 TypeVec.erase(TypeVec.begin()+i--);
434 if (TypeVec.empty()) {
435 TP.error("Type inference contradiction found, '" + InputSet.getName() +
436 "' has nothing smaller than '" + Other.getName() +"'!");
443 /// EnforceVectorEltTypeIs - 'this' is now constrained to be a vector type
444 /// whose element is specified by VTOperand.
445 bool EEVT::TypeSet::EnforceVectorEltTypeIs(MVT::SimpleValueType VT,
447 bool MadeChange = false;
449 MadeChange |= EnforceVector(TP);
451 TypeSet InputSet(*this);
453 // Filter out all the types which don't have the right element type.
454 for (unsigned i = 0; i != TypeVec.size(); ++i) {
455 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
456 if (MVT(TypeVec[i]).getVectorElementType().SimpleTy != VT) {
457 TypeVec.erase(TypeVec.begin()+i--);
462 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
463 TP.error("Type inference contradiction found, forcing '" +
464 InputSet.getName() + "' to have a vector element");
471 /// EnforceVectorEltTypeIs - 'this' is now constrained to be a vector type
472 /// whose element is specified by VTOperand.
473 bool EEVT::TypeSet::EnforceVectorEltTypeIs(EEVT::TypeSet &VTOperand,
478 // "This" must be a vector and "VTOperand" must be a scalar.
479 bool MadeChange = false;
480 MadeChange |= EnforceVector(TP);
481 MadeChange |= VTOperand.EnforceScalar(TP);
483 // If we know the vector type, it forces the scalar to agree.
485 MVT IVT = getConcrete();
486 IVT = IVT.getVectorElementType();
488 VTOperand.MergeInTypeInfo(IVT.SimpleTy, TP);
491 // If the scalar type is known, filter out vector types whose element types
493 if (!VTOperand.isConcrete())
496 MVT::SimpleValueType VT = VTOperand.getConcrete();
498 TypeSet InputSet(*this);
500 // Filter out all the types which don't have the right element type.
501 for (unsigned i = 0; i != TypeVec.size(); ++i) {
502 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
503 if (MVT(TypeVec[i]).getVectorElementType().SimpleTy != VT) {
504 TypeVec.erase(TypeVec.begin()+i--);
509 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
510 TP.error("Type inference contradiction found, forcing '" +
511 InputSet.getName() + "' to have a vector element");
517 /// EnforceVectorSubVectorTypeIs - 'this' is now constrained to be a
518 /// vector type specified by VTOperand.
519 bool EEVT::TypeSet::EnforceVectorSubVectorTypeIs(EEVT::TypeSet &VTOperand,
524 // "This" must be a vector and "VTOperand" must be a vector.
525 bool MadeChange = false;
526 MadeChange |= EnforceVector(TP);
527 MadeChange |= VTOperand.EnforceVector(TP);
529 // If one side is known to be integer or known to be FP but the other side has
530 // no information, get at least the type integrality info in there.
531 if (!hasFloatingPointTypes())
532 MadeChange |= VTOperand.EnforceInteger(TP);
533 else if (!hasIntegerTypes())
534 MadeChange |= VTOperand.EnforceFloatingPoint(TP);
535 if (!VTOperand.hasFloatingPointTypes())
536 MadeChange |= EnforceInteger(TP);
537 else if (!VTOperand.hasIntegerTypes())
538 MadeChange |= EnforceFloatingPoint(TP);
540 assert(!isCompletelyUnknown() && !VTOperand.isCompletelyUnknown() &&
541 "Should have a type list now");
543 // If we know the vector type, it forces the scalar types to agree.
544 // Also force one vector to have more elements than the other.
546 MVT IVT = getConcrete();
547 unsigned NumElems = IVT.getVectorNumElements();
548 IVT = IVT.getVectorElementType();
550 EEVT::TypeSet EltTypeSet(IVT.SimpleTy, TP);
551 MadeChange |= VTOperand.EnforceVectorEltTypeIs(EltTypeSet, TP);
553 // Only keep types that have less elements than VTOperand.
554 TypeSet InputSet(VTOperand);
556 for (unsigned i = 0; i != VTOperand.TypeVec.size(); ++i) {
557 assert(isVector(VTOperand.TypeVec[i]) && "EnforceVector didn't work");
558 if (MVT(VTOperand.TypeVec[i]).getVectorNumElements() >= NumElems) {
559 VTOperand.TypeVec.erase(VTOperand.TypeVec.begin()+i--);
563 if (VTOperand.TypeVec.empty()) { // FIXME: Really want an SMLoc here!
564 TP.error("Type inference contradiction found, forcing '" +
565 InputSet.getName() + "' to have less vector elements than '" +
569 } else if (VTOperand.isConcrete()) {
570 MVT IVT = VTOperand.getConcrete();
571 unsigned NumElems = IVT.getVectorNumElements();
572 IVT = IVT.getVectorElementType();
574 EEVT::TypeSet EltTypeSet(IVT.SimpleTy, TP);
575 MadeChange |= EnforceVectorEltTypeIs(EltTypeSet, TP);
577 // Only keep types that have more elements than 'this'.
578 TypeSet InputSet(*this);
580 for (unsigned i = 0; i != TypeVec.size(); ++i) {
581 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
582 if (MVT(TypeVec[i]).getVectorNumElements() <= NumElems) {
583 TypeVec.erase(TypeVec.begin()+i--);
587 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
588 TP.error("Type inference contradiction found, forcing '" +
589 InputSet.getName() + "' to have more vector elements than '" +
590 VTOperand.getName() + "'");
598 /// EnforceVectorSameNumElts - 'this' is now constrained to
599 /// be a vector with same num elements as VTOperand.
600 bool EEVT::TypeSet::EnforceVectorSameNumElts(EEVT::TypeSet &VTOperand,
605 // "This" must be a vector and "VTOperand" must be a vector.
606 bool MadeChange = false;
607 MadeChange |= EnforceVector(TP);
608 MadeChange |= VTOperand.EnforceVector(TP);
610 // If we know one of the vector types, it forces the other type to agree.
612 MVT IVT = getConcrete();
613 unsigned NumElems = IVT.getVectorNumElements();
615 // Only keep types that have same elements as VTOperand.
616 TypeSet InputSet(VTOperand);
618 for (unsigned i = 0; i != VTOperand.TypeVec.size(); ++i) {
619 assert(isVector(VTOperand.TypeVec[i]) && "EnforceVector didn't work");
620 if (MVT(VTOperand.TypeVec[i]).getVectorNumElements() != NumElems) {
621 VTOperand.TypeVec.erase(VTOperand.TypeVec.begin()+i--);
625 if (VTOperand.TypeVec.empty()) { // FIXME: Really want an SMLoc here!
626 TP.error("Type inference contradiction found, forcing '" +
627 InputSet.getName() + "' to have same number elements as '" +
631 } else if (VTOperand.isConcrete()) {
632 MVT IVT = VTOperand.getConcrete();
633 unsigned NumElems = IVT.getVectorNumElements();
635 // Only keep types that have same elements as 'this'.
636 TypeSet InputSet(*this);
638 for (unsigned i = 0; i != TypeVec.size(); ++i) {
639 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
640 if (MVT(TypeVec[i]).getVectorNumElements() != NumElems) {
641 TypeVec.erase(TypeVec.begin()+i--);
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() + "'");
656 //===----------------------------------------------------------------------===//
657 // Helpers for working with extended types.
659 /// Dependent variable map for CodeGenDAGPattern variant generation
660 typedef std::map<std::string, int> DepVarMap;
662 static void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
664 if (isa<DefInit>(N->getLeafValue()))
665 DepMap[N->getName()]++;
667 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
668 FindDepVarsOf(N->getChild(i), DepMap);
672 /// Find dependent variables within child patterns
673 static void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
675 FindDepVarsOf(N, depcounts);
676 for (const std::pair<std::string, int> &Pair : depcounts) {
678 DepVars.insert(Pair.first);
683 /// Dump the dependent variable set:
684 static void DumpDepVars(MultipleUseVarSet &DepVars) {
685 if (DepVars.empty()) {
686 DEBUG(errs() << "<empty set>");
688 DEBUG(errs() << "[ ");
689 for (const std::string &DepVar : DepVars) {
690 DEBUG(errs() << DepVar << " ");
692 DEBUG(errs() << "]");
698 //===----------------------------------------------------------------------===//
699 // TreePredicateFn Implementation
700 //===----------------------------------------------------------------------===//
702 /// TreePredicateFn constructor. Here 'N' is a subclass of PatFrag.
703 TreePredicateFn::TreePredicateFn(TreePattern *N) : PatFragRec(N) {
704 assert((getPredCode().empty() || getImmCode().empty()) &&
705 ".td file corrupt: can't have a node predicate *and* an imm predicate");
708 std::string TreePredicateFn::getPredCode() const {
709 return PatFragRec->getRecord()->getValueAsString("PredicateCode");
712 std::string TreePredicateFn::getImmCode() const {
713 return PatFragRec->getRecord()->getValueAsString("ImmediateCode");
717 /// isAlwaysTrue - Return true if this is a noop predicate.
718 bool TreePredicateFn::isAlwaysTrue() const {
719 return getPredCode().empty() && getImmCode().empty();
722 /// Return the name to use in the generated code to reference this, this is
723 /// "Predicate_foo" if from a pattern fragment "foo".
724 std::string TreePredicateFn::getFnName() const {
725 return "Predicate_" + PatFragRec->getRecord()->getName();
728 /// getCodeToRunOnSDNode - Return the code for the function body that
729 /// evaluates this predicate. The argument is expected to be in "Node",
730 /// not N. This handles casting and conversion to a concrete node type as
732 std::string TreePredicateFn::getCodeToRunOnSDNode() const {
733 // Handle immediate predicates first.
734 std::string ImmCode = getImmCode();
735 if (!ImmCode.empty()) {
737 " int64_t Imm = cast<ConstantSDNode>(Node)->getSExtValue();\n";
738 return Result + ImmCode;
741 // Handle arbitrary node predicates.
742 assert(!getPredCode().empty() && "Don't have any predicate code!");
743 std::string ClassName;
744 if (PatFragRec->getOnlyTree()->isLeaf())
745 ClassName = "SDNode";
747 Record *Op = PatFragRec->getOnlyTree()->getOperator();
748 ClassName = PatFragRec->getDAGPatterns().getSDNodeInfo(Op).getSDClassName();
751 if (ClassName == "SDNode")
752 Result = " SDNode *N = Node;\n";
754 Result = " auto *N = cast<" + ClassName + ">(Node);\n";
756 return Result + getPredCode();
759 //===----------------------------------------------------------------------===//
760 // PatternToMatch implementation
764 /// getPatternSize - Return the 'size' of this pattern. We want to match large
765 /// patterns before small ones. This is used to determine the size of a
767 static unsigned getPatternSize(const TreePatternNode *P,
768 const CodeGenDAGPatterns &CGP) {
769 unsigned Size = 3; // The node itself.
770 // If the root node is a ConstantSDNode, increases its size.
771 // e.g. (set R32:$dst, 0).
772 if (P->isLeaf() && isa<IntInit>(P->getLeafValue()))
775 // FIXME: This is a hack to statically increase the priority of patterns
776 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
777 // Later we can allow complexity / cost for each pattern to be (optionally)
778 // specified. To get best possible pattern match we'll need to dynamically
779 // calculate the complexity of all patterns a dag can potentially map to.
780 const ComplexPattern *AM = P->getComplexPatternInfo(CGP);
782 Size += AM->getNumOperands() * 3;
784 // We don't want to count any children twice, so return early.
788 // If this node has some predicate function that must match, it adds to the
789 // complexity of this node.
790 if (!P->getPredicateFns().empty())
793 // Count children in the count if they are also nodes.
794 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
795 TreePatternNode *Child = P->getChild(i);
796 if (!Child->isLeaf() && Child->getNumTypes() &&
797 Child->getType(0) != MVT::Other)
798 Size += getPatternSize(Child, CGP);
799 else if (Child->isLeaf()) {
800 if (isa<IntInit>(Child->getLeafValue()))
801 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
802 else if (Child->getComplexPatternInfo(CGP))
803 Size += getPatternSize(Child, CGP);
804 else if (!Child->getPredicateFns().empty())
812 /// Compute the complexity metric for the input pattern. This roughly
813 /// corresponds to the number of nodes that are covered.
815 getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
816 return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();
820 /// getPredicateCheck - Return a single string containing all of this
821 /// pattern's predicates concatenated with "&&" operators.
823 std::string PatternToMatch::getPredicateCheck() const {
824 std::string PredicateCheck;
825 for (Init *I : Predicates->getValues()) {
826 if (DefInit *Pred = dyn_cast<DefInit>(I)) {
827 Record *Def = Pred->getDef();
828 if (!Def->isSubClassOf("Predicate")) {
832 llvm_unreachable("Unknown predicate type!");
834 if (!PredicateCheck.empty())
835 PredicateCheck += " && ";
836 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
840 return PredicateCheck;
843 //===----------------------------------------------------------------------===//
844 // SDTypeConstraint implementation
847 SDTypeConstraint::SDTypeConstraint(Record *R) {
848 OperandNo = R->getValueAsInt("OperandNum");
850 if (R->isSubClassOf("SDTCisVT")) {
851 ConstraintType = SDTCisVT;
852 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
853 if (x.SDTCisVT_Info.VT == MVT::isVoid)
854 PrintFatalError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
856 } else if (R->isSubClassOf("SDTCisPtrTy")) {
857 ConstraintType = SDTCisPtrTy;
858 } else if (R->isSubClassOf("SDTCisInt")) {
859 ConstraintType = SDTCisInt;
860 } else if (R->isSubClassOf("SDTCisFP")) {
861 ConstraintType = SDTCisFP;
862 } else if (R->isSubClassOf("SDTCisVec")) {
863 ConstraintType = SDTCisVec;
864 } else if (R->isSubClassOf("SDTCisSameAs")) {
865 ConstraintType = SDTCisSameAs;
866 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
867 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
868 ConstraintType = SDTCisVTSmallerThanOp;
869 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
870 R->getValueAsInt("OtherOperandNum");
871 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
872 ConstraintType = SDTCisOpSmallerThanOp;
873 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
874 R->getValueAsInt("BigOperandNum");
875 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
876 ConstraintType = SDTCisEltOfVec;
877 x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
878 } else if (R->isSubClassOf("SDTCisSubVecOfVec")) {
879 ConstraintType = SDTCisSubVecOfVec;
880 x.SDTCisSubVecOfVec_Info.OtherOperandNum =
881 R->getValueAsInt("OtherOpNum");
882 } else if (R->isSubClassOf("SDTCVecEltisVT")) {
883 ConstraintType = SDTCVecEltisVT;
884 x.SDTCVecEltisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
885 if (MVT(x.SDTCVecEltisVT_Info.VT).isVector())
886 PrintFatalError(R->getLoc(), "Cannot use vector type as SDTCVecEltisVT");
887 if (!MVT(x.SDTCVecEltisVT_Info.VT).isInteger() &&
888 !MVT(x.SDTCVecEltisVT_Info.VT).isFloatingPoint())
889 PrintFatalError(R->getLoc(), "Must use integer or floating point type "
890 "as SDTCVecEltisVT");
891 } else if (R->isSubClassOf("SDTCisSameNumEltsAs")) {
892 ConstraintType = SDTCisSameNumEltsAs;
893 x.SDTCisSameNumEltsAs_Info.OtherOperandNum =
894 R->getValueAsInt("OtherOperandNum");
896 PrintFatalError("Unrecognized SDTypeConstraint '" + R->getName() + "'!\n");
900 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
901 /// N, and the result number in ResNo.
902 static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
903 const SDNodeInfo &NodeInfo,
905 unsigned NumResults = NodeInfo.getNumResults();
906 if (OpNo < NumResults) {
913 if (OpNo >= N->getNumChildren()) {
915 raw_string_ostream OS(S);
916 OS << "Invalid operand number in type constraint "
917 << (OpNo+NumResults) << " ";
919 PrintFatalError(OS.str());
922 return N->getChild(OpNo);
925 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
926 /// constraint to the nodes operands. This returns true if it makes a
927 /// change, false otherwise. If a type contradiction is found, flag an error.
928 bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
929 const SDNodeInfo &NodeInfo,
930 TreePattern &TP) const {
934 unsigned ResNo = 0; // The result number being referenced.
935 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
937 switch (ConstraintType) {
939 // Operand must be a particular type.
940 return NodeToApply->UpdateNodeType(ResNo, x.SDTCisVT_Info.VT, TP);
942 // Operand must be same as target pointer type.
943 return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
945 // Require it to be one of the legal integer VTs.
946 return NodeToApply->getExtType(ResNo).EnforceInteger(TP);
948 // Require it to be one of the legal fp VTs.
949 return NodeToApply->getExtType(ResNo).EnforceFloatingPoint(TP);
951 // Require it to be one of the legal vector VTs.
952 return NodeToApply->getExtType(ResNo).EnforceVector(TP);
955 TreePatternNode *OtherNode =
956 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
957 return NodeToApply->UpdateNodeType(ResNo, OtherNode->getExtType(OResNo),TP)|
958 OtherNode->UpdateNodeType(OResNo,NodeToApply->getExtType(ResNo),TP);
960 case SDTCisVTSmallerThanOp: {
961 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
962 // have an integer type that is smaller than the VT.
963 if (!NodeToApply->isLeaf() ||
964 !isa<DefInit>(NodeToApply->getLeafValue()) ||
965 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
966 ->isSubClassOf("ValueType")) {
967 TP.error(N->getOperator()->getName() + " expects a VT operand!");
970 MVT::SimpleValueType VT =
971 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
973 EEVT::TypeSet TypeListTmp(VT, TP);
976 TreePatternNode *OtherNode =
977 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
980 return TypeListTmp.EnforceSmallerThan(OtherNode->getExtType(OResNo), TP);
982 case SDTCisOpSmallerThanOp: {
984 TreePatternNode *BigOperand =
985 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
987 return NodeToApply->getExtType(ResNo).
988 EnforceSmallerThan(BigOperand->getExtType(BResNo), TP);
990 case SDTCisEltOfVec: {
992 TreePatternNode *VecOperand =
993 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
996 // Filter vector types out of VecOperand that don't have the right element
998 return VecOperand->getExtType(VResNo).
999 EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), TP);
1001 case SDTCisSubVecOfVec: {
1002 unsigned VResNo = 0;
1003 TreePatternNode *BigVecOperand =
1004 getOperandNum(x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo,
1007 // Filter vector types out of BigVecOperand that don't have the
1008 // right subvector type.
1009 return BigVecOperand->getExtType(VResNo).
1010 EnforceVectorSubVectorTypeIs(NodeToApply->getExtType(ResNo), TP);
1012 case SDTCVecEltisVT: {
1013 return NodeToApply->getExtType(ResNo).
1014 EnforceVectorEltTypeIs(x.SDTCVecEltisVT_Info.VT, TP);
1016 case SDTCisSameNumEltsAs: {
1017 unsigned OResNo = 0;
1018 TreePatternNode *OtherNode =
1019 getOperandNum(x.SDTCisSameNumEltsAs_Info.OtherOperandNum,
1020 N, NodeInfo, OResNo);
1021 return OtherNode->getExtType(OResNo).
1022 EnforceVectorSameNumElts(NodeToApply->getExtType(ResNo), TP);
1025 llvm_unreachable("Invalid ConstraintType!");
1028 // Update the node type to match an instruction operand or result as specified
1029 // in the ins or outs lists on the instruction definition. Return true if the
1030 // type was actually changed.
1031 bool TreePatternNode::UpdateNodeTypeFromInst(unsigned ResNo,
1034 // The 'unknown' operand indicates that types should be inferred from the
1036 if (Operand->isSubClassOf("unknown_class"))
1039 // The Operand class specifies a type directly.
1040 if (Operand->isSubClassOf("Operand"))
1041 return UpdateNodeType(ResNo, getValueType(Operand->getValueAsDef("Type")),
1044 // PointerLikeRegClass has a type that is determined at runtime.
1045 if (Operand->isSubClassOf("PointerLikeRegClass"))
1046 return UpdateNodeType(ResNo, MVT::iPTR, TP);
1048 // Both RegisterClass and RegisterOperand operands derive their types from a
1049 // register class def.
1050 Record *RC = nullptr;
1051 if (Operand->isSubClassOf("RegisterClass"))
1053 else if (Operand->isSubClassOf("RegisterOperand"))
1054 RC = Operand->getValueAsDef("RegClass");
1056 assert(RC && "Unknown operand type");
1057 CodeGenTarget &Tgt = TP.getDAGPatterns().getTargetInfo();
1058 return UpdateNodeType(ResNo, Tgt.getRegisterClass(RC).getValueTypes(), TP);
1062 //===----------------------------------------------------------------------===//
1063 // SDNodeInfo implementation
1065 SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
1066 EnumName = R->getValueAsString("Opcode");
1067 SDClassName = R->getValueAsString("SDClass");
1068 Record *TypeProfile = R->getValueAsDef("TypeProfile");
1069 NumResults = TypeProfile->getValueAsInt("NumResults");
1070 NumOperands = TypeProfile->getValueAsInt("NumOperands");
1072 // Parse the properties.
1074 for (Record *Property : R->getValueAsListOfDefs("Properties")) {
1075 if (Property->getName() == "SDNPCommutative") {
1076 Properties |= 1 << SDNPCommutative;
1077 } else if (Property->getName() == "SDNPAssociative") {
1078 Properties |= 1 << SDNPAssociative;
1079 } else if (Property->getName() == "SDNPHasChain") {
1080 Properties |= 1 << SDNPHasChain;
1081 } else if (Property->getName() == "SDNPOutGlue") {
1082 Properties |= 1 << SDNPOutGlue;
1083 } else if (Property->getName() == "SDNPInGlue") {
1084 Properties |= 1 << SDNPInGlue;
1085 } else if (Property->getName() == "SDNPOptInGlue") {
1086 Properties |= 1 << SDNPOptInGlue;
1087 } else if (Property->getName() == "SDNPMayStore") {
1088 Properties |= 1 << SDNPMayStore;
1089 } else if (Property->getName() == "SDNPMayLoad") {
1090 Properties |= 1 << SDNPMayLoad;
1091 } else if (Property->getName() == "SDNPSideEffect") {
1092 Properties |= 1 << SDNPSideEffect;
1093 } else if (Property->getName() == "SDNPMemOperand") {
1094 Properties |= 1 << SDNPMemOperand;
1095 } else if (Property->getName() == "SDNPVariadic") {
1096 Properties |= 1 << SDNPVariadic;
1098 PrintFatalError("Unknown SD Node property '" +
1099 Property->getName() + "' on node '" +
1100 R->getName() + "'!");
1105 // Parse the type constraints.
1106 std::vector<Record*> ConstraintList =
1107 TypeProfile->getValueAsListOfDefs("Constraints");
1108 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
1111 /// getKnownType - If the type constraints on this node imply a fixed type
1112 /// (e.g. all stores return void, etc), then return it as an
1113 /// MVT::SimpleValueType. Otherwise, return EEVT::Other.
1114 MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
1115 unsigned NumResults = getNumResults();
1116 assert(NumResults <= 1 &&
1117 "We only work with nodes with zero or one result so far!");
1118 assert(ResNo == 0 && "Only handles single result nodes so far");
1120 for (const SDTypeConstraint &Constraint : TypeConstraints) {
1121 // Make sure that this applies to the correct node result.
1122 if (Constraint.OperandNo >= NumResults) // FIXME: need value #
1125 switch (Constraint.ConstraintType) {
1127 case SDTypeConstraint::SDTCisVT:
1128 return Constraint.x.SDTCisVT_Info.VT;
1129 case SDTypeConstraint::SDTCisPtrTy:
1136 //===----------------------------------------------------------------------===//
1137 // TreePatternNode implementation
1140 TreePatternNode::~TreePatternNode() {
1141 #if 0 // FIXME: implement refcounted tree nodes!
1142 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1147 static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
1148 if (Operator->getName() == "set" ||
1149 Operator->getName() == "implicit")
1150 return 0; // All return nothing.
1152 if (Operator->isSubClassOf("Intrinsic"))
1153 return CDP.getIntrinsic(Operator).IS.RetVTs.size();
1155 if (Operator->isSubClassOf("SDNode"))
1156 return CDP.getSDNodeInfo(Operator).getNumResults();
1158 if (Operator->isSubClassOf("PatFrag")) {
1159 // If we've already parsed this pattern fragment, get it. Otherwise, handle
1160 // the forward reference case where one pattern fragment references another
1161 // before it is processed.
1162 if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator))
1163 return PFRec->getOnlyTree()->getNumTypes();
1165 // Get the result tree.
1166 DagInit *Tree = Operator->getValueAsDag("Fragment");
1167 Record *Op = nullptr;
1169 if (DefInit *DI = dyn_cast<DefInit>(Tree->getOperator()))
1171 assert(Op && "Invalid Fragment");
1172 return GetNumNodeResults(Op, CDP);
1175 if (Operator->isSubClassOf("Instruction")) {
1176 CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
1178 unsigned NumDefsToAdd = InstInfo.Operands.NumDefs;
1180 // Subtract any defaulted outputs.
1181 for (unsigned i = 0; i != InstInfo.Operands.NumDefs; ++i) {
1182 Record *OperandNode = InstInfo.Operands[i].Rec;
1184 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
1185 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1189 // Add on one implicit def if it has a resolvable type.
1190 if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
1192 return NumDefsToAdd;
1195 if (Operator->isSubClassOf("SDNodeXForm"))
1196 return 1; // FIXME: Generalize SDNodeXForm
1198 if (Operator->isSubClassOf("ValueType"))
1199 return 1; // A type-cast of one result.
1201 if (Operator->isSubClassOf("ComplexPattern"))
1205 PrintFatalError("Unhandled node in GetNumNodeResults");
1208 void TreePatternNode::print(raw_ostream &OS) const {
1210 OS << *getLeafValue();
1212 OS << '(' << getOperator()->getName();
1214 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1215 OS << ':' << getExtType(i).getName();
1218 if (getNumChildren() != 0) {
1220 getChild(0)->print(OS);
1221 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
1223 getChild(i)->print(OS);
1229 for (const TreePredicateFn &Pred : PredicateFns)
1230 OS << "<<P:" << Pred.getFnName() << ">>";
1232 OS << "<<X:" << TransformFn->getName() << ">>";
1233 if (!getName().empty())
1234 OS << ":$" << getName();
1237 void TreePatternNode::dump() const {
1241 /// isIsomorphicTo - Return true if this node is recursively
1242 /// isomorphic to the specified node. For this comparison, the node's
1243 /// entire state is considered. The assigned name is ignored, since
1244 /// nodes with differing names are considered isomorphic. However, if
1245 /// the assigned name is present in the dependent variable set, then
1246 /// the assigned name is considered significant and the node is
1247 /// isomorphic if the names match.
1248 bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
1249 const MultipleUseVarSet &DepVars) const {
1250 if (N == this) return true;
1251 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
1252 getPredicateFns() != N->getPredicateFns() ||
1253 getTransformFn() != N->getTransformFn())
1257 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
1258 if (DefInit *NDI = dyn_cast<DefInit>(N->getLeafValue())) {
1259 return ((DI->getDef() == NDI->getDef())
1260 && (DepVars.find(getName()) == DepVars.end()
1261 || getName() == N->getName()));
1264 return getLeafValue() == N->getLeafValue();
1267 if (N->getOperator() != getOperator() ||
1268 N->getNumChildren() != getNumChildren()) return false;
1269 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1270 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
1275 /// clone - Make a copy of this tree and all of its children.
1277 TreePatternNode *TreePatternNode::clone() const {
1278 TreePatternNode *New;
1280 New = new TreePatternNode(getLeafValue(), getNumTypes());
1282 std::vector<TreePatternNode*> CChildren;
1283 CChildren.reserve(Children.size());
1284 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1285 CChildren.push_back(getChild(i)->clone());
1286 New = new TreePatternNode(getOperator(), CChildren, getNumTypes());
1288 New->setName(getName());
1290 New->setPredicateFns(getPredicateFns());
1291 New->setTransformFn(getTransformFn());
1295 /// RemoveAllTypes - Recursively strip all the types of this tree.
1296 void TreePatternNode::RemoveAllTypes() {
1297 // Reset to unknown type.
1298 std::fill(Types.begin(), Types.end(), EEVT::TypeSet());
1299 if (isLeaf()) return;
1300 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1301 getChild(i)->RemoveAllTypes();
1305 /// SubstituteFormalArguments - Replace the formal arguments in this tree
1306 /// with actual values specified by ArgMap.
1307 void TreePatternNode::
1308 SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
1309 if (isLeaf()) return;
1311 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1312 TreePatternNode *Child = getChild(i);
1313 if (Child->isLeaf()) {
1314 Init *Val = Child->getLeafValue();
1315 // Note that, when substituting into an output pattern, Val might be an
1317 if (isa<UnsetInit>(Val) || (isa<DefInit>(Val) &&
1318 cast<DefInit>(Val)->getDef()->getName() == "node")) {
1319 // We found a use of a formal argument, replace it with its value.
1320 TreePatternNode *NewChild = ArgMap[Child->getName()];
1321 assert(NewChild && "Couldn't find formal argument!");
1322 assert((Child->getPredicateFns().empty() ||
1323 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1324 "Non-empty child predicate clobbered!");
1325 setChild(i, NewChild);
1328 getChild(i)->SubstituteFormalArguments(ArgMap);
1334 /// InlinePatternFragments - If this pattern refers to any pattern
1335 /// fragments, inline them into place, giving us a pattern without any
1336 /// PatFrag references.
1337 TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
1342 return this; // nothing to do.
1343 Record *Op = getOperator();
1345 if (!Op->isSubClassOf("PatFrag")) {
1346 // Just recursively inline children nodes.
1347 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1348 TreePatternNode *Child = getChild(i);
1349 TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
1351 assert((Child->getPredicateFns().empty() ||
1352 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1353 "Non-empty child predicate clobbered!");
1355 setChild(i, NewChild);
1360 // Otherwise, we found a reference to a fragment. First, look up its
1361 // TreePattern record.
1362 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
1364 // Verify that we are passing the right number of operands.
1365 if (Frag->getNumArgs() != Children.size()) {
1366 TP.error("'" + Op->getName() + "' fragment requires " +
1367 utostr(Frag->getNumArgs()) + " operands!");
1371 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
1373 TreePredicateFn PredFn(Frag);
1374 if (!PredFn.isAlwaysTrue())
1375 FragTree->addPredicateFn(PredFn);
1377 // Resolve formal arguments to their actual value.
1378 if (Frag->getNumArgs()) {
1379 // Compute the map of formal to actual arguments.
1380 std::map<std::string, TreePatternNode*> ArgMap;
1381 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
1382 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
1384 FragTree->SubstituteFormalArguments(ArgMap);
1387 FragTree->setName(getName());
1388 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1389 FragTree->UpdateNodeType(i, getExtType(i), TP);
1391 // Transfer in the old predicates.
1392 for (const TreePredicateFn &Pred : getPredicateFns())
1393 FragTree->addPredicateFn(Pred);
1395 // Get a new copy of this fragment to stitch into here.
1396 //delete this; // FIXME: implement refcounting!
1398 // The fragment we inlined could have recursive inlining that is needed. See
1399 // if there are any pattern fragments in it and inline them as needed.
1400 return FragTree->InlinePatternFragments(TP);
1403 /// getImplicitType - Check to see if the specified record has an implicit
1404 /// type which should be applied to it. This will infer the type of register
1405 /// references from the register file information, for example.
1407 /// When Unnamed is set, return the type of a DAG operand with no name, such as
1408 /// the F8RC register class argument in:
1410 /// (COPY_TO_REGCLASS GPR:$src, F8RC)
1412 /// When Unnamed is false, return the type of a named DAG operand such as the
1413 /// GPR:$src operand above.
1415 static EEVT::TypeSet getImplicitType(Record *R, unsigned ResNo,
1419 // Check to see if this is a register operand.
1420 if (R->isSubClassOf("RegisterOperand")) {
1421 assert(ResNo == 0 && "Regoperand ref only has one result!");
1423 return EEVT::TypeSet(); // Unknown.
1424 Record *RegClass = R->getValueAsDef("RegClass");
1425 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1426 return EEVT::TypeSet(T.getRegisterClass(RegClass).getValueTypes());
1429 // Check to see if this is a register or a register class.
1430 if (R->isSubClassOf("RegisterClass")) {
1431 assert(ResNo == 0 && "Regclass ref only has one result!");
1432 // An unnamed register class represents itself as an i32 immediate, for
1433 // example on a COPY_TO_REGCLASS instruction.
1435 return EEVT::TypeSet(MVT::i32, TP);
1437 // In a named operand, the register class provides the possible set of
1440 return EEVT::TypeSet(); // Unknown.
1441 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1442 return EEVT::TypeSet(T.getRegisterClass(R).getValueTypes());
1445 if (R->isSubClassOf("PatFrag")) {
1446 assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
1447 // Pattern fragment types will be resolved when they are inlined.
1448 return EEVT::TypeSet(); // Unknown.
1451 if (R->isSubClassOf("Register")) {
1452 assert(ResNo == 0 && "Registers only produce one result!");
1454 return EEVT::TypeSet(); // Unknown.
1455 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1456 return EEVT::TypeSet(T.getRegisterVTs(R));
1459 if (R->isSubClassOf("SubRegIndex")) {
1460 assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
1461 return EEVT::TypeSet(MVT::i32, TP);
1464 if (R->isSubClassOf("ValueType")) {
1465 assert(ResNo == 0 && "This node only has one result!");
1466 // An unnamed VTSDNode represents itself as an MVT::Other immediate.
1468 // (sext_inreg GPR:$src, i16)
1471 return EEVT::TypeSet(MVT::Other, TP);
1472 // With a name, the ValueType simply provides the type of the named
1475 // (sext_inreg i32:$src, i16)
1478 return EEVT::TypeSet(); // Unknown.
1479 return EEVT::TypeSet(getValueType(R), TP);
1482 if (R->isSubClassOf("CondCode")) {
1483 assert(ResNo == 0 && "This node only has one result!");
1484 // Using a CondCodeSDNode.
1485 return EEVT::TypeSet(MVT::Other, TP);
1488 if (R->isSubClassOf("ComplexPattern")) {
1489 assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
1491 return EEVT::TypeSet(); // Unknown.
1492 return EEVT::TypeSet(TP.getDAGPatterns().getComplexPattern(R).getValueType(),
1495 if (R->isSubClassOf("PointerLikeRegClass")) {
1496 assert(ResNo == 0 && "Regclass can only have one result!");
1497 return EEVT::TypeSet(MVT::iPTR, TP);
1500 if (R->getName() == "node" || R->getName() == "srcvalue" ||
1501 R->getName() == "zero_reg") {
1503 return EEVT::TypeSet(); // Unknown.
1506 if (R->isSubClassOf("Operand"))
1507 return EEVT::TypeSet(getValueType(R->getValueAsDef("Type")));
1509 TP.error("Unknown node flavor used in pattern: " + R->getName());
1510 return EEVT::TypeSet(MVT::Other, TP);
1514 /// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
1515 /// CodeGenIntrinsic information for it, otherwise return a null pointer.
1516 const CodeGenIntrinsic *TreePatternNode::
1517 getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
1518 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
1519 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
1520 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
1523 unsigned IID = cast<IntInit>(getChild(0)->getLeafValue())->getValue();
1524 return &CDP.getIntrinsicInfo(IID);
1527 /// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
1528 /// return the ComplexPattern information, otherwise return null.
1529 const ComplexPattern *
1530 TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
1533 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
1538 Rec = getOperator();
1540 if (!Rec->isSubClassOf("ComplexPattern"))
1542 return &CGP.getComplexPattern(Rec);
1545 unsigned TreePatternNode::getNumMIResults(const CodeGenDAGPatterns &CGP) const {
1546 // A ComplexPattern specifically declares how many results it fills in.
1547 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1548 return CP->getNumOperands();
1550 // If MIOperandInfo is specified, that gives the count.
1552 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
1553 if (DI && DI->getDef()->isSubClassOf("Operand")) {
1554 DagInit *MIOps = DI->getDef()->getValueAsDag("MIOperandInfo");
1555 if (MIOps->getNumArgs())
1556 return MIOps->getNumArgs();
1560 // Otherwise there is just one result.
1564 /// NodeHasProperty - Return true if this node has the specified property.
1565 bool TreePatternNode::NodeHasProperty(SDNP Property,
1566 const CodeGenDAGPatterns &CGP) const {
1568 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1569 return CP->hasProperty(Property);
1573 Record *Operator = getOperator();
1574 if (!Operator->isSubClassOf("SDNode")) return false;
1576 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
1582 /// TreeHasProperty - Return true if any node in this tree has the specified
1584 bool TreePatternNode::TreeHasProperty(SDNP Property,
1585 const CodeGenDAGPatterns &CGP) const {
1586 if (NodeHasProperty(Property, CGP))
1588 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1589 if (getChild(i)->TreeHasProperty(Property, CGP))
1594 /// isCommutativeIntrinsic - Return true if the node corresponds to a
1595 /// commutative intrinsic.
1597 TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
1598 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
1599 return Int->isCommutative;
1603 static bool isOperandClass(const TreePatternNode *N, StringRef Class) {
1605 return N->getOperator()->isSubClassOf(Class);
1607 DefInit *DI = dyn_cast<DefInit>(N->getLeafValue());
1608 if (DI && DI->getDef()->isSubClassOf(Class))
1614 static void emitTooManyOperandsError(TreePattern &TP,
1618 TP.error("Instruction '" + InstName + "' was provided " + Twine(Actual) +
1619 " operands but expected only " + Twine(Expected) + "!");
1622 static void emitTooFewOperandsError(TreePattern &TP,
1625 TP.error("Instruction '" + InstName +
1626 "' expects more than the provided " + Twine(Actual) + " operands!");
1629 /// ApplyTypeConstraints - Apply all of the type constraints relevant to
1630 /// this node and its children in the tree. This returns true if it makes a
1631 /// change, false otherwise. If a type contradiction is found, flag an error.
1632 bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
1636 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
1638 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
1639 // If it's a regclass or something else known, include the type.
1640 bool MadeChange = false;
1641 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1642 MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
1644 !hasName(), TP), TP);
1648 if (IntInit *II = dyn_cast<IntInit>(getLeafValue())) {
1649 assert(Types.size() == 1 && "Invalid IntInit");
1651 // Int inits are always integers. :)
1652 bool MadeChange = Types[0].EnforceInteger(TP);
1654 if (!Types[0].isConcrete())
1657 MVT::SimpleValueType VT = getType(0);
1658 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
1661 unsigned Size = MVT(VT).getSizeInBits();
1662 // Make sure that the value is representable for this type.
1663 if (Size >= 32) return MadeChange;
1665 // Check that the value doesn't use more bits than we have. It must either
1666 // be a sign- or zero-extended equivalent of the original.
1667 int64_t SignBitAndAbove = II->getValue() >> (Size - 1);
1668 if (SignBitAndAbove == -1 || SignBitAndAbove == 0 || SignBitAndAbove == 1)
1671 TP.error("Integer value '" + itostr(II->getValue()) +
1672 "' is out of range for type '" + getEnumName(getType(0)) + "'!");
1678 // special handling for set, which isn't really an SDNode.
1679 if (getOperator()->getName() == "set") {
1680 assert(getNumTypes() == 0 && "Set doesn't produce a value");
1681 assert(getNumChildren() >= 2 && "Missing RHS of a set?");
1682 unsigned NC = getNumChildren();
1684 TreePatternNode *SetVal = getChild(NC-1);
1685 bool MadeChange = SetVal->ApplyTypeConstraints(TP, NotRegisters);
1687 for (unsigned i = 0; i < NC-1; ++i) {
1688 TreePatternNode *Child = getChild(i);
1689 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
1691 // Types of operands must match.
1692 MadeChange |= Child->UpdateNodeType(0, SetVal->getExtType(i), TP);
1693 MadeChange |= SetVal->UpdateNodeType(i, Child->getExtType(0), TP);
1698 if (getOperator()->getName() == "implicit") {
1699 assert(getNumTypes() == 0 && "Node doesn't produce a value");
1701 bool MadeChange = false;
1702 for (unsigned i = 0; i < getNumChildren(); ++i)
1703 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1707 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
1708 bool MadeChange = false;
1710 // Apply the result type to the node.
1711 unsigned NumRetVTs = Int->IS.RetVTs.size();
1712 unsigned NumParamVTs = Int->IS.ParamVTs.size();
1714 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
1715 MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
1717 if (getNumChildren() != NumParamVTs + 1) {
1718 TP.error("Intrinsic '" + Int->Name + "' expects " +
1719 utostr(NumParamVTs) + " operands, not " +
1720 utostr(getNumChildren() - 1) + " operands!");
1724 // Apply type info to the intrinsic ID.
1725 MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
1727 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
1728 MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
1730 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
1731 assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
1732 MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
1737 if (getOperator()->isSubClassOf("SDNode")) {
1738 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
1740 // Check that the number of operands is sane. Negative operands -> varargs.
1741 if (NI.getNumOperands() >= 0 &&
1742 getNumChildren() != (unsigned)NI.getNumOperands()) {
1743 TP.error(getOperator()->getName() + " node requires exactly " +
1744 itostr(NI.getNumOperands()) + " operands!");
1748 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
1749 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1750 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1754 if (getOperator()->isSubClassOf("Instruction")) {
1755 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
1756 CodeGenInstruction &InstInfo =
1757 CDP.getTargetInfo().getInstruction(getOperator());
1759 bool MadeChange = false;
1761 // Apply the result types to the node, these come from the things in the
1762 // (outs) list of the instruction.
1763 unsigned NumResultsToAdd = std::min(InstInfo.Operands.NumDefs,
1764 Inst.getNumResults());
1765 for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo)
1766 MadeChange |= UpdateNodeTypeFromInst(ResNo, Inst.getResult(ResNo), TP);
1768 // If the instruction has implicit defs, we apply the first one as a result.
1769 // FIXME: This sucks, it should apply all implicit defs.
1770 if (!InstInfo.ImplicitDefs.empty()) {
1771 unsigned ResNo = NumResultsToAdd;
1773 // FIXME: Generalize to multiple possible types and multiple possible
1775 MVT::SimpleValueType VT =
1776 InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
1778 if (VT != MVT::Other)
1779 MadeChange |= UpdateNodeType(ResNo, VT, TP);
1782 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
1784 if (getOperator()->getName() == "INSERT_SUBREG") {
1785 assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
1786 MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
1787 MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
1788 } else if (getOperator()->getName() == "REG_SEQUENCE") {
1789 // We need to do extra, custom typechecking for REG_SEQUENCE since it is
1792 unsigned NChild = getNumChildren();
1794 TP.error("REG_SEQUENCE requires at least 3 operands!");
1798 if (NChild % 2 == 0) {
1799 TP.error("REG_SEQUENCE requires an odd number of operands!");
1803 if (!isOperandClass(getChild(0), "RegisterClass")) {
1804 TP.error("REG_SEQUENCE requires a RegisterClass for first operand!");
1808 for (unsigned I = 1; I < NChild; I += 2) {
1809 TreePatternNode *SubIdxChild = getChild(I + 1);
1810 if (!isOperandClass(SubIdxChild, "SubRegIndex")) {
1811 TP.error("REG_SEQUENCE requires a SubRegIndex for operand " +
1812 itostr(I + 1) + "!");
1818 unsigned ChildNo = 0;
1819 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
1820 Record *OperandNode = Inst.getOperand(i);
1822 // If the instruction expects a predicate or optional def operand, we
1823 // codegen this by setting the operand to it's default value if it has a
1824 // non-empty DefaultOps field.
1825 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
1826 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1829 // Verify that we didn't run out of provided operands.
1830 if (ChildNo >= getNumChildren()) {
1831 emitTooFewOperandsError(TP, getOperator()->getName(), getNumChildren());
1835 TreePatternNode *Child = getChild(ChildNo++);
1836 unsigned ChildResNo = 0; // Instructions always use res #0 of their op.
1838 // If the operand has sub-operands, they may be provided by distinct
1839 // child patterns, so attempt to match each sub-operand separately.
1840 if (OperandNode->isSubClassOf("Operand")) {
1841 DagInit *MIOpInfo = OperandNode->getValueAsDag("MIOperandInfo");
1842 if (unsigned NumArgs = MIOpInfo->getNumArgs()) {
1843 // But don't do that if the whole operand is being provided by
1844 // a single ComplexPattern-related Operand.
1846 if (Child->getNumMIResults(CDP) < NumArgs) {
1847 // Match first sub-operand against the child we already have.
1848 Record *SubRec = cast<DefInit>(MIOpInfo->getArg(0))->getDef();
1850 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
1852 // And the remaining sub-operands against subsequent children.
1853 for (unsigned Arg = 1; Arg < NumArgs; ++Arg) {
1854 if (ChildNo >= getNumChildren()) {
1855 emitTooFewOperandsError(TP, getOperator()->getName(),
1859 Child = getChild(ChildNo++);
1861 SubRec = cast<DefInit>(MIOpInfo->getArg(Arg))->getDef();
1863 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
1870 // If we didn't match by pieces above, attempt to match the whole
1872 MadeChange |= Child->UpdateNodeTypeFromInst(ChildResNo, OperandNode, TP);
1875 if (!InstInfo.Operands.isVariadic && ChildNo != getNumChildren()) {
1876 emitTooManyOperandsError(TP, getOperator()->getName(),
1877 ChildNo, getNumChildren());
1881 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1882 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1886 if (getOperator()->isSubClassOf("ComplexPattern")) {
1887 bool MadeChange = false;
1889 for (unsigned i = 0; i < getNumChildren(); ++i)
1890 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1895 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
1897 // Node transforms always take one operand.
1898 if (getNumChildren() != 1) {
1899 TP.error("Node transform '" + getOperator()->getName() +
1900 "' requires one operand!");
1904 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1907 // If either the output or input of the xform does not have exact
1908 // type info. We assume they must be the same. Otherwise, it is perfectly
1909 // legal to transform from one type to a completely different type.
1911 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
1912 bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
1913 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
1920 /// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
1921 /// RHS of a commutative operation, not the on LHS.
1922 static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
1923 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
1925 if (N->isLeaf() && isa<IntInit>(N->getLeafValue()))
1931 /// canPatternMatch - If it is impossible for this pattern to match on this
1932 /// target, fill in Reason and return false. Otherwise, return true. This is
1933 /// used as a sanity check for .td files (to prevent people from writing stuff
1934 /// that can never possibly work), and to prevent the pattern permuter from
1935 /// generating stuff that is useless.
1936 bool TreePatternNode::canPatternMatch(std::string &Reason,
1937 const CodeGenDAGPatterns &CDP) {
1938 if (isLeaf()) return true;
1940 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1941 if (!getChild(i)->canPatternMatch(Reason, CDP))
1944 // If this is an intrinsic, handle cases that would make it not match. For
1945 // example, if an operand is required to be an immediate.
1946 if (getOperator()->isSubClassOf("Intrinsic")) {
1951 if (getOperator()->isSubClassOf("ComplexPattern"))
1954 // If this node is a commutative operator, check that the LHS isn't an
1956 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
1957 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
1958 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
1959 // Scan all of the operands of the node and make sure that only the last one
1960 // is a constant node, unless the RHS also is.
1961 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
1962 bool Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
1963 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
1964 if (OnlyOnRHSOfCommutative(getChild(i))) {
1965 Reason="Immediate value must be on the RHS of commutative operators!";
1974 //===----------------------------------------------------------------------===//
1975 // TreePattern implementation
1978 TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
1979 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
1980 isInputPattern(isInput), HasError(false) {
1981 for (Init *I : RawPat->getValues())
1982 Trees.push_back(ParseTreePattern(I, ""));
1985 TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
1986 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
1987 isInputPattern(isInput), HasError(false) {
1988 Trees.push_back(ParseTreePattern(Pat, ""));
1991 TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
1992 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
1993 isInputPattern(isInput), HasError(false) {
1994 Trees.push_back(Pat);
1997 void TreePattern::error(const Twine &Msg) {
2001 PrintError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
2005 void TreePattern::ComputeNamedNodes() {
2006 for (TreePatternNode *Tree : Trees)
2007 ComputeNamedNodes(Tree);
2010 void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
2011 if (!N->getName().empty())
2012 NamedNodes[N->getName()].push_back(N);
2014 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2015 ComputeNamedNodes(N->getChild(i));
2019 TreePatternNode *TreePattern::ParseTreePattern(Init *TheInit, StringRef OpName){
2020 if (DefInit *DI = dyn_cast<DefInit>(TheInit)) {
2021 Record *R = DI->getDef();
2023 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
2024 // TreePatternNode of its own. For example:
2025 /// (foo GPR, imm) -> (foo GPR, (imm))
2026 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag"))
2027 return ParseTreePattern(
2028 DagInit::get(DI, "",
2029 std::vector<std::pair<Init*, std::string> >()),
2033 TreePatternNode *Res = new TreePatternNode(DI, 1);
2034 if (R->getName() == "node" && !OpName.empty()) {
2036 error("'node' argument requires a name to match with operand list");
2037 Args.push_back(OpName);
2040 Res->setName(OpName);
2044 // ?:$name or just $name.
2045 if (isa<UnsetInit>(TheInit)) {
2047 error("'?' argument requires a name to match with operand list");
2048 TreePatternNode *Res = new TreePatternNode(TheInit, 1);
2049 Args.push_back(OpName);
2050 Res->setName(OpName);
2054 if (IntInit *II = dyn_cast<IntInit>(TheInit)) {
2055 if (!OpName.empty())
2056 error("Constant int argument should not have a name!");
2057 return new TreePatternNode(II, 1);
2060 if (BitsInit *BI = dyn_cast<BitsInit>(TheInit)) {
2061 // Turn this into an IntInit.
2062 Init *II = BI->convertInitializerTo(IntRecTy::get());
2063 if (!II || !isa<IntInit>(II))
2064 error("Bits value must be constants!");
2065 return ParseTreePattern(II, OpName);
2068 DagInit *Dag = dyn_cast<DagInit>(TheInit);
2071 error("Pattern has unexpected init kind!");
2073 DefInit *OpDef = dyn_cast<DefInit>(Dag->getOperator());
2074 if (!OpDef) error("Pattern has unexpected operator type!");
2075 Record *Operator = OpDef->getDef();
2077 if (Operator->isSubClassOf("ValueType")) {
2078 // If the operator is a ValueType, then this must be "type cast" of a leaf
2080 if (Dag->getNumArgs() != 1)
2081 error("Type cast only takes one operand!");
2083 TreePatternNode *New = ParseTreePattern(Dag->getArg(0), Dag->getArgName(0));
2085 // Apply the type cast.
2086 assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
2087 New->UpdateNodeType(0, getValueType(Operator), *this);
2089 if (!OpName.empty())
2090 error("ValueType cast should not have a name!");
2094 // Verify that this is something that makes sense for an operator.
2095 if (!Operator->isSubClassOf("PatFrag") &&
2096 !Operator->isSubClassOf("SDNode") &&
2097 !Operator->isSubClassOf("Instruction") &&
2098 !Operator->isSubClassOf("SDNodeXForm") &&
2099 !Operator->isSubClassOf("Intrinsic") &&
2100 !Operator->isSubClassOf("ComplexPattern") &&
2101 Operator->getName() != "set" &&
2102 Operator->getName() != "implicit")
2103 error("Unrecognized node '" + Operator->getName() + "'!");
2105 // Check to see if this is something that is illegal in an input pattern.
2106 if (isInputPattern) {
2107 if (Operator->isSubClassOf("Instruction") ||
2108 Operator->isSubClassOf("SDNodeXForm"))
2109 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
2111 if (Operator->isSubClassOf("Intrinsic"))
2112 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
2114 if (Operator->isSubClassOf("SDNode") &&
2115 Operator->getName() != "imm" &&
2116 Operator->getName() != "fpimm" &&
2117 Operator->getName() != "tglobaltlsaddr" &&
2118 Operator->getName() != "tconstpool" &&
2119 Operator->getName() != "tjumptable" &&
2120 Operator->getName() != "tframeindex" &&
2121 Operator->getName() != "texternalsym" &&
2122 Operator->getName() != "tblockaddress" &&
2123 Operator->getName() != "tglobaladdr" &&
2124 Operator->getName() != "bb" &&
2125 Operator->getName() != "vt" &&
2126 Operator->getName() != "mcsym")
2127 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
2130 std::vector<TreePatternNode*> Children;
2132 // Parse all the operands.
2133 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
2134 Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgName(i)));
2136 // If the operator is an intrinsic, then this is just syntactic sugar for for
2137 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
2138 // convert the intrinsic name to a number.
2139 if (Operator->isSubClassOf("Intrinsic")) {
2140 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
2141 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
2143 // If this intrinsic returns void, it must have side-effects and thus a
2145 if (Int.IS.RetVTs.empty())
2146 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
2147 else if (Int.ModRef != CodeGenIntrinsic::NoMem)
2148 // Has side-effects, requires chain.
2149 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
2150 else // Otherwise, no chain.
2151 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
2153 TreePatternNode *IIDNode = new TreePatternNode(IntInit::get(IID), 1);
2154 Children.insert(Children.begin(), IIDNode);
2157 if (Operator->isSubClassOf("ComplexPattern")) {
2158 for (unsigned i = 0; i < Children.size(); ++i) {
2159 TreePatternNode *Child = Children[i];
2161 if (Child->getName().empty())
2162 error("All arguments to a ComplexPattern must be named");
2164 // Check that the ComplexPattern uses are consistent: "(MY_PAT $a, $b)"
2165 // and "(MY_PAT $b, $a)" should not be allowed in the same pattern;
2166 // neither should "(MY_PAT_1 $a, $b)" and "(MY_PAT_2 $a, $b)".
2167 auto OperandId = std::make_pair(Operator, i);
2168 auto PrevOp = ComplexPatternOperands.find(Child->getName());
2169 if (PrevOp != ComplexPatternOperands.end()) {
2170 if (PrevOp->getValue() != OperandId)
2171 error("All ComplexPattern operands must appear consistently: "
2172 "in the same order in just one ComplexPattern instance.");
2174 ComplexPatternOperands[Child->getName()] = OperandId;
2178 unsigned NumResults = GetNumNodeResults(Operator, CDP);
2179 TreePatternNode *Result = new TreePatternNode(Operator, Children, NumResults);
2180 Result->setName(OpName);
2182 if (!Dag->getName().empty()) {
2183 assert(Result->getName().empty());
2184 Result->setName(Dag->getName());
2189 /// SimplifyTree - See if we can simplify this tree to eliminate something that
2190 /// will never match in favor of something obvious that will. This is here
2191 /// strictly as a convenience to target authors because it allows them to write
2192 /// more type generic things and have useless type casts fold away.
2194 /// This returns true if any change is made.
2195 static bool SimplifyTree(TreePatternNode *&N) {
2199 // If we have a bitconvert with a resolved type and if the source and
2200 // destination types are the same, then the bitconvert is useless, remove it.
2201 if (N->getOperator()->getName() == "bitconvert" &&
2202 N->getExtType(0).isConcrete() &&
2203 N->getExtType(0) == N->getChild(0)->getExtType(0) &&
2204 N->getName().empty()) {
2210 // Walk all children.
2211 bool MadeChange = false;
2212 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2213 TreePatternNode *Child = N->getChild(i);
2214 MadeChange |= SimplifyTree(Child);
2215 N->setChild(i, Child);
2222 /// InferAllTypes - Infer/propagate as many types throughout the expression
2223 /// patterns as possible. Return true if all types are inferred, false
2224 /// otherwise. Flags an error if a type contradiction is found.
2226 InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
2227 if (NamedNodes.empty())
2228 ComputeNamedNodes();
2230 bool MadeChange = true;
2231 while (MadeChange) {
2233 for (TreePatternNode *Tree : Trees) {
2234 MadeChange |= Tree->ApplyTypeConstraints(*this, false);
2235 MadeChange |= SimplifyTree(Tree);
2238 // If there are constraints on our named nodes, apply them.
2239 for (auto &Entry : NamedNodes) {
2240 SmallVectorImpl<TreePatternNode*> &Nodes = Entry.second;
2242 // If we have input named node types, propagate their types to the named
2245 if (!InNamedTypes->count(Entry.getKey())) {
2246 error("Node '" + std::string(Entry.getKey()) +
2247 "' in output pattern but not input pattern");
2251 const SmallVectorImpl<TreePatternNode*> &InNodes =
2252 InNamedTypes->find(Entry.getKey())->second;
2254 // The input types should be fully resolved by now.
2255 for (TreePatternNode *Node : Nodes) {
2256 // If this node is a register class, and it is the root of the pattern
2257 // then we're mapping something onto an input register. We allow
2258 // changing the type of the input register in this case. This allows
2259 // us to match things like:
2260 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
2261 if (Node == Trees[0] && Node->isLeaf()) {
2262 DefInit *DI = dyn_cast<DefInit>(Node->getLeafValue());
2263 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2264 DI->getDef()->isSubClassOf("RegisterOperand")))
2268 assert(Node->getNumTypes() == 1 &&
2269 InNodes[0]->getNumTypes() == 1 &&
2270 "FIXME: cannot name multiple result nodes yet");
2271 MadeChange |= Node->UpdateNodeType(0, InNodes[0]->getExtType(0),
2276 // If there are multiple nodes with the same name, they must all have the
2278 if (Entry.second.size() > 1) {
2279 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
2280 TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
2281 assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
2282 "FIXME: cannot name multiple result nodes yet");
2284 MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
2285 MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
2291 bool HasUnresolvedTypes = false;
2292 for (const TreePatternNode *Tree : Trees)
2293 HasUnresolvedTypes |= Tree->ContainsUnresolvedType();
2294 return !HasUnresolvedTypes;
2297 void TreePattern::print(raw_ostream &OS) const {
2298 OS << getRecord()->getName();
2299 if (!Args.empty()) {
2300 OS << "(" << Args[0];
2301 for (unsigned i = 1, e = Args.size(); i != e; ++i)
2302 OS << ", " << Args[i];
2307 if (Trees.size() > 1)
2309 for (const TreePatternNode *Tree : Trees) {
2315 if (Trees.size() > 1)
2319 void TreePattern::dump() const { print(errs()); }
2321 //===----------------------------------------------------------------------===//
2322 // CodeGenDAGPatterns implementation
2325 CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) :
2326 Records(R), Target(R) {
2328 Intrinsics = LoadIntrinsics(Records, false);
2329 TgtIntrinsics = LoadIntrinsics(Records, true);
2331 ParseNodeTransforms();
2332 ParseComplexPatterns();
2333 ParsePatternFragments();
2334 ParseDefaultOperands();
2335 ParseInstructions();
2336 ParsePatternFragments(/*OutFrags*/true);
2339 // Generate variants. For example, commutative patterns can match
2340 // multiple ways. Add them to PatternsToMatch as well.
2343 // Infer instruction flags. For example, we can detect loads,
2344 // stores, and side effects in many cases by examining an
2345 // instruction's pattern.
2346 InferInstructionFlags();
2348 // Verify that instruction flags match the patterns.
2349 VerifyInstructionFlags();
2352 Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
2353 Record *N = Records.getDef(Name);
2354 if (!N || !N->isSubClassOf("SDNode"))
2355 PrintFatalError("Error getting SDNode '" + Name + "'!");
2360 // Parse all of the SDNode definitions for the target, populating SDNodes.
2361 void CodeGenDAGPatterns::ParseNodeInfo() {
2362 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
2363 while (!Nodes.empty()) {
2364 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
2368 // Get the builtin intrinsic nodes.
2369 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
2370 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
2371 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
2374 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
2375 /// map, and emit them to the file as functions.
2376 void CodeGenDAGPatterns::ParseNodeTransforms() {
2377 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
2378 while (!Xforms.empty()) {
2379 Record *XFormNode = Xforms.back();
2380 Record *SDNode = XFormNode->getValueAsDef("Opcode");
2381 std::string Code = XFormNode->getValueAsString("XFormFunction");
2382 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
2388 void CodeGenDAGPatterns::ParseComplexPatterns() {
2389 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
2390 while (!AMs.empty()) {
2391 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
2397 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
2398 /// file, building up the PatternFragments map. After we've collected them all,
2399 /// inline fragments together as necessary, so that there are no references left
2400 /// inside a pattern fragment to a pattern fragment.
2402 void CodeGenDAGPatterns::ParsePatternFragments(bool OutFrags) {
2403 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
2405 // First step, parse all of the fragments.
2406 for (Record *Frag : Fragments) {
2407 if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
2410 DagInit *Tree = Frag->getValueAsDag("Fragment");
2412 (PatternFragments[Frag] = llvm::make_unique<TreePattern>(
2413 Frag, Tree, !Frag->isSubClassOf("OutPatFrag"),
2416 // Validate the argument list, converting it to set, to discard duplicates.
2417 std::vector<std::string> &Args = P->getArgList();
2418 std::set<std::string> OperandsSet(Args.begin(), Args.end());
2420 if (OperandsSet.count(""))
2421 P->error("Cannot have unnamed 'node' values in pattern fragment!");
2423 // Parse the operands list.
2424 DagInit *OpsList = Frag->getValueAsDag("Operands");
2425 DefInit *OpsOp = dyn_cast<DefInit>(OpsList->getOperator());
2426 // Special cases: ops == outs == ins. Different names are used to
2427 // improve readability.
2429 (OpsOp->getDef()->getName() != "ops" &&
2430 OpsOp->getDef()->getName() != "outs" &&
2431 OpsOp->getDef()->getName() != "ins"))
2432 P->error("Operands list should start with '(ops ... '!");
2434 // Copy over the arguments.
2436 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
2437 if (!isa<DefInit>(OpsList->getArg(j)) ||
2438 cast<DefInit>(OpsList->getArg(j))->getDef()->getName() != "node")
2439 P->error("Operands list should all be 'node' values.");
2440 if (OpsList->getArgName(j).empty())
2441 P->error("Operands list should have names for each operand!");
2442 if (!OperandsSet.count(OpsList->getArgName(j)))
2443 P->error("'" + OpsList->getArgName(j) +
2444 "' does not occur in pattern or was multiply specified!");
2445 OperandsSet.erase(OpsList->getArgName(j));
2446 Args.push_back(OpsList->getArgName(j));
2449 if (!OperandsSet.empty())
2450 P->error("Operands list does not contain an entry for operand '" +
2451 *OperandsSet.begin() + "'!");
2453 // If there is a code init for this fragment, keep track of the fact that
2454 // this fragment uses it.
2455 TreePredicateFn PredFn(P);
2456 if (!PredFn.isAlwaysTrue())
2457 P->getOnlyTree()->addPredicateFn(PredFn);
2459 // If there is a node transformation corresponding to this, keep track of
2461 Record *Transform = Frag->getValueAsDef("OperandTransform");
2462 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
2463 P->getOnlyTree()->setTransformFn(Transform);
2466 // Now that we've parsed all of the tree fragments, do a closure on them so
2467 // that there are not references to PatFrags left inside of them.
2468 for (Record *Frag : Fragments) {
2469 if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
2472 TreePattern &ThePat = *PatternFragments[Frag];
2473 ThePat.InlinePatternFragments();
2475 // Infer as many types as possible. Don't worry about it if we don't infer
2476 // all of them, some may depend on the inputs of the pattern.
2477 ThePat.InferAllTypes();
2478 ThePat.resetError();
2480 // If debugging, print out the pattern fragment result.
2481 DEBUG(ThePat.dump());
2485 void CodeGenDAGPatterns::ParseDefaultOperands() {
2486 std::vector<Record*> DefaultOps;
2487 DefaultOps = Records.getAllDerivedDefinitions("OperandWithDefaultOps");
2489 // Find some SDNode.
2490 assert(!SDNodes.empty() && "No SDNodes parsed?");
2491 Init *SomeSDNode = DefInit::get(SDNodes.begin()->first);
2493 for (unsigned i = 0, e = DefaultOps.size(); i != e; ++i) {
2494 DagInit *DefaultInfo = DefaultOps[i]->getValueAsDag("DefaultOps");
2496 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
2497 // SomeSDnode so that we can parse this.
2498 std::vector<std::pair<Init*, std::string> > Ops;
2499 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
2500 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
2501 DefaultInfo->getArgName(op)));
2502 DagInit *DI = DagInit::get(SomeSDNode, "", Ops);
2504 // Create a TreePattern to parse this.
2505 TreePattern P(DefaultOps[i], DI, false, *this);
2506 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
2508 // Copy the operands over into a DAGDefaultOperand.
2509 DAGDefaultOperand DefaultOpInfo;
2511 TreePatternNode *T = P.getTree(0);
2512 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
2513 TreePatternNode *TPN = T->getChild(op);
2514 while (TPN->ApplyTypeConstraints(P, false))
2515 /* Resolve all types */;
2517 if (TPN->ContainsUnresolvedType()) {
2518 PrintFatalError("Value #" + Twine(i) + " of OperandWithDefaultOps '" +
2519 DefaultOps[i]->getName() +
2520 "' doesn't have a concrete type!");
2522 DefaultOpInfo.DefaultOps.push_back(TPN);
2525 // Insert it into the DefaultOperands map so we can find it later.
2526 DefaultOperands[DefaultOps[i]] = DefaultOpInfo;
2530 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
2531 /// instruction input. Return true if this is a real use.
2532 static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
2533 std::map<std::string, TreePatternNode*> &InstInputs) {
2534 // No name -> not interesting.
2535 if (Pat->getName().empty()) {
2536 if (Pat->isLeaf()) {
2537 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
2538 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2539 DI->getDef()->isSubClassOf("RegisterOperand")))
2540 I->error("Input " + DI->getDef()->getName() + " must be named!");
2546 if (Pat->isLeaf()) {
2547 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
2548 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
2551 Rec = Pat->getOperator();
2554 // SRCVALUE nodes are ignored.
2555 if (Rec->getName() == "srcvalue")
2558 TreePatternNode *&Slot = InstInputs[Pat->getName()];
2564 if (Slot->isLeaf()) {
2565 SlotRec = cast<DefInit>(Slot->getLeafValue())->getDef();
2567 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
2568 SlotRec = Slot->getOperator();
2571 // Ensure that the inputs agree if we've already seen this input.
2573 I->error("All $" + Pat->getName() + " inputs must agree with each other");
2574 if (Slot->getExtTypes() != Pat->getExtTypes())
2575 I->error("All $" + Pat->getName() + " inputs must agree with each other");
2579 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
2580 /// part of "I", the instruction), computing the set of inputs and outputs of
2581 /// the pattern. Report errors if we see anything naughty.
2582 void CodeGenDAGPatterns::
2583 FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
2584 std::map<std::string, TreePatternNode*> &InstInputs,
2585 std::map<std::string, TreePatternNode*>&InstResults,
2586 std::vector<Record*> &InstImpResults) {
2587 if (Pat->isLeaf()) {
2588 bool isUse = HandleUse(I, Pat, InstInputs);
2589 if (!isUse && Pat->getTransformFn())
2590 I->error("Cannot specify a transform function for a non-input value!");
2594 if (Pat->getOperator()->getName() == "implicit") {
2595 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2596 TreePatternNode *Dest = Pat->getChild(i);
2597 if (!Dest->isLeaf())
2598 I->error("implicitly defined value should be a register!");
2600 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
2601 if (!Val || !Val->getDef()->isSubClassOf("Register"))
2602 I->error("implicitly defined value should be a register!");
2603 InstImpResults.push_back(Val->getDef());
2608 if (Pat->getOperator()->getName() != "set") {
2609 // If this is not a set, verify that the children nodes are not void typed,
2611 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2612 if (Pat->getChild(i)->getNumTypes() == 0)
2613 I->error("Cannot have void nodes inside of patterns!");
2614 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
2618 // If this is a non-leaf node with no children, treat it basically as if
2619 // it were a leaf. This handles nodes like (imm).
2620 bool isUse = HandleUse(I, Pat, InstInputs);
2622 if (!isUse && Pat->getTransformFn())
2623 I->error("Cannot specify a transform function for a non-input value!");
2627 // Otherwise, this is a set, validate and collect instruction results.
2628 if (Pat->getNumChildren() == 0)
2629 I->error("set requires operands!");
2631 if (Pat->getTransformFn())
2632 I->error("Cannot specify a transform function on a set node!");
2634 // Check the set destinations.
2635 unsigned NumDests = Pat->getNumChildren()-1;
2636 for (unsigned i = 0; i != NumDests; ++i) {
2637 TreePatternNode *Dest = Pat->getChild(i);
2638 if (!Dest->isLeaf())
2639 I->error("set destination should be a register!");
2641 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
2643 I->error("set destination should be a register!");
2647 if (Val->getDef()->isSubClassOf("RegisterClass") ||
2648 Val->getDef()->isSubClassOf("ValueType") ||
2649 Val->getDef()->isSubClassOf("RegisterOperand") ||
2650 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
2651 if (Dest->getName().empty())
2652 I->error("set destination must have a name!");
2653 if (InstResults.count(Dest->getName()))
2654 I->error("cannot set '" + Dest->getName() +"' multiple times");
2655 InstResults[Dest->getName()] = Dest;
2656 } else if (Val->getDef()->isSubClassOf("Register")) {
2657 InstImpResults.push_back(Val->getDef());
2659 I->error("set destination should be a register!");
2663 // Verify and collect info from the computation.
2664 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
2665 InstInputs, InstResults, InstImpResults);
2668 //===----------------------------------------------------------------------===//
2669 // Instruction Analysis
2670 //===----------------------------------------------------------------------===//
2672 class InstAnalyzer {
2673 const CodeGenDAGPatterns &CDP;
2675 bool hasSideEffects;
2681 InstAnalyzer(const CodeGenDAGPatterns &cdp)
2682 : CDP(cdp), hasSideEffects(false), mayStore(false), mayLoad(false),
2683 isBitcast(false), isVariadic(false) {}
2685 void Analyze(const TreePattern *Pat) {
2686 // Assume only the first tree is the pattern. The others are clobber nodes.
2687 AnalyzeNode(Pat->getTree(0));
2690 void Analyze(const PatternToMatch *Pat) {
2691 AnalyzeNode(Pat->getSrcPattern());
2695 bool IsNodeBitcast(const TreePatternNode *N) const {
2696 if (hasSideEffects || mayLoad || mayStore || isVariadic)
2699 if (N->getNumChildren() != 2)
2702 const TreePatternNode *N0 = N->getChild(0);
2703 if (!N0->isLeaf() || !isa<DefInit>(N0->getLeafValue()))
2706 const TreePatternNode *N1 = N->getChild(1);
2709 if (N1->getNumChildren() != 1 || !N1->getChild(0)->isLeaf())
2712 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N1->getOperator());
2713 if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1)
2715 return OpInfo.getEnumName() == "ISD::BITCAST";
2719 void AnalyzeNode(const TreePatternNode *N) {
2721 if (DefInit *DI = dyn_cast<DefInit>(N->getLeafValue())) {
2722 Record *LeafRec = DI->getDef();
2723 // Handle ComplexPattern leaves.
2724 if (LeafRec->isSubClassOf("ComplexPattern")) {
2725 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
2726 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
2727 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
2728 if (CP.hasProperty(SDNPSideEffect)) hasSideEffects = true;
2734 // Analyze children.
2735 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2736 AnalyzeNode(N->getChild(i));
2738 // Ignore set nodes, which are not SDNodes.
2739 if (N->getOperator()->getName() == "set") {
2740 isBitcast = IsNodeBitcast(N);
2744 // Notice properties of the node.
2745 if (N->NodeHasProperty(SDNPMayStore, CDP)) mayStore = true;
2746 if (N->NodeHasProperty(SDNPMayLoad, CDP)) mayLoad = true;
2747 if (N->NodeHasProperty(SDNPSideEffect, CDP)) hasSideEffects = true;
2748 if (N->NodeHasProperty(SDNPVariadic, CDP)) isVariadic = true;
2750 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
2751 // If this is an intrinsic, analyze it.
2752 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
2753 mayLoad = true;// These may load memory.
2755 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteArgMem)
2756 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
2758 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem)
2759 // WriteMem intrinsics can have other strange effects.
2760 hasSideEffects = true;
2766 static bool InferFromPattern(CodeGenInstruction &InstInfo,
2767 const InstAnalyzer &PatInfo,
2771 // Remember where InstInfo got its flags.
2772 if (InstInfo.hasUndefFlags())
2773 InstInfo.InferredFrom = PatDef;
2775 // Check explicitly set flags for consistency.
2776 if (InstInfo.hasSideEffects != PatInfo.hasSideEffects &&
2777 !InstInfo.hasSideEffects_Unset) {
2778 // Allow explicitly setting hasSideEffects = 1 on instructions, even when
2779 // the pattern has no side effects. That could be useful for div/rem
2780 // instructions that may trap.
2781 if (!InstInfo.hasSideEffects) {
2783 PrintError(PatDef->getLoc(), "Pattern doesn't match hasSideEffects = " +
2784 Twine(InstInfo.hasSideEffects));
2788 if (InstInfo.mayStore != PatInfo.mayStore && !InstInfo.mayStore_Unset) {
2790 PrintError(PatDef->getLoc(), "Pattern doesn't match mayStore = " +
2791 Twine(InstInfo.mayStore));
2794 if (InstInfo.mayLoad != PatInfo.mayLoad && !InstInfo.mayLoad_Unset) {
2795 // Allow explicitly setting mayLoad = 1, even when the pattern has no loads.
2796 // Some targets translate immediates to loads.
2797 if (!InstInfo.mayLoad) {
2799 PrintError(PatDef->getLoc(), "Pattern doesn't match mayLoad = " +
2800 Twine(InstInfo.mayLoad));
2804 // Transfer inferred flags.
2805 InstInfo.hasSideEffects |= PatInfo.hasSideEffects;
2806 InstInfo.mayStore |= PatInfo.mayStore;
2807 InstInfo.mayLoad |= PatInfo.mayLoad;
2809 // These flags are silently added without any verification.
2810 InstInfo.isBitcast |= PatInfo.isBitcast;
2812 // Don't infer isVariadic. This flag means something different on SDNodes and
2813 // instructions. For example, a CALL SDNode is variadic because it has the
2814 // call arguments as operands, but a CALL instruction is not variadic - it
2815 // has argument registers as implicit, not explicit uses.
2820 /// hasNullFragReference - Return true if the DAG has any reference to the
2821 /// null_frag operator.
2822 static bool hasNullFragReference(DagInit *DI) {
2823 DefInit *OpDef = dyn_cast<DefInit>(DI->getOperator());
2824 if (!OpDef) return false;
2825 Record *Operator = OpDef->getDef();
2827 // If this is the null fragment, return true.
2828 if (Operator->getName() == "null_frag") return true;
2829 // If any of the arguments reference the null fragment, return true.
2830 for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {
2831 DagInit *Arg = dyn_cast<DagInit>(DI->getArg(i));
2832 if (Arg && hasNullFragReference(Arg))
2839 /// hasNullFragReference - Return true if any DAG in the list references
2840 /// the null_frag operator.
2841 static bool hasNullFragReference(ListInit *LI) {
2842 for (Init *I : LI->getValues()) {
2843 DagInit *DI = dyn_cast<DagInit>(I);
2844 assert(DI && "non-dag in an instruction Pattern list?!");
2845 if (hasNullFragReference(DI))
2851 /// Get all the instructions in a tree.
2853 getInstructionsInTree(TreePatternNode *Tree, SmallVectorImpl<Record*> &Instrs) {
2856 if (Tree->getOperator()->isSubClassOf("Instruction"))
2857 Instrs.push_back(Tree->getOperator());
2858 for (unsigned i = 0, e = Tree->getNumChildren(); i != e; ++i)
2859 getInstructionsInTree(Tree->getChild(i), Instrs);
2862 /// Check the class of a pattern leaf node against the instruction operand it
2864 static bool checkOperandClass(CGIOperandList::OperandInfo &OI,
2869 // Allow direct value types to be used in instruction set patterns.
2870 // The type will be checked later.
2871 if (Leaf->isSubClassOf("ValueType"))
2874 // Patterns can also be ComplexPattern instances.
2875 if (Leaf->isSubClassOf("ComplexPattern"))
2881 const DAGInstruction &CodeGenDAGPatterns::parseInstructionPattern(
2882 CodeGenInstruction &CGI, ListInit *Pat, DAGInstMap &DAGInsts) {
2884 assert(!DAGInsts.count(CGI.TheDef) && "Instruction already parsed!");
2886 // Parse the instruction.
2887 TreePattern *I = new TreePattern(CGI.TheDef, Pat, true, *this);
2888 // Inline pattern fragments into it.
2889 I->InlinePatternFragments();
2891 // Infer as many types as possible. If we cannot infer all of them, we can
2892 // never do anything with this instruction pattern: report it to the user.
2893 if (!I->InferAllTypes())
2894 I->error("Could not infer all types in pattern!");
2896 // InstInputs - Keep track of all of the inputs of the instruction, along
2897 // with the record they are declared as.
2898 std::map<std::string, TreePatternNode*> InstInputs;
2900 // InstResults - Keep track of all the virtual registers that are 'set'
2901 // in the instruction, including what reg class they are.
2902 std::map<std::string, TreePatternNode*> InstResults;
2904 std::vector<Record*> InstImpResults;
2906 // Verify that the top-level forms in the instruction are of void type, and
2907 // fill in the InstResults map.
2908 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
2909 TreePatternNode *Pat = I->getTree(j);
2910 if (Pat->getNumTypes() != 0)
2911 I->error("Top-level forms in instruction pattern should have"
2914 // Find inputs and outputs, and verify the structure of the uses/defs.
2915 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
2919 // Now that we have inputs and outputs of the pattern, inspect the operands
2920 // list for the instruction. This determines the order that operands are
2921 // added to the machine instruction the node corresponds to.
2922 unsigned NumResults = InstResults.size();
2924 // Parse the operands list from the (ops) list, validating it.
2925 assert(I->getArgList().empty() && "Args list should still be empty here!");
2927 // Check that all of the results occur first in the list.
2928 std::vector<Record*> Results;
2929 SmallVector<TreePatternNode *, 2> ResNodes;
2930 for (unsigned i = 0; i != NumResults; ++i) {
2931 if (i == CGI.Operands.size())
2932 I->error("'" + InstResults.begin()->first +
2933 "' set but does not appear in operand list!");
2934 const std::string &OpName = CGI.Operands[i].Name;
2936 // Check that it exists in InstResults.
2937 TreePatternNode *RNode = InstResults[OpName];
2939 I->error("Operand $" + OpName + " does not exist in operand list!");
2941 ResNodes.push_back(RNode);
2943 Record *R = cast<DefInit>(RNode->getLeafValue())->getDef();
2945 I->error("Operand $" + OpName + " should be a set destination: all "
2946 "outputs must occur before inputs in operand list!");
2948 if (!checkOperandClass(CGI.Operands[i], R))
2949 I->error("Operand $" + OpName + " class mismatch!");
2951 // Remember the return type.
2952 Results.push_back(CGI.Operands[i].Rec);
2954 // Okay, this one checks out.
2955 InstResults.erase(OpName);
2958 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
2959 // the copy while we're checking the inputs.
2960 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
2962 std::vector<TreePatternNode*> ResultNodeOperands;
2963 std::vector<Record*> Operands;
2964 for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
2965 CGIOperandList::OperandInfo &Op = CGI.Operands[i];
2966 const std::string &OpName = Op.Name;
2968 I->error("Operand #" + utostr(i) + " in operands list has no name!");
2970 if (!InstInputsCheck.count(OpName)) {
2971 // If this is an operand with a DefaultOps set filled in, we can ignore
2972 // this. When we codegen it, we will do so as always executed.
2973 if (Op.Rec->isSubClassOf("OperandWithDefaultOps")) {
2974 // Does it have a non-empty DefaultOps field? If so, ignore this
2976 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
2979 I->error("Operand $" + OpName +
2980 " does not appear in the instruction pattern");
2982 TreePatternNode *InVal = InstInputsCheck[OpName];
2983 InstInputsCheck.erase(OpName); // It occurred, remove from map.
2985 if (InVal->isLeaf() && isa<DefInit>(InVal->getLeafValue())) {
2986 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
2987 if (!checkOperandClass(Op, InRec))
2988 I->error("Operand $" + OpName + "'s register class disagrees"
2989 " between the operand and pattern");
2991 Operands.push_back(Op.Rec);
2993 // Construct the result for the dest-pattern operand list.
2994 TreePatternNode *OpNode = InVal->clone();
2996 // No predicate is useful on the result.
2997 OpNode->clearPredicateFns();
2999 // Promote the xform function to be an explicit node if set.
3000 if (Record *Xform = OpNode->getTransformFn()) {
3001 OpNode->setTransformFn(nullptr);
3002 std::vector<TreePatternNode*> Children;
3003 Children.push_back(OpNode);
3004 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
3007 ResultNodeOperands.push_back(OpNode);
3010 if (!InstInputsCheck.empty())
3011 I->error("Input operand $" + InstInputsCheck.begin()->first +
3012 " occurs in pattern but not in operands list!");
3014 TreePatternNode *ResultPattern =
3015 new TreePatternNode(I->getRecord(), ResultNodeOperands,
3016 GetNumNodeResults(I->getRecord(), *this));
3017 // Copy fully inferred output node types to instruction result pattern.
3018 for (unsigned i = 0; i != NumResults; ++i) {
3019 assert(ResNodes[i]->getNumTypes() == 1 && "FIXME: Unhandled");
3020 ResultPattern->setType(i, ResNodes[i]->getExtType(0));
3023 // Create and insert the instruction.
3024 // FIXME: InstImpResults should not be part of DAGInstruction.
3025 DAGInstruction TheInst(I, Results, Operands, InstImpResults);
3026 DAGInsts.insert(std::make_pair(I->getRecord(), TheInst));
3028 // Use a temporary tree pattern to infer all types and make sure that the
3029 // constructed result is correct. This depends on the instruction already
3030 // being inserted into the DAGInsts map.
3031 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
3032 Temp.InferAllTypes(&I->getNamedNodesMap());
3034 DAGInstruction &TheInsertedInst = DAGInsts.find(I->getRecord())->second;
3035 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
3037 return TheInsertedInst;
3040 /// ParseInstructions - Parse all of the instructions, inlining and resolving
3041 /// any fragments involved. This populates the Instructions list with fully
3042 /// resolved instructions.
3043 void CodeGenDAGPatterns::ParseInstructions() {
3044 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
3046 for (Record *Instr : Instrs) {
3047 ListInit *LI = nullptr;
3049 if (isa<ListInit>(Instr->getValueInit("Pattern")))
3050 LI = Instr->getValueAsListInit("Pattern");
3052 // If there is no pattern, only collect minimal information about the
3053 // instruction for its operand list. We have to assume that there is one
3054 // result, as we have no detailed info. A pattern which references the
3055 // null_frag operator is as-if no pattern were specified. Normally this
3056 // is from a multiclass expansion w/ a SDPatternOperator passed in as
3058 if (!LI || LI->empty() || hasNullFragReference(LI)) {
3059 std::vector<Record*> Results;
3060 std::vector<Record*> Operands;
3062 CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
3064 if (InstInfo.Operands.size() != 0) {
3065 for (unsigned j = 0, e = InstInfo.Operands.NumDefs; j < e; ++j)
3066 Results.push_back(InstInfo.Operands[j].Rec);
3068 // The rest are inputs.
3069 for (unsigned j = InstInfo.Operands.NumDefs,
3070 e = InstInfo.Operands.size(); j < e; ++j)
3071 Operands.push_back(InstInfo.Operands[j].Rec);
3074 // Create and insert the instruction.
3075 std::vector<Record*> ImpResults;
3076 Instructions.insert(std::make_pair(Instr,
3077 DAGInstruction(nullptr, Results, Operands, ImpResults)));
3078 continue; // no pattern.
3081 CodeGenInstruction &CGI = Target.getInstruction(Instr);
3082 const DAGInstruction &DI = parseInstructionPattern(CGI, LI, Instructions);
3085 DEBUG(DI.getPattern()->dump());
3088 // If we can, convert the instructions to be patterns that are matched!
3089 for (auto &Entry : Instructions) {
3090 DAGInstruction &TheInst = Entry.second;
3091 TreePattern *I = TheInst.getPattern();
3092 if (!I) continue; // No pattern.
3094 // FIXME: Assume only the first tree is the pattern. The others are clobber
3096 TreePatternNode *Pattern = I->getTree(0);
3097 TreePatternNode *SrcPattern;
3098 if (Pattern->getOperator()->getName() == "set") {
3099 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
3101 // Not a set (store or something?)
3102 SrcPattern = Pattern;
3105 Record *Instr = Entry.first;
3106 AddPatternToMatch(I,
3107 PatternToMatch(Instr,
3108 Instr->getValueAsListInit("Predicates"),
3110 TheInst.getResultPattern(),
3111 TheInst.getImpResults(),
3112 Instr->getValueAsInt("AddedComplexity"),
3118 typedef std::pair<const TreePatternNode*, unsigned> NameRecord;
3120 static void FindNames(const TreePatternNode *P,
3121 std::map<std::string, NameRecord> &Names,
3122 TreePattern *PatternTop) {
3123 if (!P->getName().empty()) {
3124 NameRecord &Rec = Names[P->getName()];
3125 // If this is the first instance of the name, remember the node.
3126 if (Rec.second++ == 0)
3128 else if (Rec.first->getExtTypes() != P->getExtTypes())
3129 PatternTop->error("repetition of value: $" + P->getName() +
3130 " where different uses have different types!");
3134 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
3135 FindNames(P->getChild(i), Names, PatternTop);
3139 void CodeGenDAGPatterns::AddPatternToMatch(TreePattern *Pattern,
3140 const PatternToMatch &PTM) {
3141 // Do some sanity checking on the pattern we're about to match.
3143 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this)) {
3144 PrintWarning(Pattern->getRecord()->getLoc(),
3145 Twine("Pattern can never match: ") + Reason);
3149 // If the source pattern's root is a complex pattern, that complex pattern
3150 // must specify the nodes it can potentially match.
3151 if (const ComplexPattern *CP =
3152 PTM.getSrcPattern()->getComplexPatternInfo(*this))
3153 if (CP->getRootNodes().empty())
3154 Pattern->error("ComplexPattern at root must specify list of opcodes it"
3158 // Find all of the named values in the input and output, ensure they have the
3160 std::map<std::string, NameRecord> SrcNames, DstNames;
3161 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
3162 FindNames(PTM.getDstPattern(), DstNames, Pattern);
3164 // Scan all of the named values in the destination pattern, rejecting them if
3165 // they don't exist in the input pattern.
3166 for (const auto &Entry : DstNames) {
3167 if (SrcNames[Entry.first].first == nullptr)
3168 Pattern->error("Pattern has input without matching name in output: $" +
3172 // Scan all of the named values in the source pattern, rejecting them if the
3173 // name isn't used in the dest, and isn't used to tie two values together.
3174 for (const auto &Entry : SrcNames)
3175 if (DstNames[Entry.first].first == nullptr &&
3176 SrcNames[Entry.first].second == 1)
3177 Pattern->error("Pattern has dead named input: $" + Entry.first);
3179 PatternsToMatch.push_back(PTM);
3184 void CodeGenDAGPatterns::InferInstructionFlags() {
3185 const std::vector<const CodeGenInstruction*> &Instructions =
3186 Target.getInstructionsByEnumValue();
3188 // First try to infer flags from the primary instruction pattern, if any.
3189 SmallVector<CodeGenInstruction*, 8> Revisit;
3190 unsigned Errors = 0;
3191 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
3192 CodeGenInstruction &InstInfo =
3193 const_cast<CodeGenInstruction &>(*Instructions[i]);
3195 // Get the primary instruction pattern.
3196 const TreePattern *Pattern = getInstruction(InstInfo.TheDef).getPattern();
3198 if (InstInfo.hasUndefFlags())
3199 Revisit.push_back(&InstInfo);
3202 InstAnalyzer PatInfo(*this);
3203 PatInfo.Analyze(Pattern);
3204 Errors += InferFromPattern(InstInfo, PatInfo, InstInfo.TheDef);
3207 // Second, look for single-instruction patterns defined outside the
3209 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3210 const PatternToMatch &PTM = *I;
3212 // We can only infer from single-instruction patterns, otherwise we won't
3213 // know which instruction should get the flags.
3214 SmallVector<Record*, 8> PatInstrs;
3215 getInstructionsInTree(PTM.getDstPattern(), PatInstrs);
3216 if (PatInstrs.size() != 1)
3219 // Get the single instruction.
3220 CodeGenInstruction &InstInfo = Target.getInstruction(PatInstrs.front());
3222 // Only infer properties from the first pattern. We'll verify the others.
3223 if (InstInfo.InferredFrom)
3226 InstAnalyzer PatInfo(*this);
3227 PatInfo.Analyze(&PTM);
3228 Errors += InferFromPattern(InstInfo, PatInfo, PTM.getSrcRecord());
3232 PrintFatalError("pattern conflicts");
3234 // Revisit instructions with undefined flags and no pattern.
3235 if (Target.guessInstructionProperties()) {
3236 for (CodeGenInstruction *InstInfo : Revisit) {
3237 if (InstInfo->InferredFrom)
3239 // The mayLoad and mayStore flags default to false.
3240 // Conservatively assume hasSideEffects if it wasn't explicit.
3241 if (InstInfo->hasSideEffects_Unset)
3242 InstInfo->hasSideEffects = true;
3247 // Complain about any flags that are still undefined.
3248 for (CodeGenInstruction *InstInfo : Revisit) {
3249 if (InstInfo->InferredFrom)
3251 if (InstInfo->hasSideEffects_Unset)
3252 PrintError(InstInfo->TheDef->getLoc(),
3253 "Can't infer hasSideEffects from patterns");
3254 if (InstInfo->mayStore_Unset)
3255 PrintError(InstInfo->TheDef->getLoc(),
3256 "Can't infer mayStore from patterns");
3257 if (InstInfo->mayLoad_Unset)
3258 PrintError(InstInfo->TheDef->getLoc(),
3259 "Can't infer mayLoad from patterns");
3264 /// Verify instruction flags against pattern node properties.
3265 void CodeGenDAGPatterns::VerifyInstructionFlags() {
3266 unsigned Errors = 0;
3267 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3268 const PatternToMatch &PTM = *I;
3269 SmallVector<Record*, 8> Instrs;
3270 getInstructionsInTree(PTM.getDstPattern(), Instrs);
3274 // Count the number of instructions with each flag set.
3275 unsigned NumSideEffects = 0;
3276 unsigned NumStores = 0;
3277 unsigned NumLoads = 0;
3278 for (const Record *Instr : Instrs) {
3279 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
3280 NumSideEffects += InstInfo.hasSideEffects;
3281 NumStores += InstInfo.mayStore;
3282 NumLoads += InstInfo.mayLoad;
3285 // Analyze the source pattern.
3286 InstAnalyzer PatInfo(*this);
3287 PatInfo.Analyze(&PTM);
3289 // Collect error messages.
3290 SmallVector<std::string, 4> Msgs;
3292 // Check for missing flags in the output.
3293 // Permit extra flags for now at least.
3294 if (PatInfo.hasSideEffects && !NumSideEffects)
3295 Msgs.push_back("pattern has side effects, but hasSideEffects isn't set");
3297 // Don't verify store flags on instructions with side effects. At least for
3298 // intrinsics, side effects implies mayStore.
3299 if (!PatInfo.hasSideEffects && PatInfo.mayStore && !NumStores)
3300 Msgs.push_back("pattern may store, but mayStore isn't set");
3302 // Similarly, mayStore implies mayLoad on intrinsics.
3303 if (!PatInfo.mayStore && PatInfo.mayLoad && !NumLoads)
3304 Msgs.push_back("pattern may load, but mayLoad isn't set");
3306 // Print error messages.
3311 for (const std::string &Msg : Msgs)
3312 PrintError(PTM.getSrcRecord()->getLoc(), Twine(Msg) + " on the " +
3313 (Instrs.size() == 1 ?
3314 "instruction" : "output instructions"));
3315 // Provide the location of the relevant instruction definitions.
3316 for (const Record *Instr : Instrs) {
3317 if (Instr != PTM.getSrcRecord())
3318 PrintError(Instr->getLoc(), "defined here");
3319 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
3320 if (InstInfo.InferredFrom &&
3321 InstInfo.InferredFrom != InstInfo.TheDef &&
3322 InstInfo.InferredFrom != PTM.getSrcRecord())
3323 PrintError(InstInfo.InferredFrom->getLoc(), "inferred from pattern");
3327 PrintFatalError("Errors in DAG patterns");
3330 /// Given a pattern result with an unresolved type, see if we can find one
3331 /// instruction with an unresolved result type. Force this result type to an
3332 /// arbitrary element if it's possible types to converge results.
3333 static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
3337 // Analyze children.
3338 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3339 if (ForceArbitraryInstResultType(N->getChild(i), TP))
3342 if (!N->getOperator()->isSubClassOf("Instruction"))
3345 // If this type is already concrete or completely unknown we can't do
3347 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
3348 if (N->getExtType(i).isCompletelyUnknown() || N->getExtType(i).isConcrete())
3351 // Otherwise, force its type to the first possibility (an arbitrary choice).
3352 if (N->getExtType(i).MergeInTypeInfo(N->getExtType(i).getTypeList()[0], TP))
3359 void CodeGenDAGPatterns::ParsePatterns() {
3360 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
3362 for (Record *CurPattern : Patterns) {
3363 DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
3365 // If the pattern references the null_frag, there's nothing to do.
3366 if (hasNullFragReference(Tree))
3369 TreePattern *Pattern = new TreePattern(CurPattern, Tree, true, *this);
3371 // Inline pattern fragments into it.
3372 Pattern->InlinePatternFragments();
3374 ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
3375 if (LI->empty()) continue; // no pattern.
3377 // Parse the instruction.
3378 TreePattern Result(CurPattern, LI, false, *this);
3380 // Inline pattern fragments into it.
3381 Result.InlinePatternFragments();
3383 if (Result.getNumTrees() != 1)
3384 Result.error("Cannot handle instructions producing instructions "
3385 "with temporaries yet!");
3387 bool IterateInference;
3388 bool InferredAllPatternTypes, InferredAllResultTypes;
3390 // Infer as many types as possible. If we cannot infer all of them, we
3391 // can never do anything with this pattern: report it to the user.
3392 InferredAllPatternTypes =
3393 Pattern->InferAllTypes(&Pattern->getNamedNodesMap());
3395 // Infer as many types as possible. If we cannot infer all of them, we
3396 // can never do anything with this pattern: report it to the user.
3397 InferredAllResultTypes =
3398 Result.InferAllTypes(&Pattern->getNamedNodesMap());
3400 IterateInference = false;
3402 // Apply the type of the result to the source pattern. This helps us
3403 // resolve cases where the input type is known to be a pointer type (which
3404 // is considered resolved), but the result knows it needs to be 32- or
3405 // 64-bits. Infer the other way for good measure.
3406 for (unsigned i = 0, e = std::min(Result.getTree(0)->getNumTypes(),
3407 Pattern->getTree(0)->getNumTypes());
3409 IterateInference = Pattern->getTree(0)->UpdateNodeType(
3410 i, Result.getTree(0)->getExtType(i), Result);
3411 IterateInference |= Result.getTree(0)->UpdateNodeType(
3412 i, Pattern->getTree(0)->getExtType(i), Result);
3415 // If our iteration has converged and the input pattern's types are fully
3416 // resolved but the result pattern is not fully resolved, we may have a
3417 // situation where we have two instructions in the result pattern and
3418 // the instructions require a common register class, but don't care about
3419 // what actual MVT is used. This is actually a bug in our modelling:
3420 // output patterns should have register classes, not MVTs.
3422 // In any case, to handle this, we just go through and disambiguate some
3423 // arbitrary types to the result pattern's nodes.
3424 if (!IterateInference && InferredAllPatternTypes &&
3425 !InferredAllResultTypes)
3427 ForceArbitraryInstResultType(Result.getTree(0), Result);
3428 } while (IterateInference);
3430 // Verify that we inferred enough types that we can do something with the
3431 // pattern and result. If these fire the user has to add type casts.
3432 if (!InferredAllPatternTypes)
3433 Pattern->error("Could not infer all types in pattern!");
3434 if (!InferredAllResultTypes) {
3436 Result.error("Could not infer all types in pattern result!");
3439 // Validate that the input pattern is correct.
3440 std::map<std::string, TreePatternNode*> InstInputs;
3441 std::map<std::string, TreePatternNode*> InstResults;
3442 std::vector<Record*> InstImpResults;
3443 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
3444 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
3445 InstInputs, InstResults,
3448 // Promote the xform function to be an explicit node if set.
3449 TreePatternNode *DstPattern = Result.getOnlyTree();
3450 std::vector<TreePatternNode*> ResultNodeOperands;
3451 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
3452 TreePatternNode *OpNode = DstPattern->getChild(ii);
3453 if (Record *Xform = OpNode->getTransformFn()) {
3454 OpNode->setTransformFn(nullptr);
3455 std::vector<TreePatternNode*> Children;
3456 Children.push_back(OpNode);
3457 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
3459 ResultNodeOperands.push_back(OpNode);
3461 DstPattern = Result.getOnlyTree();
3462 if (!DstPattern->isLeaf())
3463 DstPattern = new TreePatternNode(DstPattern->getOperator(),
3465 DstPattern->getNumTypes());
3467 for (unsigned i = 0, e = Result.getOnlyTree()->getNumTypes(); i != e; ++i)
3468 DstPattern->setType(i, Result.getOnlyTree()->getExtType(i));
3470 TreePattern Temp(Result.getRecord(), DstPattern, false, *this);
3471 Temp.InferAllTypes();
3474 AddPatternToMatch(Pattern,
3475 PatternToMatch(CurPattern,
3476 CurPattern->getValueAsListInit("Predicates"),
3477 Pattern->getTree(0),
3478 Temp.getOnlyTree(), InstImpResults,
3479 CurPattern->getValueAsInt("AddedComplexity"),
3480 CurPattern->getID()));
3484 /// CombineChildVariants - Given a bunch of permutations of each child of the
3485 /// 'operator' node, put them together in all possible ways.
3486 static void CombineChildVariants(TreePatternNode *Orig,
3487 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
3488 std::vector<TreePatternNode*> &OutVariants,
3489 CodeGenDAGPatterns &CDP,
3490 const MultipleUseVarSet &DepVars) {
3491 // Make sure that each operand has at least one variant to choose from.
3492 for (const auto &Variants : ChildVariants)
3493 if (Variants.empty())
3496 // The end result is an all-pairs construction of the resultant pattern.
3497 std::vector<unsigned> Idxs;
3498 Idxs.resize(ChildVariants.size());
3502 DEBUG(if (!Idxs.empty()) {
3503 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
3504 for (unsigned Idx : Idxs) {
3505 errs() << Idx << " ";
3510 // Create the variant and add it to the output list.
3511 std::vector<TreePatternNode*> NewChildren;
3512 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
3513 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
3514 auto R = llvm::make_unique<TreePatternNode>(
3515 Orig->getOperator(), NewChildren, Orig->getNumTypes());
3517 // Copy over properties.
3518 R->setName(Orig->getName());
3519 R->setPredicateFns(Orig->getPredicateFns());
3520 R->setTransformFn(Orig->getTransformFn());
3521 for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
3522 R->setType(i, Orig->getExtType(i));
3524 // If this pattern cannot match, do not include it as a variant.
3525 std::string ErrString;
3526 // Scan to see if this pattern has already been emitted. We can get
3527 // duplication due to things like commuting:
3528 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
3529 // which are the same pattern. Ignore the dups.
3530 if (R->canPatternMatch(ErrString, CDP) &&
3531 std::none_of(OutVariants.begin(), OutVariants.end(),
3532 [&](TreePatternNode *Variant) {
3533 return R->isIsomorphicTo(Variant, DepVars);
3535 OutVariants.push_back(R.release());
3537 // Increment indices to the next permutation by incrementing the
3538 // indices from last index backward, e.g., generate the sequence
3539 // [0, 0], [0, 1], [1, 0], [1, 1].
3541 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
3542 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
3547 NotDone = (IdxsIdx >= 0);
3551 /// CombineChildVariants - A helper function for binary operators.
3553 static void CombineChildVariants(TreePatternNode *Orig,
3554 const std::vector<TreePatternNode*> &LHS,
3555 const std::vector<TreePatternNode*> &RHS,
3556 std::vector<TreePatternNode*> &OutVariants,
3557 CodeGenDAGPatterns &CDP,
3558 const MultipleUseVarSet &DepVars) {
3559 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3560 ChildVariants.push_back(LHS);
3561 ChildVariants.push_back(RHS);
3562 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
3566 static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
3567 std::vector<TreePatternNode *> &Children) {
3568 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
3569 Record *Operator = N->getOperator();
3571 // Only permit raw nodes.
3572 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
3573 N->getTransformFn()) {
3574 Children.push_back(N);
3578 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
3579 Children.push_back(N->getChild(0));
3581 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
3583 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
3584 Children.push_back(N->getChild(1));
3586 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
3589 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
3590 /// the (potentially recursive) pattern by using algebraic laws.
3592 static void GenerateVariantsOf(TreePatternNode *N,
3593 std::vector<TreePatternNode*> &OutVariants,
3594 CodeGenDAGPatterns &CDP,
3595 const MultipleUseVarSet &DepVars) {
3596 // We cannot permute leaves or ComplexPattern uses.
3597 if (N->isLeaf() || N->getOperator()->isSubClassOf("ComplexPattern")) {
3598 OutVariants.push_back(N);
3602 // Look up interesting info about the node.
3603 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
3605 // If this node is associative, re-associate.
3606 if (NodeInfo.hasProperty(SDNPAssociative)) {
3607 // Re-associate by pulling together all of the linked operators
3608 std::vector<TreePatternNode*> MaximalChildren;
3609 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
3611 // Only handle child sizes of 3. Otherwise we'll end up trying too many
3613 if (MaximalChildren.size() == 3) {
3614 // Find the variants of all of our maximal children.
3615 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
3616 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
3617 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
3618 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
3620 // There are only two ways we can permute the tree:
3621 // (A op B) op C and A op (B op C)
3622 // Within these forms, we can also permute A/B/C.
3624 // Generate legal pair permutations of A/B/C.
3625 std::vector<TreePatternNode*> ABVariants;
3626 std::vector<TreePatternNode*> BAVariants;
3627 std::vector<TreePatternNode*> ACVariants;
3628 std::vector<TreePatternNode*> CAVariants;
3629 std::vector<TreePatternNode*> BCVariants;
3630 std::vector<TreePatternNode*> CBVariants;
3631 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
3632 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
3633 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
3634 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
3635 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
3636 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
3638 // Combine those into the result: (x op x) op x
3639 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
3640 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
3641 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
3642 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
3643 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
3644 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
3646 // Combine those into the result: x op (x op x)
3647 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
3648 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
3649 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
3650 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
3651 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
3652 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
3657 // Compute permutations of all children.
3658 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3659 ChildVariants.resize(N->getNumChildren());
3660 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3661 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
3663 // Build all permutations based on how the children were formed.
3664 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
3666 // If this node is commutative, consider the commuted order.
3667 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
3668 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
3669 assert((N->getNumChildren()==2 || isCommIntrinsic) &&
3670 "Commutative but doesn't have 2 children!");
3671 // Don't count children which are actually register references.
3673 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
3674 TreePatternNode *Child = N->getChild(i);
3675 if (Child->isLeaf())
3676 if (DefInit *DI = dyn_cast<DefInit>(Child->getLeafValue())) {
3677 Record *RR = DI->getDef();
3678 if (RR->isSubClassOf("Register"))
3683 // Consider the commuted order.
3684 if (isCommIntrinsic) {
3685 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
3686 // operands are the commutative operands, and there might be more operands
3689 "Commutative intrinsic should have at least 3 children!");
3690 std::vector<std::vector<TreePatternNode*> > Variants;
3691 Variants.push_back(ChildVariants[0]); // Intrinsic id.
3692 Variants.push_back(ChildVariants[2]);
3693 Variants.push_back(ChildVariants[1]);
3694 for (unsigned i = 3; i != NC; ++i)
3695 Variants.push_back(ChildVariants[i]);
3696 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
3698 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
3699 OutVariants, CDP, DepVars);
3704 // GenerateVariants - Generate variants. For example, commutative patterns can
3705 // match multiple ways. Add them to PatternsToMatch as well.
3706 void CodeGenDAGPatterns::GenerateVariants() {
3707 DEBUG(errs() << "Generating instruction variants.\n");
3709 // Loop over all of the patterns we've collected, checking to see if we can
3710 // generate variants of the instruction, through the exploitation of
3711 // identities. This permits the target to provide aggressive matching without
3712 // the .td file having to contain tons of variants of instructions.
3714 // Note that this loop adds new patterns to the PatternsToMatch list, but we
3715 // intentionally do not reconsider these. Any variants of added patterns have
3716 // already been added.
3718 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
3719 MultipleUseVarSet DepVars;
3720 std::vector<TreePatternNode*> Variants;
3721 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
3722 DEBUG(errs() << "Dependent/multiply used variables: ");
3723 DEBUG(DumpDepVars(DepVars));
3724 DEBUG(errs() << "\n");
3725 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this,
3728 assert(!Variants.empty() && "Must create at least original variant!");
3729 Variants.erase(Variants.begin()); // Remove the original pattern.
3731 if (Variants.empty()) // No variants for this pattern.
3734 DEBUG(errs() << "FOUND VARIANTS OF: ";
3735 PatternsToMatch[i].getSrcPattern()->dump();
3738 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
3739 TreePatternNode *Variant = Variants[v];
3741 DEBUG(errs() << " VAR#" << v << ": ";
3745 // Scan to see if an instruction or explicit pattern already matches this.
3746 bool AlreadyExists = false;
3747 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
3748 // Skip if the top level predicates do not match.
3749 if (PatternsToMatch[i].getPredicates() !=
3750 PatternsToMatch[p].getPredicates())
3752 // Check to see if this variant already exists.
3753 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),
3755 DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
3756 AlreadyExists = true;
3760 // If we already have it, ignore the variant.
3761 if (AlreadyExists) continue;
3763 // Otherwise, add it to the list of patterns we have.
3764 PatternsToMatch.emplace_back(
3765 PatternsToMatch[i].getSrcRecord(), PatternsToMatch[i].getPredicates(),
3766 Variant, PatternsToMatch[i].getDstPattern(),
3767 PatternsToMatch[i].getDstRegs(),
3768 PatternsToMatch[i].getAddedComplexity(), Record::getNewUID());
3771 DEBUG(errs() << "\n");