1 //===- CodeGenDAGPatterns.cpp - Read DAG patterns from .td file -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the CodeGenDAGPatterns class, which is used to read and
11 // represent the patterns present in a .td file for instructions.
13 //===----------------------------------------------------------------------===//
15 #include "CodeGenDAGPatterns.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/ADT/Twine.h"
19 #include "llvm/Support/Debug.h"
20 #include "llvm/Support/ErrorHandling.h"
21 #include "llvm/TableGen/Error.h"
22 #include "llvm/TableGen/Record.h"
28 #define DEBUG_TYPE "dag-patterns"
30 //===----------------------------------------------------------------------===//
31 // EEVT::TypeSet Implementation
32 //===----------------------------------------------------------------------===//
34 static inline bool isInteger(MVT::SimpleValueType VT) {
35 return MVT(VT).isInteger();
37 static inline bool isFloatingPoint(MVT::SimpleValueType VT) {
38 return MVT(VT).isFloatingPoint();
40 static inline bool isVector(MVT::SimpleValueType VT) {
41 return MVT(VT).isVector();
43 static inline bool isScalar(MVT::SimpleValueType VT) {
44 return !MVT(VT).isVector();
47 EEVT::TypeSet::TypeSet(MVT::SimpleValueType VT, TreePattern &TP) {
50 else if (VT == MVT::fAny)
51 EnforceFloatingPoint(TP);
52 else if (VT == MVT::vAny)
55 assert((VT < MVT::LAST_VALUETYPE || VT == MVT::iPTR ||
56 VT == MVT::iPTRAny || VT == MVT::Any) && "Not a concrete type!");
57 TypeVec.push_back(VT);
62 EEVT::TypeSet::TypeSet(ArrayRef<MVT::SimpleValueType> VTList) {
63 assert(!VTList.empty() && "empty list?");
64 TypeVec.append(VTList.begin(), VTList.end());
67 assert(VTList[0] != MVT::iAny && VTList[0] != MVT::vAny &&
68 VTList[0] != MVT::fAny);
70 // Verify no duplicates.
71 array_pod_sort(TypeVec.begin(), TypeVec.end());
72 assert(std::unique(TypeVec.begin(), TypeVec.end()) == TypeVec.end());
75 /// FillWithPossibleTypes - Set to all legal types and return true, only valid
76 /// on completely unknown type sets.
77 bool EEVT::TypeSet::FillWithPossibleTypes(TreePattern &TP,
78 bool (*Pred)(MVT::SimpleValueType),
79 const char *PredicateName) {
80 assert(isCompletelyUnknown());
81 ArrayRef<MVT::SimpleValueType> LegalTypes =
82 TP.getDAGPatterns().getTargetInfo().getLegalValueTypes();
87 for (MVT::SimpleValueType VT : LegalTypes)
88 if (!Pred || Pred(VT))
89 TypeVec.push_back(VT);
91 // If we have nothing that matches the predicate, bail out.
92 if (TypeVec.empty()) {
93 TP.error("Type inference contradiction found, no " +
94 std::string(PredicateName) + " types found");
97 // No need to sort with one element.
98 if (TypeVec.size() == 1) return true;
100 // Remove duplicates.
101 array_pod_sort(TypeVec.begin(), TypeVec.end());
102 TypeVec.erase(std::unique(TypeVec.begin(), TypeVec.end()), TypeVec.end());
107 /// hasIntegerTypes - Return true if this TypeSet contains iAny or an
108 /// integer value type.
109 bool EEVT::TypeSet::hasIntegerTypes() const {
110 return std::any_of(TypeVec.begin(), TypeVec.end(), isInteger);
113 /// hasFloatingPointTypes - Return true if this TypeSet contains an fAny or
114 /// a floating point value type.
115 bool EEVT::TypeSet::hasFloatingPointTypes() const {
116 return std::any_of(TypeVec.begin(), TypeVec.end(), isFloatingPoint);
119 /// hasScalarTypes - Return true if this TypeSet contains a scalar value type.
120 bool EEVT::TypeSet::hasScalarTypes() const {
121 return std::any_of(TypeVec.begin(), TypeVec.end(), isScalar);
124 /// hasVectorTypes - Return true if this TypeSet contains a vAny or a vector
126 bool EEVT::TypeSet::hasVectorTypes() const {
127 return std::any_of(TypeVec.begin(), TypeVec.end(), isVector);
131 std::string EEVT::TypeSet::getName() const {
132 if (TypeVec.empty()) return "<empty>";
136 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i) {
137 std::string VTName = llvm::getEnumName(TypeVec[i]);
138 // Strip off MVT:: prefix if present.
139 if (VTName.substr(0,5) == "MVT::")
140 VTName = VTName.substr(5);
141 if (i) Result += ':';
145 if (TypeVec.size() == 1)
147 return "{" + Result + "}";
150 /// MergeInTypeInfo - This merges in type information from the specified
151 /// argument. If 'this' changes, it returns true. If the two types are
152 /// contradictory (e.g. merge f32 into i32) then this flags an error.
153 bool EEVT::TypeSet::MergeInTypeInfo(const EEVT::TypeSet &InVT, TreePattern &TP){
154 if (InVT.isCompletelyUnknown() || *this == InVT || TP.hasError())
157 if (isCompletelyUnknown()) {
162 assert(!TypeVec.empty() && !InVT.TypeVec.empty() && "No unknowns");
164 // Handle the abstract cases, seeing if we can resolve them better.
165 switch (TypeVec[0]) {
169 if (InVT.hasIntegerTypes()) {
170 EEVT::TypeSet InCopy(InVT);
171 InCopy.EnforceInteger(TP);
172 InCopy.EnforceScalar(TP);
174 if (InCopy.isConcrete()) {
175 // If the RHS has one integer type, upgrade iPTR to i32.
176 TypeVec[0] = InVT.TypeVec[0];
180 // If the input has multiple scalar integers, this doesn't add any info.
181 if (!InCopy.isCompletelyUnknown())
187 // If the input constraint is iAny/iPTR and this is an integer type list,
188 // remove non-integer types from the list.
189 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
191 bool MadeChange = EnforceInteger(TP);
193 // If we're merging in iPTR/iPTRAny and the node currently has a list of
194 // multiple different integer types, replace them with a single iPTR.
195 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
196 TypeVec.size() != 1) {
197 TypeVec.assign(1, InVT.TypeVec[0]);
204 // If this is a type list and the RHS is a typelist as well, eliminate entries
205 // from this list that aren't in the other one.
206 TypeSet InputSet(*this);
209 std::set_intersection(InputSet.TypeVec.begin(), InputSet.TypeVec.end(),
210 InVT.TypeVec.begin(), InVT.TypeVec.end(),
211 std::back_inserter(TypeVec));
213 // If the intersection is the same size as the original set then we're done.
214 if (TypeVec.size() == InputSet.TypeVec.size())
217 // If we removed all of our types, we have a type contradiction.
218 if (!TypeVec.empty())
221 // FIXME: Really want an SMLoc here!
222 TP.error("Type inference contradiction found, merging '" +
223 InVT.getName() + "' into '" + InputSet.getName() + "'");
227 /// EnforceInteger - Remove all non-integer types from this set.
228 bool EEVT::TypeSet::EnforceInteger(TreePattern &TP) {
231 // If we know nothing, then get the full set.
233 return FillWithPossibleTypes(TP, isInteger, "integer");
235 if (!hasFloatingPointTypes())
238 TypeSet InputSet(*this);
240 // Filter out all the fp types.
241 TypeVec.erase(std::remove_if(TypeVec.begin(), TypeVec.end(),
242 std::not1(std::ptr_fun(isInteger))),
245 if (TypeVec.empty()) {
246 TP.error("Type inference contradiction found, '" +
247 InputSet.getName() + "' needs to be integer");
253 /// EnforceFloatingPoint - Remove all integer types from this set.
254 bool EEVT::TypeSet::EnforceFloatingPoint(TreePattern &TP) {
257 // If we know nothing, then get the full set.
259 return FillWithPossibleTypes(TP, isFloatingPoint, "floating point");
261 if (!hasIntegerTypes())
264 TypeSet InputSet(*this);
266 // Filter out all the integer types.
267 TypeVec.erase(std::remove_if(TypeVec.begin(), TypeVec.end(),
268 std::not1(std::ptr_fun(isFloatingPoint))),
271 if (TypeVec.empty()) {
272 TP.error("Type inference contradiction found, '" +
273 InputSet.getName() + "' needs to be floating point");
279 /// EnforceScalar - Remove all vector types from this.
280 bool EEVT::TypeSet::EnforceScalar(TreePattern &TP) {
284 // If we know nothing, then get the full set.
286 return FillWithPossibleTypes(TP, isScalar, "scalar");
288 if (!hasVectorTypes())
291 TypeSet InputSet(*this);
293 // Filter out all the vector types.
294 TypeVec.erase(std::remove_if(TypeVec.begin(), TypeVec.end(),
295 std::not1(std::ptr_fun(isScalar))),
298 if (TypeVec.empty()) {
299 TP.error("Type inference contradiction found, '" +
300 InputSet.getName() + "' needs to be scalar");
306 /// EnforceVector - Remove all vector types from this.
307 bool EEVT::TypeSet::EnforceVector(TreePattern &TP) {
311 // If we know nothing, then get the full set.
313 return FillWithPossibleTypes(TP, isVector, "vector");
315 TypeSet InputSet(*this);
316 bool MadeChange = false;
318 // Filter out all the scalar types.
319 TypeVec.erase(std::remove_if(TypeVec.begin(), TypeVec.end(),
320 std::not1(std::ptr_fun(isVector))),
323 if (TypeVec.empty()) {
324 TP.error("Type inference contradiction found, '" +
325 InputSet.getName() + "' needs to be a vector");
333 /// EnforceSmallerThan - 'this' must be a smaller VT than Other. For vectors
334 /// this should be based on the element type. Update this and other based on
335 /// this information.
336 bool EEVT::TypeSet::EnforceSmallerThan(EEVT::TypeSet &Other, TreePattern &TP) {
340 // Both operands must be integer or FP, but we don't care which.
341 bool MadeChange = false;
343 if (isCompletelyUnknown())
344 MadeChange = FillWithPossibleTypes(TP);
346 if (Other.isCompletelyUnknown())
347 MadeChange = Other.FillWithPossibleTypes(TP);
349 // If one side is known to be integer or known to be FP but the other side has
350 // no information, get at least the type integrality info in there.
351 if (!hasFloatingPointTypes())
352 MadeChange |= Other.EnforceInteger(TP);
353 else if (!hasIntegerTypes())
354 MadeChange |= Other.EnforceFloatingPoint(TP);
355 if (!Other.hasFloatingPointTypes())
356 MadeChange |= EnforceInteger(TP);
357 else if (!Other.hasIntegerTypes())
358 MadeChange |= EnforceFloatingPoint(TP);
360 assert(!isCompletelyUnknown() && !Other.isCompletelyUnknown() &&
361 "Should have a type list now");
363 // If one contains vectors but the other doesn't pull vectors out.
364 if (!hasVectorTypes())
365 MadeChange |= Other.EnforceScalar(TP);
366 else if (!hasScalarTypes())
367 MadeChange |= Other.EnforceVector(TP);
368 if (!Other.hasVectorTypes())
369 MadeChange |= EnforceScalar(TP);
370 else if (!Other.hasScalarTypes())
371 MadeChange |= EnforceVector(TP);
373 // This code does not currently handle nodes which have multiple types,
374 // where some types are integer, and some are fp. Assert that this is not
376 assert(!(hasIntegerTypes() && hasFloatingPointTypes()) &&
377 !(Other.hasIntegerTypes() && Other.hasFloatingPointTypes()) &&
378 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
383 // Okay, find the smallest type from current set and remove anything the
384 // same or smaller from the other set. We need to ensure that the scalar
385 // type size is smaller than the scalar size of the smallest type. For
386 // vectors, we also need to make sure that the total size is no larger than
387 // the size of the smallest type.
389 TypeSet InputSet(Other);
390 MVT Smallest = TypeVec[0];
391 auto I = std::remove_if(Other.TypeVec.begin(), Other.TypeVec.end(),
392 [Smallest](MVT OtherVT) {
393 // Don't compare vector and non-vector types.
394 if (OtherVT.isVector() != Smallest.isVector())
396 // The getSizeInBits() check here is only needed for vectors, but is
397 // a subset of the scalar check for scalars so no need to qualify.
398 return OtherVT.getScalarSizeInBits() <= Smallest.getScalarSizeInBits()||
399 OtherVT.getSizeInBits() < Smallest.getSizeInBits();
401 MadeChange |= I != Other.TypeVec.end(); // If we're about to remove types.
402 Other.TypeVec.erase(I, Other.TypeVec.end());
404 if (Other.TypeVec.empty()) {
405 TP.error("Type inference contradiction found, '" + InputSet.getName() +
406 "' has nothing larger than '" + getName() +"'!");
411 // Okay, find the largest type from the other set and remove anything the
412 // same or smaller from the current set. We need to ensure that the scalar
413 // type size is larger than the scalar size of the largest type. For
414 // vectors, we also need to make sure that the total size is no smaller than
415 // the size of the largest type.
417 TypeSet InputSet(*this);
418 MVT Largest = Other.TypeVec[Other.TypeVec.size()-1];
419 auto I = std::remove_if(TypeVec.begin(), TypeVec.end(),
420 [Largest](MVT OtherVT) {
421 // Don't compare vector and non-vector types.
422 if (OtherVT.isVector() != Largest.isVector())
424 return OtherVT.getScalarSizeInBits() >= Largest.getScalarSizeInBits() ||
425 OtherVT.getSizeInBits() > Largest.getSizeInBits();
427 MadeChange |= I != TypeVec.end(); // If we're about to remove types.
428 TypeVec.erase(I, TypeVec.end());
430 if (TypeVec.empty()) {
431 TP.error("Type inference contradiction found, '" + InputSet.getName() +
432 "' has nothing smaller than '" + Other.getName() +"'!");
440 /// EnforceVectorEltTypeIs - 'this' is now constrained to be a vector type
441 /// whose element is specified by VTOperand.
442 bool EEVT::TypeSet::EnforceVectorEltTypeIs(MVT::SimpleValueType VT,
444 bool MadeChange = false;
446 MadeChange |= EnforceVector(TP);
448 TypeSet InputSet(*this);
450 // Filter out all the types which don't have the right element type.
451 auto I = std::remove_if(TypeVec.begin(), TypeVec.end(),
453 return VVT.getVectorElementType().SimpleTy != VT;
455 MadeChange |= I != TypeVec.end();
456 TypeVec.erase(I, TypeVec.end());
458 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
459 TP.error("Type inference contradiction found, forcing '" +
460 InputSet.getName() + "' to have a vector element of type " +
468 /// EnforceVectorEltTypeIs - 'this' is now constrained to be a vector type
469 /// whose element is specified by VTOperand.
470 bool EEVT::TypeSet::EnforceVectorEltTypeIs(EEVT::TypeSet &VTOperand,
475 // "This" must be a vector and "VTOperand" must be a scalar.
476 bool MadeChange = false;
477 MadeChange |= EnforceVector(TP);
478 MadeChange |= VTOperand.EnforceScalar(TP);
480 // If we know the vector type, it forces the scalar to agree.
482 MVT IVT = getConcrete();
483 IVT = IVT.getVectorElementType();
484 return MadeChange || VTOperand.MergeInTypeInfo(IVT.SimpleTy, TP);
487 // If the scalar type is known, filter out vector types whose element types
489 if (!VTOperand.isConcrete())
492 MVT::SimpleValueType VT = VTOperand.getConcrete();
494 MadeChange |= EnforceVectorEltTypeIs(VT, TP);
499 /// EnforceVectorSubVectorTypeIs - 'this' is now constrained to be a
500 /// vector type specified by VTOperand.
501 bool EEVT::TypeSet::EnforceVectorSubVectorTypeIs(EEVT::TypeSet &VTOperand,
506 // "This" must be a vector and "VTOperand" must be a vector.
507 bool MadeChange = false;
508 MadeChange |= EnforceVector(TP);
509 MadeChange |= VTOperand.EnforceVector(TP);
511 // If one side is known to be integer or known to be FP but the other side has
512 // no information, get at least the type integrality info in there.
513 if (!hasFloatingPointTypes())
514 MadeChange |= VTOperand.EnforceInteger(TP);
515 else if (!hasIntegerTypes())
516 MadeChange |= VTOperand.EnforceFloatingPoint(TP);
517 if (!VTOperand.hasFloatingPointTypes())
518 MadeChange |= EnforceInteger(TP);
519 else if (!VTOperand.hasIntegerTypes())
520 MadeChange |= EnforceFloatingPoint(TP);
522 assert(!isCompletelyUnknown() && !VTOperand.isCompletelyUnknown() &&
523 "Should have a type list now");
525 // If we know the vector type, it forces the scalar types to agree.
526 // Also force one vector to have more elements than the other.
528 MVT IVT = getConcrete();
529 unsigned NumElems = IVT.getVectorNumElements();
530 IVT = IVT.getVectorElementType();
532 EEVT::TypeSet EltTypeSet(IVT.SimpleTy, TP);
533 MadeChange |= VTOperand.EnforceVectorEltTypeIs(EltTypeSet, TP);
535 // Only keep types that have less elements than VTOperand.
536 TypeSet InputSet(VTOperand);
538 auto I = std::remove_if(VTOperand.TypeVec.begin(), VTOperand.TypeVec.end(),
539 [NumElems](MVT VVT) {
540 return VVT.getVectorNumElements() >= NumElems;
542 MadeChange |= I != VTOperand.TypeVec.end();
543 VTOperand.TypeVec.erase(I, VTOperand.TypeVec.end());
545 if (VTOperand.TypeVec.empty()) { // FIXME: Really want an SMLoc here!
546 TP.error("Type inference contradiction found, forcing '" +
547 InputSet.getName() + "' to have less vector elements than '" +
551 } else if (VTOperand.isConcrete()) {
552 MVT IVT = VTOperand.getConcrete();
553 unsigned NumElems = IVT.getVectorNumElements();
554 IVT = IVT.getVectorElementType();
556 EEVT::TypeSet EltTypeSet(IVT.SimpleTy, TP);
557 MadeChange |= EnforceVectorEltTypeIs(EltTypeSet, TP);
559 // Only keep types that have more elements than 'this'.
560 TypeSet InputSet(*this);
562 auto I = std::remove_if(TypeVec.begin(), TypeVec.end(),
563 [NumElems](MVT VVT) {
564 return VVT.getVectorNumElements() <= NumElems;
566 MadeChange |= I != TypeVec.end();
567 TypeVec.erase(I, TypeVec.end());
569 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
570 TP.error("Type inference contradiction found, forcing '" +
571 InputSet.getName() + "' to have more vector elements than '" +
572 VTOperand.getName() + "'");
580 /// EnforceVectorSameNumElts - 'this' is now constrained to
581 /// be a vector with same num elements as VTOperand.
582 bool EEVT::TypeSet::EnforceVectorSameNumElts(EEVT::TypeSet &VTOperand,
587 // "This" must be a vector and "VTOperand" must be a vector.
588 bool MadeChange = false;
589 MadeChange |= EnforceVector(TP);
590 MadeChange |= VTOperand.EnforceVector(TP);
592 // If we know one of the vector types, it forces the other type to agree.
594 MVT IVT = getConcrete();
595 unsigned NumElems = IVT.getVectorNumElements();
597 // Only keep types that have same elements as 'this'.
598 TypeSet InputSet(VTOperand);
600 auto I = std::remove_if(VTOperand.TypeVec.begin(), VTOperand.TypeVec.end(),
601 [NumElems](MVT VVT) {
602 return VVT.getVectorNumElements() != NumElems;
604 MadeChange |= I != VTOperand.TypeVec.end();
605 VTOperand.TypeVec.erase(I, VTOperand.TypeVec.end());
607 if (VTOperand.TypeVec.empty()) { // FIXME: Really want an SMLoc here!
608 TP.error("Type inference contradiction found, forcing '" +
609 InputSet.getName() + "' to have same number elements as '" +
613 } else if (VTOperand.isConcrete()) {
614 MVT IVT = VTOperand.getConcrete();
615 unsigned NumElems = IVT.getVectorNumElements();
617 // Only keep types that have same elements as VTOperand.
618 TypeSet InputSet(*this);
620 auto I = std::remove_if(TypeVec.begin(), TypeVec.end(),
621 [NumElems](MVT VVT) {
622 return VVT.getVectorNumElements() != NumElems;
624 MadeChange |= I != TypeVec.end();
625 TypeVec.erase(I, TypeVec.end());
627 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
628 TP.error("Type inference contradiction found, forcing '" +
629 InputSet.getName() + "' to have same number elements than '" +
630 VTOperand.getName() + "'");
638 //===----------------------------------------------------------------------===//
639 // Helpers for working with extended types.
641 /// Dependent variable map for CodeGenDAGPattern variant generation
642 typedef std::map<std::string, int> DepVarMap;
644 static void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
646 if (isa<DefInit>(N->getLeafValue()))
647 DepMap[N->getName()]++;
649 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
650 FindDepVarsOf(N->getChild(i), DepMap);
654 /// Find dependent variables within child patterns
655 static void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
657 FindDepVarsOf(N, depcounts);
658 for (const std::pair<std::string, int> &Pair : depcounts) {
660 DepVars.insert(Pair.first);
665 /// Dump the dependent variable set:
666 static void DumpDepVars(MultipleUseVarSet &DepVars) {
667 if (DepVars.empty()) {
668 DEBUG(errs() << "<empty set>");
670 DEBUG(errs() << "[ ");
671 for (const std::string &DepVar : DepVars) {
672 DEBUG(errs() << DepVar << " ");
674 DEBUG(errs() << "]");
680 //===----------------------------------------------------------------------===//
681 // TreePredicateFn Implementation
682 //===----------------------------------------------------------------------===//
684 /// TreePredicateFn constructor. Here 'N' is a subclass of PatFrag.
685 TreePredicateFn::TreePredicateFn(TreePattern *N) : PatFragRec(N) {
686 assert((getPredCode().empty() || getImmCode().empty()) &&
687 ".td file corrupt: can't have a node predicate *and* an imm predicate");
690 std::string TreePredicateFn::getPredCode() const {
691 return PatFragRec->getRecord()->getValueAsString("PredicateCode");
694 std::string TreePredicateFn::getImmCode() const {
695 return PatFragRec->getRecord()->getValueAsString("ImmediateCode");
699 /// isAlwaysTrue - Return true if this is a noop predicate.
700 bool TreePredicateFn::isAlwaysTrue() const {
701 return getPredCode().empty() && getImmCode().empty();
704 /// Return the name to use in the generated code to reference this, this is
705 /// "Predicate_foo" if from a pattern fragment "foo".
706 std::string TreePredicateFn::getFnName() const {
707 return "Predicate_" + PatFragRec->getRecord()->getName();
710 /// getCodeToRunOnSDNode - Return the code for the function body that
711 /// evaluates this predicate. The argument is expected to be in "Node",
712 /// not N. This handles casting and conversion to a concrete node type as
714 std::string TreePredicateFn::getCodeToRunOnSDNode() const {
715 // Handle immediate predicates first.
716 std::string ImmCode = getImmCode();
717 if (!ImmCode.empty()) {
719 " int64_t Imm = cast<ConstantSDNode>(Node)->getSExtValue();\n";
720 return Result + ImmCode;
723 // Handle arbitrary node predicates.
724 assert(!getPredCode().empty() && "Don't have any predicate code!");
725 std::string ClassName;
726 if (PatFragRec->getOnlyTree()->isLeaf())
727 ClassName = "SDNode";
729 Record *Op = PatFragRec->getOnlyTree()->getOperator();
730 ClassName = PatFragRec->getDAGPatterns().getSDNodeInfo(Op).getSDClassName();
733 if (ClassName == "SDNode")
734 Result = " SDNode *N = Node;\n";
736 Result = " auto *N = cast<" + ClassName + ">(Node);\n";
738 return Result + getPredCode();
741 //===----------------------------------------------------------------------===//
742 // PatternToMatch implementation
746 /// getPatternSize - Return the 'size' of this pattern. We want to match large
747 /// patterns before small ones. This is used to determine the size of a
749 static unsigned getPatternSize(const TreePatternNode *P,
750 const CodeGenDAGPatterns &CGP) {
751 unsigned Size = 3; // The node itself.
752 // If the root node is a ConstantSDNode, increases its size.
753 // e.g. (set R32:$dst, 0).
754 if (P->isLeaf() && isa<IntInit>(P->getLeafValue()))
757 // FIXME: This is a hack to statically increase the priority of patterns
758 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
759 // Later we can allow complexity / cost for each pattern to be (optionally)
760 // specified. To get best possible pattern match we'll need to dynamically
761 // calculate the complexity of all patterns a dag can potentially map to.
762 const ComplexPattern *AM = P->getComplexPatternInfo(CGP);
764 Size += AM->getNumOperands() * 3;
766 // We don't want to count any children twice, so return early.
770 // If this node has some predicate function that must match, it adds to the
771 // complexity of this node.
772 if (!P->getPredicateFns().empty())
775 // Count children in the count if they are also nodes.
776 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
777 TreePatternNode *Child = P->getChild(i);
778 if (!Child->isLeaf() && Child->getNumTypes() &&
779 Child->getType(0) != MVT::Other)
780 Size += getPatternSize(Child, CGP);
781 else if (Child->isLeaf()) {
782 if (isa<IntInit>(Child->getLeafValue()))
783 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
784 else if (Child->getComplexPatternInfo(CGP))
785 Size += getPatternSize(Child, CGP);
786 else if (!Child->getPredicateFns().empty())
794 /// Compute the complexity metric for the input pattern. This roughly
795 /// corresponds to the number of nodes that are covered.
797 getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
798 return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();
802 /// getPredicateCheck - Return a single string containing all of this
803 /// pattern's predicates concatenated with "&&" operators.
805 std::string PatternToMatch::getPredicateCheck() const {
806 std::string PredicateCheck;
807 for (Init *I : Predicates->getValues()) {
808 if (DefInit *Pred = dyn_cast<DefInit>(I)) {
809 Record *Def = Pred->getDef();
810 if (!Def->isSubClassOf("Predicate")) {
814 llvm_unreachable("Unknown predicate type!");
816 if (!PredicateCheck.empty())
817 PredicateCheck += " && ";
818 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
822 return PredicateCheck;
825 //===----------------------------------------------------------------------===//
826 // SDTypeConstraint implementation
829 SDTypeConstraint::SDTypeConstraint(Record *R) {
830 OperandNo = R->getValueAsInt("OperandNum");
832 if (R->isSubClassOf("SDTCisVT")) {
833 ConstraintType = SDTCisVT;
834 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
835 if (x.SDTCisVT_Info.VT == MVT::isVoid)
836 PrintFatalError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
838 } else if (R->isSubClassOf("SDTCisPtrTy")) {
839 ConstraintType = SDTCisPtrTy;
840 } else if (R->isSubClassOf("SDTCisInt")) {
841 ConstraintType = SDTCisInt;
842 } else if (R->isSubClassOf("SDTCisFP")) {
843 ConstraintType = SDTCisFP;
844 } else if (R->isSubClassOf("SDTCisVec")) {
845 ConstraintType = SDTCisVec;
846 } else if (R->isSubClassOf("SDTCisSameAs")) {
847 ConstraintType = SDTCisSameAs;
848 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
849 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
850 ConstraintType = SDTCisVTSmallerThanOp;
851 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
852 R->getValueAsInt("OtherOperandNum");
853 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
854 ConstraintType = SDTCisOpSmallerThanOp;
855 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
856 R->getValueAsInt("BigOperandNum");
857 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
858 ConstraintType = SDTCisEltOfVec;
859 x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
860 } else if (R->isSubClassOf("SDTCisSubVecOfVec")) {
861 ConstraintType = SDTCisSubVecOfVec;
862 x.SDTCisSubVecOfVec_Info.OtherOperandNum =
863 R->getValueAsInt("OtherOpNum");
864 } else if (R->isSubClassOf("SDTCVecEltisVT")) {
865 ConstraintType = SDTCVecEltisVT;
866 x.SDTCVecEltisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
867 if (MVT(x.SDTCVecEltisVT_Info.VT).isVector())
868 PrintFatalError(R->getLoc(), "Cannot use vector type as SDTCVecEltisVT");
869 if (!MVT(x.SDTCVecEltisVT_Info.VT).isInteger() &&
870 !MVT(x.SDTCVecEltisVT_Info.VT).isFloatingPoint())
871 PrintFatalError(R->getLoc(), "Must use integer or floating point type "
872 "as SDTCVecEltisVT");
873 } else if (R->isSubClassOf("SDTCisSameNumEltsAs")) {
874 ConstraintType = SDTCisSameNumEltsAs;
875 x.SDTCisSameNumEltsAs_Info.OtherOperandNum =
876 R->getValueAsInt("OtherOperandNum");
878 PrintFatalError("Unrecognized SDTypeConstraint '" + R->getName() + "'!\n");
882 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
883 /// N, and the result number in ResNo.
884 static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
885 const SDNodeInfo &NodeInfo,
887 unsigned NumResults = NodeInfo.getNumResults();
888 if (OpNo < NumResults) {
895 if (OpNo >= N->getNumChildren()) {
897 raw_string_ostream OS(S);
898 OS << "Invalid operand number in type constraint "
899 << (OpNo+NumResults) << " ";
901 PrintFatalError(OS.str());
904 return N->getChild(OpNo);
907 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
908 /// constraint to the nodes operands. This returns true if it makes a
909 /// change, false otherwise. If a type contradiction is found, flag an error.
910 bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
911 const SDNodeInfo &NodeInfo,
912 TreePattern &TP) const {
916 unsigned ResNo = 0; // The result number being referenced.
917 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
919 switch (ConstraintType) {
921 // Operand must be a particular type.
922 return NodeToApply->UpdateNodeType(ResNo, x.SDTCisVT_Info.VT, TP);
924 // Operand must be same as target pointer type.
925 return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
927 // Require it to be one of the legal integer VTs.
928 return NodeToApply->getExtType(ResNo).EnforceInteger(TP);
930 // Require it to be one of the legal fp VTs.
931 return NodeToApply->getExtType(ResNo).EnforceFloatingPoint(TP);
933 // Require it to be one of the legal vector VTs.
934 return NodeToApply->getExtType(ResNo).EnforceVector(TP);
937 TreePatternNode *OtherNode =
938 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
939 return NodeToApply->UpdateNodeType(ResNo, OtherNode->getExtType(OResNo),TP)|
940 OtherNode->UpdateNodeType(OResNo,NodeToApply->getExtType(ResNo),TP);
942 case SDTCisVTSmallerThanOp: {
943 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
944 // have an integer type that is smaller than the VT.
945 if (!NodeToApply->isLeaf() ||
946 !isa<DefInit>(NodeToApply->getLeafValue()) ||
947 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
948 ->isSubClassOf("ValueType")) {
949 TP.error(N->getOperator()->getName() + " expects a VT operand!");
952 MVT::SimpleValueType VT =
953 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
955 EEVT::TypeSet TypeListTmp(VT, TP);
958 TreePatternNode *OtherNode =
959 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
962 return TypeListTmp.EnforceSmallerThan(OtherNode->getExtType(OResNo), TP);
964 case SDTCisOpSmallerThanOp: {
966 TreePatternNode *BigOperand =
967 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
969 return NodeToApply->getExtType(ResNo).
970 EnforceSmallerThan(BigOperand->getExtType(BResNo), TP);
972 case SDTCisEltOfVec: {
974 TreePatternNode *VecOperand =
975 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
978 // Filter vector types out of VecOperand that don't have the right element
980 return VecOperand->getExtType(VResNo).
981 EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), TP);
983 case SDTCisSubVecOfVec: {
985 TreePatternNode *BigVecOperand =
986 getOperandNum(x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo,
989 // Filter vector types out of BigVecOperand that don't have the
990 // right subvector type.
991 return BigVecOperand->getExtType(VResNo).
992 EnforceVectorSubVectorTypeIs(NodeToApply->getExtType(ResNo), TP);
994 case SDTCVecEltisVT: {
995 return NodeToApply->getExtType(ResNo).
996 EnforceVectorEltTypeIs(x.SDTCVecEltisVT_Info.VT, TP);
998 case SDTCisSameNumEltsAs: {
1000 TreePatternNode *OtherNode =
1001 getOperandNum(x.SDTCisSameNumEltsAs_Info.OtherOperandNum,
1002 N, NodeInfo, OResNo);
1003 return OtherNode->getExtType(OResNo).
1004 EnforceVectorSameNumElts(NodeToApply->getExtType(ResNo), TP);
1007 llvm_unreachable("Invalid ConstraintType!");
1010 // Update the node type to match an instruction operand or result as specified
1011 // in the ins or outs lists on the instruction definition. Return true if the
1012 // type was actually changed.
1013 bool TreePatternNode::UpdateNodeTypeFromInst(unsigned ResNo,
1016 // The 'unknown' operand indicates that types should be inferred from the
1018 if (Operand->isSubClassOf("unknown_class"))
1021 // The Operand class specifies a type directly.
1022 if (Operand->isSubClassOf("Operand"))
1023 return UpdateNodeType(ResNo, getValueType(Operand->getValueAsDef("Type")),
1026 // PointerLikeRegClass has a type that is determined at runtime.
1027 if (Operand->isSubClassOf("PointerLikeRegClass"))
1028 return UpdateNodeType(ResNo, MVT::iPTR, TP);
1030 // Both RegisterClass and RegisterOperand operands derive their types from a
1031 // register class def.
1032 Record *RC = nullptr;
1033 if (Operand->isSubClassOf("RegisterClass"))
1035 else if (Operand->isSubClassOf("RegisterOperand"))
1036 RC = Operand->getValueAsDef("RegClass");
1038 assert(RC && "Unknown operand type");
1039 CodeGenTarget &Tgt = TP.getDAGPatterns().getTargetInfo();
1040 return UpdateNodeType(ResNo, Tgt.getRegisterClass(RC).getValueTypes(), TP);
1044 //===----------------------------------------------------------------------===//
1045 // SDNodeInfo implementation
1047 SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
1048 EnumName = R->getValueAsString("Opcode");
1049 SDClassName = R->getValueAsString("SDClass");
1050 Record *TypeProfile = R->getValueAsDef("TypeProfile");
1051 NumResults = TypeProfile->getValueAsInt("NumResults");
1052 NumOperands = TypeProfile->getValueAsInt("NumOperands");
1054 // Parse the properties.
1056 for (Record *Property : R->getValueAsListOfDefs("Properties")) {
1057 if (Property->getName() == "SDNPCommutative") {
1058 Properties |= 1 << SDNPCommutative;
1059 } else if (Property->getName() == "SDNPAssociative") {
1060 Properties |= 1 << SDNPAssociative;
1061 } else if (Property->getName() == "SDNPHasChain") {
1062 Properties |= 1 << SDNPHasChain;
1063 } else if (Property->getName() == "SDNPOutGlue") {
1064 Properties |= 1 << SDNPOutGlue;
1065 } else if (Property->getName() == "SDNPInGlue") {
1066 Properties |= 1 << SDNPInGlue;
1067 } else if (Property->getName() == "SDNPOptInGlue") {
1068 Properties |= 1 << SDNPOptInGlue;
1069 } else if (Property->getName() == "SDNPMayStore") {
1070 Properties |= 1 << SDNPMayStore;
1071 } else if (Property->getName() == "SDNPMayLoad") {
1072 Properties |= 1 << SDNPMayLoad;
1073 } else if (Property->getName() == "SDNPSideEffect") {
1074 Properties |= 1 << SDNPSideEffect;
1075 } else if (Property->getName() == "SDNPMemOperand") {
1076 Properties |= 1 << SDNPMemOperand;
1077 } else if (Property->getName() == "SDNPVariadic") {
1078 Properties |= 1 << SDNPVariadic;
1080 PrintFatalError("Unknown SD Node property '" +
1081 Property->getName() + "' on node '" +
1082 R->getName() + "'!");
1087 // Parse the type constraints.
1088 std::vector<Record*> ConstraintList =
1089 TypeProfile->getValueAsListOfDefs("Constraints");
1090 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
1093 /// getKnownType - If the type constraints on this node imply a fixed type
1094 /// (e.g. all stores return void, etc), then return it as an
1095 /// MVT::SimpleValueType. Otherwise, return EEVT::Other.
1096 MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
1097 unsigned NumResults = getNumResults();
1098 assert(NumResults <= 1 &&
1099 "We only work with nodes with zero or one result so far!");
1100 assert(ResNo == 0 && "Only handles single result nodes so far");
1102 for (const SDTypeConstraint &Constraint : TypeConstraints) {
1103 // Make sure that this applies to the correct node result.
1104 if (Constraint.OperandNo >= NumResults) // FIXME: need value #
1107 switch (Constraint.ConstraintType) {
1109 case SDTypeConstraint::SDTCisVT:
1110 return Constraint.x.SDTCisVT_Info.VT;
1111 case SDTypeConstraint::SDTCisPtrTy:
1118 //===----------------------------------------------------------------------===//
1119 // TreePatternNode implementation
1122 TreePatternNode::~TreePatternNode() {
1123 #if 0 // FIXME: implement refcounted tree nodes!
1124 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1129 static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
1130 if (Operator->getName() == "set" ||
1131 Operator->getName() == "implicit")
1132 return 0; // All return nothing.
1134 if (Operator->isSubClassOf("Intrinsic"))
1135 return CDP.getIntrinsic(Operator).IS.RetVTs.size();
1137 if (Operator->isSubClassOf("SDNode"))
1138 return CDP.getSDNodeInfo(Operator).getNumResults();
1140 if (Operator->isSubClassOf("PatFrag")) {
1141 // If we've already parsed this pattern fragment, get it. Otherwise, handle
1142 // the forward reference case where one pattern fragment references another
1143 // before it is processed.
1144 if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator))
1145 return PFRec->getOnlyTree()->getNumTypes();
1147 // Get the result tree.
1148 DagInit *Tree = Operator->getValueAsDag("Fragment");
1149 Record *Op = nullptr;
1151 if (DefInit *DI = dyn_cast<DefInit>(Tree->getOperator()))
1153 assert(Op && "Invalid Fragment");
1154 return GetNumNodeResults(Op, CDP);
1157 if (Operator->isSubClassOf("Instruction")) {
1158 CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
1160 unsigned NumDefsToAdd = InstInfo.Operands.NumDefs;
1162 // Subtract any defaulted outputs.
1163 for (unsigned i = 0; i != InstInfo.Operands.NumDefs; ++i) {
1164 Record *OperandNode = InstInfo.Operands[i].Rec;
1166 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
1167 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1171 // Add on one implicit def if it has a resolvable type.
1172 if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
1174 return NumDefsToAdd;
1177 if (Operator->isSubClassOf("SDNodeXForm"))
1178 return 1; // FIXME: Generalize SDNodeXForm
1180 if (Operator->isSubClassOf("ValueType"))
1181 return 1; // A type-cast of one result.
1183 if (Operator->isSubClassOf("ComplexPattern"))
1187 PrintFatalError("Unhandled node in GetNumNodeResults");
1190 void TreePatternNode::print(raw_ostream &OS) const {
1192 OS << *getLeafValue();
1194 OS << '(' << getOperator()->getName();
1196 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1197 OS << ':' << getExtType(i).getName();
1200 if (getNumChildren() != 0) {
1202 getChild(0)->print(OS);
1203 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
1205 getChild(i)->print(OS);
1211 for (const TreePredicateFn &Pred : PredicateFns)
1212 OS << "<<P:" << Pred.getFnName() << ">>";
1214 OS << "<<X:" << TransformFn->getName() << ">>";
1215 if (!getName().empty())
1216 OS << ":$" << getName();
1219 void TreePatternNode::dump() const {
1223 /// isIsomorphicTo - Return true if this node is recursively
1224 /// isomorphic to the specified node. For this comparison, the node's
1225 /// entire state is considered. The assigned name is ignored, since
1226 /// nodes with differing names are considered isomorphic. However, if
1227 /// the assigned name is present in the dependent variable set, then
1228 /// the assigned name is considered significant and the node is
1229 /// isomorphic if the names match.
1230 bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
1231 const MultipleUseVarSet &DepVars) const {
1232 if (N == this) return true;
1233 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
1234 getPredicateFns() != N->getPredicateFns() ||
1235 getTransformFn() != N->getTransformFn())
1239 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
1240 if (DefInit *NDI = dyn_cast<DefInit>(N->getLeafValue())) {
1241 return ((DI->getDef() == NDI->getDef())
1242 && (DepVars.find(getName()) == DepVars.end()
1243 || getName() == N->getName()));
1246 return getLeafValue() == N->getLeafValue();
1249 if (N->getOperator() != getOperator() ||
1250 N->getNumChildren() != getNumChildren()) return false;
1251 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1252 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
1257 /// clone - Make a copy of this tree and all of its children.
1259 TreePatternNode *TreePatternNode::clone() const {
1260 TreePatternNode *New;
1262 New = new TreePatternNode(getLeafValue(), getNumTypes());
1264 std::vector<TreePatternNode*> CChildren;
1265 CChildren.reserve(Children.size());
1266 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1267 CChildren.push_back(getChild(i)->clone());
1268 New = new TreePatternNode(getOperator(), CChildren, getNumTypes());
1270 New->setName(getName());
1272 New->setPredicateFns(getPredicateFns());
1273 New->setTransformFn(getTransformFn());
1277 /// RemoveAllTypes - Recursively strip all the types of this tree.
1278 void TreePatternNode::RemoveAllTypes() {
1279 // Reset to unknown type.
1280 std::fill(Types.begin(), Types.end(), EEVT::TypeSet());
1281 if (isLeaf()) return;
1282 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1283 getChild(i)->RemoveAllTypes();
1287 /// SubstituteFormalArguments - Replace the formal arguments in this tree
1288 /// with actual values specified by ArgMap.
1289 void TreePatternNode::
1290 SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
1291 if (isLeaf()) return;
1293 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1294 TreePatternNode *Child = getChild(i);
1295 if (Child->isLeaf()) {
1296 Init *Val = Child->getLeafValue();
1297 // Note that, when substituting into an output pattern, Val might be an
1299 if (isa<UnsetInit>(Val) || (isa<DefInit>(Val) &&
1300 cast<DefInit>(Val)->getDef()->getName() == "node")) {
1301 // We found a use of a formal argument, replace it with its value.
1302 TreePatternNode *NewChild = ArgMap[Child->getName()];
1303 assert(NewChild && "Couldn't find formal argument!");
1304 assert((Child->getPredicateFns().empty() ||
1305 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1306 "Non-empty child predicate clobbered!");
1307 setChild(i, NewChild);
1310 getChild(i)->SubstituteFormalArguments(ArgMap);
1316 /// InlinePatternFragments - If this pattern refers to any pattern
1317 /// fragments, inline them into place, giving us a pattern without any
1318 /// PatFrag references.
1319 TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
1324 return this; // nothing to do.
1325 Record *Op = getOperator();
1327 if (!Op->isSubClassOf("PatFrag")) {
1328 // Just recursively inline children nodes.
1329 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1330 TreePatternNode *Child = getChild(i);
1331 TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
1333 assert((Child->getPredicateFns().empty() ||
1334 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1335 "Non-empty child predicate clobbered!");
1337 setChild(i, NewChild);
1342 // Otherwise, we found a reference to a fragment. First, look up its
1343 // TreePattern record.
1344 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
1346 // Verify that we are passing the right number of operands.
1347 if (Frag->getNumArgs() != Children.size()) {
1348 TP.error("'" + Op->getName() + "' fragment requires " +
1349 utostr(Frag->getNumArgs()) + " operands!");
1353 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
1355 TreePredicateFn PredFn(Frag);
1356 if (!PredFn.isAlwaysTrue())
1357 FragTree->addPredicateFn(PredFn);
1359 // Resolve formal arguments to their actual value.
1360 if (Frag->getNumArgs()) {
1361 // Compute the map of formal to actual arguments.
1362 std::map<std::string, TreePatternNode*> ArgMap;
1363 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
1364 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
1366 FragTree->SubstituteFormalArguments(ArgMap);
1369 FragTree->setName(getName());
1370 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1371 FragTree->UpdateNodeType(i, getExtType(i), TP);
1373 // Transfer in the old predicates.
1374 for (const TreePredicateFn &Pred : getPredicateFns())
1375 FragTree->addPredicateFn(Pred);
1377 // Get a new copy of this fragment to stitch into here.
1378 //delete this; // FIXME: implement refcounting!
1380 // The fragment we inlined could have recursive inlining that is needed. See
1381 // if there are any pattern fragments in it and inline them as needed.
1382 return FragTree->InlinePatternFragments(TP);
1385 /// getImplicitType - Check to see if the specified record has an implicit
1386 /// type which should be applied to it. This will infer the type of register
1387 /// references from the register file information, for example.
1389 /// When Unnamed is set, return the type of a DAG operand with no name, such as
1390 /// the F8RC register class argument in:
1392 /// (COPY_TO_REGCLASS GPR:$src, F8RC)
1394 /// When Unnamed is false, return the type of a named DAG operand such as the
1395 /// GPR:$src operand above.
1397 static EEVT::TypeSet getImplicitType(Record *R, unsigned ResNo,
1401 // Check to see if this is a register operand.
1402 if (R->isSubClassOf("RegisterOperand")) {
1403 assert(ResNo == 0 && "Regoperand ref only has one result!");
1405 return EEVT::TypeSet(); // Unknown.
1406 Record *RegClass = R->getValueAsDef("RegClass");
1407 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1408 return EEVT::TypeSet(T.getRegisterClass(RegClass).getValueTypes());
1411 // Check to see if this is a register or a register class.
1412 if (R->isSubClassOf("RegisterClass")) {
1413 assert(ResNo == 0 && "Regclass ref only has one result!");
1414 // An unnamed register class represents itself as an i32 immediate, for
1415 // example on a COPY_TO_REGCLASS instruction.
1417 return EEVT::TypeSet(MVT::i32, TP);
1419 // In a named operand, the register class provides the possible set of
1422 return EEVT::TypeSet(); // Unknown.
1423 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1424 return EEVT::TypeSet(T.getRegisterClass(R).getValueTypes());
1427 if (R->isSubClassOf("PatFrag")) {
1428 assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
1429 // Pattern fragment types will be resolved when they are inlined.
1430 return EEVT::TypeSet(); // Unknown.
1433 if (R->isSubClassOf("Register")) {
1434 assert(ResNo == 0 && "Registers only produce one result!");
1436 return EEVT::TypeSet(); // Unknown.
1437 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1438 return EEVT::TypeSet(T.getRegisterVTs(R));
1441 if (R->isSubClassOf("SubRegIndex")) {
1442 assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
1443 return EEVT::TypeSet(MVT::i32, TP);
1446 if (R->isSubClassOf("ValueType")) {
1447 assert(ResNo == 0 && "This node only has one result!");
1448 // An unnamed VTSDNode represents itself as an MVT::Other immediate.
1450 // (sext_inreg GPR:$src, i16)
1453 return EEVT::TypeSet(MVT::Other, TP);
1454 // With a name, the ValueType simply provides the type of the named
1457 // (sext_inreg i32:$src, i16)
1460 return EEVT::TypeSet(); // Unknown.
1461 return EEVT::TypeSet(getValueType(R), TP);
1464 if (R->isSubClassOf("CondCode")) {
1465 assert(ResNo == 0 && "This node only has one result!");
1466 // Using a CondCodeSDNode.
1467 return EEVT::TypeSet(MVT::Other, TP);
1470 if (R->isSubClassOf("ComplexPattern")) {
1471 assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
1473 return EEVT::TypeSet(); // Unknown.
1474 return EEVT::TypeSet(TP.getDAGPatterns().getComplexPattern(R).getValueType(),
1477 if (R->isSubClassOf("PointerLikeRegClass")) {
1478 assert(ResNo == 0 && "Regclass can only have one result!");
1479 return EEVT::TypeSet(MVT::iPTR, TP);
1482 if (R->getName() == "node" || R->getName() == "srcvalue" ||
1483 R->getName() == "zero_reg") {
1485 return EEVT::TypeSet(); // Unknown.
1488 if (R->isSubClassOf("Operand"))
1489 return EEVT::TypeSet(getValueType(R->getValueAsDef("Type")));
1491 TP.error("Unknown node flavor used in pattern: " + R->getName());
1492 return EEVT::TypeSet(MVT::Other, TP);
1496 /// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
1497 /// CodeGenIntrinsic information for it, otherwise return a null pointer.
1498 const CodeGenIntrinsic *TreePatternNode::
1499 getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
1500 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
1501 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
1502 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
1505 unsigned IID = cast<IntInit>(getChild(0)->getLeafValue())->getValue();
1506 return &CDP.getIntrinsicInfo(IID);
1509 /// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
1510 /// return the ComplexPattern information, otherwise return null.
1511 const ComplexPattern *
1512 TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
1515 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
1520 Rec = getOperator();
1522 if (!Rec->isSubClassOf("ComplexPattern"))
1524 return &CGP.getComplexPattern(Rec);
1527 unsigned TreePatternNode::getNumMIResults(const CodeGenDAGPatterns &CGP) const {
1528 // A ComplexPattern specifically declares how many results it fills in.
1529 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1530 return CP->getNumOperands();
1532 // If MIOperandInfo is specified, that gives the count.
1534 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
1535 if (DI && DI->getDef()->isSubClassOf("Operand")) {
1536 DagInit *MIOps = DI->getDef()->getValueAsDag("MIOperandInfo");
1537 if (MIOps->getNumArgs())
1538 return MIOps->getNumArgs();
1542 // Otherwise there is just one result.
1546 /// NodeHasProperty - Return true if this node has the specified property.
1547 bool TreePatternNode::NodeHasProperty(SDNP Property,
1548 const CodeGenDAGPatterns &CGP) const {
1550 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1551 return CP->hasProperty(Property);
1555 Record *Operator = getOperator();
1556 if (!Operator->isSubClassOf("SDNode")) return false;
1558 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
1564 /// TreeHasProperty - Return true if any node in this tree has the specified
1566 bool TreePatternNode::TreeHasProperty(SDNP Property,
1567 const CodeGenDAGPatterns &CGP) const {
1568 if (NodeHasProperty(Property, CGP))
1570 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1571 if (getChild(i)->TreeHasProperty(Property, CGP))
1576 /// isCommutativeIntrinsic - Return true if the node corresponds to a
1577 /// commutative intrinsic.
1579 TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
1580 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
1581 return Int->isCommutative;
1585 static bool isOperandClass(const TreePatternNode *N, StringRef Class) {
1587 return N->getOperator()->isSubClassOf(Class);
1589 DefInit *DI = dyn_cast<DefInit>(N->getLeafValue());
1590 if (DI && DI->getDef()->isSubClassOf(Class))
1596 static void emitTooManyOperandsError(TreePattern &TP,
1600 TP.error("Instruction '" + InstName + "' was provided " + Twine(Actual) +
1601 " operands but expected only " + Twine(Expected) + "!");
1604 static void emitTooFewOperandsError(TreePattern &TP,
1607 TP.error("Instruction '" + InstName +
1608 "' expects more than the provided " + Twine(Actual) + " operands!");
1611 /// ApplyTypeConstraints - Apply all of the type constraints relevant to
1612 /// this node and its children in the tree. This returns true if it makes a
1613 /// change, false otherwise. If a type contradiction is found, flag an error.
1614 bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
1618 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
1620 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
1621 // If it's a regclass or something else known, include the type.
1622 bool MadeChange = false;
1623 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1624 MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
1626 !hasName(), TP), TP);
1630 if (IntInit *II = dyn_cast<IntInit>(getLeafValue())) {
1631 assert(Types.size() == 1 && "Invalid IntInit");
1633 // Int inits are always integers. :)
1634 bool MadeChange = Types[0].EnforceInteger(TP);
1636 if (!Types[0].isConcrete())
1639 MVT::SimpleValueType VT = getType(0);
1640 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
1643 unsigned Size = MVT(VT).getSizeInBits();
1644 // Make sure that the value is representable for this type.
1645 if (Size >= 32) return MadeChange;
1647 // Check that the value doesn't use more bits than we have. It must either
1648 // be a sign- or zero-extended equivalent of the original.
1649 int64_t SignBitAndAbove = II->getValue() >> (Size - 1);
1650 if (SignBitAndAbove == -1 || SignBitAndAbove == 0 || SignBitAndAbove == 1)
1653 TP.error("Integer value '" + itostr(II->getValue()) +
1654 "' is out of range for type '" + getEnumName(getType(0)) + "'!");
1660 // special handling for set, which isn't really an SDNode.
1661 if (getOperator()->getName() == "set") {
1662 assert(getNumTypes() == 0 && "Set doesn't produce a value");
1663 assert(getNumChildren() >= 2 && "Missing RHS of a set?");
1664 unsigned NC = getNumChildren();
1666 TreePatternNode *SetVal = getChild(NC-1);
1667 bool MadeChange = SetVal->ApplyTypeConstraints(TP, NotRegisters);
1669 for (unsigned i = 0; i < NC-1; ++i) {
1670 TreePatternNode *Child = getChild(i);
1671 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
1673 // Types of operands must match.
1674 MadeChange |= Child->UpdateNodeType(0, SetVal->getExtType(i), TP);
1675 MadeChange |= SetVal->UpdateNodeType(i, Child->getExtType(0), TP);
1680 if (getOperator()->getName() == "implicit") {
1681 assert(getNumTypes() == 0 && "Node doesn't produce a value");
1683 bool MadeChange = false;
1684 for (unsigned i = 0; i < getNumChildren(); ++i)
1685 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1689 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
1690 bool MadeChange = false;
1692 // Apply the result type to the node.
1693 unsigned NumRetVTs = Int->IS.RetVTs.size();
1694 unsigned NumParamVTs = Int->IS.ParamVTs.size();
1696 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
1697 MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
1699 if (getNumChildren() != NumParamVTs + 1) {
1700 TP.error("Intrinsic '" + Int->Name + "' expects " +
1701 utostr(NumParamVTs) + " operands, not " +
1702 utostr(getNumChildren() - 1) + " operands!");
1706 // Apply type info to the intrinsic ID.
1707 MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
1709 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
1710 MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
1712 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
1713 assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
1714 MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
1719 if (getOperator()->isSubClassOf("SDNode")) {
1720 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
1722 // Check that the number of operands is sane. Negative operands -> varargs.
1723 if (NI.getNumOperands() >= 0 &&
1724 getNumChildren() != (unsigned)NI.getNumOperands()) {
1725 TP.error(getOperator()->getName() + " node requires exactly " +
1726 itostr(NI.getNumOperands()) + " operands!");
1730 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
1731 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1732 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1736 if (getOperator()->isSubClassOf("Instruction")) {
1737 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
1738 CodeGenInstruction &InstInfo =
1739 CDP.getTargetInfo().getInstruction(getOperator());
1741 bool MadeChange = false;
1743 // Apply the result types to the node, these come from the things in the
1744 // (outs) list of the instruction.
1745 unsigned NumResultsToAdd = std::min(InstInfo.Operands.NumDefs,
1746 Inst.getNumResults());
1747 for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo)
1748 MadeChange |= UpdateNodeTypeFromInst(ResNo, Inst.getResult(ResNo), TP);
1750 // If the instruction has implicit defs, we apply the first one as a result.
1751 // FIXME: This sucks, it should apply all implicit defs.
1752 if (!InstInfo.ImplicitDefs.empty()) {
1753 unsigned ResNo = NumResultsToAdd;
1755 // FIXME: Generalize to multiple possible types and multiple possible
1757 MVT::SimpleValueType VT =
1758 InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
1760 if (VT != MVT::Other)
1761 MadeChange |= UpdateNodeType(ResNo, VT, TP);
1764 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
1766 if (getOperator()->getName() == "INSERT_SUBREG") {
1767 assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
1768 MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
1769 MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
1770 } else if (getOperator()->getName() == "REG_SEQUENCE") {
1771 // We need to do extra, custom typechecking for REG_SEQUENCE since it is
1774 unsigned NChild = getNumChildren();
1776 TP.error("REG_SEQUENCE requires at least 3 operands!");
1780 if (NChild % 2 == 0) {
1781 TP.error("REG_SEQUENCE requires an odd number of operands!");
1785 if (!isOperandClass(getChild(0), "RegisterClass")) {
1786 TP.error("REG_SEQUENCE requires a RegisterClass for first operand!");
1790 for (unsigned I = 1; I < NChild; I += 2) {
1791 TreePatternNode *SubIdxChild = getChild(I + 1);
1792 if (!isOperandClass(SubIdxChild, "SubRegIndex")) {
1793 TP.error("REG_SEQUENCE requires a SubRegIndex for operand " +
1794 itostr(I + 1) + "!");
1800 unsigned ChildNo = 0;
1801 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
1802 Record *OperandNode = Inst.getOperand(i);
1804 // If the instruction expects a predicate or optional def operand, we
1805 // codegen this by setting the operand to it's default value if it has a
1806 // non-empty DefaultOps field.
1807 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
1808 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1811 // Verify that we didn't run out of provided operands.
1812 if (ChildNo >= getNumChildren()) {
1813 emitTooFewOperandsError(TP, getOperator()->getName(), getNumChildren());
1817 TreePatternNode *Child = getChild(ChildNo++);
1818 unsigned ChildResNo = 0; // Instructions always use res #0 of their op.
1820 // If the operand has sub-operands, they may be provided by distinct
1821 // child patterns, so attempt to match each sub-operand separately.
1822 if (OperandNode->isSubClassOf("Operand")) {
1823 DagInit *MIOpInfo = OperandNode->getValueAsDag("MIOperandInfo");
1824 if (unsigned NumArgs = MIOpInfo->getNumArgs()) {
1825 // But don't do that if the whole operand is being provided by
1826 // a single ComplexPattern-related Operand.
1828 if (Child->getNumMIResults(CDP) < NumArgs) {
1829 // Match first sub-operand against the child we already have.
1830 Record *SubRec = cast<DefInit>(MIOpInfo->getArg(0))->getDef();
1832 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
1834 // And the remaining sub-operands against subsequent children.
1835 for (unsigned Arg = 1; Arg < NumArgs; ++Arg) {
1836 if (ChildNo >= getNumChildren()) {
1837 emitTooFewOperandsError(TP, getOperator()->getName(),
1841 Child = getChild(ChildNo++);
1843 SubRec = cast<DefInit>(MIOpInfo->getArg(Arg))->getDef();
1845 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
1852 // If we didn't match by pieces above, attempt to match the whole
1854 MadeChange |= Child->UpdateNodeTypeFromInst(ChildResNo, OperandNode, TP);
1857 if (!InstInfo.Operands.isVariadic && ChildNo != getNumChildren()) {
1858 emitTooManyOperandsError(TP, getOperator()->getName(),
1859 ChildNo, getNumChildren());
1863 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1864 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1868 if (getOperator()->isSubClassOf("ComplexPattern")) {
1869 bool MadeChange = false;
1871 for (unsigned i = 0; i < getNumChildren(); ++i)
1872 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1877 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
1879 // Node transforms always take one operand.
1880 if (getNumChildren() != 1) {
1881 TP.error("Node transform '" + getOperator()->getName() +
1882 "' requires one operand!");
1886 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1889 // If either the output or input of the xform does not have exact
1890 // type info. We assume they must be the same. Otherwise, it is perfectly
1891 // legal to transform from one type to a completely different type.
1893 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
1894 bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
1895 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
1902 /// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
1903 /// RHS of a commutative operation, not the on LHS.
1904 static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
1905 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
1907 if (N->isLeaf() && isa<IntInit>(N->getLeafValue()))
1913 /// canPatternMatch - If it is impossible for this pattern to match on this
1914 /// target, fill in Reason and return false. Otherwise, return true. This is
1915 /// used as a sanity check for .td files (to prevent people from writing stuff
1916 /// that can never possibly work), and to prevent the pattern permuter from
1917 /// generating stuff that is useless.
1918 bool TreePatternNode::canPatternMatch(std::string &Reason,
1919 const CodeGenDAGPatterns &CDP) {
1920 if (isLeaf()) return true;
1922 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1923 if (!getChild(i)->canPatternMatch(Reason, CDP))
1926 // If this is an intrinsic, handle cases that would make it not match. For
1927 // example, if an operand is required to be an immediate.
1928 if (getOperator()->isSubClassOf("Intrinsic")) {
1933 if (getOperator()->isSubClassOf("ComplexPattern"))
1936 // If this node is a commutative operator, check that the LHS isn't an
1938 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
1939 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
1940 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
1941 // Scan all of the operands of the node and make sure that only the last one
1942 // is a constant node, unless the RHS also is.
1943 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
1944 bool Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
1945 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
1946 if (OnlyOnRHSOfCommutative(getChild(i))) {
1947 Reason="Immediate value must be on the RHS of commutative operators!";
1956 //===----------------------------------------------------------------------===//
1957 // TreePattern implementation
1960 TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
1961 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
1962 isInputPattern(isInput), HasError(false) {
1963 for (Init *I : RawPat->getValues())
1964 Trees.push_back(ParseTreePattern(I, ""));
1967 TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
1968 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
1969 isInputPattern(isInput), HasError(false) {
1970 Trees.push_back(ParseTreePattern(Pat, ""));
1973 TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
1974 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
1975 isInputPattern(isInput), HasError(false) {
1976 Trees.push_back(Pat);
1979 void TreePattern::error(const Twine &Msg) {
1983 PrintError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
1987 void TreePattern::ComputeNamedNodes() {
1988 for (TreePatternNode *Tree : Trees)
1989 ComputeNamedNodes(Tree);
1992 void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
1993 if (!N->getName().empty())
1994 NamedNodes[N->getName()].push_back(N);
1996 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1997 ComputeNamedNodes(N->getChild(i));
2001 TreePatternNode *TreePattern::ParseTreePattern(Init *TheInit, StringRef OpName){
2002 if (DefInit *DI = dyn_cast<DefInit>(TheInit)) {
2003 Record *R = DI->getDef();
2005 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
2006 // TreePatternNode of its own. For example:
2007 /// (foo GPR, imm) -> (foo GPR, (imm))
2008 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag"))
2009 return ParseTreePattern(
2010 DagInit::get(DI, "",
2011 std::vector<std::pair<Init*, std::string> >()),
2015 TreePatternNode *Res = new TreePatternNode(DI, 1);
2016 if (R->getName() == "node" && !OpName.empty()) {
2018 error("'node' argument requires a name to match with operand list");
2019 Args.push_back(OpName);
2022 Res->setName(OpName);
2026 // ?:$name or just $name.
2027 if (isa<UnsetInit>(TheInit)) {
2029 error("'?' argument requires a name to match with operand list");
2030 TreePatternNode *Res = new TreePatternNode(TheInit, 1);
2031 Args.push_back(OpName);
2032 Res->setName(OpName);
2036 if (IntInit *II = dyn_cast<IntInit>(TheInit)) {
2037 if (!OpName.empty())
2038 error("Constant int argument should not have a name!");
2039 return new TreePatternNode(II, 1);
2042 if (BitsInit *BI = dyn_cast<BitsInit>(TheInit)) {
2043 // Turn this into an IntInit.
2044 Init *II = BI->convertInitializerTo(IntRecTy::get());
2045 if (!II || !isa<IntInit>(II))
2046 error("Bits value must be constants!");
2047 return ParseTreePattern(II, OpName);
2050 DagInit *Dag = dyn_cast<DagInit>(TheInit);
2053 error("Pattern has unexpected init kind!");
2055 DefInit *OpDef = dyn_cast<DefInit>(Dag->getOperator());
2056 if (!OpDef) error("Pattern has unexpected operator type!");
2057 Record *Operator = OpDef->getDef();
2059 if (Operator->isSubClassOf("ValueType")) {
2060 // If the operator is a ValueType, then this must be "type cast" of a leaf
2062 if (Dag->getNumArgs() != 1)
2063 error("Type cast only takes one operand!");
2065 TreePatternNode *New = ParseTreePattern(Dag->getArg(0), Dag->getArgName(0));
2067 // Apply the type cast.
2068 assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
2069 New->UpdateNodeType(0, getValueType(Operator), *this);
2071 if (!OpName.empty())
2072 error("ValueType cast should not have a name!");
2076 // Verify that this is something that makes sense for an operator.
2077 if (!Operator->isSubClassOf("PatFrag") &&
2078 !Operator->isSubClassOf("SDNode") &&
2079 !Operator->isSubClassOf("Instruction") &&
2080 !Operator->isSubClassOf("SDNodeXForm") &&
2081 !Operator->isSubClassOf("Intrinsic") &&
2082 !Operator->isSubClassOf("ComplexPattern") &&
2083 Operator->getName() != "set" &&
2084 Operator->getName() != "implicit")
2085 error("Unrecognized node '" + Operator->getName() + "'!");
2087 // Check to see if this is something that is illegal in an input pattern.
2088 if (isInputPattern) {
2089 if (Operator->isSubClassOf("Instruction") ||
2090 Operator->isSubClassOf("SDNodeXForm"))
2091 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
2093 if (Operator->isSubClassOf("Intrinsic"))
2094 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
2096 if (Operator->isSubClassOf("SDNode") &&
2097 Operator->getName() != "imm" &&
2098 Operator->getName() != "fpimm" &&
2099 Operator->getName() != "tglobaltlsaddr" &&
2100 Operator->getName() != "tconstpool" &&
2101 Operator->getName() != "tjumptable" &&
2102 Operator->getName() != "tframeindex" &&
2103 Operator->getName() != "texternalsym" &&
2104 Operator->getName() != "tblockaddress" &&
2105 Operator->getName() != "tglobaladdr" &&
2106 Operator->getName() != "bb" &&
2107 Operator->getName() != "vt" &&
2108 Operator->getName() != "mcsym")
2109 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
2112 std::vector<TreePatternNode*> Children;
2114 // Parse all the operands.
2115 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
2116 Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgName(i)));
2118 // If the operator is an intrinsic, then this is just syntactic sugar for for
2119 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
2120 // convert the intrinsic name to a number.
2121 if (Operator->isSubClassOf("Intrinsic")) {
2122 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
2123 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
2125 // If this intrinsic returns void, it must have side-effects and thus a
2127 if (Int.IS.RetVTs.empty())
2128 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
2129 else if (Int.ModRef != CodeGenIntrinsic::NoMem)
2130 // Has side-effects, requires chain.
2131 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
2132 else // Otherwise, no chain.
2133 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
2135 TreePatternNode *IIDNode = new TreePatternNode(IntInit::get(IID), 1);
2136 Children.insert(Children.begin(), IIDNode);
2139 if (Operator->isSubClassOf("ComplexPattern")) {
2140 for (unsigned i = 0; i < Children.size(); ++i) {
2141 TreePatternNode *Child = Children[i];
2143 if (Child->getName().empty())
2144 error("All arguments to a ComplexPattern must be named");
2146 // Check that the ComplexPattern uses are consistent: "(MY_PAT $a, $b)"
2147 // and "(MY_PAT $b, $a)" should not be allowed in the same pattern;
2148 // neither should "(MY_PAT_1 $a, $b)" and "(MY_PAT_2 $a, $b)".
2149 auto OperandId = std::make_pair(Operator, i);
2150 auto PrevOp = ComplexPatternOperands.find(Child->getName());
2151 if (PrevOp != ComplexPatternOperands.end()) {
2152 if (PrevOp->getValue() != OperandId)
2153 error("All ComplexPattern operands must appear consistently: "
2154 "in the same order in just one ComplexPattern instance.");
2156 ComplexPatternOperands[Child->getName()] = OperandId;
2160 unsigned NumResults = GetNumNodeResults(Operator, CDP);
2161 TreePatternNode *Result = new TreePatternNode(Operator, Children, NumResults);
2162 Result->setName(OpName);
2164 if (!Dag->getName().empty()) {
2165 assert(Result->getName().empty());
2166 Result->setName(Dag->getName());
2171 /// SimplifyTree - See if we can simplify this tree to eliminate something that
2172 /// will never match in favor of something obvious that will. This is here
2173 /// strictly as a convenience to target authors because it allows them to write
2174 /// more type generic things and have useless type casts fold away.
2176 /// This returns true if any change is made.
2177 static bool SimplifyTree(TreePatternNode *&N) {
2181 // If we have a bitconvert with a resolved type and if the source and
2182 // destination types are the same, then the bitconvert is useless, remove it.
2183 if (N->getOperator()->getName() == "bitconvert" &&
2184 N->getExtType(0).isConcrete() &&
2185 N->getExtType(0) == N->getChild(0)->getExtType(0) &&
2186 N->getName().empty()) {
2192 // Walk all children.
2193 bool MadeChange = false;
2194 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2195 TreePatternNode *Child = N->getChild(i);
2196 MadeChange |= SimplifyTree(Child);
2197 N->setChild(i, Child);
2204 /// InferAllTypes - Infer/propagate as many types throughout the expression
2205 /// patterns as possible. Return true if all types are inferred, false
2206 /// otherwise. Flags an error if a type contradiction is found.
2208 InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
2209 if (NamedNodes.empty())
2210 ComputeNamedNodes();
2212 bool MadeChange = true;
2213 while (MadeChange) {
2215 for (TreePatternNode *Tree : Trees) {
2216 MadeChange |= Tree->ApplyTypeConstraints(*this, false);
2217 MadeChange |= SimplifyTree(Tree);
2220 // If there are constraints on our named nodes, apply them.
2221 for (auto &Entry : NamedNodes) {
2222 SmallVectorImpl<TreePatternNode*> &Nodes = Entry.second;
2224 // If we have input named node types, propagate their types to the named
2227 if (!InNamedTypes->count(Entry.getKey())) {
2228 error("Node '" + std::string(Entry.getKey()) +
2229 "' in output pattern but not input pattern");
2233 const SmallVectorImpl<TreePatternNode*> &InNodes =
2234 InNamedTypes->find(Entry.getKey())->second;
2236 // The input types should be fully resolved by now.
2237 for (TreePatternNode *Node : Nodes) {
2238 // If this node is a register class, and it is the root of the pattern
2239 // then we're mapping something onto an input register. We allow
2240 // changing the type of the input register in this case. This allows
2241 // us to match things like:
2242 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
2243 if (Node == Trees[0] && Node->isLeaf()) {
2244 DefInit *DI = dyn_cast<DefInit>(Node->getLeafValue());
2245 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2246 DI->getDef()->isSubClassOf("RegisterOperand")))
2250 assert(Node->getNumTypes() == 1 &&
2251 InNodes[0]->getNumTypes() == 1 &&
2252 "FIXME: cannot name multiple result nodes yet");
2253 MadeChange |= Node->UpdateNodeType(0, InNodes[0]->getExtType(0),
2258 // If there are multiple nodes with the same name, they must all have the
2260 if (Entry.second.size() > 1) {
2261 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
2262 TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
2263 assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
2264 "FIXME: cannot name multiple result nodes yet");
2266 MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
2267 MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
2273 bool HasUnresolvedTypes = false;
2274 for (const TreePatternNode *Tree : Trees)
2275 HasUnresolvedTypes |= Tree->ContainsUnresolvedType();
2276 return !HasUnresolvedTypes;
2279 void TreePattern::print(raw_ostream &OS) const {
2280 OS << getRecord()->getName();
2281 if (!Args.empty()) {
2282 OS << "(" << Args[0];
2283 for (unsigned i = 1, e = Args.size(); i != e; ++i)
2284 OS << ", " << Args[i];
2289 if (Trees.size() > 1)
2291 for (const TreePatternNode *Tree : Trees) {
2297 if (Trees.size() > 1)
2301 void TreePattern::dump() const { print(errs()); }
2303 //===----------------------------------------------------------------------===//
2304 // CodeGenDAGPatterns implementation
2307 CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) :
2308 Records(R), Target(R) {
2310 Intrinsics = LoadIntrinsics(Records, false);
2311 TgtIntrinsics = LoadIntrinsics(Records, true);
2313 ParseNodeTransforms();
2314 ParseComplexPatterns();
2315 ParsePatternFragments();
2316 ParseDefaultOperands();
2317 ParseInstructions();
2318 ParsePatternFragments(/*OutFrags*/true);
2321 // Generate variants. For example, commutative patterns can match
2322 // multiple ways. Add them to PatternsToMatch as well.
2325 // Infer instruction flags. For example, we can detect loads,
2326 // stores, and side effects in many cases by examining an
2327 // instruction's pattern.
2328 InferInstructionFlags();
2330 // Verify that instruction flags match the patterns.
2331 VerifyInstructionFlags();
2334 Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
2335 Record *N = Records.getDef(Name);
2336 if (!N || !N->isSubClassOf("SDNode"))
2337 PrintFatalError("Error getting SDNode '" + Name + "'!");
2342 // Parse all of the SDNode definitions for the target, populating SDNodes.
2343 void CodeGenDAGPatterns::ParseNodeInfo() {
2344 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
2345 while (!Nodes.empty()) {
2346 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
2350 // Get the builtin intrinsic nodes.
2351 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
2352 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
2353 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
2356 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
2357 /// map, and emit them to the file as functions.
2358 void CodeGenDAGPatterns::ParseNodeTransforms() {
2359 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
2360 while (!Xforms.empty()) {
2361 Record *XFormNode = Xforms.back();
2362 Record *SDNode = XFormNode->getValueAsDef("Opcode");
2363 std::string Code = XFormNode->getValueAsString("XFormFunction");
2364 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
2370 void CodeGenDAGPatterns::ParseComplexPatterns() {
2371 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
2372 while (!AMs.empty()) {
2373 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
2379 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
2380 /// file, building up the PatternFragments map. After we've collected them all,
2381 /// inline fragments together as necessary, so that there are no references left
2382 /// inside a pattern fragment to a pattern fragment.
2384 void CodeGenDAGPatterns::ParsePatternFragments(bool OutFrags) {
2385 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
2387 // First step, parse all of the fragments.
2388 for (Record *Frag : Fragments) {
2389 if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
2392 DagInit *Tree = Frag->getValueAsDag("Fragment");
2394 (PatternFragments[Frag] = llvm::make_unique<TreePattern>(
2395 Frag, Tree, !Frag->isSubClassOf("OutPatFrag"),
2398 // Validate the argument list, converting it to set, to discard duplicates.
2399 std::vector<std::string> &Args = P->getArgList();
2400 std::set<std::string> OperandsSet(Args.begin(), Args.end());
2402 if (OperandsSet.count(""))
2403 P->error("Cannot have unnamed 'node' values in pattern fragment!");
2405 // Parse the operands list.
2406 DagInit *OpsList = Frag->getValueAsDag("Operands");
2407 DefInit *OpsOp = dyn_cast<DefInit>(OpsList->getOperator());
2408 // Special cases: ops == outs == ins. Different names are used to
2409 // improve readability.
2411 (OpsOp->getDef()->getName() != "ops" &&
2412 OpsOp->getDef()->getName() != "outs" &&
2413 OpsOp->getDef()->getName() != "ins"))
2414 P->error("Operands list should start with '(ops ... '!");
2416 // Copy over the arguments.
2418 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
2419 if (!isa<DefInit>(OpsList->getArg(j)) ||
2420 cast<DefInit>(OpsList->getArg(j))->getDef()->getName() != "node")
2421 P->error("Operands list should all be 'node' values.");
2422 if (OpsList->getArgName(j).empty())
2423 P->error("Operands list should have names for each operand!");
2424 if (!OperandsSet.count(OpsList->getArgName(j)))
2425 P->error("'" + OpsList->getArgName(j) +
2426 "' does not occur in pattern or was multiply specified!");
2427 OperandsSet.erase(OpsList->getArgName(j));
2428 Args.push_back(OpsList->getArgName(j));
2431 if (!OperandsSet.empty())
2432 P->error("Operands list does not contain an entry for operand '" +
2433 *OperandsSet.begin() + "'!");
2435 // If there is a code init for this fragment, keep track of the fact that
2436 // this fragment uses it.
2437 TreePredicateFn PredFn(P);
2438 if (!PredFn.isAlwaysTrue())
2439 P->getOnlyTree()->addPredicateFn(PredFn);
2441 // If there is a node transformation corresponding to this, keep track of
2443 Record *Transform = Frag->getValueAsDef("OperandTransform");
2444 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
2445 P->getOnlyTree()->setTransformFn(Transform);
2448 // Now that we've parsed all of the tree fragments, do a closure on them so
2449 // that there are not references to PatFrags left inside of them.
2450 for (Record *Frag : Fragments) {
2451 if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
2454 TreePattern &ThePat = *PatternFragments[Frag];
2455 ThePat.InlinePatternFragments();
2457 // Infer as many types as possible. Don't worry about it if we don't infer
2458 // all of them, some may depend on the inputs of the pattern.
2459 ThePat.InferAllTypes();
2460 ThePat.resetError();
2462 // If debugging, print out the pattern fragment result.
2463 DEBUG(ThePat.dump());
2467 void CodeGenDAGPatterns::ParseDefaultOperands() {
2468 std::vector<Record*> DefaultOps;
2469 DefaultOps = Records.getAllDerivedDefinitions("OperandWithDefaultOps");
2471 // Find some SDNode.
2472 assert(!SDNodes.empty() && "No SDNodes parsed?");
2473 Init *SomeSDNode = DefInit::get(SDNodes.begin()->first);
2475 for (unsigned i = 0, e = DefaultOps.size(); i != e; ++i) {
2476 DagInit *DefaultInfo = DefaultOps[i]->getValueAsDag("DefaultOps");
2478 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
2479 // SomeSDnode so that we can parse this.
2480 std::vector<std::pair<Init*, std::string> > Ops;
2481 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
2482 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
2483 DefaultInfo->getArgName(op)));
2484 DagInit *DI = DagInit::get(SomeSDNode, "", Ops);
2486 // Create a TreePattern to parse this.
2487 TreePattern P(DefaultOps[i], DI, false, *this);
2488 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
2490 // Copy the operands over into a DAGDefaultOperand.
2491 DAGDefaultOperand DefaultOpInfo;
2493 TreePatternNode *T = P.getTree(0);
2494 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
2495 TreePatternNode *TPN = T->getChild(op);
2496 while (TPN->ApplyTypeConstraints(P, false))
2497 /* Resolve all types */;
2499 if (TPN->ContainsUnresolvedType()) {
2500 PrintFatalError("Value #" + Twine(i) + " of OperandWithDefaultOps '" +
2501 DefaultOps[i]->getName() +
2502 "' doesn't have a concrete type!");
2504 DefaultOpInfo.DefaultOps.push_back(TPN);
2507 // Insert it into the DefaultOperands map so we can find it later.
2508 DefaultOperands[DefaultOps[i]] = DefaultOpInfo;
2512 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
2513 /// instruction input. Return true if this is a real use.
2514 static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
2515 std::map<std::string, TreePatternNode*> &InstInputs) {
2516 // No name -> not interesting.
2517 if (Pat->getName().empty()) {
2518 if (Pat->isLeaf()) {
2519 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
2520 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2521 DI->getDef()->isSubClassOf("RegisterOperand")))
2522 I->error("Input " + DI->getDef()->getName() + " must be named!");
2528 if (Pat->isLeaf()) {
2529 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
2530 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
2533 Rec = Pat->getOperator();
2536 // SRCVALUE nodes are ignored.
2537 if (Rec->getName() == "srcvalue")
2540 TreePatternNode *&Slot = InstInputs[Pat->getName()];
2546 if (Slot->isLeaf()) {
2547 SlotRec = cast<DefInit>(Slot->getLeafValue())->getDef();
2549 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
2550 SlotRec = Slot->getOperator();
2553 // Ensure that the inputs agree if we've already seen this input.
2555 I->error("All $" + Pat->getName() + " inputs must agree with each other");
2556 if (Slot->getExtTypes() != Pat->getExtTypes())
2557 I->error("All $" + Pat->getName() + " inputs must agree with each other");
2561 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
2562 /// part of "I", the instruction), computing the set of inputs and outputs of
2563 /// the pattern. Report errors if we see anything naughty.
2564 void CodeGenDAGPatterns::
2565 FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
2566 std::map<std::string, TreePatternNode*> &InstInputs,
2567 std::map<std::string, TreePatternNode*>&InstResults,
2568 std::vector<Record*> &InstImpResults) {
2569 if (Pat->isLeaf()) {
2570 bool isUse = HandleUse(I, Pat, InstInputs);
2571 if (!isUse && Pat->getTransformFn())
2572 I->error("Cannot specify a transform function for a non-input value!");
2576 if (Pat->getOperator()->getName() == "implicit") {
2577 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2578 TreePatternNode *Dest = Pat->getChild(i);
2579 if (!Dest->isLeaf())
2580 I->error("implicitly defined value should be a register!");
2582 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
2583 if (!Val || !Val->getDef()->isSubClassOf("Register"))
2584 I->error("implicitly defined value should be a register!");
2585 InstImpResults.push_back(Val->getDef());
2590 if (Pat->getOperator()->getName() != "set") {
2591 // If this is not a set, verify that the children nodes are not void typed,
2593 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2594 if (Pat->getChild(i)->getNumTypes() == 0)
2595 I->error("Cannot have void nodes inside of patterns!");
2596 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
2600 // If this is a non-leaf node with no children, treat it basically as if
2601 // it were a leaf. This handles nodes like (imm).
2602 bool isUse = HandleUse(I, Pat, InstInputs);
2604 if (!isUse && Pat->getTransformFn())
2605 I->error("Cannot specify a transform function for a non-input value!");
2609 // Otherwise, this is a set, validate and collect instruction results.
2610 if (Pat->getNumChildren() == 0)
2611 I->error("set requires operands!");
2613 if (Pat->getTransformFn())
2614 I->error("Cannot specify a transform function on a set node!");
2616 // Check the set destinations.
2617 unsigned NumDests = Pat->getNumChildren()-1;
2618 for (unsigned i = 0; i != NumDests; ++i) {
2619 TreePatternNode *Dest = Pat->getChild(i);
2620 if (!Dest->isLeaf())
2621 I->error("set destination should be a register!");
2623 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
2625 I->error("set destination should be a register!");
2629 if (Val->getDef()->isSubClassOf("RegisterClass") ||
2630 Val->getDef()->isSubClassOf("ValueType") ||
2631 Val->getDef()->isSubClassOf("RegisterOperand") ||
2632 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
2633 if (Dest->getName().empty())
2634 I->error("set destination must have a name!");
2635 if (InstResults.count(Dest->getName()))
2636 I->error("cannot set '" + Dest->getName() +"' multiple times");
2637 InstResults[Dest->getName()] = Dest;
2638 } else if (Val->getDef()->isSubClassOf("Register")) {
2639 InstImpResults.push_back(Val->getDef());
2641 I->error("set destination should be a register!");
2645 // Verify and collect info from the computation.
2646 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
2647 InstInputs, InstResults, InstImpResults);
2650 //===----------------------------------------------------------------------===//
2651 // Instruction Analysis
2652 //===----------------------------------------------------------------------===//
2654 class InstAnalyzer {
2655 const CodeGenDAGPatterns &CDP;
2657 bool hasSideEffects;
2663 InstAnalyzer(const CodeGenDAGPatterns &cdp)
2664 : CDP(cdp), hasSideEffects(false), mayStore(false), mayLoad(false),
2665 isBitcast(false), isVariadic(false) {}
2667 void Analyze(const TreePattern *Pat) {
2668 // Assume only the first tree is the pattern. The others are clobber nodes.
2669 AnalyzeNode(Pat->getTree(0));
2672 void Analyze(const PatternToMatch *Pat) {
2673 AnalyzeNode(Pat->getSrcPattern());
2677 bool IsNodeBitcast(const TreePatternNode *N) const {
2678 if (hasSideEffects || mayLoad || mayStore || isVariadic)
2681 if (N->getNumChildren() != 2)
2684 const TreePatternNode *N0 = N->getChild(0);
2685 if (!N0->isLeaf() || !isa<DefInit>(N0->getLeafValue()))
2688 const TreePatternNode *N1 = N->getChild(1);
2691 if (N1->getNumChildren() != 1 || !N1->getChild(0)->isLeaf())
2694 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N1->getOperator());
2695 if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1)
2697 return OpInfo.getEnumName() == "ISD::BITCAST";
2701 void AnalyzeNode(const TreePatternNode *N) {
2703 if (DefInit *DI = dyn_cast<DefInit>(N->getLeafValue())) {
2704 Record *LeafRec = DI->getDef();
2705 // Handle ComplexPattern leaves.
2706 if (LeafRec->isSubClassOf("ComplexPattern")) {
2707 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
2708 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
2709 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
2710 if (CP.hasProperty(SDNPSideEffect)) hasSideEffects = true;
2716 // Analyze children.
2717 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2718 AnalyzeNode(N->getChild(i));
2720 // Ignore set nodes, which are not SDNodes.
2721 if (N->getOperator()->getName() == "set") {
2722 isBitcast = IsNodeBitcast(N);
2726 // Notice properties of the node.
2727 if (N->NodeHasProperty(SDNPMayStore, CDP)) mayStore = true;
2728 if (N->NodeHasProperty(SDNPMayLoad, CDP)) mayLoad = true;
2729 if (N->NodeHasProperty(SDNPSideEffect, CDP)) hasSideEffects = true;
2730 if (N->NodeHasProperty(SDNPVariadic, CDP)) isVariadic = true;
2732 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
2733 // If this is an intrinsic, analyze it.
2734 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
2735 mayLoad = true;// These may load memory.
2737 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteArgMem)
2738 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
2740 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem)
2741 // WriteMem intrinsics can have other strange effects.
2742 hasSideEffects = true;
2748 static bool InferFromPattern(CodeGenInstruction &InstInfo,
2749 const InstAnalyzer &PatInfo,
2753 // Remember where InstInfo got its flags.
2754 if (InstInfo.hasUndefFlags())
2755 InstInfo.InferredFrom = PatDef;
2757 // Check explicitly set flags for consistency.
2758 if (InstInfo.hasSideEffects != PatInfo.hasSideEffects &&
2759 !InstInfo.hasSideEffects_Unset) {
2760 // Allow explicitly setting hasSideEffects = 1 on instructions, even when
2761 // the pattern has no side effects. That could be useful for div/rem
2762 // instructions that may trap.
2763 if (!InstInfo.hasSideEffects) {
2765 PrintError(PatDef->getLoc(), "Pattern doesn't match hasSideEffects = " +
2766 Twine(InstInfo.hasSideEffects));
2770 if (InstInfo.mayStore != PatInfo.mayStore && !InstInfo.mayStore_Unset) {
2772 PrintError(PatDef->getLoc(), "Pattern doesn't match mayStore = " +
2773 Twine(InstInfo.mayStore));
2776 if (InstInfo.mayLoad != PatInfo.mayLoad && !InstInfo.mayLoad_Unset) {
2777 // Allow explicitly setting mayLoad = 1, even when the pattern has no loads.
2778 // Some targets translate immediates to loads.
2779 if (!InstInfo.mayLoad) {
2781 PrintError(PatDef->getLoc(), "Pattern doesn't match mayLoad = " +
2782 Twine(InstInfo.mayLoad));
2786 // Transfer inferred flags.
2787 InstInfo.hasSideEffects |= PatInfo.hasSideEffects;
2788 InstInfo.mayStore |= PatInfo.mayStore;
2789 InstInfo.mayLoad |= PatInfo.mayLoad;
2791 // These flags are silently added without any verification.
2792 InstInfo.isBitcast |= PatInfo.isBitcast;
2794 // Don't infer isVariadic. This flag means something different on SDNodes and
2795 // instructions. For example, a CALL SDNode is variadic because it has the
2796 // call arguments as operands, but a CALL instruction is not variadic - it
2797 // has argument registers as implicit, not explicit uses.
2802 /// hasNullFragReference - Return true if the DAG has any reference to the
2803 /// null_frag operator.
2804 static bool hasNullFragReference(DagInit *DI) {
2805 DefInit *OpDef = dyn_cast<DefInit>(DI->getOperator());
2806 if (!OpDef) return false;
2807 Record *Operator = OpDef->getDef();
2809 // If this is the null fragment, return true.
2810 if (Operator->getName() == "null_frag") return true;
2811 // If any of the arguments reference the null fragment, return true.
2812 for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {
2813 DagInit *Arg = dyn_cast<DagInit>(DI->getArg(i));
2814 if (Arg && hasNullFragReference(Arg))
2821 /// hasNullFragReference - Return true if any DAG in the list references
2822 /// the null_frag operator.
2823 static bool hasNullFragReference(ListInit *LI) {
2824 for (Init *I : LI->getValues()) {
2825 DagInit *DI = dyn_cast<DagInit>(I);
2826 assert(DI && "non-dag in an instruction Pattern list?!");
2827 if (hasNullFragReference(DI))
2833 /// Get all the instructions in a tree.
2835 getInstructionsInTree(TreePatternNode *Tree, SmallVectorImpl<Record*> &Instrs) {
2838 if (Tree->getOperator()->isSubClassOf("Instruction"))
2839 Instrs.push_back(Tree->getOperator());
2840 for (unsigned i = 0, e = Tree->getNumChildren(); i != e; ++i)
2841 getInstructionsInTree(Tree->getChild(i), Instrs);
2844 /// Check the class of a pattern leaf node against the instruction operand it
2846 static bool checkOperandClass(CGIOperandList::OperandInfo &OI,
2851 // Allow direct value types to be used in instruction set patterns.
2852 // The type will be checked later.
2853 if (Leaf->isSubClassOf("ValueType"))
2856 // Patterns can also be ComplexPattern instances.
2857 if (Leaf->isSubClassOf("ComplexPattern"))
2863 const DAGInstruction &CodeGenDAGPatterns::parseInstructionPattern(
2864 CodeGenInstruction &CGI, ListInit *Pat, DAGInstMap &DAGInsts) {
2866 assert(!DAGInsts.count(CGI.TheDef) && "Instruction already parsed!");
2868 // Parse the instruction.
2869 TreePattern *I = new TreePattern(CGI.TheDef, Pat, true, *this);
2870 // Inline pattern fragments into it.
2871 I->InlinePatternFragments();
2873 // Infer as many types as possible. If we cannot infer all of them, we can
2874 // never do anything with this instruction pattern: report it to the user.
2875 if (!I->InferAllTypes())
2876 I->error("Could not infer all types in pattern!");
2878 // InstInputs - Keep track of all of the inputs of the instruction, along
2879 // with the record they are declared as.
2880 std::map<std::string, TreePatternNode*> InstInputs;
2882 // InstResults - Keep track of all the virtual registers that are 'set'
2883 // in the instruction, including what reg class they are.
2884 std::map<std::string, TreePatternNode*> InstResults;
2886 std::vector<Record*> InstImpResults;
2888 // Verify that the top-level forms in the instruction are of void type, and
2889 // fill in the InstResults map.
2890 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
2891 TreePatternNode *Pat = I->getTree(j);
2892 if (Pat->getNumTypes() != 0)
2893 I->error("Top-level forms in instruction pattern should have"
2896 // Find inputs and outputs, and verify the structure of the uses/defs.
2897 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
2901 // Now that we have inputs and outputs of the pattern, inspect the operands
2902 // list for the instruction. This determines the order that operands are
2903 // added to the machine instruction the node corresponds to.
2904 unsigned NumResults = InstResults.size();
2906 // Parse the operands list from the (ops) list, validating it.
2907 assert(I->getArgList().empty() && "Args list should still be empty here!");
2909 // Check that all of the results occur first in the list.
2910 std::vector<Record*> Results;
2911 SmallVector<TreePatternNode *, 2> ResNodes;
2912 for (unsigned i = 0; i != NumResults; ++i) {
2913 if (i == CGI.Operands.size())
2914 I->error("'" + InstResults.begin()->first +
2915 "' set but does not appear in operand list!");
2916 const std::string &OpName = CGI.Operands[i].Name;
2918 // Check that it exists in InstResults.
2919 TreePatternNode *RNode = InstResults[OpName];
2921 I->error("Operand $" + OpName + " does not exist in operand list!");
2923 ResNodes.push_back(RNode);
2925 Record *R = cast<DefInit>(RNode->getLeafValue())->getDef();
2927 I->error("Operand $" + OpName + " should be a set destination: all "
2928 "outputs must occur before inputs in operand list!");
2930 if (!checkOperandClass(CGI.Operands[i], R))
2931 I->error("Operand $" + OpName + " class mismatch!");
2933 // Remember the return type.
2934 Results.push_back(CGI.Operands[i].Rec);
2936 // Okay, this one checks out.
2937 InstResults.erase(OpName);
2940 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
2941 // the copy while we're checking the inputs.
2942 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
2944 std::vector<TreePatternNode*> ResultNodeOperands;
2945 std::vector<Record*> Operands;
2946 for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
2947 CGIOperandList::OperandInfo &Op = CGI.Operands[i];
2948 const std::string &OpName = Op.Name;
2950 I->error("Operand #" + utostr(i) + " in operands list has no name!");
2952 if (!InstInputsCheck.count(OpName)) {
2953 // If this is an operand with a DefaultOps set filled in, we can ignore
2954 // this. When we codegen it, we will do so as always executed.
2955 if (Op.Rec->isSubClassOf("OperandWithDefaultOps")) {
2956 // Does it have a non-empty DefaultOps field? If so, ignore this
2958 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
2961 I->error("Operand $" + OpName +
2962 " does not appear in the instruction pattern");
2964 TreePatternNode *InVal = InstInputsCheck[OpName];
2965 InstInputsCheck.erase(OpName); // It occurred, remove from map.
2967 if (InVal->isLeaf() && isa<DefInit>(InVal->getLeafValue())) {
2968 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
2969 if (!checkOperandClass(Op, InRec))
2970 I->error("Operand $" + OpName + "'s register class disagrees"
2971 " between the operand and pattern");
2973 Operands.push_back(Op.Rec);
2975 // Construct the result for the dest-pattern operand list.
2976 TreePatternNode *OpNode = InVal->clone();
2978 // No predicate is useful on the result.
2979 OpNode->clearPredicateFns();
2981 // Promote the xform function to be an explicit node if set.
2982 if (Record *Xform = OpNode->getTransformFn()) {
2983 OpNode->setTransformFn(nullptr);
2984 std::vector<TreePatternNode*> Children;
2985 Children.push_back(OpNode);
2986 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
2989 ResultNodeOperands.push_back(OpNode);
2992 if (!InstInputsCheck.empty())
2993 I->error("Input operand $" + InstInputsCheck.begin()->first +
2994 " occurs in pattern but not in operands list!");
2996 TreePatternNode *ResultPattern =
2997 new TreePatternNode(I->getRecord(), ResultNodeOperands,
2998 GetNumNodeResults(I->getRecord(), *this));
2999 // Copy fully inferred output node types to instruction result pattern.
3000 for (unsigned i = 0; i != NumResults; ++i) {
3001 assert(ResNodes[i]->getNumTypes() == 1 && "FIXME: Unhandled");
3002 ResultPattern->setType(i, ResNodes[i]->getExtType(0));
3005 // Create and insert the instruction.
3006 // FIXME: InstImpResults should not be part of DAGInstruction.
3007 DAGInstruction TheInst(I, Results, Operands, InstImpResults);
3008 DAGInsts.insert(std::make_pair(I->getRecord(), TheInst));
3010 // Use a temporary tree pattern to infer all types and make sure that the
3011 // constructed result is correct. This depends on the instruction already
3012 // being inserted into the DAGInsts map.
3013 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
3014 Temp.InferAllTypes(&I->getNamedNodesMap());
3016 DAGInstruction &TheInsertedInst = DAGInsts.find(I->getRecord())->second;
3017 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
3019 return TheInsertedInst;
3022 /// ParseInstructions - Parse all of the instructions, inlining and resolving
3023 /// any fragments involved. This populates the Instructions list with fully
3024 /// resolved instructions.
3025 void CodeGenDAGPatterns::ParseInstructions() {
3026 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
3028 for (Record *Instr : Instrs) {
3029 ListInit *LI = nullptr;
3031 if (isa<ListInit>(Instr->getValueInit("Pattern")))
3032 LI = Instr->getValueAsListInit("Pattern");
3034 // If there is no pattern, only collect minimal information about the
3035 // instruction for its operand list. We have to assume that there is one
3036 // result, as we have no detailed info. A pattern which references the
3037 // null_frag operator is as-if no pattern were specified. Normally this
3038 // is from a multiclass expansion w/ a SDPatternOperator passed in as
3040 if (!LI || LI->empty() || hasNullFragReference(LI)) {
3041 std::vector<Record*> Results;
3042 std::vector<Record*> Operands;
3044 CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
3046 if (InstInfo.Operands.size() != 0) {
3047 for (unsigned j = 0, e = InstInfo.Operands.NumDefs; j < e; ++j)
3048 Results.push_back(InstInfo.Operands[j].Rec);
3050 // The rest are inputs.
3051 for (unsigned j = InstInfo.Operands.NumDefs,
3052 e = InstInfo.Operands.size(); j < e; ++j)
3053 Operands.push_back(InstInfo.Operands[j].Rec);
3056 // Create and insert the instruction.
3057 std::vector<Record*> ImpResults;
3058 Instructions.insert(std::make_pair(Instr,
3059 DAGInstruction(nullptr, Results, Operands, ImpResults)));
3060 continue; // no pattern.
3063 CodeGenInstruction &CGI = Target.getInstruction(Instr);
3064 const DAGInstruction &DI = parseInstructionPattern(CGI, LI, Instructions);
3067 DEBUG(DI.getPattern()->dump());
3070 // If we can, convert the instructions to be patterns that are matched!
3071 for (auto &Entry : Instructions) {
3072 DAGInstruction &TheInst = Entry.second;
3073 TreePattern *I = TheInst.getPattern();
3074 if (!I) continue; // No pattern.
3076 // FIXME: Assume only the first tree is the pattern. The others are clobber
3078 TreePatternNode *Pattern = I->getTree(0);
3079 TreePatternNode *SrcPattern;
3080 if (Pattern->getOperator()->getName() == "set") {
3081 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
3083 // Not a set (store or something?)
3084 SrcPattern = Pattern;
3087 Record *Instr = Entry.first;
3088 AddPatternToMatch(I,
3089 PatternToMatch(Instr,
3090 Instr->getValueAsListInit("Predicates"),
3092 TheInst.getResultPattern(),
3093 TheInst.getImpResults(),
3094 Instr->getValueAsInt("AddedComplexity"),
3100 typedef std::pair<const TreePatternNode*, unsigned> NameRecord;
3102 static void FindNames(const TreePatternNode *P,
3103 std::map<std::string, NameRecord> &Names,
3104 TreePattern *PatternTop) {
3105 if (!P->getName().empty()) {
3106 NameRecord &Rec = Names[P->getName()];
3107 // If this is the first instance of the name, remember the node.
3108 if (Rec.second++ == 0)
3110 else if (Rec.first->getExtTypes() != P->getExtTypes())
3111 PatternTop->error("repetition of value: $" + P->getName() +
3112 " where different uses have different types!");
3116 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
3117 FindNames(P->getChild(i), Names, PatternTop);
3121 void CodeGenDAGPatterns::AddPatternToMatch(TreePattern *Pattern,
3122 const PatternToMatch &PTM) {
3123 // Do some sanity checking on the pattern we're about to match.
3125 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this)) {
3126 PrintWarning(Pattern->getRecord()->getLoc(),
3127 Twine("Pattern can never match: ") + Reason);
3131 // If the source pattern's root is a complex pattern, that complex pattern
3132 // must specify the nodes it can potentially match.
3133 if (const ComplexPattern *CP =
3134 PTM.getSrcPattern()->getComplexPatternInfo(*this))
3135 if (CP->getRootNodes().empty())
3136 Pattern->error("ComplexPattern at root must specify list of opcodes it"
3140 // Find all of the named values in the input and output, ensure they have the
3142 std::map<std::string, NameRecord> SrcNames, DstNames;
3143 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
3144 FindNames(PTM.getDstPattern(), DstNames, Pattern);
3146 // Scan all of the named values in the destination pattern, rejecting them if
3147 // they don't exist in the input pattern.
3148 for (const auto &Entry : DstNames) {
3149 if (SrcNames[Entry.first].first == nullptr)
3150 Pattern->error("Pattern has input without matching name in output: $" +
3154 // Scan all of the named values in the source pattern, rejecting them if the
3155 // name isn't used in the dest, and isn't used to tie two values together.
3156 for (const auto &Entry : SrcNames)
3157 if (DstNames[Entry.first].first == nullptr &&
3158 SrcNames[Entry.first].second == 1)
3159 Pattern->error("Pattern has dead named input: $" + Entry.first);
3161 PatternsToMatch.push_back(PTM);
3166 void CodeGenDAGPatterns::InferInstructionFlags() {
3167 const std::vector<const CodeGenInstruction*> &Instructions =
3168 Target.getInstructionsByEnumValue();
3170 // First try to infer flags from the primary instruction pattern, if any.
3171 SmallVector<CodeGenInstruction*, 8> Revisit;
3172 unsigned Errors = 0;
3173 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
3174 CodeGenInstruction &InstInfo =
3175 const_cast<CodeGenInstruction &>(*Instructions[i]);
3177 // Get the primary instruction pattern.
3178 const TreePattern *Pattern = getInstruction(InstInfo.TheDef).getPattern();
3180 if (InstInfo.hasUndefFlags())
3181 Revisit.push_back(&InstInfo);
3184 InstAnalyzer PatInfo(*this);
3185 PatInfo.Analyze(Pattern);
3186 Errors += InferFromPattern(InstInfo, PatInfo, InstInfo.TheDef);
3189 // Second, look for single-instruction patterns defined outside the
3191 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3192 const PatternToMatch &PTM = *I;
3194 // We can only infer from single-instruction patterns, otherwise we won't
3195 // know which instruction should get the flags.
3196 SmallVector<Record*, 8> PatInstrs;
3197 getInstructionsInTree(PTM.getDstPattern(), PatInstrs);
3198 if (PatInstrs.size() != 1)
3201 // Get the single instruction.
3202 CodeGenInstruction &InstInfo = Target.getInstruction(PatInstrs.front());
3204 // Only infer properties from the first pattern. We'll verify the others.
3205 if (InstInfo.InferredFrom)
3208 InstAnalyzer PatInfo(*this);
3209 PatInfo.Analyze(&PTM);
3210 Errors += InferFromPattern(InstInfo, PatInfo, PTM.getSrcRecord());
3214 PrintFatalError("pattern conflicts");
3216 // Revisit instructions with undefined flags and no pattern.
3217 if (Target.guessInstructionProperties()) {
3218 for (CodeGenInstruction *InstInfo : Revisit) {
3219 if (InstInfo->InferredFrom)
3221 // The mayLoad and mayStore flags default to false.
3222 // Conservatively assume hasSideEffects if it wasn't explicit.
3223 if (InstInfo->hasSideEffects_Unset)
3224 InstInfo->hasSideEffects = true;
3229 // Complain about any flags that are still undefined.
3230 for (CodeGenInstruction *InstInfo : Revisit) {
3231 if (InstInfo->InferredFrom)
3233 if (InstInfo->hasSideEffects_Unset)
3234 PrintError(InstInfo->TheDef->getLoc(),
3235 "Can't infer hasSideEffects from patterns");
3236 if (InstInfo->mayStore_Unset)
3237 PrintError(InstInfo->TheDef->getLoc(),
3238 "Can't infer mayStore from patterns");
3239 if (InstInfo->mayLoad_Unset)
3240 PrintError(InstInfo->TheDef->getLoc(),
3241 "Can't infer mayLoad from patterns");
3246 /// Verify instruction flags against pattern node properties.
3247 void CodeGenDAGPatterns::VerifyInstructionFlags() {
3248 unsigned Errors = 0;
3249 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3250 const PatternToMatch &PTM = *I;
3251 SmallVector<Record*, 8> Instrs;
3252 getInstructionsInTree(PTM.getDstPattern(), Instrs);
3256 // Count the number of instructions with each flag set.
3257 unsigned NumSideEffects = 0;
3258 unsigned NumStores = 0;
3259 unsigned NumLoads = 0;
3260 for (const Record *Instr : Instrs) {
3261 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
3262 NumSideEffects += InstInfo.hasSideEffects;
3263 NumStores += InstInfo.mayStore;
3264 NumLoads += InstInfo.mayLoad;
3267 // Analyze the source pattern.
3268 InstAnalyzer PatInfo(*this);
3269 PatInfo.Analyze(&PTM);
3271 // Collect error messages.
3272 SmallVector<std::string, 4> Msgs;
3274 // Check for missing flags in the output.
3275 // Permit extra flags for now at least.
3276 if (PatInfo.hasSideEffects && !NumSideEffects)
3277 Msgs.push_back("pattern has side effects, but hasSideEffects isn't set");
3279 // Don't verify store flags on instructions with side effects. At least for
3280 // intrinsics, side effects implies mayStore.
3281 if (!PatInfo.hasSideEffects && PatInfo.mayStore && !NumStores)
3282 Msgs.push_back("pattern may store, but mayStore isn't set");
3284 // Similarly, mayStore implies mayLoad on intrinsics.
3285 if (!PatInfo.mayStore && PatInfo.mayLoad && !NumLoads)
3286 Msgs.push_back("pattern may load, but mayLoad isn't set");
3288 // Print error messages.
3293 for (const std::string &Msg : Msgs)
3294 PrintError(PTM.getSrcRecord()->getLoc(), Twine(Msg) + " on the " +
3295 (Instrs.size() == 1 ?
3296 "instruction" : "output instructions"));
3297 // Provide the location of the relevant instruction definitions.
3298 for (const Record *Instr : Instrs) {
3299 if (Instr != PTM.getSrcRecord())
3300 PrintError(Instr->getLoc(), "defined here");
3301 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
3302 if (InstInfo.InferredFrom &&
3303 InstInfo.InferredFrom != InstInfo.TheDef &&
3304 InstInfo.InferredFrom != PTM.getSrcRecord())
3305 PrintError(InstInfo.InferredFrom->getLoc(), "inferred from pattern");
3309 PrintFatalError("Errors in DAG patterns");
3312 /// Given a pattern result with an unresolved type, see if we can find one
3313 /// instruction with an unresolved result type. Force this result type to an
3314 /// arbitrary element if it's possible types to converge results.
3315 static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
3319 // Analyze children.
3320 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3321 if (ForceArbitraryInstResultType(N->getChild(i), TP))
3324 if (!N->getOperator()->isSubClassOf("Instruction"))
3327 // If this type is already concrete or completely unknown we can't do
3329 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
3330 if (N->getExtType(i).isCompletelyUnknown() || N->getExtType(i).isConcrete())
3333 // Otherwise, force its type to the first possibility (an arbitrary choice).
3334 if (N->getExtType(i).MergeInTypeInfo(N->getExtType(i).getTypeList()[0], TP))
3341 void CodeGenDAGPatterns::ParsePatterns() {
3342 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
3344 for (Record *CurPattern : Patterns) {
3345 DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
3347 // If the pattern references the null_frag, there's nothing to do.
3348 if (hasNullFragReference(Tree))
3351 TreePattern *Pattern = new TreePattern(CurPattern, Tree, true, *this);
3353 // Inline pattern fragments into it.
3354 Pattern->InlinePatternFragments();
3356 ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
3357 if (LI->empty()) continue; // no pattern.
3359 // Parse the instruction.
3360 TreePattern Result(CurPattern, LI, false, *this);
3362 // Inline pattern fragments into it.
3363 Result.InlinePatternFragments();
3365 if (Result.getNumTrees() != 1)
3366 Result.error("Cannot handle instructions producing instructions "
3367 "with temporaries yet!");
3369 bool IterateInference;
3370 bool InferredAllPatternTypes, InferredAllResultTypes;
3372 // Infer as many types as possible. If we cannot infer all of them, we
3373 // can never do anything with this pattern: report it to the user.
3374 InferredAllPatternTypes =
3375 Pattern->InferAllTypes(&Pattern->getNamedNodesMap());
3377 // Infer as many types as possible. If we cannot infer all of them, we
3378 // can never do anything with this pattern: report it to the user.
3379 InferredAllResultTypes =
3380 Result.InferAllTypes(&Pattern->getNamedNodesMap());
3382 IterateInference = false;
3384 // Apply the type of the result to the source pattern. This helps us
3385 // resolve cases where the input type is known to be a pointer type (which
3386 // is considered resolved), but the result knows it needs to be 32- or
3387 // 64-bits. Infer the other way for good measure.
3388 for (unsigned i = 0, e = std::min(Result.getTree(0)->getNumTypes(),
3389 Pattern->getTree(0)->getNumTypes());
3391 IterateInference = Pattern->getTree(0)->UpdateNodeType(
3392 i, Result.getTree(0)->getExtType(i), Result);
3393 IterateInference |= Result.getTree(0)->UpdateNodeType(
3394 i, Pattern->getTree(0)->getExtType(i), Result);
3397 // If our iteration has converged and the input pattern's types are fully
3398 // resolved but the result pattern is not fully resolved, we may have a
3399 // situation where we have two instructions in the result pattern and
3400 // the instructions require a common register class, but don't care about
3401 // what actual MVT is used. This is actually a bug in our modelling:
3402 // output patterns should have register classes, not MVTs.
3404 // In any case, to handle this, we just go through and disambiguate some
3405 // arbitrary types to the result pattern's nodes.
3406 if (!IterateInference && InferredAllPatternTypes &&
3407 !InferredAllResultTypes)
3409 ForceArbitraryInstResultType(Result.getTree(0), Result);
3410 } while (IterateInference);
3412 // Verify that we inferred enough types that we can do something with the
3413 // pattern and result. If these fire the user has to add type casts.
3414 if (!InferredAllPatternTypes)
3415 Pattern->error("Could not infer all types in pattern!");
3416 if (!InferredAllResultTypes) {
3418 Result.error("Could not infer all types in pattern result!");
3421 // Validate that the input pattern is correct.
3422 std::map<std::string, TreePatternNode*> InstInputs;
3423 std::map<std::string, TreePatternNode*> InstResults;
3424 std::vector<Record*> InstImpResults;
3425 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
3426 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
3427 InstInputs, InstResults,
3430 // Promote the xform function to be an explicit node if set.
3431 TreePatternNode *DstPattern = Result.getOnlyTree();
3432 std::vector<TreePatternNode*> ResultNodeOperands;
3433 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
3434 TreePatternNode *OpNode = DstPattern->getChild(ii);
3435 if (Record *Xform = OpNode->getTransformFn()) {
3436 OpNode->setTransformFn(nullptr);
3437 std::vector<TreePatternNode*> Children;
3438 Children.push_back(OpNode);
3439 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
3441 ResultNodeOperands.push_back(OpNode);
3443 DstPattern = Result.getOnlyTree();
3444 if (!DstPattern->isLeaf())
3445 DstPattern = new TreePatternNode(DstPattern->getOperator(),
3447 DstPattern->getNumTypes());
3449 for (unsigned i = 0, e = Result.getOnlyTree()->getNumTypes(); i != e; ++i)
3450 DstPattern->setType(i, Result.getOnlyTree()->getExtType(i));
3452 TreePattern Temp(Result.getRecord(), DstPattern, false, *this);
3453 Temp.InferAllTypes();
3456 AddPatternToMatch(Pattern,
3457 PatternToMatch(CurPattern,
3458 CurPattern->getValueAsListInit("Predicates"),
3459 Pattern->getTree(0),
3460 Temp.getOnlyTree(), InstImpResults,
3461 CurPattern->getValueAsInt("AddedComplexity"),
3462 CurPattern->getID()));
3466 /// CombineChildVariants - Given a bunch of permutations of each child of the
3467 /// 'operator' node, put them together in all possible ways.
3468 static void CombineChildVariants(TreePatternNode *Orig,
3469 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
3470 std::vector<TreePatternNode*> &OutVariants,
3471 CodeGenDAGPatterns &CDP,
3472 const MultipleUseVarSet &DepVars) {
3473 // Make sure that each operand has at least one variant to choose from.
3474 for (const auto &Variants : ChildVariants)
3475 if (Variants.empty())
3478 // The end result is an all-pairs construction of the resultant pattern.
3479 std::vector<unsigned> Idxs;
3480 Idxs.resize(ChildVariants.size());
3484 DEBUG(if (!Idxs.empty()) {
3485 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
3486 for (unsigned Idx : Idxs) {
3487 errs() << Idx << " ";
3492 // Create the variant and add it to the output list.
3493 std::vector<TreePatternNode*> NewChildren;
3494 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
3495 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
3496 auto R = llvm::make_unique<TreePatternNode>(
3497 Orig->getOperator(), NewChildren, Orig->getNumTypes());
3499 // Copy over properties.
3500 R->setName(Orig->getName());
3501 R->setPredicateFns(Orig->getPredicateFns());
3502 R->setTransformFn(Orig->getTransformFn());
3503 for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
3504 R->setType(i, Orig->getExtType(i));
3506 // If this pattern cannot match, do not include it as a variant.
3507 std::string ErrString;
3508 // Scan to see if this pattern has already been emitted. We can get
3509 // duplication due to things like commuting:
3510 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
3511 // which are the same pattern. Ignore the dups.
3512 if (R->canPatternMatch(ErrString, CDP) &&
3513 std::none_of(OutVariants.begin(), OutVariants.end(),
3514 [&](TreePatternNode *Variant) {
3515 return R->isIsomorphicTo(Variant, DepVars);
3517 OutVariants.push_back(R.release());
3519 // Increment indices to the next permutation by incrementing the
3520 // indices from last index backward, e.g., generate the sequence
3521 // [0, 0], [0, 1], [1, 0], [1, 1].
3523 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
3524 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
3529 NotDone = (IdxsIdx >= 0);
3533 /// CombineChildVariants - A helper function for binary operators.
3535 static void CombineChildVariants(TreePatternNode *Orig,
3536 const std::vector<TreePatternNode*> &LHS,
3537 const std::vector<TreePatternNode*> &RHS,
3538 std::vector<TreePatternNode*> &OutVariants,
3539 CodeGenDAGPatterns &CDP,
3540 const MultipleUseVarSet &DepVars) {
3541 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3542 ChildVariants.push_back(LHS);
3543 ChildVariants.push_back(RHS);
3544 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
3548 static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
3549 std::vector<TreePatternNode *> &Children) {
3550 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
3551 Record *Operator = N->getOperator();
3553 // Only permit raw nodes.
3554 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
3555 N->getTransformFn()) {
3556 Children.push_back(N);
3560 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
3561 Children.push_back(N->getChild(0));
3563 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
3565 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
3566 Children.push_back(N->getChild(1));
3568 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
3571 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
3572 /// the (potentially recursive) pattern by using algebraic laws.
3574 static void GenerateVariantsOf(TreePatternNode *N,
3575 std::vector<TreePatternNode*> &OutVariants,
3576 CodeGenDAGPatterns &CDP,
3577 const MultipleUseVarSet &DepVars) {
3578 // We cannot permute leaves or ComplexPattern uses.
3579 if (N->isLeaf() || N->getOperator()->isSubClassOf("ComplexPattern")) {
3580 OutVariants.push_back(N);
3584 // Look up interesting info about the node.
3585 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
3587 // If this node is associative, re-associate.
3588 if (NodeInfo.hasProperty(SDNPAssociative)) {
3589 // Re-associate by pulling together all of the linked operators
3590 std::vector<TreePatternNode*> MaximalChildren;
3591 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
3593 // Only handle child sizes of 3. Otherwise we'll end up trying too many
3595 if (MaximalChildren.size() == 3) {
3596 // Find the variants of all of our maximal children.
3597 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
3598 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
3599 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
3600 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
3602 // There are only two ways we can permute the tree:
3603 // (A op B) op C and A op (B op C)
3604 // Within these forms, we can also permute A/B/C.
3606 // Generate legal pair permutations of A/B/C.
3607 std::vector<TreePatternNode*> ABVariants;
3608 std::vector<TreePatternNode*> BAVariants;
3609 std::vector<TreePatternNode*> ACVariants;
3610 std::vector<TreePatternNode*> CAVariants;
3611 std::vector<TreePatternNode*> BCVariants;
3612 std::vector<TreePatternNode*> CBVariants;
3613 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
3614 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
3615 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
3616 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
3617 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
3618 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
3620 // Combine those into the result: (x op x) op x
3621 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
3622 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
3623 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
3624 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
3625 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
3626 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
3628 // Combine those into the result: x op (x op x)
3629 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
3630 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
3631 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
3632 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
3633 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
3634 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
3639 // Compute permutations of all children.
3640 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3641 ChildVariants.resize(N->getNumChildren());
3642 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3643 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
3645 // Build all permutations based on how the children were formed.
3646 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
3648 // If this node is commutative, consider the commuted order.
3649 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
3650 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
3651 assert((N->getNumChildren()==2 || isCommIntrinsic) &&
3652 "Commutative but doesn't have 2 children!");
3653 // Don't count children which are actually register references.
3655 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
3656 TreePatternNode *Child = N->getChild(i);
3657 if (Child->isLeaf())
3658 if (DefInit *DI = dyn_cast<DefInit>(Child->getLeafValue())) {
3659 Record *RR = DI->getDef();
3660 if (RR->isSubClassOf("Register"))
3665 // Consider the commuted order.
3666 if (isCommIntrinsic) {
3667 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
3668 // operands are the commutative operands, and there might be more operands
3671 "Commutative intrinsic should have at least 3 children!");
3672 std::vector<std::vector<TreePatternNode*> > Variants;
3673 Variants.push_back(ChildVariants[0]); // Intrinsic id.
3674 Variants.push_back(ChildVariants[2]);
3675 Variants.push_back(ChildVariants[1]);
3676 for (unsigned i = 3; i != NC; ++i)
3677 Variants.push_back(ChildVariants[i]);
3678 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
3680 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
3681 OutVariants, CDP, DepVars);
3686 // GenerateVariants - Generate variants. For example, commutative patterns can
3687 // match multiple ways. Add them to PatternsToMatch as well.
3688 void CodeGenDAGPatterns::GenerateVariants() {
3689 DEBUG(errs() << "Generating instruction variants.\n");
3691 // Loop over all of the patterns we've collected, checking to see if we can
3692 // generate variants of the instruction, through the exploitation of
3693 // identities. This permits the target to provide aggressive matching without
3694 // the .td file having to contain tons of variants of instructions.
3696 // Note that this loop adds new patterns to the PatternsToMatch list, but we
3697 // intentionally do not reconsider these. Any variants of added patterns have
3698 // already been added.
3700 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
3701 MultipleUseVarSet DepVars;
3702 std::vector<TreePatternNode*> Variants;
3703 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
3704 DEBUG(errs() << "Dependent/multiply used variables: ");
3705 DEBUG(DumpDepVars(DepVars));
3706 DEBUG(errs() << "\n");
3707 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this,
3710 assert(!Variants.empty() && "Must create at least original variant!");
3711 Variants.erase(Variants.begin()); // Remove the original pattern.
3713 if (Variants.empty()) // No variants for this pattern.
3716 DEBUG(errs() << "FOUND VARIANTS OF: ";
3717 PatternsToMatch[i].getSrcPattern()->dump();
3720 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
3721 TreePatternNode *Variant = Variants[v];
3723 DEBUG(errs() << " VAR#" << v << ": ";
3727 // Scan to see if an instruction or explicit pattern already matches this.
3728 bool AlreadyExists = false;
3729 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
3730 // Skip if the top level predicates do not match.
3731 if (PatternsToMatch[i].getPredicates() !=
3732 PatternsToMatch[p].getPredicates())
3734 // Check to see if this variant already exists.
3735 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),
3737 DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
3738 AlreadyExists = true;
3742 // If we already have it, ignore the variant.
3743 if (AlreadyExists) continue;
3745 // Otherwise, add it to the list of patterns we have.
3746 PatternsToMatch.emplace_back(
3747 PatternsToMatch[i].getSrcRecord(), PatternsToMatch[i].getPredicates(),
3748 Variant, PatternsToMatch[i].getDstPattern(),
3749 PatternsToMatch[i].getDstRegs(),
3750 PatternsToMatch[i].getAddedComplexity(), Record::getNewUID());
3753 DEBUG(errs() << "\n");