1 //===- CodeGenDAGPatterns.cpp - Read DAG patterns from .td file -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the CodeGenDAGPatterns class, which is used to read and
11 // represent the patterns present in a .td file for instructions.
13 //===----------------------------------------------------------------------===//
15 #include "CodeGenDAGPatterns.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/ADT/Twine.h"
19 #include "llvm/Support/Debug.h"
20 #include "llvm/Support/ErrorHandling.h"
21 #include "llvm/TableGen/Error.h"
22 #include "llvm/TableGen/Record.h"
28 #define DEBUG_TYPE "dag-patterns"
30 //===----------------------------------------------------------------------===//
31 // EEVT::TypeSet Implementation
32 //===----------------------------------------------------------------------===//
34 static inline bool isInteger(MVT::SimpleValueType VT) {
35 return MVT(VT).isInteger();
37 static inline bool isFloatingPoint(MVT::SimpleValueType VT) {
38 return MVT(VT).isFloatingPoint();
40 static inline bool isVector(MVT::SimpleValueType VT) {
41 return MVT(VT).isVector();
43 static inline bool isScalar(MVT::SimpleValueType VT) {
44 return !MVT(VT).isVector();
47 EEVT::TypeSet::TypeSet(MVT::SimpleValueType VT, TreePattern &TP) {
50 else if (VT == MVT::fAny)
51 EnforceFloatingPoint(TP);
52 else if (VT == MVT::vAny)
55 assert((VT < MVT::LAST_VALUETYPE || VT == MVT::iPTR ||
56 VT == MVT::iPTRAny || VT == MVT::Any) && "Not a concrete type!");
57 TypeVec.push_back(VT);
62 EEVT::TypeSet::TypeSet(ArrayRef<MVT::SimpleValueType> VTList) {
63 assert(!VTList.empty() && "empty list?");
64 TypeVec.append(VTList.begin(), VTList.end());
67 assert(VTList[0] != MVT::iAny && VTList[0] != MVT::vAny &&
68 VTList[0] != MVT::fAny);
70 // Verify no duplicates.
71 array_pod_sort(TypeVec.begin(), TypeVec.end());
72 assert(std::unique(TypeVec.begin(), TypeVec.end()) == TypeVec.end());
75 /// FillWithPossibleTypes - Set to all legal types and return true, only valid
76 /// on completely unknown type sets.
77 bool EEVT::TypeSet::FillWithPossibleTypes(TreePattern &TP,
78 bool (*Pred)(MVT::SimpleValueType),
79 const char *PredicateName) {
80 assert(isCompletelyUnknown());
81 ArrayRef<MVT::SimpleValueType> LegalTypes =
82 TP.getDAGPatterns().getTargetInfo().getLegalValueTypes();
87 for (MVT::SimpleValueType VT : LegalTypes)
88 if (!Pred || Pred(VT))
89 TypeVec.push_back(VT);
91 // If we have nothing that matches the predicate, bail out.
92 if (TypeVec.empty()) {
93 TP.error("Type inference contradiction found, no " +
94 std::string(PredicateName) + " types found");
97 // No need to sort with one element.
98 if (TypeVec.size() == 1) return true;
100 // Remove duplicates.
101 array_pod_sort(TypeVec.begin(), TypeVec.end());
102 TypeVec.erase(std::unique(TypeVec.begin(), TypeVec.end()), TypeVec.end());
107 /// hasIntegerTypes - Return true if this TypeSet contains iAny or an
108 /// integer value type.
109 bool EEVT::TypeSet::hasIntegerTypes() const {
110 return std::any_of(TypeVec.begin(), TypeVec.end(), isInteger);
113 /// hasFloatingPointTypes - Return true if this TypeSet contains an fAny or
114 /// a floating point value type.
115 bool EEVT::TypeSet::hasFloatingPointTypes() const {
116 return std::any_of(TypeVec.begin(), TypeVec.end(), isFloatingPoint);
119 /// hasScalarTypes - Return true if this TypeSet contains a scalar value type.
120 bool EEVT::TypeSet::hasScalarTypes() const {
121 return std::any_of(TypeVec.begin(), TypeVec.end(), isScalar);
124 /// hasVectorTypes - Return true if this TypeSet contains a vAny or a vector
126 bool EEVT::TypeSet::hasVectorTypes() const {
127 return std::any_of(TypeVec.begin(), TypeVec.end(), isVector);
131 std::string EEVT::TypeSet::getName() const {
132 if (TypeVec.empty()) return "<empty>";
136 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i) {
137 std::string VTName = llvm::getEnumName(TypeVec[i]);
138 // Strip off MVT:: prefix if present.
139 if (VTName.substr(0,5) == "MVT::")
140 VTName = VTName.substr(5);
141 if (i) Result += ':';
145 if (TypeVec.size() == 1)
147 return "{" + Result + "}";
150 /// MergeInTypeInfo - This merges in type information from the specified
151 /// argument. If 'this' changes, it returns true. If the two types are
152 /// contradictory (e.g. merge f32 into i32) then this flags an error.
153 bool EEVT::TypeSet::MergeInTypeInfo(const EEVT::TypeSet &InVT, TreePattern &TP){
154 if (InVT.isCompletelyUnknown() || *this == InVT || TP.hasError())
157 if (isCompletelyUnknown()) {
162 assert(!TypeVec.empty() && !InVT.TypeVec.empty() && "No unknowns");
164 // Handle the abstract cases, seeing if we can resolve them better.
165 switch (TypeVec[0]) {
169 if (InVT.hasIntegerTypes()) {
170 EEVT::TypeSet InCopy(InVT);
171 InCopy.EnforceInteger(TP);
172 InCopy.EnforceScalar(TP);
174 if (InCopy.isConcrete()) {
175 // If the RHS has one integer type, upgrade iPTR to i32.
176 TypeVec[0] = InVT.TypeVec[0];
180 // If the input has multiple scalar integers, this doesn't add any info.
181 if (!InCopy.isCompletelyUnknown())
187 // If the input constraint is iAny/iPTR and this is an integer type list,
188 // remove non-integer types from the list.
189 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
191 bool MadeChange = EnforceInteger(TP);
193 // If we're merging in iPTR/iPTRAny and the node currently has a list of
194 // multiple different integer types, replace them with a single iPTR.
195 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
196 TypeVec.size() != 1) {
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");
237 if (!hasFloatingPointTypes())
240 TypeSet InputSet(*this);
242 // Filter out all the fp types.
243 TypeVec.erase(std::remove_if(TypeVec.begin(), TypeVec.end(),
244 std::not1(std::ptr_fun(isInteger))),
247 if (TypeVec.empty()) {
248 TP.error("Type inference contradiction found, '" +
249 InputSet.getName() + "' needs to be integer");
255 /// EnforceFloatingPoint - Remove all integer types from this set.
256 bool EEVT::TypeSet::EnforceFloatingPoint(TreePattern &TP) {
259 // If we know nothing, then get the full set.
261 return FillWithPossibleTypes(TP, isFloatingPoint, "floating point");
263 if (!hasIntegerTypes())
266 TypeSet InputSet(*this);
268 // Filter out all the integer types.
269 TypeVec.erase(std::remove_if(TypeVec.begin(), TypeVec.end(),
270 std::not1(std::ptr_fun(isFloatingPoint))),
273 if (TypeVec.empty()) {
274 TP.error("Type inference contradiction found, '" +
275 InputSet.getName() + "' needs to be floating point");
281 /// EnforceScalar - Remove all vector types from this.
282 bool EEVT::TypeSet::EnforceScalar(TreePattern &TP) {
286 // If we know nothing, then get the full set.
288 return FillWithPossibleTypes(TP, isScalar, "scalar");
290 if (!hasVectorTypes())
293 TypeSet InputSet(*this);
295 // Filter out all the vector types.
296 TypeVec.erase(std::remove_if(TypeVec.begin(), TypeVec.end(),
297 std::not1(std::ptr_fun(isScalar))),
300 if (TypeVec.empty()) {
301 TP.error("Type inference contradiction found, '" +
302 InputSet.getName() + "' needs to be scalar");
308 /// EnforceVector - Remove all vector types from this.
309 bool EEVT::TypeSet::EnforceVector(TreePattern &TP) {
313 // If we know nothing, then get the full set.
315 return FillWithPossibleTypes(TP, isVector, "vector");
317 TypeSet InputSet(*this);
318 bool MadeChange = false;
320 // Filter out all the scalar types.
321 TypeVec.erase(std::remove_if(TypeVec.begin(), TypeVec.end(),
322 std::not1(std::ptr_fun(isVector))),
325 if (TypeVec.empty()) {
326 TP.error("Type inference contradiction found, '" +
327 InputSet.getName() + "' needs to be a vector");
335 /// EnforceSmallerThan - 'this' must be a smaller VT than Other. For vectors
336 /// this should be based on the element type. Update this and other based on
337 /// this information.
338 bool EEVT::TypeSet::EnforceSmallerThan(EEVT::TypeSet &Other, TreePattern &TP) {
342 // Both operands must be integer or FP, but we don't care which.
343 bool MadeChange = false;
345 if (isCompletelyUnknown())
346 MadeChange = FillWithPossibleTypes(TP);
348 if (Other.isCompletelyUnknown())
349 MadeChange = Other.FillWithPossibleTypes(TP);
351 // If one side is known to be integer or known to be FP but the other side has
352 // no information, get at least the type integrality info in there.
353 if (!hasFloatingPointTypes())
354 MadeChange |= Other.EnforceInteger(TP);
355 else if (!hasIntegerTypes())
356 MadeChange |= Other.EnforceFloatingPoint(TP);
357 if (!Other.hasFloatingPointTypes())
358 MadeChange |= EnforceInteger(TP);
359 else if (!Other.hasIntegerTypes())
360 MadeChange |= EnforceFloatingPoint(TP);
362 assert(!isCompletelyUnknown() && !Other.isCompletelyUnknown() &&
363 "Should have a type list now");
365 // If one contains vectors but the other doesn't pull vectors out.
366 if (!hasVectorTypes())
367 MadeChange |= Other.EnforceScalar(TP);
368 else if (!hasScalarTypes())
369 MadeChange |= Other.EnforceVector(TP);
370 if (!Other.hasVectorTypes())
371 MadeChange |= EnforceScalar(TP);
372 else if (!Other.hasScalarTypes())
373 MadeChange |= EnforceVector(TP);
375 // This code does not currently handle nodes which have multiple types,
376 // where some types are integer, and some are fp. Assert that this is not
378 assert(!(hasIntegerTypes() && hasFloatingPointTypes()) &&
379 !(Other.hasIntegerTypes() && Other.hasFloatingPointTypes()) &&
380 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
385 // Okay, find the smallest type from current set and remove anything the
386 // same or smaller from the other set. We need to ensure that the scalar
387 // type size is smaller than the scalar size of the smallest type. For
388 // vectors, we also need to make sure that the total size is no larger than
389 // the size of the smallest type.
390 TypeSet InputSet(Other);
391 MVT Smallest = TypeVec[0];
392 for (unsigned i = 0; i != Other.TypeVec.size(); ++i) {
393 MVT OtherVT = Other.TypeVec[i];
394 // Don't compare vector and non-vector types.
395 if (OtherVT.isVector() != Smallest.isVector())
397 // The getSizeInBits() check here is only needed for vectors, but is
398 // a subset of the scalar check for scalars so no need to qualify.
399 if (OtherVT.getScalarSizeInBits() <= Smallest.getScalarSizeInBits() ||
400 OtherVT.getSizeInBits() < Smallest.getSizeInBits()) {
401 Other.TypeVec.erase(Other.TypeVec.begin()+i--);
406 if (Other.TypeVec.empty()) {
407 TP.error("Type inference contradiction found, '" + InputSet.getName() +
408 "' has nothing larger than '" + getName() +"'!");
412 // Okay, find the largest type from the other set and remove anything the
413 // same or smaller from the current set. We need to ensure that the scalar
414 // type size is larger than the scalar size of the largest type. For
415 // vectors, we also need to make sure that the total size is no smaller than
416 // the size of the largest type.
417 InputSet = TypeSet(*this);
418 MVT Largest = Other.TypeVec[Other.TypeVec.size()-1];
419 for (unsigned i = 0; i != TypeVec.size(); ++i) {
420 MVT OtherVT = TypeVec[i];
421 // Don't compare vector and non-vector types.
422 if (OtherVT.isVector() != Largest.isVector())
424 // The getSizeInBits() check here is only needed for vectors, but is
425 // a subset of the scalar check for scalars so no need to qualify.
426 if (OtherVT.getScalarSizeInBits() >= Largest.getScalarSizeInBits() ||
427 OtherVT.getSizeInBits() > Largest.getSizeInBits()) {
428 TypeVec.erase(TypeVec.begin()+i--);
433 if (TypeVec.empty()) {
434 TP.error("Type inference contradiction found, '" + InputSet.getName() +
435 "' has nothing smaller than '" + Other.getName() +"'!");
442 /// EnforceVectorEltTypeIs - 'this' is now constrained to be a vector type
443 /// whose element is specified by VTOperand.
444 bool EEVT::TypeSet::EnforceVectorEltTypeIs(MVT::SimpleValueType VT,
446 bool MadeChange = false;
448 MadeChange |= EnforceVector(TP);
450 TypeSet InputSet(*this);
452 // Filter out all the types which don't have the right element type.
453 for (unsigned i = 0; i != TypeVec.size(); ++i) {
454 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
455 if (MVT(TypeVec[i]).getVectorElementType().SimpleTy != VT) {
456 TypeVec.erase(TypeVec.begin()+i--);
461 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
462 TP.error("Type inference contradiction found, forcing '" +
463 InputSet.getName() + "' to have a vector element");
470 /// EnforceVectorEltTypeIs - 'this' is now constrained to be a vector type
471 /// whose element is specified by VTOperand.
472 bool EEVT::TypeSet::EnforceVectorEltTypeIs(EEVT::TypeSet &VTOperand,
477 // "This" must be a vector and "VTOperand" must be a scalar.
478 bool MadeChange = false;
479 MadeChange |= EnforceVector(TP);
480 MadeChange |= VTOperand.EnforceScalar(TP);
482 // If we know the vector type, it forces the scalar to agree.
484 MVT IVT = getConcrete();
485 IVT = IVT.getVectorElementType();
487 VTOperand.MergeInTypeInfo(IVT.SimpleTy, TP);
490 // If the scalar type is known, filter out vector types whose element types
492 if (!VTOperand.isConcrete())
495 MVT::SimpleValueType VT = VTOperand.getConcrete();
497 TypeSet InputSet(*this);
499 // Filter out all the types which don't have the right element type.
500 for (unsigned i = 0; i != TypeVec.size(); ++i) {
501 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
502 if (MVT(TypeVec[i]).getVectorElementType().SimpleTy != VT) {
503 TypeVec.erase(TypeVec.begin()+i--);
508 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
509 TP.error("Type inference contradiction found, forcing '" +
510 InputSet.getName() + "' to have a vector element");
516 /// EnforceVectorSubVectorTypeIs - 'this' is now constrained to be a
517 /// vector type specified by VTOperand.
518 bool EEVT::TypeSet::EnforceVectorSubVectorTypeIs(EEVT::TypeSet &VTOperand,
523 // "This" must be a vector and "VTOperand" must be a vector.
524 bool MadeChange = false;
525 MadeChange |= EnforceVector(TP);
526 MadeChange |= VTOperand.EnforceVector(TP);
528 // If one side is known to be integer or known to be FP but the other side has
529 // no information, get at least the type integrality info in there.
530 if (!hasFloatingPointTypes())
531 MadeChange |= VTOperand.EnforceInteger(TP);
532 else if (!hasIntegerTypes())
533 MadeChange |= VTOperand.EnforceFloatingPoint(TP);
534 if (!VTOperand.hasFloatingPointTypes())
535 MadeChange |= EnforceInteger(TP);
536 else if (!VTOperand.hasIntegerTypes())
537 MadeChange |= EnforceFloatingPoint(TP);
539 assert(!isCompletelyUnknown() && !VTOperand.isCompletelyUnknown() &&
540 "Should have a type list now");
542 // If we know the vector type, it forces the scalar types to agree.
543 // Also force one vector to have more elements than the other.
545 MVT IVT = getConcrete();
546 unsigned NumElems = IVT.getVectorNumElements();
547 IVT = IVT.getVectorElementType();
549 EEVT::TypeSet EltTypeSet(IVT.SimpleTy, TP);
550 MadeChange |= VTOperand.EnforceVectorEltTypeIs(EltTypeSet, TP);
552 // Only keep types that have less elements than VTOperand.
553 TypeSet InputSet(VTOperand);
555 for (unsigned i = 0; i != VTOperand.TypeVec.size(); ++i) {
556 assert(isVector(VTOperand.TypeVec[i]) && "EnforceVector didn't work");
557 if (MVT(VTOperand.TypeVec[i]).getVectorNumElements() >= NumElems) {
558 VTOperand.TypeVec.erase(VTOperand.TypeVec.begin()+i--);
562 if (VTOperand.TypeVec.empty()) { // FIXME: Really want an SMLoc here!
563 TP.error("Type inference contradiction found, forcing '" +
564 InputSet.getName() + "' to have less vector elements than '" +
568 } else if (VTOperand.isConcrete()) {
569 MVT IVT = VTOperand.getConcrete();
570 unsigned NumElems = IVT.getVectorNumElements();
571 IVT = IVT.getVectorElementType();
573 EEVT::TypeSet EltTypeSet(IVT.SimpleTy, TP);
574 MadeChange |= EnforceVectorEltTypeIs(EltTypeSet, TP);
576 // Only keep types that have more elements than 'this'.
577 TypeSet InputSet(*this);
579 for (unsigned i = 0; i != TypeVec.size(); ++i) {
580 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
581 if (MVT(TypeVec[i]).getVectorNumElements() <= NumElems) {
582 TypeVec.erase(TypeVec.begin()+i--);
586 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
587 TP.error("Type inference contradiction found, forcing '" +
588 InputSet.getName() + "' to have more vector elements than '" +
589 VTOperand.getName() + "'");
597 /// EnforceVectorSameNumElts - 'this' is now constrained to
598 /// be a vector with same num elements as VTOperand.
599 bool EEVT::TypeSet::EnforceVectorSameNumElts(EEVT::TypeSet &VTOperand,
604 // "This" must be a vector and "VTOperand" must be a vector.
605 bool MadeChange = false;
606 MadeChange |= EnforceVector(TP);
607 MadeChange |= VTOperand.EnforceVector(TP);
609 // If we know one of the vector types, it forces the other type to agree.
611 MVT IVT = getConcrete();
612 unsigned NumElems = IVT.getVectorNumElements();
614 // Only keep types that have same elements as VTOperand.
615 TypeSet InputSet(VTOperand);
617 for (unsigned i = 0; i != VTOperand.TypeVec.size(); ++i) {
618 assert(isVector(VTOperand.TypeVec[i]) && "EnforceVector didn't work");
619 if (MVT(VTOperand.TypeVec[i]).getVectorNumElements() != NumElems) {
620 VTOperand.TypeVec.erase(VTOperand.TypeVec.begin()+i--);
624 if (VTOperand.TypeVec.empty()) { // FIXME: Really want an SMLoc here!
625 TP.error("Type inference contradiction found, forcing '" +
626 InputSet.getName() + "' to have same number elements as '" +
630 } else if (VTOperand.isConcrete()) {
631 MVT IVT = VTOperand.getConcrete();
632 unsigned NumElems = IVT.getVectorNumElements();
634 // Only keep types that have same elements as 'this'.
635 TypeSet InputSet(*this);
637 for (unsigned i = 0; i != TypeVec.size(); ++i) {
638 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
639 if (MVT(TypeVec[i]).getVectorNumElements() != NumElems) {
640 TypeVec.erase(TypeVec.begin()+i--);
644 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
645 TP.error("Type inference contradiction found, forcing '" +
646 InputSet.getName() + "' to have same number elements than '" +
647 VTOperand.getName() + "'");
655 //===----------------------------------------------------------------------===//
656 // Helpers for working with extended types.
658 /// Dependent variable map for CodeGenDAGPattern variant generation
659 typedef std::map<std::string, int> DepVarMap;
661 static void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
663 if (isa<DefInit>(N->getLeafValue()))
664 DepMap[N->getName()]++;
666 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
667 FindDepVarsOf(N->getChild(i), DepMap);
671 /// Find dependent variables within child patterns
672 static void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
674 FindDepVarsOf(N, depcounts);
675 for (const std::pair<std::string, int> &Pair : depcounts) {
677 DepVars.insert(Pair.first);
682 /// Dump the dependent variable set:
683 static void DumpDepVars(MultipleUseVarSet &DepVars) {
684 if (DepVars.empty()) {
685 DEBUG(errs() << "<empty set>");
687 DEBUG(errs() << "[ ");
688 for (const std::string &DepVar : DepVars) {
689 DEBUG(errs() << DepVar << " ");
691 DEBUG(errs() << "]");
697 //===----------------------------------------------------------------------===//
698 // TreePredicateFn Implementation
699 //===----------------------------------------------------------------------===//
701 /// TreePredicateFn constructor. Here 'N' is a subclass of PatFrag.
702 TreePredicateFn::TreePredicateFn(TreePattern *N) : PatFragRec(N) {
703 assert((getPredCode().empty() || getImmCode().empty()) &&
704 ".td file corrupt: can't have a node predicate *and* an imm predicate");
707 std::string TreePredicateFn::getPredCode() const {
708 return PatFragRec->getRecord()->getValueAsString("PredicateCode");
711 std::string TreePredicateFn::getImmCode() const {
712 return PatFragRec->getRecord()->getValueAsString("ImmediateCode");
716 /// isAlwaysTrue - Return true if this is a noop predicate.
717 bool TreePredicateFn::isAlwaysTrue() const {
718 return getPredCode().empty() && getImmCode().empty();
721 /// Return the name to use in the generated code to reference this, this is
722 /// "Predicate_foo" if from a pattern fragment "foo".
723 std::string TreePredicateFn::getFnName() const {
724 return "Predicate_" + PatFragRec->getRecord()->getName();
727 /// getCodeToRunOnSDNode - Return the code for the function body that
728 /// evaluates this predicate. The argument is expected to be in "Node",
729 /// not N. This handles casting and conversion to a concrete node type as
731 std::string TreePredicateFn::getCodeToRunOnSDNode() const {
732 // Handle immediate predicates first.
733 std::string ImmCode = getImmCode();
734 if (!ImmCode.empty()) {
736 " int64_t Imm = cast<ConstantSDNode>(Node)->getSExtValue();\n";
737 return Result + ImmCode;
740 // Handle arbitrary node predicates.
741 assert(!getPredCode().empty() && "Don't have any predicate code!");
742 std::string ClassName;
743 if (PatFragRec->getOnlyTree()->isLeaf())
744 ClassName = "SDNode";
746 Record *Op = PatFragRec->getOnlyTree()->getOperator();
747 ClassName = PatFragRec->getDAGPatterns().getSDNodeInfo(Op).getSDClassName();
750 if (ClassName == "SDNode")
751 Result = " SDNode *N = Node;\n";
753 Result = " auto *N = cast<" + ClassName + ">(Node);\n";
755 return Result + getPredCode();
758 //===----------------------------------------------------------------------===//
759 // PatternToMatch implementation
763 /// getPatternSize - Return the 'size' of this pattern. We want to match large
764 /// patterns before small ones. This is used to determine the size of a
766 static unsigned getPatternSize(const TreePatternNode *P,
767 const CodeGenDAGPatterns &CGP) {
768 unsigned Size = 3; // The node itself.
769 // If the root node is a ConstantSDNode, increases its size.
770 // e.g. (set R32:$dst, 0).
771 if (P->isLeaf() && isa<IntInit>(P->getLeafValue()))
774 // FIXME: This is a hack to statically increase the priority of patterns
775 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
776 // Later we can allow complexity / cost for each pattern to be (optionally)
777 // specified. To get best possible pattern match we'll need to dynamically
778 // calculate the complexity of all patterns a dag can potentially map to.
779 const ComplexPattern *AM = P->getComplexPatternInfo(CGP);
781 Size += AM->getNumOperands() * 3;
783 // We don't want to count any children twice, so return early.
787 // If this node has some predicate function that must match, it adds to the
788 // complexity of this node.
789 if (!P->getPredicateFns().empty())
792 // Count children in the count if they are also nodes.
793 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
794 TreePatternNode *Child = P->getChild(i);
795 if (!Child->isLeaf() && Child->getNumTypes() &&
796 Child->getType(0) != MVT::Other)
797 Size += getPatternSize(Child, CGP);
798 else if (Child->isLeaf()) {
799 if (isa<IntInit>(Child->getLeafValue()))
800 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
801 else if (Child->getComplexPatternInfo(CGP))
802 Size += getPatternSize(Child, CGP);
803 else if (!Child->getPredicateFns().empty())
811 /// Compute the complexity metric for the input pattern. This roughly
812 /// corresponds to the number of nodes that are covered.
814 getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
815 return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();
819 /// getPredicateCheck - Return a single string containing all of this
820 /// pattern's predicates concatenated with "&&" operators.
822 std::string PatternToMatch::getPredicateCheck() const {
823 std::string PredicateCheck;
824 for (Init *I : Predicates->getValues()) {
825 if (DefInit *Pred = dyn_cast<DefInit>(I)) {
826 Record *Def = Pred->getDef();
827 if (!Def->isSubClassOf("Predicate")) {
831 llvm_unreachable("Unknown predicate type!");
833 if (!PredicateCheck.empty())
834 PredicateCheck += " && ";
835 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
839 return PredicateCheck;
842 //===----------------------------------------------------------------------===//
843 // SDTypeConstraint implementation
846 SDTypeConstraint::SDTypeConstraint(Record *R) {
847 OperandNo = R->getValueAsInt("OperandNum");
849 if (R->isSubClassOf("SDTCisVT")) {
850 ConstraintType = SDTCisVT;
851 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
852 if (x.SDTCisVT_Info.VT == MVT::isVoid)
853 PrintFatalError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
855 } else if (R->isSubClassOf("SDTCisPtrTy")) {
856 ConstraintType = SDTCisPtrTy;
857 } else if (R->isSubClassOf("SDTCisInt")) {
858 ConstraintType = SDTCisInt;
859 } else if (R->isSubClassOf("SDTCisFP")) {
860 ConstraintType = SDTCisFP;
861 } else if (R->isSubClassOf("SDTCisVec")) {
862 ConstraintType = SDTCisVec;
863 } else if (R->isSubClassOf("SDTCisSameAs")) {
864 ConstraintType = SDTCisSameAs;
865 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
866 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
867 ConstraintType = SDTCisVTSmallerThanOp;
868 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
869 R->getValueAsInt("OtherOperandNum");
870 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
871 ConstraintType = SDTCisOpSmallerThanOp;
872 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
873 R->getValueAsInt("BigOperandNum");
874 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
875 ConstraintType = SDTCisEltOfVec;
876 x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
877 } else if (R->isSubClassOf("SDTCisSubVecOfVec")) {
878 ConstraintType = SDTCisSubVecOfVec;
879 x.SDTCisSubVecOfVec_Info.OtherOperandNum =
880 R->getValueAsInt("OtherOpNum");
881 } else if (R->isSubClassOf("SDTCVecEltisVT")) {
882 ConstraintType = SDTCVecEltisVT;
883 x.SDTCVecEltisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
884 if (MVT(x.SDTCVecEltisVT_Info.VT).isVector())
885 PrintFatalError(R->getLoc(), "Cannot use vector type as SDTCVecEltisVT");
886 if (!MVT(x.SDTCVecEltisVT_Info.VT).isInteger() &&
887 !MVT(x.SDTCVecEltisVT_Info.VT).isFloatingPoint())
888 PrintFatalError(R->getLoc(), "Must use integer or floating point type "
889 "as SDTCVecEltisVT");
890 } else if (R->isSubClassOf("SDTCisSameNumEltsAs")) {
891 ConstraintType = SDTCisSameNumEltsAs;
892 x.SDTCisSameNumEltsAs_Info.OtherOperandNum =
893 R->getValueAsInt("OtherOperandNum");
895 PrintFatalError("Unrecognized SDTypeConstraint '" + R->getName() + "'!\n");
899 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
900 /// N, and the result number in ResNo.
901 static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
902 const SDNodeInfo &NodeInfo,
904 unsigned NumResults = NodeInfo.getNumResults();
905 if (OpNo < NumResults) {
912 if (OpNo >= N->getNumChildren()) {
914 raw_string_ostream OS(S);
915 OS << "Invalid operand number in type constraint "
916 << (OpNo+NumResults) << " ";
918 PrintFatalError(OS.str());
921 return N->getChild(OpNo);
924 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
925 /// constraint to the nodes operands. This returns true if it makes a
926 /// change, false otherwise. If a type contradiction is found, flag an error.
927 bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
928 const SDNodeInfo &NodeInfo,
929 TreePattern &TP) const {
933 unsigned ResNo = 0; // The result number being referenced.
934 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
936 switch (ConstraintType) {
938 // Operand must be a particular type.
939 return NodeToApply->UpdateNodeType(ResNo, x.SDTCisVT_Info.VT, TP);
941 // Operand must be same as target pointer type.
942 return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
944 // Require it to be one of the legal integer VTs.
945 return NodeToApply->getExtType(ResNo).EnforceInteger(TP);
947 // Require it to be one of the legal fp VTs.
948 return NodeToApply->getExtType(ResNo).EnforceFloatingPoint(TP);
950 // Require it to be one of the legal vector VTs.
951 return NodeToApply->getExtType(ResNo).EnforceVector(TP);
954 TreePatternNode *OtherNode =
955 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
956 return NodeToApply->UpdateNodeType(ResNo, OtherNode->getExtType(OResNo),TP)|
957 OtherNode->UpdateNodeType(OResNo,NodeToApply->getExtType(ResNo),TP);
959 case SDTCisVTSmallerThanOp: {
960 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
961 // have an integer type that is smaller than the VT.
962 if (!NodeToApply->isLeaf() ||
963 !isa<DefInit>(NodeToApply->getLeafValue()) ||
964 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
965 ->isSubClassOf("ValueType")) {
966 TP.error(N->getOperator()->getName() + " expects a VT operand!");
969 MVT::SimpleValueType VT =
970 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
972 EEVT::TypeSet TypeListTmp(VT, TP);
975 TreePatternNode *OtherNode =
976 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
979 return TypeListTmp.EnforceSmallerThan(OtherNode->getExtType(OResNo), TP);
981 case SDTCisOpSmallerThanOp: {
983 TreePatternNode *BigOperand =
984 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
986 return NodeToApply->getExtType(ResNo).
987 EnforceSmallerThan(BigOperand->getExtType(BResNo), TP);
989 case SDTCisEltOfVec: {
991 TreePatternNode *VecOperand =
992 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
995 // Filter vector types out of VecOperand that don't have the right element
997 return VecOperand->getExtType(VResNo).
998 EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), TP);
1000 case SDTCisSubVecOfVec: {
1001 unsigned VResNo = 0;
1002 TreePatternNode *BigVecOperand =
1003 getOperandNum(x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo,
1006 // Filter vector types out of BigVecOperand that don't have the
1007 // right subvector type.
1008 return BigVecOperand->getExtType(VResNo).
1009 EnforceVectorSubVectorTypeIs(NodeToApply->getExtType(ResNo), TP);
1011 case SDTCVecEltisVT: {
1012 return NodeToApply->getExtType(ResNo).
1013 EnforceVectorEltTypeIs(x.SDTCVecEltisVT_Info.VT, TP);
1015 case SDTCisSameNumEltsAs: {
1016 unsigned OResNo = 0;
1017 TreePatternNode *OtherNode =
1018 getOperandNum(x.SDTCisSameNumEltsAs_Info.OtherOperandNum,
1019 N, NodeInfo, OResNo);
1020 return OtherNode->getExtType(OResNo).
1021 EnforceVectorSameNumElts(NodeToApply->getExtType(ResNo), TP);
1024 llvm_unreachable("Invalid ConstraintType!");
1027 // Update the node type to match an instruction operand or result as specified
1028 // in the ins or outs lists on the instruction definition. Return true if the
1029 // type was actually changed.
1030 bool TreePatternNode::UpdateNodeTypeFromInst(unsigned ResNo,
1033 // The 'unknown' operand indicates that types should be inferred from the
1035 if (Operand->isSubClassOf("unknown_class"))
1038 // The Operand class specifies a type directly.
1039 if (Operand->isSubClassOf("Operand"))
1040 return UpdateNodeType(ResNo, getValueType(Operand->getValueAsDef("Type")),
1043 // PointerLikeRegClass has a type that is determined at runtime.
1044 if (Operand->isSubClassOf("PointerLikeRegClass"))
1045 return UpdateNodeType(ResNo, MVT::iPTR, TP);
1047 // Both RegisterClass and RegisterOperand operands derive their types from a
1048 // register class def.
1049 Record *RC = nullptr;
1050 if (Operand->isSubClassOf("RegisterClass"))
1052 else if (Operand->isSubClassOf("RegisterOperand"))
1053 RC = Operand->getValueAsDef("RegClass");
1055 assert(RC && "Unknown operand type");
1056 CodeGenTarget &Tgt = TP.getDAGPatterns().getTargetInfo();
1057 return UpdateNodeType(ResNo, Tgt.getRegisterClass(RC).getValueTypes(), TP);
1061 //===----------------------------------------------------------------------===//
1062 // SDNodeInfo implementation
1064 SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
1065 EnumName = R->getValueAsString("Opcode");
1066 SDClassName = R->getValueAsString("SDClass");
1067 Record *TypeProfile = R->getValueAsDef("TypeProfile");
1068 NumResults = TypeProfile->getValueAsInt("NumResults");
1069 NumOperands = TypeProfile->getValueAsInt("NumOperands");
1071 // Parse the properties.
1073 for (Record *Property : R->getValueAsListOfDefs("Properties")) {
1074 if (Property->getName() == "SDNPCommutative") {
1075 Properties |= 1 << SDNPCommutative;
1076 } else if (Property->getName() == "SDNPAssociative") {
1077 Properties |= 1 << SDNPAssociative;
1078 } else if (Property->getName() == "SDNPHasChain") {
1079 Properties |= 1 << SDNPHasChain;
1080 } else if (Property->getName() == "SDNPOutGlue") {
1081 Properties |= 1 << SDNPOutGlue;
1082 } else if (Property->getName() == "SDNPInGlue") {
1083 Properties |= 1 << SDNPInGlue;
1084 } else if (Property->getName() == "SDNPOptInGlue") {
1085 Properties |= 1 << SDNPOptInGlue;
1086 } else if (Property->getName() == "SDNPMayStore") {
1087 Properties |= 1 << SDNPMayStore;
1088 } else if (Property->getName() == "SDNPMayLoad") {
1089 Properties |= 1 << SDNPMayLoad;
1090 } else if (Property->getName() == "SDNPSideEffect") {
1091 Properties |= 1 << SDNPSideEffect;
1092 } else if (Property->getName() == "SDNPMemOperand") {
1093 Properties |= 1 << SDNPMemOperand;
1094 } else if (Property->getName() == "SDNPVariadic") {
1095 Properties |= 1 << SDNPVariadic;
1097 PrintFatalError("Unknown SD Node property '" +
1098 Property->getName() + "' on node '" +
1099 R->getName() + "'!");
1104 // Parse the type constraints.
1105 std::vector<Record*> ConstraintList =
1106 TypeProfile->getValueAsListOfDefs("Constraints");
1107 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
1110 /// getKnownType - If the type constraints on this node imply a fixed type
1111 /// (e.g. all stores return void, etc), then return it as an
1112 /// MVT::SimpleValueType. Otherwise, return EEVT::Other.
1113 MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
1114 unsigned NumResults = getNumResults();
1115 assert(NumResults <= 1 &&
1116 "We only work with nodes with zero or one result so far!");
1117 assert(ResNo == 0 && "Only handles single result nodes so far");
1119 for (const SDTypeConstraint &Constraint : TypeConstraints) {
1120 // Make sure that this applies to the correct node result.
1121 if (Constraint.OperandNo >= NumResults) // FIXME: need value #
1124 switch (Constraint.ConstraintType) {
1126 case SDTypeConstraint::SDTCisVT:
1127 return Constraint.x.SDTCisVT_Info.VT;
1128 case SDTypeConstraint::SDTCisPtrTy:
1135 //===----------------------------------------------------------------------===//
1136 // TreePatternNode implementation
1139 TreePatternNode::~TreePatternNode() {
1140 #if 0 // FIXME: implement refcounted tree nodes!
1141 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1146 static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
1147 if (Operator->getName() == "set" ||
1148 Operator->getName() == "implicit")
1149 return 0; // All return nothing.
1151 if (Operator->isSubClassOf("Intrinsic"))
1152 return CDP.getIntrinsic(Operator).IS.RetVTs.size();
1154 if (Operator->isSubClassOf("SDNode"))
1155 return CDP.getSDNodeInfo(Operator).getNumResults();
1157 if (Operator->isSubClassOf("PatFrag")) {
1158 // If we've already parsed this pattern fragment, get it. Otherwise, handle
1159 // the forward reference case where one pattern fragment references another
1160 // before it is processed.
1161 if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator))
1162 return PFRec->getOnlyTree()->getNumTypes();
1164 // Get the result tree.
1165 DagInit *Tree = Operator->getValueAsDag("Fragment");
1166 Record *Op = nullptr;
1168 if (DefInit *DI = dyn_cast<DefInit>(Tree->getOperator()))
1170 assert(Op && "Invalid Fragment");
1171 return GetNumNodeResults(Op, CDP);
1174 if (Operator->isSubClassOf("Instruction")) {
1175 CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
1177 unsigned NumDefsToAdd = InstInfo.Operands.NumDefs;
1179 // Subtract any defaulted outputs.
1180 for (unsigned i = 0; i != InstInfo.Operands.NumDefs; ++i) {
1181 Record *OperandNode = InstInfo.Operands[i].Rec;
1183 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
1184 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1188 // Add on one implicit def if it has a resolvable type.
1189 if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
1191 return NumDefsToAdd;
1194 if (Operator->isSubClassOf("SDNodeXForm"))
1195 return 1; // FIXME: Generalize SDNodeXForm
1197 if (Operator->isSubClassOf("ValueType"))
1198 return 1; // A type-cast of one result.
1200 if (Operator->isSubClassOf("ComplexPattern"))
1204 PrintFatalError("Unhandled node in GetNumNodeResults");
1207 void TreePatternNode::print(raw_ostream &OS) const {
1209 OS << *getLeafValue();
1211 OS << '(' << getOperator()->getName();
1213 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1214 OS << ':' << getExtType(i).getName();
1217 if (getNumChildren() != 0) {
1219 getChild(0)->print(OS);
1220 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
1222 getChild(i)->print(OS);
1228 for (const TreePredicateFn &Pred : PredicateFns)
1229 OS << "<<P:" << Pred.getFnName() << ">>";
1231 OS << "<<X:" << TransformFn->getName() << ">>";
1232 if (!getName().empty())
1233 OS << ":$" << getName();
1236 void TreePatternNode::dump() const {
1240 /// isIsomorphicTo - Return true if this node is recursively
1241 /// isomorphic to the specified node. For this comparison, the node's
1242 /// entire state is considered. The assigned name is ignored, since
1243 /// nodes with differing names are considered isomorphic. However, if
1244 /// the assigned name is present in the dependent variable set, then
1245 /// the assigned name is considered significant and the node is
1246 /// isomorphic if the names match.
1247 bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
1248 const MultipleUseVarSet &DepVars) const {
1249 if (N == this) return true;
1250 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
1251 getPredicateFns() != N->getPredicateFns() ||
1252 getTransformFn() != N->getTransformFn())
1256 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
1257 if (DefInit *NDI = dyn_cast<DefInit>(N->getLeafValue())) {
1258 return ((DI->getDef() == NDI->getDef())
1259 && (DepVars.find(getName()) == DepVars.end()
1260 || getName() == N->getName()));
1263 return getLeafValue() == N->getLeafValue();
1266 if (N->getOperator() != getOperator() ||
1267 N->getNumChildren() != getNumChildren()) return false;
1268 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1269 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
1274 /// clone - Make a copy of this tree and all of its children.
1276 TreePatternNode *TreePatternNode::clone() const {
1277 TreePatternNode *New;
1279 New = new TreePatternNode(getLeafValue(), getNumTypes());
1281 std::vector<TreePatternNode*> CChildren;
1282 CChildren.reserve(Children.size());
1283 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1284 CChildren.push_back(getChild(i)->clone());
1285 New = new TreePatternNode(getOperator(), CChildren, getNumTypes());
1287 New->setName(getName());
1289 New->setPredicateFns(getPredicateFns());
1290 New->setTransformFn(getTransformFn());
1294 /// RemoveAllTypes - Recursively strip all the types of this tree.
1295 void TreePatternNode::RemoveAllTypes() {
1296 // Reset to unknown type.
1297 std::fill(Types.begin(), Types.end(), EEVT::TypeSet());
1298 if (isLeaf()) return;
1299 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1300 getChild(i)->RemoveAllTypes();
1304 /// SubstituteFormalArguments - Replace the formal arguments in this tree
1305 /// with actual values specified by ArgMap.
1306 void TreePatternNode::
1307 SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
1308 if (isLeaf()) return;
1310 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1311 TreePatternNode *Child = getChild(i);
1312 if (Child->isLeaf()) {
1313 Init *Val = Child->getLeafValue();
1314 // Note that, when substituting into an output pattern, Val might be an
1316 if (isa<UnsetInit>(Val) || (isa<DefInit>(Val) &&
1317 cast<DefInit>(Val)->getDef()->getName() == "node")) {
1318 // We found a use of a formal argument, replace it with its value.
1319 TreePatternNode *NewChild = ArgMap[Child->getName()];
1320 assert(NewChild && "Couldn't find formal argument!");
1321 assert((Child->getPredicateFns().empty() ||
1322 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1323 "Non-empty child predicate clobbered!");
1324 setChild(i, NewChild);
1327 getChild(i)->SubstituteFormalArguments(ArgMap);
1333 /// InlinePatternFragments - If this pattern refers to any pattern
1334 /// fragments, inline them into place, giving us a pattern without any
1335 /// PatFrag references.
1336 TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
1341 return this; // nothing to do.
1342 Record *Op = getOperator();
1344 if (!Op->isSubClassOf("PatFrag")) {
1345 // Just recursively inline children nodes.
1346 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1347 TreePatternNode *Child = getChild(i);
1348 TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
1350 assert((Child->getPredicateFns().empty() ||
1351 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1352 "Non-empty child predicate clobbered!");
1354 setChild(i, NewChild);
1359 // Otherwise, we found a reference to a fragment. First, look up its
1360 // TreePattern record.
1361 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
1363 // Verify that we are passing the right number of operands.
1364 if (Frag->getNumArgs() != Children.size()) {
1365 TP.error("'" + Op->getName() + "' fragment requires " +
1366 utostr(Frag->getNumArgs()) + " operands!");
1370 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
1372 TreePredicateFn PredFn(Frag);
1373 if (!PredFn.isAlwaysTrue())
1374 FragTree->addPredicateFn(PredFn);
1376 // Resolve formal arguments to their actual value.
1377 if (Frag->getNumArgs()) {
1378 // Compute the map of formal to actual arguments.
1379 std::map<std::string, TreePatternNode*> ArgMap;
1380 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
1381 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
1383 FragTree->SubstituteFormalArguments(ArgMap);
1386 FragTree->setName(getName());
1387 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1388 FragTree->UpdateNodeType(i, getExtType(i), TP);
1390 // Transfer in the old predicates.
1391 for (const TreePredicateFn &Pred : getPredicateFns())
1392 FragTree->addPredicateFn(Pred);
1394 // Get a new copy of this fragment to stitch into here.
1395 //delete this; // FIXME: implement refcounting!
1397 // The fragment we inlined could have recursive inlining that is needed. See
1398 // if there are any pattern fragments in it and inline them as needed.
1399 return FragTree->InlinePatternFragments(TP);
1402 /// getImplicitType - Check to see if the specified record has an implicit
1403 /// type which should be applied to it. This will infer the type of register
1404 /// references from the register file information, for example.
1406 /// When Unnamed is set, return the type of a DAG operand with no name, such as
1407 /// the F8RC register class argument in:
1409 /// (COPY_TO_REGCLASS GPR:$src, F8RC)
1411 /// When Unnamed is false, return the type of a named DAG operand such as the
1412 /// GPR:$src operand above.
1414 static EEVT::TypeSet getImplicitType(Record *R, unsigned ResNo,
1418 // Check to see if this is a register operand.
1419 if (R->isSubClassOf("RegisterOperand")) {
1420 assert(ResNo == 0 && "Regoperand ref only has one result!");
1422 return EEVT::TypeSet(); // Unknown.
1423 Record *RegClass = R->getValueAsDef("RegClass");
1424 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1425 return EEVT::TypeSet(T.getRegisterClass(RegClass).getValueTypes());
1428 // Check to see if this is a register or a register class.
1429 if (R->isSubClassOf("RegisterClass")) {
1430 assert(ResNo == 0 && "Regclass ref only has one result!");
1431 // An unnamed register class represents itself as an i32 immediate, for
1432 // example on a COPY_TO_REGCLASS instruction.
1434 return EEVT::TypeSet(MVT::i32, TP);
1436 // In a named operand, the register class provides the possible set of
1439 return EEVT::TypeSet(); // Unknown.
1440 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1441 return EEVT::TypeSet(T.getRegisterClass(R).getValueTypes());
1444 if (R->isSubClassOf("PatFrag")) {
1445 assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
1446 // Pattern fragment types will be resolved when they are inlined.
1447 return EEVT::TypeSet(); // Unknown.
1450 if (R->isSubClassOf("Register")) {
1451 assert(ResNo == 0 && "Registers only produce one result!");
1453 return EEVT::TypeSet(); // Unknown.
1454 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1455 return EEVT::TypeSet(T.getRegisterVTs(R));
1458 if (R->isSubClassOf("SubRegIndex")) {
1459 assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
1460 return EEVT::TypeSet(MVT::i32, TP);
1463 if (R->isSubClassOf("ValueType")) {
1464 assert(ResNo == 0 && "This node only has one result!");
1465 // An unnamed VTSDNode represents itself as an MVT::Other immediate.
1467 // (sext_inreg GPR:$src, i16)
1470 return EEVT::TypeSet(MVT::Other, TP);
1471 // With a name, the ValueType simply provides the type of the named
1474 // (sext_inreg i32:$src, i16)
1477 return EEVT::TypeSet(); // Unknown.
1478 return EEVT::TypeSet(getValueType(R), TP);
1481 if (R->isSubClassOf("CondCode")) {
1482 assert(ResNo == 0 && "This node only has one result!");
1483 // Using a CondCodeSDNode.
1484 return EEVT::TypeSet(MVT::Other, TP);
1487 if (R->isSubClassOf("ComplexPattern")) {
1488 assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
1490 return EEVT::TypeSet(); // Unknown.
1491 return EEVT::TypeSet(TP.getDAGPatterns().getComplexPattern(R).getValueType(),
1494 if (R->isSubClassOf("PointerLikeRegClass")) {
1495 assert(ResNo == 0 && "Regclass can only have one result!");
1496 return EEVT::TypeSet(MVT::iPTR, TP);
1499 if (R->getName() == "node" || R->getName() == "srcvalue" ||
1500 R->getName() == "zero_reg") {
1502 return EEVT::TypeSet(); // Unknown.
1505 if (R->isSubClassOf("Operand"))
1506 return EEVT::TypeSet(getValueType(R->getValueAsDef("Type")));
1508 TP.error("Unknown node flavor used in pattern: " + R->getName());
1509 return EEVT::TypeSet(MVT::Other, TP);
1513 /// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
1514 /// CodeGenIntrinsic information for it, otherwise return a null pointer.
1515 const CodeGenIntrinsic *TreePatternNode::
1516 getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
1517 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
1518 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
1519 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
1522 unsigned IID = cast<IntInit>(getChild(0)->getLeafValue())->getValue();
1523 return &CDP.getIntrinsicInfo(IID);
1526 /// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
1527 /// return the ComplexPattern information, otherwise return null.
1528 const ComplexPattern *
1529 TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
1532 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
1537 Rec = getOperator();
1539 if (!Rec->isSubClassOf("ComplexPattern"))
1541 return &CGP.getComplexPattern(Rec);
1544 unsigned TreePatternNode::getNumMIResults(const CodeGenDAGPatterns &CGP) const {
1545 // A ComplexPattern specifically declares how many results it fills in.
1546 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1547 return CP->getNumOperands();
1549 // If MIOperandInfo is specified, that gives the count.
1551 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
1552 if (DI && DI->getDef()->isSubClassOf("Operand")) {
1553 DagInit *MIOps = DI->getDef()->getValueAsDag("MIOperandInfo");
1554 if (MIOps->getNumArgs())
1555 return MIOps->getNumArgs();
1559 // Otherwise there is just one result.
1563 /// NodeHasProperty - Return true if this node has the specified property.
1564 bool TreePatternNode::NodeHasProperty(SDNP Property,
1565 const CodeGenDAGPatterns &CGP) const {
1567 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1568 return CP->hasProperty(Property);
1572 Record *Operator = getOperator();
1573 if (!Operator->isSubClassOf("SDNode")) return false;
1575 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
1581 /// TreeHasProperty - Return true if any node in this tree has the specified
1583 bool TreePatternNode::TreeHasProperty(SDNP Property,
1584 const CodeGenDAGPatterns &CGP) const {
1585 if (NodeHasProperty(Property, CGP))
1587 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1588 if (getChild(i)->TreeHasProperty(Property, CGP))
1593 /// isCommutativeIntrinsic - Return true if the node corresponds to a
1594 /// commutative intrinsic.
1596 TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
1597 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
1598 return Int->isCommutative;
1602 static bool isOperandClass(const TreePatternNode *N, StringRef Class) {
1604 return N->getOperator()->isSubClassOf(Class);
1606 DefInit *DI = dyn_cast<DefInit>(N->getLeafValue());
1607 if (DI && DI->getDef()->isSubClassOf(Class))
1613 static void emitTooManyOperandsError(TreePattern &TP,
1617 TP.error("Instruction '" + InstName + "' was provided " + Twine(Actual) +
1618 " operands but expected only " + Twine(Expected) + "!");
1621 static void emitTooFewOperandsError(TreePattern &TP,
1624 TP.error("Instruction '" + InstName +
1625 "' expects more than the provided " + Twine(Actual) + " operands!");
1628 /// ApplyTypeConstraints - Apply all of the type constraints relevant to
1629 /// this node and its children in the tree. This returns true if it makes a
1630 /// change, false otherwise. If a type contradiction is found, flag an error.
1631 bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
1635 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
1637 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
1638 // If it's a regclass or something else known, include the type.
1639 bool MadeChange = false;
1640 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1641 MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
1643 !hasName(), TP), TP);
1647 if (IntInit *II = dyn_cast<IntInit>(getLeafValue())) {
1648 assert(Types.size() == 1 && "Invalid IntInit");
1650 // Int inits are always integers. :)
1651 bool MadeChange = Types[0].EnforceInteger(TP);
1653 if (!Types[0].isConcrete())
1656 MVT::SimpleValueType VT = getType(0);
1657 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
1660 unsigned Size = MVT(VT).getSizeInBits();
1661 // Make sure that the value is representable for this type.
1662 if (Size >= 32) return MadeChange;
1664 // Check that the value doesn't use more bits than we have. It must either
1665 // be a sign- or zero-extended equivalent of the original.
1666 int64_t SignBitAndAbove = II->getValue() >> (Size - 1);
1667 if (SignBitAndAbove == -1 || SignBitAndAbove == 0 || SignBitAndAbove == 1)
1670 TP.error("Integer value '" + itostr(II->getValue()) +
1671 "' is out of range for type '" + getEnumName(getType(0)) + "'!");
1677 // special handling for set, which isn't really an SDNode.
1678 if (getOperator()->getName() == "set") {
1679 assert(getNumTypes() == 0 && "Set doesn't produce a value");
1680 assert(getNumChildren() >= 2 && "Missing RHS of a set?");
1681 unsigned NC = getNumChildren();
1683 TreePatternNode *SetVal = getChild(NC-1);
1684 bool MadeChange = SetVal->ApplyTypeConstraints(TP, NotRegisters);
1686 for (unsigned i = 0; i < NC-1; ++i) {
1687 TreePatternNode *Child = getChild(i);
1688 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
1690 // Types of operands must match.
1691 MadeChange |= Child->UpdateNodeType(0, SetVal->getExtType(i), TP);
1692 MadeChange |= SetVal->UpdateNodeType(i, Child->getExtType(0), TP);
1697 if (getOperator()->getName() == "implicit") {
1698 assert(getNumTypes() == 0 && "Node doesn't produce a value");
1700 bool MadeChange = false;
1701 for (unsigned i = 0; i < getNumChildren(); ++i)
1702 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1706 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
1707 bool MadeChange = false;
1709 // Apply the result type to the node.
1710 unsigned NumRetVTs = Int->IS.RetVTs.size();
1711 unsigned NumParamVTs = Int->IS.ParamVTs.size();
1713 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
1714 MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
1716 if (getNumChildren() != NumParamVTs + 1) {
1717 TP.error("Intrinsic '" + Int->Name + "' expects " +
1718 utostr(NumParamVTs) + " operands, not " +
1719 utostr(getNumChildren() - 1) + " operands!");
1723 // Apply type info to the intrinsic ID.
1724 MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
1726 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
1727 MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
1729 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
1730 assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
1731 MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
1736 if (getOperator()->isSubClassOf("SDNode")) {
1737 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
1739 // Check that the number of operands is sane. Negative operands -> varargs.
1740 if (NI.getNumOperands() >= 0 &&
1741 getNumChildren() != (unsigned)NI.getNumOperands()) {
1742 TP.error(getOperator()->getName() + " node requires exactly " +
1743 itostr(NI.getNumOperands()) + " operands!");
1747 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
1748 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1749 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1753 if (getOperator()->isSubClassOf("Instruction")) {
1754 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
1755 CodeGenInstruction &InstInfo =
1756 CDP.getTargetInfo().getInstruction(getOperator());
1758 bool MadeChange = false;
1760 // Apply the result types to the node, these come from the things in the
1761 // (outs) list of the instruction.
1762 unsigned NumResultsToAdd = std::min(InstInfo.Operands.NumDefs,
1763 Inst.getNumResults());
1764 for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo)
1765 MadeChange |= UpdateNodeTypeFromInst(ResNo, Inst.getResult(ResNo), TP);
1767 // If the instruction has implicit defs, we apply the first one as a result.
1768 // FIXME: This sucks, it should apply all implicit defs.
1769 if (!InstInfo.ImplicitDefs.empty()) {
1770 unsigned ResNo = NumResultsToAdd;
1772 // FIXME: Generalize to multiple possible types and multiple possible
1774 MVT::SimpleValueType VT =
1775 InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
1777 if (VT != MVT::Other)
1778 MadeChange |= UpdateNodeType(ResNo, VT, TP);
1781 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
1783 if (getOperator()->getName() == "INSERT_SUBREG") {
1784 assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
1785 MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
1786 MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
1787 } else if (getOperator()->getName() == "REG_SEQUENCE") {
1788 // We need to do extra, custom typechecking for REG_SEQUENCE since it is
1791 unsigned NChild = getNumChildren();
1793 TP.error("REG_SEQUENCE requires at least 3 operands!");
1797 if (NChild % 2 == 0) {
1798 TP.error("REG_SEQUENCE requires an odd number of operands!");
1802 if (!isOperandClass(getChild(0), "RegisterClass")) {
1803 TP.error("REG_SEQUENCE requires a RegisterClass for first operand!");
1807 for (unsigned I = 1; I < NChild; I += 2) {
1808 TreePatternNode *SubIdxChild = getChild(I + 1);
1809 if (!isOperandClass(SubIdxChild, "SubRegIndex")) {
1810 TP.error("REG_SEQUENCE requires a SubRegIndex for operand " +
1811 itostr(I + 1) + "!");
1817 unsigned ChildNo = 0;
1818 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
1819 Record *OperandNode = Inst.getOperand(i);
1821 // If the instruction expects a predicate or optional def operand, we
1822 // codegen this by setting the operand to it's default value if it has a
1823 // non-empty DefaultOps field.
1824 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
1825 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1828 // Verify that we didn't run out of provided operands.
1829 if (ChildNo >= getNumChildren()) {
1830 emitTooFewOperandsError(TP, getOperator()->getName(), getNumChildren());
1834 TreePatternNode *Child = getChild(ChildNo++);
1835 unsigned ChildResNo = 0; // Instructions always use res #0 of their op.
1837 // If the operand has sub-operands, they may be provided by distinct
1838 // child patterns, so attempt to match each sub-operand separately.
1839 if (OperandNode->isSubClassOf("Operand")) {
1840 DagInit *MIOpInfo = OperandNode->getValueAsDag("MIOperandInfo");
1841 if (unsigned NumArgs = MIOpInfo->getNumArgs()) {
1842 // But don't do that if the whole operand is being provided by
1843 // a single ComplexPattern-related Operand.
1845 if (Child->getNumMIResults(CDP) < NumArgs) {
1846 // Match first sub-operand against the child we already have.
1847 Record *SubRec = cast<DefInit>(MIOpInfo->getArg(0))->getDef();
1849 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
1851 // And the remaining sub-operands against subsequent children.
1852 for (unsigned Arg = 1; Arg < NumArgs; ++Arg) {
1853 if (ChildNo >= getNumChildren()) {
1854 emitTooFewOperandsError(TP, getOperator()->getName(),
1858 Child = getChild(ChildNo++);
1860 SubRec = cast<DefInit>(MIOpInfo->getArg(Arg))->getDef();
1862 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
1869 // If we didn't match by pieces above, attempt to match the whole
1871 MadeChange |= Child->UpdateNodeTypeFromInst(ChildResNo, OperandNode, TP);
1874 if (!InstInfo.Operands.isVariadic && ChildNo != getNumChildren()) {
1875 emitTooManyOperandsError(TP, getOperator()->getName(),
1876 ChildNo, getNumChildren());
1880 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1881 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1885 if (getOperator()->isSubClassOf("ComplexPattern")) {
1886 bool MadeChange = false;
1888 for (unsigned i = 0; i < getNumChildren(); ++i)
1889 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1894 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
1896 // Node transforms always take one operand.
1897 if (getNumChildren() != 1) {
1898 TP.error("Node transform '" + getOperator()->getName() +
1899 "' requires one operand!");
1903 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1906 // If either the output or input of the xform does not have exact
1907 // type info. We assume they must be the same. Otherwise, it is perfectly
1908 // legal to transform from one type to a completely different type.
1910 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
1911 bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
1912 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
1919 /// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
1920 /// RHS of a commutative operation, not the on LHS.
1921 static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
1922 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
1924 if (N->isLeaf() && isa<IntInit>(N->getLeafValue()))
1930 /// canPatternMatch - If it is impossible for this pattern to match on this
1931 /// target, fill in Reason and return false. Otherwise, return true. This is
1932 /// used as a sanity check for .td files (to prevent people from writing stuff
1933 /// that can never possibly work), and to prevent the pattern permuter from
1934 /// generating stuff that is useless.
1935 bool TreePatternNode::canPatternMatch(std::string &Reason,
1936 const CodeGenDAGPatterns &CDP) {
1937 if (isLeaf()) return true;
1939 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1940 if (!getChild(i)->canPatternMatch(Reason, CDP))
1943 // If this is an intrinsic, handle cases that would make it not match. For
1944 // example, if an operand is required to be an immediate.
1945 if (getOperator()->isSubClassOf("Intrinsic")) {
1950 if (getOperator()->isSubClassOf("ComplexPattern"))
1953 // If this node is a commutative operator, check that the LHS isn't an
1955 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
1956 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
1957 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
1958 // Scan all of the operands of the node and make sure that only the last one
1959 // is a constant node, unless the RHS also is.
1960 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
1961 bool Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
1962 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
1963 if (OnlyOnRHSOfCommutative(getChild(i))) {
1964 Reason="Immediate value must be on the RHS of commutative operators!";
1973 //===----------------------------------------------------------------------===//
1974 // TreePattern implementation
1977 TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
1978 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
1979 isInputPattern(isInput), HasError(false) {
1980 for (Init *I : RawPat->getValues())
1981 Trees.push_back(ParseTreePattern(I, ""));
1984 TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
1985 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
1986 isInputPattern(isInput), HasError(false) {
1987 Trees.push_back(ParseTreePattern(Pat, ""));
1990 TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
1991 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
1992 isInputPattern(isInput), HasError(false) {
1993 Trees.push_back(Pat);
1996 void TreePattern::error(const Twine &Msg) {
2000 PrintError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
2004 void TreePattern::ComputeNamedNodes() {
2005 for (TreePatternNode *Tree : Trees)
2006 ComputeNamedNodes(Tree);
2009 void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
2010 if (!N->getName().empty())
2011 NamedNodes[N->getName()].push_back(N);
2013 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2014 ComputeNamedNodes(N->getChild(i));
2018 TreePatternNode *TreePattern::ParseTreePattern(Init *TheInit, StringRef OpName){
2019 if (DefInit *DI = dyn_cast<DefInit>(TheInit)) {
2020 Record *R = DI->getDef();
2022 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
2023 // TreePatternNode of its own. For example:
2024 /// (foo GPR, imm) -> (foo GPR, (imm))
2025 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag"))
2026 return ParseTreePattern(
2027 DagInit::get(DI, "",
2028 std::vector<std::pair<Init*, std::string> >()),
2032 TreePatternNode *Res = new TreePatternNode(DI, 1);
2033 if (R->getName() == "node" && !OpName.empty()) {
2035 error("'node' argument requires a name to match with operand list");
2036 Args.push_back(OpName);
2039 Res->setName(OpName);
2043 // ?:$name or just $name.
2044 if (isa<UnsetInit>(TheInit)) {
2046 error("'?' argument requires a name to match with operand list");
2047 TreePatternNode *Res = new TreePatternNode(TheInit, 1);
2048 Args.push_back(OpName);
2049 Res->setName(OpName);
2053 if (IntInit *II = dyn_cast<IntInit>(TheInit)) {
2054 if (!OpName.empty())
2055 error("Constant int argument should not have a name!");
2056 return new TreePatternNode(II, 1);
2059 if (BitsInit *BI = dyn_cast<BitsInit>(TheInit)) {
2060 // Turn this into an IntInit.
2061 Init *II = BI->convertInitializerTo(IntRecTy::get());
2062 if (!II || !isa<IntInit>(II))
2063 error("Bits value must be constants!");
2064 return ParseTreePattern(II, OpName);
2067 DagInit *Dag = dyn_cast<DagInit>(TheInit);
2070 error("Pattern has unexpected init kind!");
2072 DefInit *OpDef = dyn_cast<DefInit>(Dag->getOperator());
2073 if (!OpDef) error("Pattern has unexpected operator type!");
2074 Record *Operator = OpDef->getDef();
2076 if (Operator->isSubClassOf("ValueType")) {
2077 // If the operator is a ValueType, then this must be "type cast" of a leaf
2079 if (Dag->getNumArgs() != 1)
2080 error("Type cast only takes one operand!");
2082 TreePatternNode *New = ParseTreePattern(Dag->getArg(0), Dag->getArgName(0));
2084 // Apply the type cast.
2085 assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
2086 New->UpdateNodeType(0, getValueType(Operator), *this);
2088 if (!OpName.empty())
2089 error("ValueType cast should not have a name!");
2093 // Verify that this is something that makes sense for an operator.
2094 if (!Operator->isSubClassOf("PatFrag") &&
2095 !Operator->isSubClassOf("SDNode") &&
2096 !Operator->isSubClassOf("Instruction") &&
2097 !Operator->isSubClassOf("SDNodeXForm") &&
2098 !Operator->isSubClassOf("Intrinsic") &&
2099 !Operator->isSubClassOf("ComplexPattern") &&
2100 Operator->getName() != "set" &&
2101 Operator->getName() != "implicit")
2102 error("Unrecognized node '" + Operator->getName() + "'!");
2104 // Check to see if this is something that is illegal in an input pattern.
2105 if (isInputPattern) {
2106 if (Operator->isSubClassOf("Instruction") ||
2107 Operator->isSubClassOf("SDNodeXForm"))
2108 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
2110 if (Operator->isSubClassOf("Intrinsic"))
2111 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
2113 if (Operator->isSubClassOf("SDNode") &&
2114 Operator->getName() != "imm" &&
2115 Operator->getName() != "fpimm" &&
2116 Operator->getName() != "tglobaltlsaddr" &&
2117 Operator->getName() != "tconstpool" &&
2118 Operator->getName() != "tjumptable" &&
2119 Operator->getName() != "tframeindex" &&
2120 Operator->getName() != "texternalsym" &&
2121 Operator->getName() != "tblockaddress" &&
2122 Operator->getName() != "tglobaladdr" &&
2123 Operator->getName() != "bb" &&
2124 Operator->getName() != "vt" &&
2125 Operator->getName() != "mcsym")
2126 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
2129 std::vector<TreePatternNode*> Children;
2131 // Parse all the operands.
2132 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
2133 Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgName(i)));
2135 // If the operator is an intrinsic, then this is just syntactic sugar for for
2136 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
2137 // convert the intrinsic name to a number.
2138 if (Operator->isSubClassOf("Intrinsic")) {
2139 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
2140 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
2142 // If this intrinsic returns void, it must have side-effects and thus a
2144 if (Int.IS.RetVTs.empty())
2145 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
2146 else if (Int.ModRef != CodeGenIntrinsic::NoMem)
2147 // Has side-effects, requires chain.
2148 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
2149 else // Otherwise, no chain.
2150 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
2152 TreePatternNode *IIDNode = new TreePatternNode(IntInit::get(IID), 1);
2153 Children.insert(Children.begin(), IIDNode);
2156 if (Operator->isSubClassOf("ComplexPattern")) {
2157 for (unsigned i = 0; i < Children.size(); ++i) {
2158 TreePatternNode *Child = Children[i];
2160 if (Child->getName().empty())
2161 error("All arguments to a ComplexPattern must be named");
2163 // Check that the ComplexPattern uses are consistent: "(MY_PAT $a, $b)"
2164 // and "(MY_PAT $b, $a)" should not be allowed in the same pattern;
2165 // neither should "(MY_PAT_1 $a, $b)" and "(MY_PAT_2 $a, $b)".
2166 auto OperandId = std::make_pair(Operator, i);
2167 auto PrevOp = ComplexPatternOperands.find(Child->getName());
2168 if (PrevOp != ComplexPatternOperands.end()) {
2169 if (PrevOp->getValue() != OperandId)
2170 error("All ComplexPattern operands must appear consistently: "
2171 "in the same order in just one ComplexPattern instance.");
2173 ComplexPatternOperands[Child->getName()] = OperandId;
2177 unsigned NumResults = GetNumNodeResults(Operator, CDP);
2178 TreePatternNode *Result = new TreePatternNode(Operator, Children, NumResults);
2179 Result->setName(OpName);
2181 if (!Dag->getName().empty()) {
2182 assert(Result->getName().empty());
2183 Result->setName(Dag->getName());
2188 /// SimplifyTree - See if we can simplify this tree to eliminate something that
2189 /// will never match in favor of something obvious that will. This is here
2190 /// strictly as a convenience to target authors because it allows them to write
2191 /// more type generic things and have useless type casts fold away.
2193 /// This returns true if any change is made.
2194 static bool SimplifyTree(TreePatternNode *&N) {
2198 // If we have a bitconvert with a resolved type and if the source and
2199 // destination types are the same, then the bitconvert is useless, remove it.
2200 if (N->getOperator()->getName() == "bitconvert" &&
2201 N->getExtType(0).isConcrete() &&
2202 N->getExtType(0) == N->getChild(0)->getExtType(0) &&
2203 N->getName().empty()) {
2209 // Walk all children.
2210 bool MadeChange = false;
2211 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2212 TreePatternNode *Child = N->getChild(i);
2213 MadeChange |= SimplifyTree(Child);
2214 N->setChild(i, Child);
2221 /// InferAllTypes - Infer/propagate as many types throughout the expression
2222 /// patterns as possible. Return true if all types are inferred, false
2223 /// otherwise. Flags an error if a type contradiction is found.
2225 InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
2226 if (NamedNodes.empty())
2227 ComputeNamedNodes();
2229 bool MadeChange = true;
2230 while (MadeChange) {
2232 for (TreePatternNode *Tree : Trees) {
2233 MadeChange |= Tree->ApplyTypeConstraints(*this, false);
2234 MadeChange |= SimplifyTree(Tree);
2237 // If there are constraints on our named nodes, apply them.
2238 for (auto &Entry : NamedNodes) {
2239 SmallVectorImpl<TreePatternNode*> &Nodes = Entry.second;
2241 // If we have input named node types, propagate their types to the named
2244 if (!InNamedTypes->count(Entry.getKey())) {
2245 error("Node '" + std::string(Entry.getKey()) +
2246 "' in output pattern but not input pattern");
2250 const SmallVectorImpl<TreePatternNode*> &InNodes =
2251 InNamedTypes->find(Entry.getKey())->second;
2253 // The input types should be fully resolved by now.
2254 for (TreePatternNode *Node : Nodes) {
2255 // If this node is a register class, and it is the root of the pattern
2256 // then we're mapping something onto an input register. We allow
2257 // changing the type of the input register in this case. This allows
2258 // us to match things like:
2259 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
2260 if (Node == Trees[0] && Node->isLeaf()) {
2261 DefInit *DI = dyn_cast<DefInit>(Node->getLeafValue());
2262 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2263 DI->getDef()->isSubClassOf("RegisterOperand")))
2267 assert(Node->getNumTypes() == 1 &&
2268 InNodes[0]->getNumTypes() == 1 &&
2269 "FIXME: cannot name multiple result nodes yet");
2270 MadeChange |= Node->UpdateNodeType(0, InNodes[0]->getExtType(0),
2275 // If there are multiple nodes with the same name, they must all have the
2277 if (Entry.second.size() > 1) {
2278 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
2279 TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
2280 assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
2281 "FIXME: cannot name multiple result nodes yet");
2283 MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
2284 MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
2290 bool HasUnresolvedTypes = false;
2291 for (const TreePatternNode *Tree : Trees)
2292 HasUnresolvedTypes |= Tree->ContainsUnresolvedType();
2293 return !HasUnresolvedTypes;
2296 void TreePattern::print(raw_ostream &OS) const {
2297 OS << getRecord()->getName();
2298 if (!Args.empty()) {
2299 OS << "(" << Args[0];
2300 for (unsigned i = 1, e = Args.size(); i != e; ++i)
2301 OS << ", " << Args[i];
2306 if (Trees.size() > 1)
2308 for (const TreePatternNode *Tree : Trees) {
2314 if (Trees.size() > 1)
2318 void TreePattern::dump() const { print(errs()); }
2320 //===----------------------------------------------------------------------===//
2321 // CodeGenDAGPatterns implementation
2324 CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) :
2325 Records(R), Target(R) {
2327 Intrinsics = LoadIntrinsics(Records, false);
2328 TgtIntrinsics = LoadIntrinsics(Records, true);
2330 ParseNodeTransforms();
2331 ParseComplexPatterns();
2332 ParsePatternFragments();
2333 ParseDefaultOperands();
2334 ParseInstructions();
2335 ParsePatternFragments(/*OutFrags*/true);
2338 // Generate variants. For example, commutative patterns can match
2339 // multiple ways. Add them to PatternsToMatch as well.
2342 // Infer instruction flags. For example, we can detect loads,
2343 // stores, and side effects in many cases by examining an
2344 // instruction's pattern.
2345 InferInstructionFlags();
2347 // Verify that instruction flags match the patterns.
2348 VerifyInstructionFlags();
2351 Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
2352 Record *N = Records.getDef(Name);
2353 if (!N || !N->isSubClassOf("SDNode"))
2354 PrintFatalError("Error getting SDNode '" + Name + "'!");
2359 // Parse all of the SDNode definitions for the target, populating SDNodes.
2360 void CodeGenDAGPatterns::ParseNodeInfo() {
2361 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
2362 while (!Nodes.empty()) {
2363 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
2367 // Get the builtin intrinsic nodes.
2368 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
2369 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
2370 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
2373 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
2374 /// map, and emit them to the file as functions.
2375 void CodeGenDAGPatterns::ParseNodeTransforms() {
2376 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
2377 while (!Xforms.empty()) {
2378 Record *XFormNode = Xforms.back();
2379 Record *SDNode = XFormNode->getValueAsDef("Opcode");
2380 std::string Code = XFormNode->getValueAsString("XFormFunction");
2381 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
2387 void CodeGenDAGPatterns::ParseComplexPatterns() {
2388 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
2389 while (!AMs.empty()) {
2390 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
2396 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
2397 /// file, building up the PatternFragments map. After we've collected them all,
2398 /// inline fragments together as necessary, so that there are no references left
2399 /// inside a pattern fragment to a pattern fragment.
2401 void CodeGenDAGPatterns::ParsePatternFragments(bool OutFrags) {
2402 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
2404 // First step, parse all of the fragments.
2405 for (Record *Frag : Fragments) {
2406 if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
2409 DagInit *Tree = Frag->getValueAsDag("Fragment");
2411 (PatternFragments[Frag] = llvm::make_unique<TreePattern>(
2412 Frag, Tree, !Frag->isSubClassOf("OutPatFrag"),
2415 // Validate the argument list, converting it to set, to discard duplicates.
2416 std::vector<std::string> &Args = P->getArgList();
2417 std::set<std::string> OperandsSet(Args.begin(), Args.end());
2419 if (OperandsSet.count(""))
2420 P->error("Cannot have unnamed 'node' values in pattern fragment!");
2422 // Parse the operands list.
2423 DagInit *OpsList = Frag->getValueAsDag("Operands");
2424 DefInit *OpsOp = dyn_cast<DefInit>(OpsList->getOperator());
2425 // Special cases: ops == outs == ins. Different names are used to
2426 // improve readability.
2428 (OpsOp->getDef()->getName() != "ops" &&
2429 OpsOp->getDef()->getName() != "outs" &&
2430 OpsOp->getDef()->getName() != "ins"))
2431 P->error("Operands list should start with '(ops ... '!");
2433 // Copy over the arguments.
2435 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
2436 if (!isa<DefInit>(OpsList->getArg(j)) ||
2437 cast<DefInit>(OpsList->getArg(j))->getDef()->getName() != "node")
2438 P->error("Operands list should all be 'node' values.");
2439 if (OpsList->getArgName(j).empty())
2440 P->error("Operands list should have names for each operand!");
2441 if (!OperandsSet.count(OpsList->getArgName(j)))
2442 P->error("'" + OpsList->getArgName(j) +
2443 "' does not occur in pattern or was multiply specified!");
2444 OperandsSet.erase(OpsList->getArgName(j));
2445 Args.push_back(OpsList->getArgName(j));
2448 if (!OperandsSet.empty())
2449 P->error("Operands list does not contain an entry for operand '" +
2450 *OperandsSet.begin() + "'!");
2452 // If there is a code init for this fragment, keep track of the fact that
2453 // this fragment uses it.
2454 TreePredicateFn PredFn(P);
2455 if (!PredFn.isAlwaysTrue())
2456 P->getOnlyTree()->addPredicateFn(PredFn);
2458 // If there is a node transformation corresponding to this, keep track of
2460 Record *Transform = Frag->getValueAsDef("OperandTransform");
2461 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
2462 P->getOnlyTree()->setTransformFn(Transform);
2465 // Now that we've parsed all of the tree fragments, do a closure on them so
2466 // that there are not references to PatFrags left inside of them.
2467 for (Record *Frag : Fragments) {
2468 if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
2471 TreePattern &ThePat = *PatternFragments[Frag];
2472 ThePat.InlinePatternFragments();
2474 // Infer as many types as possible. Don't worry about it if we don't infer
2475 // all of them, some may depend on the inputs of the pattern.
2476 ThePat.InferAllTypes();
2477 ThePat.resetError();
2479 // If debugging, print out the pattern fragment result.
2480 DEBUG(ThePat.dump());
2484 void CodeGenDAGPatterns::ParseDefaultOperands() {
2485 std::vector<Record*> DefaultOps;
2486 DefaultOps = Records.getAllDerivedDefinitions("OperandWithDefaultOps");
2488 // Find some SDNode.
2489 assert(!SDNodes.empty() && "No SDNodes parsed?");
2490 Init *SomeSDNode = DefInit::get(SDNodes.begin()->first);
2492 for (unsigned i = 0, e = DefaultOps.size(); i != e; ++i) {
2493 DagInit *DefaultInfo = DefaultOps[i]->getValueAsDag("DefaultOps");
2495 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
2496 // SomeSDnode so that we can parse this.
2497 std::vector<std::pair<Init*, std::string> > Ops;
2498 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
2499 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
2500 DefaultInfo->getArgName(op)));
2501 DagInit *DI = DagInit::get(SomeSDNode, "", Ops);
2503 // Create a TreePattern to parse this.
2504 TreePattern P(DefaultOps[i], DI, false, *this);
2505 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
2507 // Copy the operands over into a DAGDefaultOperand.
2508 DAGDefaultOperand DefaultOpInfo;
2510 TreePatternNode *T = P.getTree(0);
2511 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
2512 TreePatternNode *TPN = T->getChild(op);
2513 while (TPN->ApplyTypeConstraints(P, false))
2514 /* Resolve all types */;
2516 if (TPN->ContainsUnresolvedType()) {
2517 PrintFatalError("Value #" + Twine(i) + " of OperandWithDefaultOps '" +
2518 DefaultOps[i]->getName() +
2519 "' doesn't have a concrete type!");
2521 DefaultOpInfo.DefaultOps.push_back(TPN);
2524 // Insert it into the DefaultOperands map so we can find it later.
2525 DefaultOperands[DefaultOps[i]] = DefaultOpInfo;
2529 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
2530 /// instruction input. Return true if this is a real use.
2531 static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
2532 std::map<std::string, TreePatternNode*> &InstInputs) {
2533 // No name -> not interesting.
2534 if (Pat->getName().empty()) {
2535 if (Pat->isLeaf()) {
2536 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
2537 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2538 DI->getDef()->isSubClassOf("RegisterOperand")))
2539 I->error("Input " + DI->getDef()->getName() + " must be named!");
2545 if (Pat->isLeaf()) {
2546 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
2547 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
2550 Rec = Pat->getOperator();
2553 // SRCVALUE nodes are ignored.
2554 if (Rec->getName() == "srcvalue")
2557 TreePatternNode *&Slot = InstInputs[Pat->getName()];
2563 if (Slot->isLeaf()) {
2564 SlotRec = cast<DefInit>(Slot->getLeafValue())->getDef();
2566 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
2567 SlotRec = Slot->getOperator();
2570 // Ensure that the inputs agree if we've already seen this input.
2572 I->error("All $" + Pat->getName() + " inputs must agree with each other");
2573 if (Slot->getExtTypes() != Pat->getExtTypes())
2574 I->error("All $" + Pat->getName() + " inputs must agree with each other");
2578 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
2579 /// part of "I", the instruction), computing the set of inputs and outputs of
2580 /// the pattern. Report errors if we see anything naughty.
2581 void CodeGenDAGPatterns::
2582 FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
2583 std::map<std::string, TreePatternNode*> &InstInputs,
2584 std::map<std::string, TreePatternNode*>&InstResults,
2585 std::vector<Record*> &InstImpResults) {
2586 if (Pat->isLeaf()) {
2587 bool isUse = HandleUse(I, Pat, InstInputs);
2588 if (!isUse && Pat->getTransformFn())
2589 I->error("Cannot specify a transform function for a non-input value!");
2593 if (Pat->getOperator()->getName() == "implicit") {
2594 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2595 TreePatternNode *Dest = Pat->getChild(i);
2596 if (!Dest->isLeaf())
2597 I->error("implicitly defined value should be a register!");
2599 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
2600 if (!Val || !Val->getDef()->isSubClassOf("Register"))
2601 I->error("implicitly defined value should be a register!");
2602 InstImpResults.push_back(Val->getDef());
2607 if (Pat->getOperator()->getName() != "set") {
2608 // If this is not a set, verify that the children nodes are not void typed,
2610 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2611 if (Pat->getChild(i)->getNumTypes() == 0)
2612 I->error("Cannot have void nodes inside of patterns!");
2613 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
2617 // If this is a non-leaf node with no children, treat it basically as if
2618 // it were a leaf. This handles nodes like (imm).
2619 bool isUse = HandleUse(I, Pat, InstInputs);
2621 if (!isUse && Pat->getTransformFn())
2622 I->error("Cannot specify a transform function for a non-input value!");
2626 // Otherwise, this is a set, validate and collect instruction results.
2627 if (Pat->getNumChildren() == 0)
2628 I->error("set requires operands!");
2630 if (Pat->getTransformFn())
2631 I->error("Cannot specify a transform function on a set node!");
2633 // Check the set destinations.
2634 unsigned NumDests = Pat->getNumChildren()-1;
2635 for (unsigned i = 0; i != NumDests; ++i) {
2636 TreePatternNode *Dest = Pat->getChild(i);
2637 if (!Dest->isLeaf())
2638 I->error("set destination should be a register!");
2640 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
2642 I->error("set destination should be a register!");
2646 if (Val->getDef()->isSubClassOf("RegisterClass") ||
2647 Val->getDef()->isSubClassOf("ValueType") ||
2648 Val->getDef()->isSubClassOf("RegisterOperand") ||
2649 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
2650 if (Dest->getName().empty())
2651 I->error("set destination must have a name!");
2652 if (InstResults.count(Dest->getName()))
2653 I->error("cannot set '" + Dest->getName() +"' multiple times");
2654 InstResults[Dest->getName()] = Dest;
2655 } else if (Val->getDef()->isSubClassOf("Register")) {
2656 InstImpResults.push_back(Val->getDef());
2658 I->error("set destination should be a register!");
2662 // Verify and collect info from the computation.
2663 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
2664 InstInputs, InstResults, InstImpResults);
2667 //===----------------------------------------------------------------------===//
2668 // Instruction Analysis
2669 //===----------------------------------------------------------------------===//
2671 class InstAnalyzer {
2672 const CodeGenDAGPatterns &CDP;
2674 bool hasSideEffects;
2680 InstAnalyzer(const CodeGenDAGPatterns &cdp)
2681 : CDP(cdp), hasSideEffects(false), mayStore(false), mayLoad(false),
2682 isBitcast(false), isVariadic(false) {}
2684 void Analyze(const TreePattern *Pat) {
2685 // Assume only the first tree is the pattern. The others are clobber nodes.
2686 AnalyzeNode(Pat->getTree(0));
2689 void Analyze(const PatternToMatch *Pat) {
2690 AnalyzeNode(Pat->getSrcPattern());
2694 bool IsNodeBitcast(const TreePatternNode *N) const {
2695 if (hasSideEffects || mayLoad || mayStore || isVariadic)
2698 if (N->getNumChildren() != 2)
2701 const TreePatternNode *N0 = N->getChild(0);
2702 if (!N0->isLeaf() || !isa<DefInit>(N0->getLeafValue()))
2705 const TreePatternNode *N1 = N->getChild(1);
2708 if (N1->getNumChildren() != 1 || !N1->getChild(0)->isLeaf())
2711 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N1->getOperator());
2712 if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1)
2714 return OpInfo.getEnumName() == "ISD::BITCAST";
2718 void AnalyzeNode(const TreePatternNode *N) {
2720 if (DefInit *DI = dyn_cast<DefInit>(N->getLeafValue())) {
2721 Record *LeafRec = DI->getDef();
2722 // Handle ComplexPattern leaves.
2723 if (LeafRec->isSubClassOf("ComplexPattern")) {
2724 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
2725 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
2726 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
2727 if (CP.hasProperty(SDNPSideEffect)) hasSideEffects = true;
2733 // Analyze children.
2734 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2735 AnalyzeNode(N->getChild(i));
2737 // Ignore set nodes, which are not SDNodes.
2738 if (N->getOperator()->getName() == "set") {
2739 isBitcast = IsNodeBitcast(N);
2743 // Notice properties of the node.
2744 if (N->NodeHasProperty(SDNPMayStore, CDP)) mayStore = true;
2745 if (N->NodeHasProperty(SDNPMayLoad, CDP)) mayLoad = true;
2746 if (N->NodeHasProperty(SDNPSideEffect, CDP)) hasSideEffects = true;
2747 if (N->NodeHasProperty(SDNPVariadic, CDP)) isVariadic = true;
2749 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
2750 // If this is an intrinsic, analyze it.
2751 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
2752 mayLoad = true;// These may load memory.
2754 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteArgMem)
2755 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
2757 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem)
2758 // WriteMem intrinsics can have other strange effects.
2759 hasSideEffects = true;
2765 static bool InferFromPattern(CodeGenInstruction &InstInfo,
2766 const InstAnalyzer &PatInfo,
2770 // Remember where InstInfo got its flags.
2771 if (InstInfo.hasUndefFlags())
2772 InstInfo.InferredFrom = PatDef;
2774 // Check explicitly set flags for consistency.
2775 if (InstInfo.hasSideEffects != PatInfo.hasSideEffects &&
2776 !InstInfo.hasSideEffects_Unset) {
2777 // Allow explicitly setting hasSideEffects = 1 on instructions, even when
2778 // the pattern has no side effects. That could be useful for div/rem
2779 // instructions that may trap.
2780 if (!InstInfo.hasSideEffects) {
2782 PrintError(PatDef->getLoc(), "Pattern doesn't match hasSideEffects = " +
2783 Twine(InstInfo.hasSideEffects));
2787 if (InstInfo.mayStore != PatInfo.mayStore && !InstInfo.mayStore_Unset) {
2789 PrintError(PatDef->getLoc(), "Pattern doesn't match mayStore = " +
2790 Twine(InstInfo.mayStore));
2793 if (InstInfo.mayLoad != PatInfo.mayLoad && !InstInfo.mayLoad_Unset) {
2794 // Allow explicitly setting mayLoad = 1, even when the pattern has no loads.
2795 // Some targets translate immediates to loads.
2796 if (!InstInfo.mayLoad) {
2798 PrintError(PatDef->getLoc(), "Pattern doesn't match mayLoad = " +
2799 Twine(InstInfo.mayLoad));
2803 // Transfer inferred flags.
2804 InstInfo.hasSideEffects |= PatInfo.hasSideEffects;
2805 InstInfo.mayStore |= PatInfo.mayStore;
2806 InstInfo.mayLoad |= PatInfo.mayLoad;
2808 // These flags are silently added without any verification.
2809 InstInfo.isBitcast |= PatInfo.isBitcast;
2811 // Don't infer isVariadic. This flag means something different on SDNodes and
2812 // instructions. For example, a CALL SDNode is variadic because it has the
2813 // call arguments as operands, but a CALL instruction is not variadic - it
2814 // has argument registers as implicit, not explicit uses.
2819 /// hasNullFragReference - Return true if the DAG has any reference to the
2820 /// null_frag operator.
2821 static bool hasNullFragReference(DagInit *DI) {
2822 DefInit *OpDef = dyn_cast<DefInit>(DI->getOperator());
2823 if (!OpDef) return false;
2824 Record *Operator = OpDef->getDef();
2826 // If this is the null fragment, return true.
2827 if (Operator->getName() == "null_frag") return true;
2828 // If any of the arguments reference the null fragment, return true.
2829 for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {
2830 DagInit *Arg = dyn_cast<DagInit>(DI->getArg(i));
2831 if (Arg && hasNullFragReference(Arg))
2838 /// hasNullFragReference - Return true if any DAG in the list references
2839 /// the null_frag operator.
2840 static bool hasNullFragReference(ListInit *LI) {
2841 for (Init *I : LI->getValues()) {
2842 DagInit *DI = dyn_cast<DagInit>(I);
2843 assert(DI && "non-dag in an instruction Pattern list?!");
2844 if (hasNullFragReference(DI))
2850 /// Get all the instructions in a tree.
2852 getInstructionsInTree(TreePatternNode *Tree, SmallVectorImpl<Record*> &Instrs) {
2855 if (Tree->getOperator()->isSubClassOf("Instruction"))
2856 Instrs.push_back(Tree->getOperator());
2857 for (unsigned i = 0, e = Tree->getNumChildren(); i != e; ++i)
2858 getInstructionsInTree(Tree->getChild(i), Instrs);
2861 /// Check the class of a pattern leaf node against the instruction operand it
2863 static bool checkOperandClass(CGIOperandList::OperandInfo &OI,
2868 // Allow direct value types to be used in instruction set patterns.
2869 // The type will be checked later.
2870 if (Leaf->isSubClassOf("ValueType"))
2873 // Patterns can also be ComplexPattern instances.
2874 if (Leaf->isSubClassOf("ComplexPattern"))
2880 const DAGInstruction &CodeGenDAGPatterns::parseInstructionPattern(
2881 CodeGenInstruction &CGI, ListInit *Pat, DAGInstMap &DAGInsts) {
2883 assert(!DAGInsts.count(CGI.TheDef) && "Instruction already parsed!");
2885 // Parse the instruction.
2886 TreePattern *I = new TreePattern(CGI.TheDef, Pat, true, *this);
2887 // Inline pattern fragments into it.
2888 I->InlinePatternFragments();
2890 // Infer as many types as possible. If we cannot infer all of them, we can
2891 // never do anything with this instruction pattern: report it to the user.
2892 if (!I->InferAllTypes())
2893 I->error("Could not infer all types in pattern!");
2895 // InstInputs - Keep track of all of the inputs of the instruction, along
2896 // with the record they are declared as.
2897 std::map<std::string, TreePatternNode*> InstInputs;
2899 // InstResults - Keep track of all the virtual registers that are 'set'
2900 // in the instruction, including what reg class they are.
2901 std::map<std::string, TreePatternNode*> InstResults;
2903 std::vector<Record*> InstImpResults;
2905 // Verify that the top-level forms in the instruction are of void type, and
2906 // fill in the InstResults map.
2907 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
2908 TreePatternNode *Pat = I->getTree(j);
2909 if (Pat->getNumTypes() != 0)
2910 I->error("Top-level forms in instruction pattern should have"
2913 // Find inputs and outputs, and verify the structure of the uses/defs.
2914 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
2918 // Now that we have inputs and outputs of the pattern, inspect the operands
2919 // list for the instruction. This determines the order that operands are
2920 // added to the machine instruction the node corresponds to.
2921 unsigned NumResults = InstResults.size();
2923 // Parse the operands list from the (ops) list, validating it.
2924 assert(I->getArgList().empty() && "Args list should still be empty here!");
2926 // Check that all of the results occur first in the list.
2927 std::vector<Record*> Results;
2928 SmallVector<TreePatternNode *, 2> ResNodes;
2929 for (unsigned i = 0; i != NumResults; ++i) {
2930 if (i == CGI.Operands.size())
2931 I->error("'" + InstResults.begin()->first +
2932 "' set but does not appear in operand list!");
2933 const std::string &OpName = CGI.Operands[i].Name;
2935 // Check that it exists in InstResults.
2936 TreePatternNode *RNode = InstResults[OpName];
2938 I->error("Operand $" + OpName + " does not exist in operand list!");
2940 ResNodes.push_back(RNode);
2942 Record *R = cast<DefInit>(RNode->getLeafValue())->getDef();
2944 I->error("Operand $" + OpName + " should be a set destination: all "
2945 "outputs must occur before inputs in operand list!");
2947 if (!checkOperandClass(CGI.Operands[i], R))
2948 I->error("Operand $" + OpName + " class mismatch!");
2950 // Remember the return type.
2951 Results.push_back(CGI.Operands[i].Rec);
2953 // Okay, this one checks out.
2954 InstResults.erase(OpName);
2957 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
2958 // the copy while we're checking the inputs.
2959 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
2961 std::vector<TreePatternNode*> ResultNodeOperands;
2962 std::vector<Record*> Operands;
2963 for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
2964 CGIOperandList::OperandInfo &Op = CGI.Operands[i];
2965 const std::string &OpName = Op.Name;
2967 I->error("Operand #" + utostr(i) + " in operands list has no name!");
2969 if (!InstInputsCheck.count(OpName)) {
2970 // If this is an operand with a DefaultOps set filled in, we can ignore
2971 // this. When we codegen it, we will do so as always executed.
2972 if (Op.Rec->isSubClassOf("OperandWithDefaultOps")) {
2973 // Does it have a non-empty DefaultOps field? If so, ignore this
2975 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
2978 I->error("Operand $" + OpName +
2979 " does not appear in the instruction pattern");
2981 TreePatternNode *InVal = InstInputsCheck[OpName];
2982 InstInputsCheck.erase(OpName); // It occurred, remove from map.
2984 if (InVal->isLeaf() && isa<DefInit>(InVal->getLeafValue())) {
2985 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
2986 if (!checkOperandClass(Op, InRec))
2987 I->error("Operand $" + OpName + "'s register class disagrees"
2988 " between the operand and pattern");
2990 Operands.push_back(Op.Rec);
2992 // Construct the result for the dest-pattern operand list.
2993 TreePatternNode *OpNode = InVal->clone();
2995 // No predicate is useful on the result.
2996 OpNode->clearPredicateFns();
2998 // Promote the xform function to be an explicit node if set.
2999 if (Record *Xform = OpNode->getTransformFn()) {
3000 OpNode->setTransformFn(nullptr);
3001 std::vector<TreePatternNode*> Children;
3002 Children.push_back(OpNode);
3003 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
3006 ResultNodeOperands.push_back(OpNode);
3009 if (!InstInputsCheck.empty())
3010 I->error("Input operand $" + InstInputsCheck.begin()->first +
3011 " occurs in pattern but not in operands list!");
3013 TreePatternNode *ResultPattern =
3014 new TreePatternNode(I->getRecord(), ResultNodeOperands,
3015 GetNumNodeResults(I->getRecord(), *this));
3016 // Copy fully inferred output node types to instruction result pattern.
3017 for (unsigned i = 0; i != NumResults; ++i) {
3018 assert(ResNodes[i]->getNumTypes() == 1 && "FIXME: Unhandled");
3019 ResultPattern->setType(i, ResNodes[i]->getExtType(0));
3022 // Create and insert the instruction.
3023 // FIXME: InstImpResults should not be part of DAGInstruction.
3024 DAGInstruction TheInst(I, Results, Operands, InstImpResults);
3025 DAGInsts.insert(std::make_pair(I->getRecord(), TheInst));
3027 // Use a temporary tree pattern to infer all types and make sure that the
3028 // constructed result is correct. This depends on the instruction already
3029 // being inserted into the DAGInsts map.
3030 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
3031 Temp.InferAllTypes(&I->getNamedNodesMap());
3033 DAGInstruction &TheInsertedInst = DAGInsts.find(I->getRecord())->second;
3034 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
3036 return TheInsertedInst;
3039 /// ParseInstructions - Parse all of the instructions, inlining and resolving
3040 /// any fragments involved. This populates the Instructions list with fully
3041 /// resolved instructions.
3042 void CodeGenDAGPatterns::ParseInstructions() {
3043 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
3045 for (Record *Instr : Instrs) {
3046 ListInit *LI = nullptr;
3048 if (isa<ListInit>(Instr->getValueInit("Pattern")))
3049 LI = Instr->getValueAsListInit("Pattern");
3051 // If there is no pattern, only collect minimal information about the
3052 // instruction for its operand list. We have to assume that there is one
3053 // result, as we have no detailed info. A pattern which references the
3054 // null_frag operator is as-if no pattern were specified. Normally this
3055 // is from a multiclass expansion w/ a SDPatternOperator passed in as
3057 if (!LI || LI->empty() || hasNullFragReference(LI)) {
3058 std::vector<Record*> Results;
3059 std::vector<Record*> Operands;
3061 CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
3063 if (InstInfo.Operands.size() != 0) {
3064 for (unsigned j = 0, e = InstInfo.Operands.NumDefs; j < e; ++j)
3065 Results.push_back(InstInfo.Operands[j].Rec);
3067 // The rest are inputs.
3068 for (unsigned j = InstInfo.Operands.NumDefs,
3069 e = InstInfo.Operands.size(); j < e; ++j)
3070 Operands.push_back(InstInfo.Operands[j].Rec);
3073 // Create and insert the instruction.
3074 std::vector<Record*> ImpResults;
3075 Instructions.insert(std::make_pair(Instr,
3076 DAGInstruction(nullptr, Results, Operands, ImpResults)));
3077 continue; // no pattern.
3080 CodeGenInstruction &CGI = Target.getInstruction(Instr);
3081 const DAGInstruction &DI = parseInstructionPattern(CGI, LI, Instructions);
3084 DEBUG(DI.getPattern()->dump());
3087 // If we can, convert the instructions to be patterns that are matched!
3088 for (auto &Entry : Instructions) {
3089 DAGInstruction &TheInst = Entry.second;
3090 TreePattern *I = TheInst.getPattern();
3091 if (!I) continue; // No pattern.
3093 // FIXME: Assume only the first tree is the pattern. The others are clobber
3095 TreePatternNode *Pattern = I->getTree(0);
3096 TreePatternNode *SrcPattern;
3097 if (Pattern->getOperator()->getName() == "set") {
3098 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
3100 // Not a set (store or something?)
3101 SrcPattern = Pattern;
3104 Record *Instr = Entry.first;
3105 AddPatternToMatch(I,
3106 PatternToMatch(Instr,
3107 Instr->getValueAsListInit("Predicates"),
3109 TheInst.getResultPattern(),
3110 TheInst.getImpResults(),
3111 Instr->getValueAsInt("AddedComplexity"),
3117 typedef std::pair<const TreePatternNode*, unsigned> NameRecord;
3119 static void FindNames(const TreePatternNode *P,
3120 std::map<std::string, NameRecord> &Names,
3121 TreePattern *PatternTop) {
3122 if (!P->getName().empty()) {
3123 NameRecord &Rec = Names[P->getName()];
3124 // If this is the first instance of the name, remember the node.
3125 if (Rec.second++ == 0)
3127 else if (Rec.first->getExtTypes() != P->getExtTypes())
3128 PatternTop->error("repetition of value: $" + P->getName() +
3129 " where different uses have different types!");
3133 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
3134 FindNames(P->getChild(i), Names, PatternTop);
3138 void CodeGenDAGPatterns::AddPatternToMatch(TreePattern *Pattern,
3139 const PatternToMatch &PTM) {
3140 // Do some sanity checking on the pattern we're about to match.
3142 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this)) {
3143 PrintWarning(Pattern->getRecord()->getLoc(),
3144 Twine("Pattern can never match: ") + Reason);
3148 // If the source pattern's root is a complex pattern, that complex pattern
3149 // must specify the nodes it can potentially match.
3150 if (const ComplexPattern *CP =
3151 PTM.getSrcPattern()->getComplexPatternInfo(*this))
3152 if (CP->getRootNodes().empty())
3153 Pattern->error("ComplexPattern at root must specify list of opcodes it"
3157 // Find all of the named values in the input and output, ensure they have the
3159 std::map<std::string, NameRecord> SrcNames, DstNames;
3160 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
3161 FindNames(PTM.getDstPattern(), DstNames, Pattern);
3163 // Scan all of the named values in the destination pattern, rejecting them if
3164 // they don't exist in the input pattern.
3165 for (const auto &Entry : DstNames) {
3166 if (SrcNames[Entry.first].first == nullptr)
3167 Pattern->error("Pattern has input without matching name in output: $" +
3171 // Scan all of the named values in the source pattern, rejecting them if the
3172 // name isn't used in the dest, and isn't used to tie two values together.
3173 for (const auto &Entry : SrcNames)
3174 if (DstNames[Entry.first].first == nullptr &&
3175 SrcNames[Entry.first].second == 1)
3176 Pattern->error("Pattern has dead named input: $" + Entry.first);
3178 PatternsToMatch.push_back(PTM);
3183 void CodeGenDAGPatterns::InferInstructionFlags() {
3184 const std::vector<const CodeGenInstruction*> &Instructions =
3185 Target.getInstructionsByEnumValue();
3187 // First try to infer flags from the primary instruction pattern, if any.
3188 SmallVector<CodeGenInstruction*, 8> Revisit;
3189 unsigned Errors = 0;
3190 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
3191 CodeGenInstruction &InstInfo =
3192 const_cast<CodeGenInstruction &>(*Instructions[i]);
3194 // Get the primary instruction pattern.
3195 const TreePattern *Pattern = getInstruction(InstInfo.TheDef).getPattern();
3197 if (InstInfo.hasUndefFlags())
3198 Revisit.push_back(&InstInfo);
3201 InstAnalyzer PatInfo(*this);
3202 PatInfo.Analyze(Pattern);
3203 Errors += InferFromPattern(InstInfo, PatInfo, InstInfo.TheDef);
3206 // Second, look for single-instruction patterns defined outside the
3208 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3209 const PatternToMatch &PTM = *I;
3211 // We can only infer from single-instruction patterns, otherwise we won't
3212 // know which instruction should get the flags.
3213 SmallVector<Record*, 8> PatInstrs;
3214 getInstructionsInTree(PTM.getDstPattern(), PatInstrs);
3215 if (PatInstrs.size() != 1)
3218 // Get the single instruction.
3219 CodeGenInstruction &InstInfo = Target.getInstruction(PatInstrs.front());
3221 // Only infer properties from the first pattern. We'll verify the others.
3222 if (InstInfo.InferredFrom)
3225 InstAnalyzer PatInfo(*this);
3226 PatInfo.Analyze(&PTM);
3227 Errors += InferFromPattern(InstInfo, PatInfo, PTM.getSrcRecord());
3231 PrintFatalError("pattern conflicts");
3233 // Revisit instructions with undefined flags and no pattern.
3234 if (Target.guessInstructionProperties()) {
3235 for (CodeGenInstruction *InstInfo : Revisit) {
3236 if (InstInfo->InferredFrom)
3238 // The mayLoad and mayStore flags default to false.
3239 // Conservatively assume hasSideEffects if it wasn't explicit.
3240 if (InstInfo->hasSideEffects_Unset)
3241 InstInfo->hasSideEffects = true;
3246 // Complain about any flags that are still undefined.
3247 for (CodeGenInstruction *InstInfo : Revisit) {
3248 if (InstInfo->InferredFrom)
3250 if (InstInfo->hasSideEffects_Unset)
3251 PrintError(InstInfo->TheDef->getLoc(),
3252 "Can't infer hasSideEffects from patterns");
3253 if (InstInfo->mayStore_Unset)
3254 PrintError(InstInfo->TheDef->getLoc(),
3255 "Can't infer mayStore from patterns");
3256 if (InstInfo->mayLoad_Unset)
3257 PrintError(InstInfo->TheDef->getLoc(),
3258 "Can't infer mayLoad from patterns");
3263 /// Verify instruction flags against pattern node properties.
3264 void CodeGenDAGPatterns::VerifyInstructionFlags() {
3265 unsigned Errors = 0;
3266 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3267 const PatternToMatch &PTM = *I;
3268 SmallVector<Record*, 8> Instrs;
3269 getInstructionsInTree(PTM.getDstPattern(), Instrs);
3273 // Count the number of instructions with each flag set.
3274 unsigned NumSideEffects = 0;
3275 unsigned NumStores = 0;
3276 unsigned NumLoads = 0;
3277 for (const Record *Instr : Instrs) {
3278 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
3279 NumSideEffects += InstInfo.hasSideEffects;
3280 NumStores += InstInfo.mayStore;
3281 NumLoads += InstInfo.mayLoad;
3284 // Analyze the source pattern.
3285 InstAnalyzer PatInfo(*this);
3286 PatInfo.Analyze(&PTM);
3288 // Collect error messages.
3289 SmallVector<std::string, 4> Msgs;
3291 // Check for missing flags in the output.
3292 // Permit extra flags for now at least.
3293 if (PatInfo.hasSideEffects && !NumSideEffects)
3294 Msgs.push_back("pattern has side effects, but hasSideEffects isn't set");
3296 // Don't verify store flags on instructions with side effects. At least for
3297 // intrinsics, side effects implies mayStore.
3298 if (!PatInfo.hasSideEffects && PatInfo.mayStore && !NumStores)
3299 Msgs.push_back("pattern may store, but mayStore isn't set");
3301 // Similarly, mayStore implies mayLoad on intrinsics.
3302 if (!PatInfo.mayStore && PatInfo.mayLoad && !NumLoads)
3303 Msgs.push_back("pattern may load, but mayLoad isn't set");
3305 // Print error messages.
3310 for (const std::string &Msg : Msgs)
3311 PrintError(PTM.getSrcRecord()->getLoc(), Twine(Msg) + " on the " +
3312 (Instrs.size() == 1 ?
3313 "instruction" : "output instructions"));
3314 // Provide the location of the relevant instruction definitions.
3315 for (const Record *Instr : Instrs) {
3316 if (Instr != PTM.getSrcRecord())
3317 PrintError(Instr->getLoc(), "defined here");
3318 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
3319 if (InstInfo.InferredFrom &&
3320 InstInfo.InferredFrom != InstInfo.TheDef &&
3321 InstInfo.InferredFrom != PTM.getSrcRecord())
3322 PrintError(InstInfo.InferredFrom->getLoc(), "inferred from pattern");
3326 PrintFatalError("Errors in DAG patterns");
3329 /// Given a pattern result with an unresolved type, see if we can find one
3330 /// instruction with an unresolved result type. Force this result type to an
3331 /// arbitrary element if it's possible types to converge results.
3332 static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
3336 // Analyze children.
3337 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3338 if (ForceArbitraryInstResultType(N->getChild(i), TP))
3341 if (!N->getOperator()->isSubClassOf("Instruction"))
3344 // If this type is already concrete or completely unknown we can't do
3346 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
3347 if (N->getExtType(i).isCompletelyUnknown() || N->getExtType(i).isConcrete())
3350 // Otherwise, force its type to the first possibility (an arbitrary choice).
3351 if (N->getExtType(i).MergeInTypeInfo(N->getExtType(i).getTypeList()[0], TP))
3358 void CodeGenDAGPatterns::ParsePatterns() {
3359 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
3361 for (Record *CurPattern : Patterns) {
3362 DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
3364 // If the pattern references the null_frag, there's nothing to do.
3365 if (hasNullFragReference(Tree))
3368 TreePattern *Pattern = new TreePattern(CurPattern, Tree, true, *this);
3370 // Inline pattern fragments into it.
3371 Pattern->InlinePatternFragments();
3373 ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
3374 if (LI->empty()) continue; // no pattern.
3376 // Parse the instruction.
3377 TreePattern Result(CurPattern, LI, false, *this);
3379 // Inline pattern fragments into it.
3380 Result.InlinePatternFragments();
3382 if (Result.getNumTrees() != 1)
3383 Result.error("Cannot handle instructions producing instructions "
3384 "with temporaries yet!");
3386 bool IterateInference;
3387 bool InferredAllPatternTypes, InferredAllResultTypes;
3389 // Infer as many types as possible. If we cannot infer all of them, we
3390 // can never do anything with this pattern: report it to the user.
3391 InferredAllPatternTypes =
3392 Pattern->InferAllTypes(&Pattern->getNamedNodesMap());
3394 // Infer as many types as possible. If we cannot infer all of them, we
3395 // can never do anything with this pattern: report it to the user.
3396 InferredAllResultTypes =
3397 Result.InferAllTypes(&Pattern->getNamedNodesMap());
3399 IterateInference = false;
3401 // Apply the type of the result to the source pattern. This helps us
3402 // resolve cases where the input type is known to be a pointer type (which
3403 // is considered resolved), but the result knows it needs to be 32- or
3404 // 64-bits. Infer the other way for good measure.
3405 for (unsigned i = 0, e = std::min(Result.getTree(0)->getNumTypes(),
3406 Pattern->getTree(0)->getNumTypes());
3408 IterateInference = Pattern->getTree(0)->UpdateNodeType(
3409 i, Result.getTree(0)->getExtType(i), Result);
3410 IterateInference |= Result.getTree(0)->UpdateNodeType(
3411 i, Pattern->getTree(0)->getExtType(i), Result);
3414 // If our iteration has converged and the input pattern's types are fully
3415 // resolved but the result pattern is not fully resolved, we may have a
3416 // situation where we have two instructions in the result pattern and
3417 // the instructions require a common register class, but don't care about
3418 // what actual MVT is used. This is actually a bug in our modelling:
3419 // output patterns should have register classes, not MVTs.
3421 // In any case, to handle this, we just go through and disambiguate some
3422 // arbitrary types to the result pattern's nodes.
3423 if (!IterateInference && InferredAllPatternTypes &&
3424 !InferredAllResultTypes)
3426 ForceArbitraryInstResultType(Result.getTree(0), Result);
3427 } while (IterateInference);
3429 // Verify that we inferred enough types that we can do something with the
3430 // pattern and result. If these fire the user has to add type casts.
3431 if (!InferredAllPatternTypes)
3432 Pattern->error("Could not infer all types in pattern!");
3433 if (!InferredAllResultTypes) {
3435 Result.error("Could not infer all types in pattern result!");
3438 // Validate that the input pattern is correct.
3439 std::map<std::string, TreePatternNode*> InstInputs;
3440 std::map<std::string, TreePatternNode*> InstResults;
3441 std::vector<Record*> InstImpResults;
3442 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
3443 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
3444 InstInputs, InstResults,
3447 // Promote the xform function to be an explicit node if set.
3448 TreePatternNode *DstPattern = Result.getOnlyTree();
3449 std::vector<TreePatternNode*> ResultNodeOperands;
3450 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
3451 TreePatternNode *OpNode = DstPattern->getChild(ii);
3452 if (Record *Xform = OpNode->getTransformFn()) {
3453 OpNode->setTransformFn(nullptr);
3454 std::vector<TreePatternNode*> Children;
3455 Children.push_back(OpNode);
3456 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
3458 ResultNodeOperands.push_back(OpNode);
3460 DstPattern = Result.getOnlyTree();
3461 if (!DstPattern->isLeaf())
3462 DstPattern = new TreePatternNode(DstPattern->getOperator(),
3464 DstPattern->getNumTypes());
3466 for (unsigned i = 0, e = Result.getOnlyTree()->getNumTypes(); i != e; ++i)
3467 DstPattern->setType(i, Result.getOnlyTree()->getExtType(i));
3469 TreePattern Temp(Result.getRecord(), DstPattern, false, *this);
3470 Temp.InferAllTypes();
3473 AddPatternToMatch(Pattern,
3474 PatternToMatch(CurPattern,
3475 CurPattern->getValueAsListInit("Predicates"),
3476 Pattern->getTree(0),
3477 Temp.getOnlyTree(), InstImpResults,
3478 CurPattern->getValueAsInt("AddedComplexity"),
3479 CurPattern->getID()));
3483 /// CombineChildVariants - Given a bunch of permutations of each child of the
3484 /// 'operator' node, put them together in all possible ways.
3485 static void CombineChildVariants(TreePatternNode *Orig,
3486 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
3487 std::vector<TreePatternNode*> &OutVariants,
3488 CodeGenDAGPatterns &CDP,
3489 const MultipleUseVarSet &DepVars) {
3490 // Make sure that each operand has at least one variant to choose from.
3491 for (const auto &Variants : ChildVariants)
3492 if (Variants.empty())
3495 // The end result is an all-pairs construction of the resultant pattern.
3496 std::vector<unsigned> Idxs;
3497 Idxs.resize(ChildVariants.size());
3501 DEBUG(if (!Idxs.empty()) {
3502 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
3503 for (unsigned Idx : Idxs) {
3504 errs() << Idx << " ";
3509 // Create the variant and add it to the output list.
3510 std::vector<TreePatternNode*> NewChildren;
3511 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
3512 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
3513 auto R = llvm::make_unique<TreePatternNode>(
3514 Orig->getOperator(), NewChildren, Orig->getNumTypes());
3516 // Copy over properties.
3517 R->setName(Orig->getName());
3518 R->setPredicateFns(Orig->getPredicateFns());
3519 R->setTransformFn(Orig->getTransformFn());
3520 for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
3521 R->setType(i, Orig->getExtType(i));
3523 // If this pattern cannot match, do not include it as a variant.
3524 std::string ErrString;
3525 // Scan to see if this pattern has already been emitted. We can get
3526 // duplication due to things like commuting:
3527 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
3528 // which are the same pattern. Ignore the dups.
3529 if (R->canPatternMatch(ErrString, CDP) &&
3530 std::none_of(OutVariants.begin(), OutVariants.end(),
3531 [&](TreePatternNode *Variant) {
3532 return R->isIsomorphicTo(Variant, DepVars);
3534 OutVariants.push_back(R.release());
3536 // Increment indices to the next permutation by incrementing the
3537 // indices from last index backward, e.g., generate the sequence
3538 // [0, 0], [0, 1], [1, 0], [1, 1].
3540 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
3541 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
3546 NotDone = (IdxsIdx >= 0);
3550 /// CombineChildVariants - A helper function for binary operators.
3552 static void CombineChildVariants(TreePatternNode *Orig,
3553 const std::vector<TreePatternNode*> &LHS,
3554 const std::vector<TreePatternNode*> &RHS,
3555 std::vector<TreePatternNode*> &OutVariants,
3556 CodeGenDAGPatterns &CDP,
3557 const MultipleUseVarSet &DepVars) {
3558 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3559 ChildVariants.push_back(LHS);
3560 ChildVariants.push_back(RHS);
3561 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
3565 static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
3566 std::vector<TreePatternNode *> &Children) {
3567 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
3568 Record *Operator = N->getOperator();
3570 // Only permit raw nodes.
3571 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
3572 N->getTransformFn()) {
3573 Children.push_back(N);
3577 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
3578 Children.push_back(N->getChild(0));
3580 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
3582 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
3583 Children.push_back(N->getChild(1));
3585 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
3588 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
3589 /// the (potentially recursive) pattern by using algebraic laws.
3591 static void GenerateVariantsOf(TreePatternNode *N,
3592 std::vector<TreePatternNode*> &OutVariants,
3593 CodeGenDAGPatterns &CDP,
3594 const MultipleUseVarSet &DepVars) {
3595 // We cannot permute leaves or ComplexPattern uses.
3596 if (N->isLeaf() || N->getOperator()->isSubClassOf("ComplexPattern")) {
3597 OutVariants.push_back(N);
3601 // Look up interesting info about the node.
3602 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
3604 // If this node is associative, re-associate.
3605 if (NodeInfo.hasProperty(SDNPAssociative)) {
3606 // Re-associate by pulling together all of the linked operators
3607 std::vector<TreePatternNode*> MaximalChildren;
3608 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
3610 // Only handle child sizes of 3. Otherwise we'll end up trying too many
3612 if (MaximalChildren.size() == 3) {
3613 // Find the variants of all of our maximal children.
3614 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
3615 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
3616 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
3617 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
3619 // There are only two ways we can permute the tree:
3620 // (A op B) op C and A op (B op C)
3621 // Within these forms, we can also permute A/B/C.
3623 // Generate legal pair permutations of A/B/C.
3624 std::vector<TreePatternNode*> ABVariants;
3625 std::vector<TreePatternNode*> BAVariants;
3626 std::vector<TreePatternNode*> ACVariants;
3627 std::vector<TreePatternNode*> CAVariants;
3628 std::vector<TreePatternNode*> BCVariants;
3629 std::vector<TreePatternNode*> CBVariants;
3630 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
3631 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
3632 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
3633 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
3634 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
3635 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
3637 // Combine those into the result: (x op x) op x
3638 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
3639 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
3640 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
3641 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
3642 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
3643 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
3645 // Combine those into the result: x op (x op x)
3646 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
3647 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
3648 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
3649 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
3650 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
3651 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
3656 // Compute permutations of all children.
3657 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3658 ChildVariants.resize(N->getNumChildren());
3659 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3660 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
3662 // Build all permutations based on how the children were formed.
3663 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
3665 // If this node is commutative, consider the commuted order.
3666 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
3667 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
3668 assert((N->getNumChildren()==2 || isCommIntrinsic) &&
3669 "Commutative but doesn't have 2 children!");
3670 // Don't count children which are actually register references.
3672 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
3673 TreePatternNode *Child = N->getChild(i);
3674 if (Child->isLeaf())
3675 if (DefInit *DI = dyn_cast<DefInit>(Child->getLeafValue())) {
3676 Record *RR = DI->getDef();
3677 if (RR->isSubClassOf("Register"))
3682 // Consider the commuted order.
3683 if (isCommIntrinsic) {
3684 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
3685 // operands are the commutative operands, and there might be more operands
3688 "Commutative intrinsic should have at least 3 children!");
3689 std::vector<std::vector<TreePatternNode*> > Variants;
3690 Variants.push_back(ChildVariants[0]); // Intrinsic id.
3691 Variants.push_back(ChildVariants[2]);
3692 Variants.push_back(ChildVariants[1]);
3693 for (unsigned i = 3; i != NC; ++i)
3694 Variants.push_back(ChildVariants[i]);
3695 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
3697 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
3698 OutVariants, CDP, DepVars);
3703 // GenerateVariants - Generate variants. For example, commutative patterns can
3704 // match multiple ways. Add them to PatternsToMatch as well.
3705 void CodeGenDAGPatterns::GenerateVariants() {
3706 DEBUG(errs() << "Generating instruction variants.\n");
3708 // Loop over all of the patterns we've collected, checking to see if we can
3709 // generate variants of the instruction, through the exploitation of
3710 // identities. This permits the target to provide aggressive matching without
3711 // the .td file having to contain tons of variants of instructions.
3713 // Note that this loop adds new patterns to the PatternsToMatch list, but we
3714 // intentionally do not reconsider these. Any variants of added patterns have
3715 // already been added.
3717 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
3718 MultipleUseVarSet DepVars;
3719 std::vector<TreePatternNode*> Variants;
3720 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
3721 DEBUG(errs() << "Dependent/multiply used variables: ");
3722 DEBUG(DumpDepVars(DepVars));
3723 DEBUG(errs() << "\n");
3724 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this,
3727 assert(!Variants.empty() && "Must create at least original variant!");
3728 Variants.erase(Variants.begin()); // Remove the original pattern.
3730 if (Variants.empty()) // No variants for this pattern.
3733 DEBUG(errs() << "FOUND VARIANTS OF: ";
3734 PatternsToMatch[i].getSrcPattern()->dump();
3737 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
3738 TreePatternNode *Variant = Variants[v];
3740 DEBUG(errs() << " VAR#" << v << ": ";
3744 // Scan to see if an instruction or explicit pattern already matches this.
3745 bool AlreadyExists = false;
3746 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
3747 // Skip if the top level predicates do not match.
3748 if (PatternsToMatch[i].getPredicates() !=
3749 PatternsToMatch[p].getPredicates())
3751 // Check to see if this variant already exists.
3752 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),
3754 DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
3755 AlreadyExists = true;
3759 // If we already have it, ignore the variant.
3760 if (AlreadyExists) continue;
3762 // Otherwise, add it to the list of patterns we have.
3763 PatternsToMatch.emplace_back(
3764 PatternsToMatch[i].getSrcRecord(), PatternsToMatch[i].getPredicates(),
3765 Variant, PatternsToMatch[i].getDstPattern(),
3766 PatternsToMatch[i].getDstRegs(),
3767 PatternsToMatch[i].getAddedComplexity(), Record::getNewUID());
3770 DEBUG(errs() << "\n");