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/TableGen/Error.h"
17 #include "llvm/TableGen/Record.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/Twine.h"
21 #include "llvm/Support/Debug.h"
22 #include "llvm/Support/ErrorHandling.h"
28 //===----------------------------------------------------------------------===//
29 // EEVT::TypeSet Implementation
30 //===----------------------------------------------------------------------===//
32 static inline bool isInteger(MVT::SimpleValueType VT) {
33 return EVT(VT).isInteger();
35 static inline bool isFloatingPoint(MVT::SimpleValueType VT) {
36 return EVT(VT).isFloatingPoint();
38 static inline bool isVector(MVT::SimpleValueType VT) {
39 return EVT(VT).isVector();
41 static inline bool isScalar(MVT::SimpleValueType VT) {
42 return !EVT(VT).isVector();
45 EEVT::TypeSet::TypeSet(MVT::SimpleValueType VT, TreePattern &TP) {
48 else if (VT == MVT::fAny)
49 EnforceFloatingPoint(TP);
50 else if (VT == MVT::vAny)
53 assert((VT < MVT::LAST_VALUETYPE || VT == MVT::iPTR ||
54 VT == MVT::iPTRAny) && "Not a concrete type!");
55 TypeVec.push_back(VT);
60 EEVT::TypeSet::TypeSet(const std::vector<MVT::SimpleValueType> &VTList) {
61 assert(!VTList.empty() && "empty list?");
62 TypeVec.append(VTList.begin(), VTList.end());
65 assert(VTList[0] != MVT::iAny && VTList[0] != MVT::vAny &&
66 VTList[0] != MVT::fAny);
68 // Verify no duplicates.
69 array_pod_sort(TypeVec.begin(), TypeVec.end());
70 assert(std::unique(TypeVec.begin(), TypeVec.end()) == TypeVec.end());
73 /// FillWithPossibleTypes - Set to all legal types and return true, only valid
74 /// on completely unknown type sets.
75 bool EEVT::TypeSet::FillWithPossibleTypes(TreePattern &TP,
76 bool (*Pred)(MVT::SimpleValueType),
77 const char *PredicateName) {
78 assert(isCompletelyUnknown());
79 const std::vector<MVT::SimpleValueType> &LegalTypes =
80 TP.getDAGPatterns().getTargetInfo().getLegalValueTypes();
82 for (unsigned i = 0, e = LegalTypes.size(); i != e; ++i)
83 if (Pred == 0 || Pred(LegalTypes[i]))
84 TypeVec.push_back(LegalTypes[i]);
86 // If we have nothing that matches the predicate, bail out.
88 TP.error("Type inference contradiction found, no " +
89 std::string(PredicateName) + " types found");
90 // No need to sort with one element.
91 if (TypeVec.size() == 1) return true;
94 array_pod_sort(TypeVec.begin(), TypeVec.end());
95 TypeVec.erase(std::unique(TypeVec.begin(), TypeVec.end()), TypeVec.end());
100 /// hasIntegerTypes - Return true if this TypeSet contains iAny or an
101 /// integer value type.
102 bool EEVT::TypeSet::hasIntegerTypes() const {
103 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
104 if (isInteger(TypeVec[i]))
109 /// hasFloatingPointTypes - Return true if this TypeSet contains an fAny or
110 /// a floating point value type.
111 bool EEVT::TypeSet::hasFloatingPointTypes() const {
112 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
113 if (isFloatingPoint(TypeVec[i]))
118 /// hasVectorTypes - Return true if this TypeSet contains a vAny or a vector
120 bool EEVT::TypeSet::hasVectorTypes() const {
121 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
122 if (isVector(TypeVec[i]))
128 std::string EEVT::TypeSet::getName() const {
129 if (TypeVec.empty()) return "<empty>";
133 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i) {
134 std::string VTName = llvm::getEnumName(TypeVec[i]);
135 // Strip off MVT:: prefix if present.
136 if (VTName.substr(0,5) == "MVT::")
137 VTName = VTName.substr(5);
138 if (i) Result += ':';
142 if (TypeVec.size() == 1)
144 return "{" + Result + "}";
147 /// MergeInTypeInfo - This merges in type information from the specified
148 /// argument. If 'this' changes, it returns true. If the two types are
149 /// contradictory (e.g. merge f32 into i32) then this throws an exception.
150 bool EEVT::TypeSet::MergeInTypeInfo(const EEVT::TypeSet &InVT, TreePattern &TP){
151 if (InVT.isCompletelyUnknown() || *this == InVT)
154 if (isCompletelyUnknown()) {
159 assert(TypeVec.size() >= 1 && InVT.TypeVec.size() >= 1 && "No unknowns");
161 // Handle the abstract cases, seeing if we can resolve them better.
162 switch (TypeVec[0]) {
166 if (InVT.hasIntegerTypes()) {
167 EEVT::TypeSet InCopy(InVT);
168 InCopy.EnforceInteger(TP);
169 InCopy.EnforceScalar(TP);
171 if (InCopy.isConcrete()) {
172 // If the RHS has one integer type, upgrade iPTR to i32.
173 TypeVec[0] = InVT.TypeVec[0];
177 // If the input has multiple scalar integers, this doesn't add any info.
178 if (!InCopy.isCompletelyUnknown())
184 // If the input constraint is iAny/iPTR and this is an integer type list,
185 // remove non-integer types from the list.
186 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
188 bool MadeChange = EnforceInteger(TP);
190 // If we're merging in iPTR/iPTRAny and the node currently has a list of
191 // multiple different integer types, replace them with a single iPTR.
192 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
193 TypeVec.size() != 1) {
195 TypeVec[0] = InVT.TypeVec[0];
202 // If this is a type list and the RHS is a typelist as well, eliminate entries
203 // from this list that aren't in the other one.
204 bool MadeChange = false;
205 TypeSet InputSet(*this);
207 for (unsigned i = 0; i != TypeVec.size(); ++i) {
209 for (unsigned j = 0, e = InVT.TypeVec.size(); j != e; ++j)
210 if (TypeVec[i] == InVT.TypeVec[j]) {
215 if (InInVT) continue;
216 TypeVec.erase(TypeVec.begin()+i--);
220 // If we removed all of our types, we have a type contradiction.
221 if (!TypeVec.empty())
224 // FIXME: Really want an SMLoc here!
225 TP.error("Type inference contradiction found, merging '" +
226 InVT.getName() + "' into '" + InputSet.getName() + "'");
227 return true; // unreachable
230 /// EnforceInteger - Remove all non-integer types from this set.
231 bool EEVT::TypeSet::EnforceInteger(TreePattern &TP) {
232 // If we know nothing, then get the full set.
234 return FillWithPossibleTypes(TP, isInteger, "integer");
235 if (!hasFloatingPointTypes())
238 TypeSet InputSet(*this);
240 // Filter out all the fp types.
241 for (unsigned i = 0; i != TypeVec.size(); ++i)
242 if (!isInteger(TypeVec[i]))
243 TypeVec.erase(TypeVec.begin()+i--);
246 TP.error("Type inference contradiction found, '" +
247 InputSet.getName() + "' needs to be integer");
251 /// EnforceFloatingPoint - Remove all integer types from this set.
252 bool EEVT::TypeSet::EnforceFloatingPoint(TreePattern &TP) {
253 // If we know nothing, then get the full set.
255 return FillWithPossibleTypes(TP, isFloatingPoint, "floating point");
257 if (!hasIntegerTypes())
260 TypeSet InputSet(*this);
262 // Filter out all the fp types.
263 for (unsigned i = 0; i != TypeVec.size(); ++i)
264 if (!isFloatingPoint(TypeVec[i]))
265 TypeVec.erase(TypeVec.begin()+i--);
268 TP.error("Type inference contradiction found, '" +
269 InputSet.getName() + "' needs to be floating point");
273 /// EnforceScalar - Remove all vector types from this.
274 bool EEVT::TypeSet::EnforceScalar(TreePattern &TP) {
275 // If we know nothing, then get the full set.
277 return FillWithPossibleTypes(TP, isScalar, "scalar");
279 if (!hasVectorTypes())
282 TypeSet InputSet(*this);
284 // Filter out all the vector types.
285 for (unsigned i = 0; i != TypeVec.size(); ++i)
286 if (!isScalar(TypeVec[i]))
287 TypeVec.erase(TypeVec.begin()+i--);
290 TP.error("Type inference contradiction found, '" +
291 InputSet.getName() + "' needs to be scalar");
295 /// EnforceVector - Remove all vector types from this.
296 bool EEVT::TypeSet::EnforceVector(TreePattern &TP) {
297 // If we know nothing, then get the full set.
299 return FillWithPossibleTypes(TP, isVector, "vector");
301 TypeSet InputSet(*this);
302 bool MadeChange = false;
304 // Filter out all the scalar types.
305 for (unsigned i = 0; i != TypeVec.size(); ++i)
306 if (!isVector(TypeVec[i])) {
307 TypeVec.erase(TypeVec.begin()+i--);
312 TP.error("Type inference contradiction found, '" +
313 InputSet.getName() + "' needs to be a vector");
319 /// EnforceSmallerThan - 'this' must be a smaller VT than Other. Update
320 /// this an other based on this information.
321 bool EEVT::TypeSet::EnforceSmallerThan(EEVT::TypeSet &Other, TreePattern &TP) {
322 // Both operands must be integer or FP, but we don't care which.
323 bool MadeChange = false;
325 if (isCompletelyUnknown())
326 MadeChange = FillWithPossibleTypes(TP);
328 if (Other.isCompletelyUnknown())
329 MadeChange = Other.FillWithPossibleTypes(TP);
331 // If one side is known to be integer or known to be FP but the other side has
332 // no information, get at least the type integrality info in there.
333 if (!hasFloatingPointTypes())
334 MadeChange |= Other.EnforceInteger(TP);
335 else if (!hasIntegerTypes())
336 MadeChange |= Other.EnforceFloatingPoint(TP);
337 if (!Other.hasFloatingPointTypes())
338 MadeChange |= EnforceInteger(TP);
339 else if (!Other.hasIntegerTypes())
340 MadeChange |= EnforceFloatingPoint(TP);
342 assert(!isCompletelyUnknown() && !Other.isCompletelyUnknown() &&
343 "Should have a type list now");
345 // If one contains vectors but the other doesn't pull vectors out.
346 if (!hasVectorTypes())
347 MadeChange |= Other.EnforceScalar(TP);
348 if (!hasVectorTypes())
349 MadeChange |= EnforceScalar(TP);
351 if (TypeVec.size() == 1 && Other.TypeVec.size() == 1) {
352 // If we are down to concrete types, this code does not currently
353 // handle nodes which have multiple types, where some types are
354 // integer, and some are fp. Assert that this is not the case.
355 assert(!(hasIntegerTypes() && hasFloatingPointTypes()) &&
356 !(Other.hasIntegerTypes() && Other.hasFloatingPointTypes()) &&
357 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
359 // Otherwise, if these are both vector types, either this vector
360 // must have a larger bitsize than the other, or this element type
361 // must be larger than the other.
362 EVT Type(TypeVec[0]);
363 EVT OtherType(Other.TypeVec[0]);
365 if (hasVectorTypes() && Other.hasVectorTypes()) {
366 if (Type.getSizeInBits() >= OtherType.getSizeInBits())
367 if (Type.getVectorElementType().getSizeInBits()
368 >= OtherType.getVectorElementType().getSizeInBits())
369 TP.error("Type inference contradiction found, '" +
370 getName() + "' element type not smaller than '" +
371 Other.getName() +"'!");
374 // For scalar types, the bitsize of this type must be larger
375 // than that of the other.
376 if (Type.getSizeInBits() >= OtherType.getSizeInBits())
377 TP.error("Type inference contradiction found, '" +
378 getName() + "' is not smaller than '" +
379 Other.getName() +"'!");
384 // Handle int and fp as disjoint sets. This won't work for patterns
385 // that have mixed fp/int types but those are likely rare and would
386 // not have been accepted by this code previously.
388 // Okay, find the smallest type from the current set and remove it from the
390 MVT::SimpleValueType SmallestInt = MVT::LAST_VALUETYPE;
391 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
392 if (isInteger(TypeVec[i])) {
393 SmallestInt = TypeVec[i];
396 for (unsigned i = 1, e = TypeVec.size(); i != e; ++i)
397 if (isInteger(TypeVec[i]) && TypeVec[i] < SmallestInt)
398 SmallestInt = TypeVec[i];
400 MVT::SimpleValueType SmallestFP = MVT::LAST_VALUETYPE;
401 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
402 if (isFloatingPoint(TypeVec[i])) {
403 SmallestFP = TypeVec[i];
406 for (unsigned i = 1, e = TypeVec.size(); i != e; ++i)
407 if (isFloatingPoint(TypeVec[i]) && TypeVec[i] < SmallestFP)
408 SmallestFP = TypeVec[i];
410 int OtherIntSize = 0;
412 for (SmallVector<MVT::SimpleValueType, 2>::iterator TVI =
413 Other.TypeVec.begin();
414 TVI != Other.TypeVec.end();
416 if (isInteger(*TVI)) {
418 if (*TVI == SmallestInt) {
419 TVI = Other.TypeVec.erase(TVI);
425 else if (isFloatingPoint(*TVI)) {
427 if (*TVI == SmallestFP) {
428 TVI = Other.TypeVec.erase(TVI);
437 // If this is the only type in the large set, the constraint can never be
439 if ((Other.hasIntegerTypes() && OtherIntSize == 0)
440 || (Other.hasFloatingPointTypes() && OtherFPSize == 0))
441 TP.error("Type inference contradiction found, '" +
442 Other.getName() + "' has nothing larger than '" + getName() +"'!");
444 // Okay, find the largest type in the Other set and remove it from the
446 MVT::SimpleValueType LargestInt = MVT::Other;
447 for (unsigned i = 0, e = Other.TypeVec.size(); i != e; ++i)
448 if (isInteger(Other.TypeVec[i])) {
449 LargestInt = Other.TypeVec[i];
452 for (unsigned i = 1, e = Other.TypeVec.size(); i != e; ++i)
453 if (isInteger(Other.TypeVec[i]) && Other.TypeVec[i] > LargestInt)
454 LargestInt = Other.TypeVec[i];
456 MVT::SimpleValueType LargestFP = MVT::Other;
457 for (unsigned i = 0, e = Other.TypeVec.size(); i != e; ++i)
458 if (isFloatingPoint(Other.TypeVec[i])) {
459 LargestFP = Other.TypeVec[i];
462 for (unsigned i = 1, e = Other.TypeVec.size(); i != e; ++i)
463 if (isFloatingPoint(Other.TypeVec[i]) && Other.TypeVec[i] > LargestFP)
464 LargestFP = Other.TypeVec[i];
468 for (SmallVector<MVT::SimpleValueType, 2>::iterator TVI =
470 TVI != TypeVec.end();
472 if (isInteger(*TVI)) {
474 if (*TVI == LargestInt) {
475 TVI = TypeVec.erase(TVI);
481 else if (isFloatingPoint(*TVI)) {
483 if (*TVI == LargestFP) {
484 TVI = TypeVec.erase(TVI);
493 // If this is the only type in the small set, the constraint can never be
495 if ((hasIntegerTypes() && IntSize == 0)
496 || (hasFloatingPointTypes() && FPSize == 0))
497 TP.error("Type inference contradiction found, '" +
498 getName() + "' has nothing smaller than '" + Other.getName()+"'!");
503 /// EnforceVectorEltTypeIs - 'this' is now constrainted to be a vector type
504 /// whose element is specified by VTOperand.
505 bool EEVT::TypeSet::EnforceVectorEltTypeIs(EEVT::TypeSet &VTOperand,
507 // "This" must be a vector and "VTOperand" must be a scalar.
508 bool MadeChange = false;
509 MadeChange |= EnforceVector(TP);
510 MadeChange |= VTOperand.EnforceScalar(TP);
512 // If we know the vector type, it forces the scalar to agree.
514 EVT IVT = getConcrete();
515 IVT = IVT.getVectorElementType();
517 VTOperand.MergeInTypeInfo(IVT.getSimpleVT().SimpleTy, TP);
520 // If the scalar type is known, filter out vector types whose element types
522 if (!VTOperand.isConcrete())
525 MVT::SimpleValueType VT = VTOperand.getConcrete();
527 TypeSet InputSet(*this);
529 // Filter out all the types which don't have the right element type.
530 for (unsigned i = 0; i != TypeVec.size(); ++i) {
531 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
532 if (EVT(TypeVec[i]).getVectorElementType().getSimpleVT().SimpleTy != VT) {
533 TypeVec.erase(TypeVec.begin()+i--);
538 if (TypeVec.empty()) // FIXME: Really want an SMLoc here!
539 TP.error("Type inference contradiction found, forcing '" +
540 InputSet.getName() + "' to have a vector element");
544 /// EnforceVectorSubVectorTypeIs - 'this' is now constrainted to be a
545 /// vector type specified by VTOperand.
546 bool EEVT::TypeSet::EnforceVectorSubVectorTypeIs(EEVT::TypeSet &VTOperand,
548 // "This" must be a vector and "VTOperand" must be a vector.
549 bool MadeChange = false;
550 MadeChange |= EnforceVector(TP);
551 MadeChange |= VTOperand.EnforceVector(TP);
553 // "This" must be larger than "VTOperand."
554 MadeChange |= VTOperand.EnforceSmallerThan(*this, TP);
556 // If we know the vector type, it forces the scalar types to agree.
558 EVT IVT = getConcrete();
559 IVT = IVT.getVectorElementType();
561 EEVT::TypeSet EltTypeSet(IVT.getSimpleVT().SimpleTy, TP);
562 MadeChange |= VTOperand.EnforceVectorEltTypeIs(EltTypeSet, TP);
563 } else if (VTOperand.isConcrete()) {
564 EVT IVT = VTOperand.getConcrete();
565 IVT = IVT.getVectorElementType();
567 EEVT::TypeSet EltTypeSet(IVT.getSimpleVT().SimpleTy, TP);
568 MadeChange |= EnforceVectorEltTypeIs(EltTypeSet, TP);
574 //===----------------------------------------------------------------------===//
575 // Helpers for working with extended types.
577 bool RecordPtrCmp::operator()(const Record *LHS, const Record *RHS) const {
578 return LHS->getID() < RHS->getID();
581 /// Dependent variable map for CodeGenDAGPattern variant generation
582 typedef std::map<std::string, int> DepVarMap;
584 /// Const iterator shorthand for DepVarMap
585 typedef DepVarMap::const_iterator DepVarMap_citer;
587 static void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
589 if (dynamic_cast<DefInit*>(N->getLeafValue()) != NULL)
590 DepMap[N->getName()]++;
592 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
593 FindDepVarsOf(N->getChild(i), DepMap);
597 /// Find dependent variables within child patterns
598 static void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
600 FindDepVarsOf(N, depcounts);
601 for (DepVarMap_citer i = depcounts.begin(); i != depcounts.end(); ++i) {
602 if (i->second > 1) // std::pair<std::string, int>
603 DepVars.insert(i->first);
608 /// Dump the dependent variable set:
609 static void DumpDepVars(MultipleUseVarSet &DepVars) {
610 if (DepVars.empty()) {
611 DEBUG(errs() << "<empty set>");
613 DEBUG(errs() << "[ ");
614 for (MultipleUseVarSet::const_iterator i = DepVars.begin(),
615 e = DepVars.end(); i != e; ++i) {
616 DEBUG(errs() << (*i) << " ");
618 DEBUG(errs() << "]");
624 //===----------------------------------------------------------------------===//
625 // TreePredicateFn Implementation
626 //===----------------------------------------------------------------------===//
628 /// TreePredicateFn constructor. Here 'N' is a subclass of PatFrag.
629 TreePredicateFn::TreePredicateFn(TreePattern *N) : PatFragRec(N) {
630 assert((getPredCode().empty() || getImmCode().empty()) &&
631 ".td file corrupt: can't have a node predicate *and* an imm predicate");
634 std::string TreePredicateFn::getPredCode() const {
635 return PatFragRec->getRecord()->getValueAsString("PredicateCode");
638 std::string TreePredicateFn::getImmCode() const {
639 return PatFragRec->getRecord()->getValueAsString("ImmediateCode");
643 /// isAlwaysTrue - Return true if this is a noop predicate.
644 bool TreePredicateFn::isAlwaysTrue() const {
645 return getPredCode().empty() && getImmCode().empty();
648 /// Return the name to use in the generated code to reference this, this is
649 /// "Predicate_foo" if from a pattern fragment "foo".
650 std::string TreePredicateFn::getFnName() const {
651 return "Predicate_" + PatFragRec->getRecord()->getName();
654 /// getCodeToRunOnSDNode - Return the code for the function body that
655 /// evaluates this predicate. The argument is expected to be in "Node",
656 /// not N. This handles casting and conversion to a concrete node type as
658 std::string TreePredicateFn::getCodeToRunOnSDNode() const {
659 // Handle immediate predicates first.
660 std::string ImmCode = getImmCode();
661 if (!ImmCode.empty()) {
663 " int64_t Imm = cast<ConstantSDNode>(Node)->getSExtValue();\n";
664 return Result + ImmCode;
667 // Handle arbitrary node predicates.
668 assert(!getPredCode().empty() && "Don't have any predicate code!");
669 std::string ClassName;
670 if (PatFragRec->getOnlyTree()->isLeaf())
671 ClassName = "SDNode";
673 Record *Op = PatFragRec->getOnlyTree()->getOperator();
674 ClassName = PatFragRec->getDAGPatterns().getSDNodeInfo(Op).getSDClassName();
677 if (ClassName == "SDNode")
678 Result = " SDNode *N = Node;\n";
680 Result = " " + ClassName + "*N = cast<" + ClassName + ">(Node);\n";
682 return Result + getPredCode();
685 //===----------------------------------------------------------------------===//
686 // PatternToMatch implementation
690 /// getPatternSize - Return the 'size' of this pattern. We want to match large
691 /// patterns before small ones. This is used to determine the size of a
693 static unsigned getPatternSize(const TreePatternNode *P,
694 const CodeGenDAGPatterns &CGP) {
695 unsigned Size = 3; // The node itself.
696 // If the root node is a ConstantSDNode, increases its size.
697 // e.g. (set R32:$dst, 0).
698 if (P->isLeaf() && dynamic_cast<IntInit*>(P->getLeafValue()))
701 // FIXME: This is a hack to statically increase the priority of patterns
702 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
703 // Later we can allow complexity / cost for each pattern to be (optionally)
704 // specified. To get best possible pattern match we'll need to dynamically
705 // calculate the complexity of all patterns a dag can potentially map to.
706 const ComplexPattern *AM = P->getComplexPatternInfo(CGP);
708 Size += AM->getNumOperands() * 3;
710 // If this node has some predicate function that must match, it adds to the
711 // complexity of this node.
712 if (!P->getPredicateFns().empty())
715 // Count children in the count if they are also nodes.
716 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
717 TreePatternNode *Child = P->getChild(i);
718 if (!Child->isLeaf() && Child->getNumTypes() &&
719 Child->getType(0) != MVT::Other)
720 Size += getPatternSize(Child, CGP);
721 else if (Child->isLeaf()) {
722 if (dynamic_cast<IntInit*>(Child->getLeafValue()))
723 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
724 else if (Child->getComplexPatternInfo(CGP))
725 Size += getPatternSize(Child, CGP);
726 else if (!Child->getPredicateFns().empty())
734 /// Compute the complexity metric for the input pattern. This roughly
735 /// corresponds to the number of nodes that are covered.
736 unsigned PatternToMatch::
737 getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
738 return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();
742 /// getPredicateCheck - Return a single string containing all of this
743 /// pattern's predicates concatenated with "&&" operators.
745 std::string PatternToMatch::getPredicateCheck() const {
746 std::string PredicateCheck;
747 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
748 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
749 Record *Def = Pred->getDef();
750 if (!Def->isSubClassOf("Predicate")) {
754 llvm_unreachable("Unknown predicate type!");
756 if (!PredicateCheck.empty())
757 PredicateCheck += " && ";
758 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
762 return PredicateCheck;
765 //===----------------------------------------------------------------------===//
766 // SDTypeConstraint implementation
769 SDTypeConstraint::SDTypeConstraint(Record *R) {
770 OperandNo = R->getValueAsInt("OperandNum");
772 if (R->isSubClassOf("SDTCisVT")) {
773 ConstraintType = SDTCisVT;
774 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
775 if (x.SDTCisVT_Info.VT == MVT::isVoid)
776 throw TGError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
778 } else if (R->isSubClassOf("SDTCisPtrTy")) {
779 ConstraintType = SDTCisPtrTy;
780 } else if (R->isSubClassOf("SDTCisInt")) {
781 ConstraintType = SDTCisInt;
782 } else if (R->isSubClassOf("SDTCisFP")) {
783 ConstraintType = SDTCisFP;
784 } else if (R->isSubClassOf("SDTCisVec")) {
785 ConstraintType = SDTCisVec;
786 } else if (R->isSubClassOf("SDTCisSameAs")) {
787 ConstraintType = SDTCisSameAs;
788 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
789 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
790 ConstraintType = SDTCisVTSmallerThanOp;
791 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
792 R->getValueAsInt("OtherOperandNum");
793 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
794 ConstraintType = SDTCisOpSmallerThanOp;
795 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
796 R->getValueAsInt("BigOperandNum");
797 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
798 ConstraintType = SDTCisEltOfVec;
799 x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
800 } else if (R->isSubClassOf("SDTCisSubVecOfVec")) {
801 ConstraintType = SDTCisSubVecOfVec;
802 x.SDTCisSubVecOfVec_Info.OtherOperandNum =
803 R->getValueAsInt("OtherOpNum");
805 errs() << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
810 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
811 /// N, and the result number in ResNo.
812 static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
813 const SDNodeInfo &NodeInfo,
815 unsigned NumResults = NodeInfo.getNumResults();
816 if (OpNo < NumResults) {
823 if (OpNo >= N->getNumChildren()) {
824 errs() << "Invalid operand number in type constraint "
825 << (OpNo+NumResults) << " ";
831 return N->getChild(OpNo);
834 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
835 /// constraint to the nodes operands. This returns true if it makes a
836 /// change, false otherwise. If a type contradiction is found, throw an
838 bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
839 const SDNodeInfo &NodeInfo,
840 TreePattern &TP) const {
841 unsigned ResNo = 0; // The result number being referenced.
842 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
844 switch (ConstraintType) {
846 // Operand must be a particular type.
847 return NodeToApply->UpdateNodeType(ResNo, x.SDTCisVT_Info.VT, TP);
849 // Operand must be same as target pointer type.
850 return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
852 // Require it to be one of the legal integer VTs.
853 return NodeToApply->getExtType(ResNo).EnforceInteger(TP);
855 // Require it to be one of the legal fp VTs.
856 return NodeToApply->getExtType(ResNo).EnforceFloatingPoint(TP);
858 // Require it to be one of the legal vector VTs.
859 return NodeToApply->getExtType(ResNo).EnforceVector(TP);
862 TreePatternNode *OtherNode =
863 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
864 return NodeToApply->UpdateNodeType(OResNo, OtherNode->getExtType(ResNo),TP)|
865 OtherNode->UpdateNodeType(ResNo,NodeToApply->getExtType(OResNo),TP);
867 case SDTCisVTSmallerThanOp: {
868 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
869 // have an integer type that is smaller than the VT.
870 if (!NodeToApply->isLeaf() ||
871 !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
872 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
873 ->isSubClassOf("ValueType"))
874 TP.error(N->getOperator()->getName() + " expects a VT operand!");
875 MVT::SimpleValueType VT =
876 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
878 EEVT::TypeSet TypeListTmp(VT, TP);
881 TreePatternNode *OtherNode =
882 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
885 return TypeListTmp.EnforceSmallerThan(OtherNode->getExtType(OResNo), TP);
887 case SDTCisOpSmallerThanOp: {
889 TreePatternNode *BigOperand =
890 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
892 return NodeToApply->getExtType(ResNo).
893 EnforceSmallerThan(BigOperand->getExtType(BResNo), TP);
895 case SDTCisEltOfVec: {
897 TreePatternNode *VecOperand =
898 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
901 // Filter vector types out of VecOperand that don't have the right element
903 return VecOperand->getExtType(VResNo).
904 EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), TP);
906 case SDTCisSubVecOfVec: {
908 TreePatternNode *BigVecOperand =
909 getOperandNum(x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo,
912 // Filter vector types out of BigVecOperand that don't have the
913 // right subvector type.
914 return BigVecOperand->getExtType(VResNo).
915 EnforceVectorSubVectorTypeIs(NodeToApply->getExtType(ResNo), TP);
918 llvm_unreachable("Invalid ConstraintType!");
921 //===----------------------------------------------------------------------===//
922 // SDNodeInfo implementation
924 SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
925 EnumName = R->getValueAsString("Opcode");
926 SDClassName = R->getValueAsString("SDClass");
927 Record *TypeProfile = R->getValueAsDef("TypeProfile");
928 NumResults = TypeProfile->getValueAsInt("NumResults");
929 NumOperands = TypeProfile->getValueAsInt("NumOperands");
931 // Parse the properties.
933 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
934 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
935 if (PropList[i]->getName() == "SDNPCommutative") {
936 Properties |= 1 << SDNPCommutative;
937 } else if (PropList[i]->getName() == "SDNPAssociative") {
938 Properties |= 1 << SDNPAssociative;
939 } else if (PropList[i]->getName() == "SDNPHasChain") {
940 Properties |= 1 << SDNPHasChain;
941 } else if (PropList[i]->getName() == "SDNPOutGlue") {
942 Properties |= 1 << SDNPOutGlue;
943 } else if (PropList[i]->getName() == "SDNPInGlue") {
944 Properties |= 1 << SDNPInGlue;
945 } else if (PropList[i]->getName() == "SDNPOptInGlue") {
946 Properties |= 1 << SDNPOptInGlue;
947 } else if (PropList[i]->getName() == "SDNPMayStore") {
948 Properties |= 1 << SDNPMayStore;
949 } else if (PropList[i]->getName() == "SDNPMayLoad") {
950 Properties |= 1 << SDNPMayLoad;
951 } else if (PropList[i]->getName() == "SDNPSideEffect") {
952 Properties |= 1 << SDNPSideEffect;
953 } else if (PropList[i]->getName() == "SDNPMemOperand") {
954 Properties |= 1 << SDNPMemOperand;
955 } else if (PropList[i]->getName() == "SDNPVariadic") {
956 Properties |= 1 << SDNPVariadic;
958 errs() << "Unknown SD Node property '" << PropList[i]->getName()
959 << "' on node '" << R->getName() << "'!\n";
965 // Parse the type constraints.
966 std::vector<Record*> ConstraintList =
967 TypeProfile->getValueAsListOfDefs("Constraints");
968 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
971 /// getKnownType - If the type constraints on this node imply a fixed type
972 /// (e.g. all stores return void, etc), then return it as an
973 /// MVT::SimpleValueType. Otherwise, return EEVT::Other.
974 MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
975 unsigned NumResults = getNumResults();
976 assert(NumResults <= 1 &&
977 "We only work with nodes with zero or one result so far!");
978 assert(ResNo == 0 && "Only handles single result nodes so far");
980 for (unsigned i = 0, e = TypeConstraints.size(); i != e; ++i) {
981 // Make sure that this applies to the correct node result.
982 if (TypeConstraints[i].OperandNo >= NumResults) // FIXME: need value #
985 switch (TypeConstraints[i].ConstraintType) {
987 case SDTypeConstraint::SDTCisVT:
988 return TypeConstraints[i].x.SDTCisVT_Info.VT;
989 case SDTypeConstraint::SDTCisPtrTy:
996 //===----------------------------------------------------------------------===//
997 // TreePatternNode implementation
1000 TreePatternNode::~TreePatternNode() {
1001 #if 0 // FIXME: implement refcounted tree nodes!
1002 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1007 static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
1008 if (Operator->getName() == "set" ||
1009 Operator->getName() == "implicit")
1010 return 0; // All return nothing.
1012 if (Operator->isSubClassOf("Intrinsic"))
1013 return CDP.getIntrinsic(Operator).IS.RetVTs.size();
1015 if (Operator->isSubClassOf("SDNode"))
1016 return CDP.getSDNodeInfo(Operator).getNumResults();
1018 if (Operator->isSubClassOf("PatFrag")) {
1019 // If we've already parsed this pattern fragment, get it. Otherwise, handle
1020 // the forward reference case where one pattern fragment references another
1021 // before it is processed.
1022 if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator))
1023 return PFRec->getOnlyTree()->getNumTypes();
1025 // Get the result tree.
1026 DagInit *Tree = Operator->getValueAsDag("Fragment");
1028 if (Tree && dynamic_cast<DefInit*>(Tree->getOperator()))
1029 Op = dynamic_cast<DefInit*>(Tree->getOperator())->getDef();
1030 assert(Op && "Invalid Fragment");
1031 return GetNumNodeResults(Op, CDP);
1034 if (Operator->isSubClassOf("Instruction")) {
1035 CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
1037 // FIXME: Should allow access to all the results here.
1038 unsigned NumDefsToAdd = InstInfo.Operands.NumDefs ? 1 : 0;
1040 // Add on one implicit def if it has a resolvable type.
1041 if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
1043 return NumDefsToAdd;
1046 if (Operator->isSubClassOf("SDNodeXForm"))
1047 return 1; // FIXME: Generalize SDNodeXForm
1050 errs() << "Unhandled node in GetNumNodeResults\n";
1054 void TreePatternNode::print(raw_ostream &OS) const {
1056 OS << *getLeafValue();
1058 OS << '(' << getOperator()->getName();
1060 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1061 OS << ':' << getExtType(i).getName();
1064 if (getNumChildren() != 0) {
1066 getChild(0)->print(OS);
1067 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
1069 getChild(i)->print(OS);
1075 for (unsigned i = 0, e = PredicateFns.size(); i != e; ++i)
1076 OS << "<<P:" << PredicateFns[i].getFnName() << ">>";
1078 OS << "<<X:" << TransformFn->getName() << ">>";
1079 if (!getName().empty())
1080 OS << ":$" << getName();
1083 void TreePatternNode::dump() const {
1087 /// isIsomorphicTo - Return true if this node is recursively
1088 /// isomorphic to the specified node. For this comparison, the node's
1089 /// entire state is considered. The assigned name is ignored, since
1090 /// nodes with differing names are considered isomorphic. However, if
1091 /// the assigned name is present in the dependent variable set, then
1092 /// the assigned name is considered significant and the node is
1093 /// isomorphic if the names match.
1094 bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
1095 const MultipleUseVarSet &DepVars) const {
1096 if (N == this) return true;
1097 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
1098 getPredicateFns() != N->getPredicateFns() ||
1099 getTransformFn() != N->getTransformFn())
1103 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
1104 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue())) {
1105 return ((DI->getDef() == NDI->getDef())
1106 && (DepVars.find(getName()) == DepVars.end()
1107 || getName() == N->getName()));
1110 return getLeafValue() == N->getLeafValue();
1113 if (N->getOperator() != getOperator() ||
1114 N->getNumChildren() != getNumChildren()) return false;
1115 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1116 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
1121 /// clone - Make a copy of this tree and all of its children.
1123 TreePatternNode *TreePatternNode::clone() const {
1124 TreePatternNode *New;
1126 New = new TreePatternNode(getLeafValue(), getNumTypes());
1128 std::vector<TreePatternNode*> CChildren;
1129 CChildren.reserve(Children.size());
1130 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1131 CChildren.push_back(getChild(i)->clone());
1132 New = new TreePatternNode(getOperator(), CChildren, getNumTypes());
1134 New->setName(getName());
1136 New->setPredicateFns(getPredicateFns());
1137 New->setTransformFn(getTransformFn());
1141 /// RemoveAllTypes - Recursively strip all the types of this tree.
1142 void TreePatternNode::RemoveAllTypes() {
1143 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1144 Types[i] = EEVT::TypeSet(); // Reset to unknown type.
1145 if (isLeaf()) return;
1146 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1147 getChild(i)->RemoveAllTypes();
1151 /// SubstituteFormalArguments - Replace the formal arguments in this tree
1152 /// with actual values specified by ArgMap.
1153 void TreePatternNode::
1154 SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
1155 if (isLeaf()) return;
1157 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1158 TreePatternNode *Child = getChild(i);
1159 if (Child->isLeaf()) {
1160 Init *Val = Child->getLeafValue();
1161 if (dynamic_cast<DefInit*>(Val) &&
1162 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
1163 // We found a use of a formal argument, replace it with its value.
1164 TreePatternNode *NewChild = ArgMap[Child->getName()];
1165 assert(NewChild && "Couldn't find formal argument!");
1166 assert((Child->getPredicateFns().empty() ||
1167 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1168 "Non-empty child predicate clobbered!");
1169 setChild(i, NewChild);
1172 getChild(i)->SubstituteFormalArguments(ArgMap);
1178 /// InlinePatternFragments - If this pattern refers to any pattern
1179 /// fragments, inline them into place, giving us a pattern without any
1180 /// PatFrag references.
1181 TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
1182 if (isLeaf()) return this; // nothing to do.
1183 Record *Op = getOperator();
1185 if (!Op->isSubClassOf("PatFrag")) {
1186 // Just recursively inline children nodes.
1187 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1188 TreePatternNode *Child = getChild(i);
1189 TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
1191 assert((Child->getPredicateFns().empty() ||
1192 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1193 "Non-empty child predicate clobbered!");
1195 setChild(i, NewChild);
1200 // Otherwise, we found a reference to a fragment. First, look up its
1201 // TreePattern record.
1202 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
1204 // Verify that we are passing the right number of operands.
1205 if (Frag->getNumArgs() != Children.size())
1206 TP.error("'" + Op->getName() + "' fragment requires " +
1207 utostr(Frag->getNumArgs()) + " operands!");
1209 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
1211 TreePredicateFn PredFn(Frag);
1212 if (!PredFn.isAlwaysTrue())
1213 FragTree->addPredicateFn(PredFn);
1215 // Resolve formal arguments to their actual value.
1216 if (Frag->getNumArgs()) {
1217 // Compute the map of formal to actual arguments.
1218 std::map<std::string, TreePatternNode*> ArgMap;
1219 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
1220 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
1222 FragTree->SubstituteFormalArguments(ArgMap);
1225 FragTree->setName(getName());
1226 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1227 FragTree->UpdateNodeType(i, getExtType(i), TP);
1229 // Transfer in the old predicates.
1230 for (unsigned i = 0, e = getPredicateFns().size(); i != e; ++i)
1231 FragTree->addPredicateFn(getPredicateFns()[i]);
1233 // Get a new copy of this fragment to stitch into here.
1234 //delete this; // FIXME: implement refcounting!
1236 // The fragment we inlined could have recursive inlining that is needed. See
1237 // if there are any pattern fragments in it and inline them as needed.
1238 return FragTree->InlinePatternFragments(TP);
1241 /// getImplicitType - Check to see if the specified record has an implicit
1242 /// type which should be applied to it. This will infer the type of register
1243 /// references from the register file information, for example.
1245 static EEVT::TypeSet getImplicitType(Record *R, unsigned ResNo,
1246 bool NotRegisters, TreePattern &TP) {
1247 // Check to see if this is a register operand.
1248 if (R->isSubClassOf("RegisterOperand")) {
1249 assert(ResNo == 0 && "Regoperand ref only has one result!");
1251 return EEVT::TypeSet(); // Unknown.
1252 Record *RegClass = R->getValueAsDef("RegClass");
1253 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1254 return EEVT::TypeSet(T.getRegisterClass(RegClass).getValueTypes());
1257 // Check to see if this is a register or a register class.
1258 if (R->isSubClassOf("RegisterClass")) {
1259 assert(ResNo == 0 && "Regclass ref only has one result!");
1261 return EEVT::TypeSet(); // Unknown.
1262 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1263 return EEVT::TypeSet(T.getRegisterClass(R).getValueTypes());
1266 if (R->isSubClassOf("PatFrag")) {
1267 assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
1268 // Pattern fragment types will be resolved when they are inlined.
1269 return EEVT::TypeSet(); // Unknown.
1272 if (R->isSubClassOf("Register")) {
1273 assert(ResNo == 0 && "Registers only produce one result!");
1275 return EEVT::TypeSet(); // Unknown.
1276 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1277 return EEVT::TypeSet(T.getRegisterVTs(R));
1280 if (R->isSubClassOf("SubRegIndex")) {
1281 assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
1282 return EEVT::TypeSet();
1285 if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
1286 assert(ResNo == 0 && "This node only has one result!");
1287 // Using a VTSDNode or CondCodeSDNode.
1288 return EEVT::TypeSet(MVT::Other, TP);
1291 if (R->isSubClassOf("ComplexPattern")) {
1292 assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
1294 return EEVT::TypeSet(); // Unknown.
1295 return EEVT::TypeSet(TP.getDAGPatterns().getComplexPattern(R).getValueType(),
1298 if (R->isSubClassOf("PointerLikeRegClass")) {
1299 assert(ResNo == 0 && "Regclass can only have one result!");
1300 return EEVT::TypeSet(MVT::iPTR, TP);
1303 if (R->getName() == "node" || R->getName() == "srcvalue" ||
1304 R->getName() == "zero_reg") {
1306 return EEVT::TypeSet(); // Unknown.
1309 TP.error("Unknown node flavor used in pattern: " + R->getName());
1310 return EEVT::TypeSet(MVT::Other, TP);
1314 /// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
1315 /// CodeGenIntrinsic information for it, otherwise return a null pointer.
1316 const CodeGenIntrinsic *TreePatternNode::
1317 getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
1318 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
1319 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
1320 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
1324 dynamic_cast<IntInit*>(getChild(0)->getLeafValue())->getValue();
1325 return &CDP.getIntrinsicInfo(IID);
1328 /// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
1329 /// return the ComplexPattern information, otherwise return null.
1330 const ComplexPattern *
1331 TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
1332 if (!isLeaf()) return 0;
1334 DefInit *DI = dynamic_cast<DefInit*>(getLeafValue());
1335 if (DI && DI->getDef()->isSubClassOf("ComplexPattern"))
1336 return &CGP.getComplexPattern(DI->getDef());
1340 /// NodeHasProperty - Return true if this node has the specified property.
1341 bool TreePatternNode::NodeHasProperty(SDNP Property,
1342 const CodeGenDAGPatterns &CGP) const {
1344 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1345 return CP->hasProperty(Property);
1349 Record *Operator = getOperator();
1350 if (!Operator->isSubClassOf("SDNode")) return false;
1352 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
1358 /// TreeHasProperty - Return true if any node in this tree has the specified
1360 bool TreePatternNode::TreeHasProperty(SDNP Property,
1361 const CodeGenDAGPatterns &CGP) const {
1362 if (NodeHasProperty(Property, CGP))
1364 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1365 if (getChild(i)->TreeHasProperty(Property, CGP))
1370 /// isCommutativeIntrinsic - Return true if the node corresponds to a
1371 /// commutative intrinsic.
1373 TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
1374 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
1375 return Int->isCommutative;
1380 /// ApplyTypeConstraints - Apply all of the type constraints relevant to
1381 /// this node and its children in the tree. This returns true if it makes a
1382 /// change, false otherwise. If a type contradiction is found, throw an
1384 bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
1385 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
1387 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
1388 // If it's a regclass or something else known, include the type.
1389 bool MadeChange = false;
1390 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1391 MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
1392 NotRegisters, TP), TP);
1396 if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
1397 assert(Types.size() == 1 && "Invalid IntInit");
1399 // Int inits are always integers. :)
1400 bool MadeChange = Types[0].EnforceInteger(TP);
1402 if (!Types[0].isConcrete())
1405 MVT::SimpleValueType VT = getType(0);
1406 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
1409 unsigned Size = EVT(VT).getSizeInBits();
1410 // Make sure that the value is representable for this type.
1411 if (Size >= 32) return MadeChange;
1413 // Check that the value doesn't use more bits than we have. It must either
1414 // be a sign- or zero-extended equivalent of the original.
1415 int64_t SignBitAndAbove = II->getValue() >> (Size - 1);
1416 if (SignBitAndAbove == -1 || SignBitAndAbove == 0 || SignBitAndAbove == 1)
1419 TP.error("Integer value '" + itostr(II->getValue()) +
1420 "' is out of range for type '" + getEnumName(getType(0)) + "'!");
1426 // special handling for set, which isn't really an SDNode.
1427 if (getOperator()->getName() == "set") {
1428 assert(getNumTypes() == 0 && "Set doesn't produce a value");
1429 assert(getNumChildren() >= 2 && "Missing RHS of a set?");
1430 unsigned NC = getNumChildren();
1432 TreePatternNode *SetVal = getChild(NC-1);
1433 bool MadeChange = SetVal->ApplyTypeConstraints(TP, NotRegisters);
1435 for (unsigned i = 0; i < NC-1; ++i) {
1436 TreePatternNode *Child = getChild(i);
1437 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
1439 // Types of operands must match.
1440 MadeChange |= Child->UpdateNodeType(0, SetVal->getExtType(i), TP);
1441 MadeChange |= SetVal->UpdateNodeType(i, Child->getExtType(0), TP);
1446 if (getOperator()->getName() == "implicit") {
1447 assert(getNumTypes() == 0 && "Node doesn't produce a value");
1449 bool MadeChange = false;
1450 for (unsigned i = 0; i < getNumChildren(); ++i)
1451 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1455 if (getOperator()->getName() == "COPY_TO_REGCLASS") {
1456 bool MadeChange = false;
1457 MadeChange |= getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1458 MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
1460 assert(getChild(0)->getNumTypes() == 1 &&
1461 getChild(1)->getNumTypes() == 1 && "Unhandled case");
1463 // child #1 of COPY_TO_REGCLASS should be a register class. We don't care
1464 // what type it gets, so if it didn't get a concrete type just give it the
1465 // first viable type from the reg class.
1466 if (!getChild(1)->hasTypeSet(0) &&
1467 !getChild(1)->getExtType(0).isCompletelyUnknown()) {
1468 MVT::SimpleValueType RCVT = getChild(1)->getExtType(0).getTypeList()[0];
1469 MadeChange |= getChild(1)->UpdateNodeType(0, RCVT, TP);
1474 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
1475 bool MadeChange = false;
1477 // Apply the result type to the node.
1478 unsigned NumRetVTs = Int->IS.RetVTs.size();
1479 unsigned NumParamVTs = Int->IS.ParamVTs.size();
1481 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
1482 MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
1484 if (getNumChildren() != NumParamVTs + 1)
1485 TP.error("Intrinsic '" + Int->Name + "' expects " +
1486 utostr(NumParamVTs) + " operands, not " +
1487 utostr(getNumChildren() - 1) + " operands!");
1489 // Apply type info to the intrinsic ID.
1490 MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
1492 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
1493 MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
1495 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
1496 assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
1497 MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
1502 if (getOperator()->isSubClassOf("SDNode")) {
1503 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
1505 // Check that the number of operands is sane. Negative operands -> varargs.
1506 if (NI.getNumOperands() >= 0 &&
1507 getNumChildren() != (unsigned)NI.getNumOperands())
1508 TP.error(getOperator()->getName() + " node requires exactly " +
1509 itostr(NI.getNumOperands()) + " operands!");
1511 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
1512 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1513 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1517 if (getOperator()->isSubClassOf("Instruction")) {
1518 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
1519 CodeGenInstruction &InstInfo =
1520 CDP.getTargetInfo().getInstruction(getOperator());
1522 bool MadeChange = false;
1524 // Apply the result types to the node, these come from the things in the
1525 // (outs) list of the instruction.
1526 // FIXME: Cap at one result so far.
1527 unsigned NumResultsToAdd = InstInfo.Operands.NumDefs ? 1 : 0;
1528 for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo) {
1529 Record *ResultNode = Inst.getResult(ResNo);
1531 if (ResultNode->isSubClassOf("PointerLikeRegClass")) {
1532 MadeChange |= UpdateNodeType(ResNo, MVT::iPTR, TP);
1533 } else if (ResultNode->isSubClassOf("RegisterOperand")) {
1534 Record *RegClass = ResultNode->getValueAsDef("RegClass");
1535 const CodeGenRegisterClass &RC =
1536 CDP.getTargetInfo().getRegisterClass(RegClass);
1537 MadeChange |= UpdateNodeType(ResNo, RC.getValueTypes(), TP);
1538 } else if (ResultNode->getName() == "unknown") {
1541 assert(ResultNode->isSubClassOf("RegisterClass") &&
1542 "Operands should be register classes!");
1543 const CodeGenRegisterClass &RC =
1544 CDP.getTargetInfo().getRegisterClass(ResultNode);
1545 MadeChange |= UpdateNodeType(ResNo, RC.getValueTypes(), TP);
1549 // If the instruction has implicit defs, we apply the first one as a result.
1550 // FIXME: This sucks, it should apply all implicit defs.
1551 if (!InstInfo.ImplicitDefs.empty()) {
1552 unsigned ResNo = NumResultsToAdd;
1554 // FIXME: Generalize to multiple possible types and multiple possible
1556 MVT::SimpleValueType VT =
1557 InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
1559 if (VT != MVT::Other)
1560 MadeChange |= UpdateNodeType(ResNo, VT, TP);
1563 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
1565 if (getOperator()->getName() == "INSERT_SUBREG") {
1566 assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
1567 MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
1568 MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
1571 unsigned ChildNo = 0;
1572 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
1573 Record *OperandNode = Inst.getOperand(i);
1575 // If the instruction expects a predicate or optional def operand, we
1576 // codegen this by setting the operand to it's default value if it has a
1577 // non-empty DefaultOps field.
1578 if ((OperandNode->isSubClassOf("PredicateOperand") ||
1579 OperandNode->isSubClassOf("OptionalDefOperand")) &&
1580 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1583 // Verify that we didn't run out of provided operands.
1584 if (ChildNo >= getNumChildren())
1585 TP.error("Instruction '" + getOperator()->getName() +
1586 "' expects more operands than were provided.");
1588 MVT::SimpleValueType VT;
1589 TreePatternNode *Child = getChild(ChildNo++);
1590 unsigned ChildResNo = 0; // Instructions always use res #0 of their op.
1592 if (OperandNode->isSubClassOf("RegisterClass")) {
1593 const CodeGenRegisterClass &RC =
1594 CDP.getTargetInfo().getRegisterClass(OperandNode);
1595 MadeChange |= Child->UpdateNodeType(ChildResNo, RC.getValueTypes(), TP);
1596 } else if (OperandNode->isSubClassOf("RegisterOperand")) {
1597 Record *RegClass = OperandNode->getValueAsDef("RegClass");
1598 const CodeGenRegisterClass &RC =
1599 CDP.getTargetInfo().getRegisterClass(RegClass);
1600 MadeChange |= Child->UpdateNodeType(ChildResNo, RC.getValueTypes(), TP);
1601 } else if (OperandNode->isSubClassOf("Operand")) {
1602 VT = getValueType(OperandNode->getValueAsDef("Type"));
1603 MadeChange |= Child->UpdateNodeType(ChildResNo, VT, TP);
1604 } else if (OperandNode->isSubClassOf("PointerLikeRegClass")) {
1605 MadeChange |= Child->UpdateNodeType(ChildResNo, MVT::iPTR, TP);
1606 } else if (OperandNode->getName() == "unknown") {
1609 llvm_unreachable("Unknown operand type!");
1611 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
1614 if (ChildNo != getNumChildren())
1615 TP.error("Instruction '" + getOperator()->getName() +
1616 "' was provided too many operands!");
1621 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
1623 // Node transforms always take one operand.
1624 if (getNumChildren() != 1)
1625 TP.error("Node transform '" + getOperator()->getName() +
1626 "' requires one operand!");
1628 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1631 // If either the output or input of the xform does not have exact
1632 // type info. We assume they must be the same. Otherwise, it is perfectly
1633 // legal to transform from one type to a completely different type.
1635 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
1636 bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
1637 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
1644 /// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
1645 /// RHS of a commutative operation, not the on LHS.
1646 static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
1647 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
1649 if (N->isLeaf() && dynamic_cast<IntInit*>(N->getLeafValue()))
1655 /// canPatternMatch - If it is impossible for this pattern to match on this
1656 /// target, fill in Reason and return false. Otherwise, return true. This is
1657 /// used as a sanity check for .td files (to prevent people from writing stuff
1658 /// that can never possibly work), and to prevent the pattern permuter from
1659 /// generating stuff that is useless.
1660 bool TreePatternNode::canPatternMatch(std::string &Reason,
1661 const CodeGenDAGPatterns &CDP) {
1662 if (isLeaf()) return true;
1664 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1665 if (!getChild(i)->canPatternMatch(Reason, CDP))
1668 // If this is an intrinsic, handle cases that would make it not match. For
1669 // example, if an operand is required to be an immediate.
1670 if (getOperator()->isSubClassOf("Intrinsic")) {
1675 // If this node is a commutative operator, check that the LHS isn't an
1677 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
1678 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
1679 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
1680 // Scan all of the operands of the node and make sure that only the last one
1681 // is a constant node, unless the RHS also is.
1682 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
1683 bool Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
1684 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
1685 if (OnlyOnRHSOfCommutative(getChild(i))) {
1686 Reason="Immediate value must be on the RHS of commutative operators!";
1695 //===----------------------------------------------------------------------===//
1696 // TreePattern implementation
1699 TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
1700 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
1701 isInputPattern = isInput;
1702 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
1703 Trees.push_back(ParseTreePattern(RawPat->getElement(i), ""));
1706 TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
1707 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
1708 isInputPattern = isInput;
1709 Trees.push_back(ParseTreePattern(Pat, ""));
1712 TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
1713 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
1714 isInputPattern = isInput;
1715 Trees.push_back(Pat);
1718 void TreePattern::error(const std::string &Msg) const {
1720 throw TGError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
1723 void TreePattern::ComputeNamedNodes() {
1724 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1725 ComputeNamedNodes(Trees[i]);
1728 void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
1729 if (!N->getName().empty())
1730 NamedNodes[N->getName()].push_back(N);
1732 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1733 ComputeNamedNodes(N->getChild(i));
1737 TreePatternNode *TreePattern::ParseTreePattern(Init *TheInit, StringRef OpName){
1738 if (DefInit *DI = dynamic_cast<DefInit*>(TheInit)) {
1739 Record *R = DI->getDef();
1741 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
1742 // TreePatternNode of its own. For example:
1743 /// (foo GPR, imm) -> (foo GPR, (imm))
1744 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag"))
1745 return ParseTreePattern(
1746 DagInit::get(DI, "",
1747 std::vector<std::pair<Init*, std::string> >()),
1751 TreePatternNode *Res = new TreePatternNode(DI, 1);
1752 if (R->getName() == "node" && !OpName.empty()) {
1754 error("'node' argument requires a name to match with operand list");
1755 Args.push_back(OpName);
1758 Res->setName(OpName);
1762 if (IntInit *II = dynamic_cast<IntInit*>(TheInit)) {
1763 if (!OpName.empty())
1764 error("Constant int argument should not have a name!");
1765 return new TreePatternNode(II, 1);
1768 if (BitsInit *BI = dynamic_cast<BitsInit*>(TheInit)) {
1769 // Turn this into an IntInit.
1770 Init *II = BI->convertInitializerTo(IntRecTy::get());
1771 if (II == 0 || !dynamic_cast<IntInit*>(II))
1772 error("Bits value must be constants!");
1773 return ParseTreePattern(II, OpName);
1776 DagInit *Dag = dynamic_cast<DagInit*>(TheInit);
1779 error("Pattern has unexpected init kind!");
1781 DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
1782 if (!OpDef) error("Pattern has unexpected operator type!");
1783 Record *Operator = OpDef->getDef();
1785 if (Operator->isSubClassOf("ValueType")) {
1786 // If the operator is a ValueType, then this must be "type cast" of a leaf
1788 if (Dag->getNumArgs() != 1)
1789 error("Type cast only takes one operand!");
1791 TreePatternNode *New = ParseTreePattern(Dag->getArg(0), Dag->getArgName(0));
1793 // Apply the type cast.
1794 assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
1795 New->UpdateNodeType(0, getValueType(Operator), *this);
1797 if (!OpName.empty())
1798 error("ValueType cast should not have a name!");
1802 // Verify that this is something that makes sense for an operator.
1803 if (!Operator->isSubClassOf("PatFrag") &&
1804 !Operator->isSubClassOf("SDNode") &&
1805 !Operator->isSubClassOf("Instruction") &&
1806 !Operator->isSubClassOf("SDNodeXForm") &&
1807 !Operator->isSubClassOf("Intrinsic") &&
1808 Operator->getName() != "set" &&
1809 Operator->getName() != "implicit")
1810 error("Unrecognized node '" + Operator->getName() + "'!");
1812 // Check to see if this is something that is illegal in an input pattern.
1813 if (isInputPattern) {
1814 if (Operator->isSubClassOf("Instruction") ||
1815 Operator->isSubClassOf("SDNodeXForm"))
1816 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
1818 if (Operator->isSubClassOf("Intrinsic"))
1819 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
1821 if (Operator->isSubClassOf("SDNode") &&
1822 Operator->getName() != "imm" &&
1823 Operator->getName() != "fpimm" &&
1824 Operator->getName() != "tglobaltlsaddr" &&
1825 Operator->getName() != "tconstpool" &&
1826 Operator->getName() != "tjumptable" &&
1827 Operator->getName() != "tframeindex" &&
1828 Operator->getName() != "texternalsym" &&
1829 Operator->getName() != "tblockaddress" &&
1830 Operator->getName() != "tglobaladdr" &&
1831 Operator->getName() != "bb" &&
1832 Operator->getName() != "vt")
1833 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
1836 std::vector<TreePatternNode*> Children;
1838 // Parse all the operands.
1839 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
1840 Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgName(i)));
1842 // If the operator is an intrinsic, then this is just syntactic sugar for for
1843 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
1844 // convert the intrinsic name to a number.
1845 if (Operator->isSubClassOf("Intrinsic")) {
1846 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
1847 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
1849 // If this intrinsic returns void, it must have side-effects and thus a
1851 if (Int.IS.RetVTs.empty())
1852 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
1853 else if (Int.ModRef != CodeGenIntrinsic::NoMem)
1854 // Has side-effects, requires chain.
1855 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
1856 else // Otherwise, no chain.
1857 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
1859 TreePatternNode *IIDNode = new TreePatternNode(IntInit::get(IID), 1);
1860 Children.insert(Children.begin(), IIDNode);
1863 unsigned NumResults = GetNumNodeResults(Operator, CDP);
1864 TreePatternNode *Result = new TreePatternNode(Operator, Children, NumResults);
1865 Result->setName(OpName);
1867 if (!Dag->getName().empty()) {
1868 assert(Result->getName().empty());
1869 Result->setName(Dag->getName());
1874 /// SimplifyTree - See if we can simplify this tree to eliminate something that
1875 /// will never match in favor of something obvious that will. This is here
1876 /// strictly as a convenience to target authors because it allows them to write
1877 /// more type generic things and have useless type casts fold away.
1879 /// This returns true if any change is made.
1880 static bool SimplifyTree(TreePatternNode *&N) {
1884 // If we have a bitconvert with a resolved type and if the source and
1885 // destination types are the same, then the bitconvert is useless, remove it.
1886 if (N->getOperator()->getName() == "bitconvert" &&
1887 N->getExtType(0).isConcrete() &&
1888 N->getExtType(0) == N->getChild(0)->getExtType(0) &&
1889 N->getName().empty()) {
1895 // Walk all children.
1896 bool MadeChange = false;
1897 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
1898 TreePatternNode *Child = N->getChild(i);
1899 MadeChange |= SimplifyTree(Child);
1900 N->setChild(i, Child);
1907 /// InferAllTypes - Infer/propagate as many types throughout the expression
1908 /// patterns as possible. Return true if all types are inferred, false
1909 /// otherwise. Throw an exception if a type contradiction is found.
1911 InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
1912 if (NamedNodes.empty())
1913 ComputeNamedNodes();
1915 bool MadeChange = true;
1916 while (MadeChange) {
1918 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
1919 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
1920 MadeChange |= SimplifyTree(Trees[i]);
1923 // If there are constraints on our named nodes, apply them.
1924 for (StringMap<SmallVector<TreePatternNode*,1> >::iterator
1925 I = NamedNodes.begin(), E = NamedNodes.end(); I != E; ++I) {
1926 SmallVectorImpl<TreePatternNode*> &Nodes = I->second;
1928 // If we have input named node types, propagate their types to the named
1931 // FIXME: Should be error?
1932 assert(InNamedTypes->count(I->getKey()) &&
1933 "Named node in output pattern but not input pattern?");
1935 const SmallVectorImpl<TreePatternNode*> &InNodes =
1936 InNamedTypes->find(I->getKey())->second;
1938 // The input types should be fully resolved by now.
1939 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
1940 // If this node is a register class, and it is the root of the pattern
1941 // then we're mapping something onto an input register. We allow
1942 // changing the type of the input register in this case. This allows
1943 // us to match things like:
1944 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
1945 if (Nodes[i] == Trees[0] && Nodes[i]->isLeaf()) {
1946 DefInit *DI = dynamic_cast<DefInit*>(Nodes[i]->getLeafValue());
1947 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
1948 DI->getDef()->isSubClassOf("RegisterOperand")))
1952 assert(Nodes[i]->getNumTypes() == 1 &&
1953 InNodes[0]->getNumTypes() == 1 &&
1954 "FIXME: cannot name multiple result nodes yet");
1955 MadeChange |= Nodes[i]->UpdateNodeType(0, InNodes[0]->getExtType(0),
1960 // If there are multiple nodes with the same name, they must all have the
1962 if (I->second.size() > 1) {
1963 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
1964 TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
1965 assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
1966 "FIXME: cannot name multiple result nodes yet");
1968 MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
1969 MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
1975 bool HasUnresolvedTypes = false;
1976 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1977 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
1978 return !HasUnresolvedTypes;
1981 void TreePattern::print(raw_ostream &OS) const {
1982 OS << getRecord()->getName();
1983 if (!Args.empty()) {
1984 OS << "(" << Args[0];
1985 for (unsigned i = 1, e = Args.size(); i != e; ++i)
1986 OS << ", " << Args[i];
1991 if (Trees.size() > 1)
1993 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
1995 Trees[i]->print(OS);
1999 if (Trees.size() > 1)
2003 void TreePattern::dump() const { print(errs()); }
2005 //===----------------------------------------------------------------------===//
2006 // CodeGenDAGPatterns implementation
2009 CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) :
2010 Records(R), Target(R) {
2012 Intrinsics = LoadIntrinsics(Records, false);
2013 TgtIntrinsics = LoadIntrinsics(Records, true);
2015 ParseNodeTransforms();
2016 ParseComplexPatterns();
2017 ParsePatternFragments();
2018 ParseDefaultOperands();
2019 ParseInstructions();
2022 // Generate variants. For example, commutative patterns can match
2023 // multiple ways. Add them to PatternsToMatch as well.
2026 // Infer instruction flags. For example, we can detect loads,
2027 // stores, and side effects in many cases by examining an
2028 // instruction's pattern.
2029 InferInstructionFlags();
2032 CodeGenDAGPatterns::~CodeGenDAGPatterns() {
2033 for (pf_iterator I = PatternFragments.begin(),
2034 E = PatternFragments.end(); I != E; ++I)
2039 Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
2040 Record *N = Records.getDef(Name);
2041 if (!N || !N->isSubClassOf("SDNode")) {
2042 errs() << "Error getting SDNode '" << Name << "'!\n";
2048 // Parse all of the SDNode definitions for the target, populating SDNodes.
2049 void CodeGenDAGPatterns::ParseNodeInfo() {
2050 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
2051 while (!Nodes.empty()) {
2052 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
2056 // Get the builtin intrinsic nodes.
2057 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
2058 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
2059 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
2062 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
2063 /// map, and emit them to the file as functions.
2064 void CodeGenDAGPatterns::ParseNodeTransforms() {
2065 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
2066 while (!Xforms.empty()) {
2067 Record *XFormNode = Xforms.back();
2068 Record *SDNode = XFormNode->getValueAsDef("Opcode");
2069 std::string Code = XFormNode->getValueAsString("XFormFunction");
2070 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
2076 void CodeGenDAGPatterns::ParseComplexPatterns() {
2077 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
2078 while (!AMs.empty()) {
2079 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
2085 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
2086 /// file, building up the PatternFragments map. After we've collected them all,
2087 /// inline fragments together as necessary, so that there are no references left
2088 /// inside a pattern fragment to a pattern fragment.
2090 void CodeGenDAGPatterns::ParsePatternFragments() {
2091 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
2093 // First step, parse all of the fragments.
2094 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
2095 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
2096 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
2097 PatternFragments[Fragments[i]] = P;
2099 // Validate the argument list, converting it to set, to discard duplicates.
2100 std::vector<std::string> &Args = P->getArgList();
2101 std::set<std::string> OperandsSet(Args.begin(), Args.end());
2103 if (OperandsSet.count(""))
2104 P->error("Cannot have unnamed 'node' values in pattern fragment!");
2106 // Parse the operands list.
2107 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
2108 DefInit *OpsOp = dynamic_cast<DefInit*>(OpsList->getOperator());
2109 // Special cases: ops == outs == ins. Different names are used to
2110 // improve readability.
2112 (OpsOp->getDef()->getName() != "ops" &&
2113 OpsOp->getDef()->getName() != "outs" &&
2114 OpsOp->getDef()->getName() != "ins"))
2115 P->error("Operands list should start with '(ops ... '!");
2117 // Copy over the arguments.
2119 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
2120 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
2121 static_cast<DefInit*>(OpsList->getArg(j))->
2122 getDef()->getName() != "node")
2123 P->error("Operands list should all be 'node' values.");
2124 if (OpsList->getArgName(j).empty())
2125 P->error("Operands list should have names for each operand!");
2126 if (!OperandsSet.count(OpsList->getArgName(j)))
2127 P->error("'" + OpsList->getArgName(j) +
2128 "' does not occur in pattern or was multiply specified!");
2129 OperandsSet.erase(OpsList->getArgName(j));
2130 Args.push_back(OpsList->getArgName(j));
2133 if (!OperandsSet.empty())
2134 P->error("Operands list does not contain an entry for operand '" +
2135 *OperandsSet.begin() + "'!");
2137 // If there is a code init for this fragment, keep track of the fact that
2138 // this fragment uses it.
2139 TreePredicateFn PredFn(P);
2140 if (!PredFn.isAlwaysTrue())
2141 P->getOnlyTree()->addPredicateFn(PredFn);
2143 // If there is a node transformation corresponding to this, keep track of
2145 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
2146 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
2147 P->getOnlyTree()->setTransformFn(Transform);
2150 // Now that we've parsed all of the tree fragments, do a closure on them so
2151 // that there are not references to PatFrags left inside of them.
2152 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
2153 TreePattern *ThePat = PatternFragments[Fragments[i]];
2154 ThePat->InlinePatternFragments();
2156 // Infer as many types as possible. Don't worry about it if we don't infer
2157 // all of them, some may depend on the inputs of the pattern.
2159 ThePat->InferAllTypes();
2161 // If this pattern fragment is not supported by this target (no types can
2162 // satisfy its constraints), just ignore it. If the bogus pattern is
2163 // actually used by instructions, the type consistency error will be
2167 // If debugging, print out the pattern fragment result.
2168 DEBUG(ThePat->dump());
2172 void CodeGenDAGPatterns::ParseDefaultOperands() {
2173 std::vector<Record*> DefaultOps[2];
2174 DefaultOps[0] = Records.getAllDerivedDefinitions("PredicateOperand");
2175 DefaultOps[1] = Records.getAllDerivedDefinitions("OptionalDefOperand");
2177 // Find some SDNode.
2178 assert(!SDNodes.empty() && "No SDNodes parsed?");
2179 Init *SomeSDNode = DefInit::get(SDNodes.begin()->first);
2181 for (unsigned iter = 0; iter != 2; ++iter) {
2182 for (unsigned i = 0, e = DefaultOps[iter].size(); i != e; ++i) {
2183 DagInit *DefaultInfo = DefaultOps[iter][i]->getValueAsDag("DefaultOps");
2185 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
2186 // SomeSDnode so that we can parse this.
2187 std::vector<std::pair<Init*, std::string> > Ops;
2188 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
2189 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
2190 DefaultInfo->getArgName(op)));
2191 DagInit *DI = DagInit::get(SomeSDNode, "", Ops);
2193 // Create a TreePattern to parse this.
2194 TreePattern P(DefaultOps[iter][i], DI, false, *this);
2195 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
2197 // Copy the operands over into a DAGDefaultOperand.
2198 DAGDefaultOperand DefaultOpInfo;
2200 TreePatternNode *T = P.getTree(0);
2201 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
2202 TreePatternNode *TPN = T->getChild(op);
2203 while (TPN->ApplyTypeConstraints(P, false))
2204 /* Resolve all types */;
2206 if (TPN->ContainsUnresolvedType()) {
2208 throw "Value #" + utostr(i) + " of PredicateOperand '" +
2209 DefaultOps[iter][i]->getName() +"' doesn't have a concrete type!";
2211 throw "Value #" + utostr(i) + " of OptionalDefOperand '" +
2212 DefaultOps[iter][i]->getName() +"' doesn't have a concrete type!";
2214 DefaultOpInfo.DefaultOps.push_back(TPN);
2217 // Insert it into the DefaultOperands map so we can find it later.
2218 DefaultOperands[DefaultOps[iter][i]] = DefaultOpInfo;
2223 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
2224 /// instruction input. Return true if this is a real use.
2225 static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
2226 std::map<std::string, TreePatternNode*> &InstInputs) {
2227 // No name -> not interesting.
2228 if (Pat->getName().empty()) {
2229 if (Pat->isLeaf()) {
2230 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
2231 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2232 DI->getDef()->isSubClassOf("RegisterOperand")))
2233 I->error("Input " + DI->getDef()->getName() + " must be named!");
2239 if (Pat->isLeaf()) {
2240 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
2241 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
2244 Rec = Pat->getOperator();
2247 // SRCVALUE nodes are ignored.
2248 if (Rec->getName() == "srcvalue")
2251 TreePatternNode *&Slot = InstInputs[Pat->getName()];
2257 if (Slot->isLeaf()) {
2258 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
2260 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
2261 SlotRec = Slot->getOperator();
2264 // Ensure that the inputs agree if we've already seen this input.
2266 I->error("All $" + Pat->getName() + " inputs must agree with each other");
2267 if (Slot->getExtTypes() != Pat->getExtTypes())
2268 I->error("All $" + Pat->getName() + " inputs must agree with each other");
2272 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
2273 /// part of "I", the instruction), computing the set of inputs and outputs of
2274 /// the pattern. Report errors if we see anything naughty.
2275 void CodeGenDAGPatterns::
2276 FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
2277 std::map<std::string, TreePatternNode*> &InstInputs,
2278 std::map<std::string, TreePatternNode*>&InstResults,
2279 std::vector<Record*> &InstImpResults) {
2280 if (Pat->isLeaf()) {
2281 bool isUse = HandleUse(I, Pat, InstInputs);
2282 if (!isUse && Pat->getTransformFn())
2283 I->error("Cannot specify a transform function for a non-input value!");
2287 if (Pat->getOperator()->getName() == "implicit") {
2288 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2289 TreePatternNode *Dest = Pat->getChild(i);
2290 if (!Dest->isLeaf())
2291 I->error("implicitly defined value should be a register!");
2293 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
2294 if (!Val || !Val->getDef()->isSubClassOf("Register"))
2295 I->error("implicitly defined value should be a register!");
2296 InstImpResults.push_back(Val->getDef());
2301 if (Pat->getOperator()->getName() != "set") {
2302 // If this is not a set, verify that the children nodes are not void typed,
2304 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2305 if (Pat->getChild(i)->getNumTypes() == 0)
2306 I->error("Cannot have void nodes inside of patterns!");
2307 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
2311 // If this is a non-leaf node with no children, treat it basically as if
2312 // it were a leaf. This handles nodes like (imm).
2313 bool isUse = HandleUse(I, Pat, InstInputs);
2315 if (!isUse && Pat->getTransformFn())
2316 I->error("Cannot specify a transform function for a non-input value!");
2320 // Otherwise, this is a set, validate and collect instruction results.
2321 if (Pat->getNumChildren() == 0)
2322 I->error("set requires operands!");
2324 if (Pat->getTransformFn())
2325 I->error("Cannot specify a transform function on a set node!");
2327 // Check the set destinations.
2328 unsigned NumDests = Pat->getNumChildren()-1;
2329 for (unsigned i = 0; i != NumDests; ++i) {
2330 TreePatternNode *Dest = Pat->getChild(i);
2331 if (!Dest->isLeaf())
2332 I->error("set destination should be a register!");
2334 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
2336 I->error("set destination should be a register!");
2338 if (Val->getDef()->isSubClassOf("RegisterClass") ||
2339 Val->getDef()->isSubClassOf("RegisterOperand") ||
2340 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
2341 if (Dest->getName().empty())
2342 I->error("set destination must have a name!");
2343 if (InstResults.count(Dest->getName()))
2344 I->error("cannot set '" + Dest->getName() +"' multiple times");
2345 InstResults[Dest->getName()] = Dest;
2346 } else if (Val->getDef()->isSubClassOf("Register")) {
2347 InstImpResults.push_back(Val->getDef());
2349 I->error("set destination should be a register!");
2353 // Verify and collect info from the computation.
2354 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
2355 InstInputs, InstResults, InstImpResults);
2358 //===----------------------------------------------------------------------===//
2359 // Instruction Analysis
2360 //===----------------------------------------------------------------------===//
2362 class InstAnalyzer {
2363 const CodeGenDAGPatterns &CDP;
2365 bool hasSideEffects;
2371 InstAnalyzer(const CodeGenDAGPatterns &cdp)
2372 : CDP(cdp), hasSideEffects(false), mayStore(false), mayLoad(false),
2373 isBitcast(false), isVariadic(false) {}
2375 void Analyze(const TreePattern *Pat) {
2376 // Assume only the first tree is the pattern. The others are clobber nodes.
2377 AnalyzeNode(Pat->getTree(0));
2380 void Analyze(const PatternToMatch *Pat) {
2381 AnalyzeNode(Pat->getSrcPattern());
2385 bool IsNodeBitcast(const TreePatternNode *N) const {
2386 if (hasSideEffects || mayLoad || mayStore || isVariadic)
2389 if (N->getNumChildren() != 2)
2392 const TreePatternNode *N0 = N->getChild(0);
2393 if (!N0->isLeaf() || !dynamic_cast<DefInit*>(N0->getLeafValue()))
2396 const TreePatternNode *N1 = N->getChild(1);
2399 if (N1->getNumChildren() != 1 || !N1->getChild(0)->isLeaf())
2402 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N1->getOperator());
2403 if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1)
2405 return OpInfo.getEnumName() == "ISD::BITCAST";
2408 void AnalyzeNode(const TreePatternNode *N) {
2410 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
2411 Record *LeafRec = DI->getDef();
2412 // Handle ComplexPattern leaves.
2413 if (LeafRec->isSubClassOf("ComplexPattern")) {
2414 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
2415 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
2416 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
2417 if (CP.hasProperty(SDNPSideEffect)) hasSideEffects = true;
2423 // Analyze children.
2424 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2425 AnalyzeNode(N->getChild(i));
2427 // Ignore set nodes, which are not SDNodes.
2428 if (N->getOperator()->getName() == "set") {
2429 isBitcast = IsNodeBitcast(N);
2433 // Get information about the SDNode for the operator.
2434 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N->getOperator());
2436 // Notice properties of the node.
2437 if (OpInfo.hasProperty(SDNPMayStore)) mayStore = true;
2438 if (OpInfo.hasProperty(SDNPMayLoad)) mayLoad = true;
2439 if (OpInfo.hasProperty(SDNPSideEffect)) hasSideEffects = true;
2440 if (OpInfo.hasProperty(SDNPVariadic)) isVariadic = true;
2442 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
2443 // If this is an intrinsic, analyze it.
2444 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
2445 mayLoad = true;// These may load memory.
2447 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteArgMem)
2448 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
2450 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem)
2451 // WriteMem intrinsics can have other strange effects.
2452 hasSideEffects = true;
2458 static bool InferFromPattern(CodeGenInstruction &InstInfo,
2459 const InstAnalyzer &PatInfo,
2463 // Remember where InstInfo got its flags.
2464 if (InstInfo.hasUndefFlags())
2465 InstInfo.InferredFrom = PatDef;
2467 // Check explicitly set flags for consistency.
2468 if (InstInfo.hasSideEffects != PatInfo.hasSideEffects &&
2469 !InstInfo.hasSideEffects_Unset) {
2470 // Allow explicitly setting hasSideEffects = 1 on instructions, even when
2471 // the pattern has no side effects. That could be useful for div/rem
2472 // instructions that may trap.
2473 if (!InstInfo.hasSideEffects) {
2475 PrintError(PatDef->getLoc(), "Pattern doesn't match hasSideEffects = " +
2476 Twine(InstInfo.hasSideEffects));
2480 if (InstInfo.mayStore != PatInfo.mayStore && !InstInfo.mayStore_Unset) {
2482 PrintError(PatDef->getLoc(), "Pattern doesn't match mayStore = " +
2483 Twine(InstInfo.mayStore));
2486 if (InstInfo.mayLoad != PatInfo.mayLoad && !InstInfo.mayLoad_Unset) {
2487 // Allow explicitly setting mayLoad = 1, even when the pattern has no loads.
2488 // Some targets translate imediates to loads.
2489 if (!InstInfo.mayLoad) {
2491 PrintError(PatDef->getLoc(), "Pattern doesn't match mayLoad = " +
2492 Twine(InstInfo.mayLoad));
2496 // Transfer inferred flags.
2497 InstInfo.hasSideEffects |= PatInfo.hasSideEffects;
2498 InstInfo.mayStore |= PatInfo.mayStore;
2499 InstInfo.mayLoad |= PatInfo.mayLoad;
2501 // These flags are silently added without any verification.
2502 InstInfo.isBitcast |= PatInfo.isBitcast;
2504 // Don't infer isVariadic. This flag means something different on SDNodes and
2505 // instructions. For example, a CALL SDNode is variadic because it has the
2506 // call arguments as operands, but a CALL instruction is not variadic - it
2507 // has argument registers as implicit, not explicit uses.
2512 /// hasNullFragReference - Return true if the DAG has any reference to the
2513 /// null_frag operator.
2514 static bool hasNullFragReference(DagInit *DI) {
2515 DefInit *OpDef = dynamic_cast<DefInit*>(DI->getOperator());
2516 if (!OpDef) return false;
2517 Record *Operator = OpDef->getDef();
2519 // If this is the null fragment, return true.
2520 if (Operator->getName() == "null_frag") return true;
2521 // If any of the arguments reference the null fragment, return true.
2522 for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {
2523 DagInit *Arg = dynamic_cast<DagInit*>(DI->getArg(i));
2524 if (Arg && hasNullFragReference(Arg))
2531 /// hasNullFragReference - Return true if any DAG in the list references
2532 /// the null_frag operator.
2533 static bool hasNullFragReference(ListInit *LI) {
2534 for (unsigned i = 0, e = LI->getSize(); i != e; ++i) {
2535 DagInit *DI = dynamic_cast<DagInit*>(LI->getElement(i));
2536 assert(DI && "non-dag in an instruction Pattern list?!");
2537 if (hasNullFragReference(DI))
2543 /// Get all the instructions in a tree.
2545 getInstructionsInTree(TreePatternNode *Tree, SmallVectorImpl<Record*> &Instrs) {
2548 if (Tree->getOperator()->isSubClassOf("Instruction"))
2549 Instrs.push_back(Tree->getOperator());
2550 for (unsigned i = 0, e = Tree->getNumChildren(); i != e; ++i)
2551 getInstructionsInTree(Tree->getChild(i), Instrs);
2554 /// ParseInstructions - Parse all of the instructions, inlining and resolving
2555 /// any fragments involved. This populates the Instructions list with fully
2556 /// resolved instructions.
2557 void CodeGenDAGPatterns::ParseInstructions() {
2558 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
2560 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
2563 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
2564 LI = Instrs[i]->getValueAsListInit("Pattern");
2566 // If there is no pattern, only collect minimal information about the
2567 // instruction for its operand list. We have to assume that there is one
2568 // result, as we have no detailed info. A pattern which references the
2569 // null_frag operator is as-if no pattern were specified. Normally this
2570 // is from a multiclass expansion w/ a SDPatternOperator passed in as
2572 if (!LI || LI->getSize() == 0 || hasNullFragReference(LI)) {
2573 std::vector<Record*> Results;
2574 std::vector<Record*> Operands;
2576 CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
2578 if (InstInfo.Operands.size() != 0) {
2579 if (InstInfo.Operands.NumDefs == 0) {
2580 // These produce no results
2581 for (unsigned j = 0, e = InstInfo.Operands.size(); j < e; ++j)
2582 Operands.push_back(InstInfo.Operands[j].Rec);
2584 // Assume the first operand is the result.
2585 Results.push_back(InstInfo.Operands[0].Rec);
2587 // The rest are inputs.
2588 for (unsigned j = 1, e = InstInfo.Operands.size(); j < e; ++j)
2589 Operands.push_back(InstInfo.Operands[j].Rec);
2593 // Create and insert the instruction.
2594 std::vector<Record*> ImpResults;
2595 Instructions.insert(std::make_pair(Instrs[i],
2596 DAGInstruction(0, Results, Operands, ImpResults)));
2597 continue; // no pattern.
2600 // Parse the instruction.
2601 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
2602 // Inline pattern fragments into it.
2603 I->InlinePatternFragments();
2605 // Infer as many types as possible. If we cannot infer all of them, we can
2606 // never do anything with this instruction pattern: report it to the user.
2607 if (!I->InferAllTypes())
2608 I->error("Could not infer all types in pattern!");
2610 // InstInputs - Keep track of all of the inputs of the instruction, along
2611 // with the record they are declared as.
2612 std::map<std::string, TreePatternNode*> InstInputs;
2614 // InstResults - Keep track of all the virtual registers that are 'set'
2615 // in the instruction, including what reg class they are.
2616 std::map<std::string, TreePatternNode*> InstResults;
2618 std::vector<Record*> InstImpResults;
2620 // Verify that the top-level forms in the instruction are of void type, and
2621 // fill in the InstResults map.
2622 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
2623 TreePatternNode *Pat = I->getTree(j);
2624 if (Pat->getNumTypes() != 0)
2625 I->error("Top-level forms in instruction pattern should have"
2628 // Find inputs and outputs, and verify the structure of the uses/defs.
2629 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
2633 // Now that we have inputs and outputs of the pattern, inspect the operands
2634 // list for the instruction. This determines the order that operands are
2635 // added to the machine instruction the node corresponds to.
2636 unsigned NumResults = InstResults.size();
2638 // Parse the operands list from the (ops) list, validating it.
2639 assert(I->getArgList().empty() && "Args list should still be empty here!");
2640 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]);
2642 // Check that all of the results occur first in the list.
2643 std::vector<Record*> Results;
2644 TreePatternNode *Res0Node = 0;
2645 for (unsigned i = 0; i != NumResults; ++i) {
2646 if (i == CGI.Operands.size())
2647 I->error("'" + InstResults.begin()->first +
2648 "' set but does not appear in operand list!");
2649 const std::string &OpName = CGI.Operands[i].Name;
2651 // Check that it exists in InstResults.
2652 TreePatternNode *RNode = InstResults[OpName];
2654 I->error("Operand $" + OpName + " does not exist in operand list!");
2658 Record *R = dynamic_cast<DefInit*>(RNode->getLeafValue())->getDef();
2660 I->error("Operand $" + OpName + " should be a set destination: all "
2661 "outputs must occur before inputs in operand list!");
2663 if (CGI.Operands[i].Rec != R)
2664 I->error("Operand $" + OpName + " class mismatch!");
2666 // Remember the return type.
2667 Results.push_back(CGI.Operands[i].Rec);
2669 // Okay, this one checks out.
2670 InstResults.erase(OpName);
2673 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
2674 // the copy while we're checking the inputs.
2675 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
2677 std::vector<TreePatternNode*> ResultNodeOperands;
2678 std::vector<Record*> Operands;
2679 for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
2680 CGIOperandList::OperandInfo &Op = CGI.Operands[i];
2681 const std::string &OpName = Op.Name;
2683 I->error("Operand #" + utostr(i) + " in operands list has no name!");
2685 if (!InstInputsCheck.count(OpName)) {
2686 // If this is an predicate operand or optional def operand with an
2687 // DefaultOps set filled in, we can ignore this. When we codegen it,
2688 // we will do so as always executed.
2689 if (Op.Rec->isSubClassOf("PredicateOperand") ||
2690 Op.Rec->isSubClassOf("OptionalDefOperand")) {
2691 // Does it have a non-empty DefaultOps field? If so, ignore this
2693 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
2696 I->error("Operand $" + OpName +
2697 " does not appear in the instruction pattern");
2699 TreePatternNode *InVal = InstInputsCheck[OpName];
2700 InstInputsCheck.erase(OpName); // It occurred, remove from map.
2702 if (InVal->isLeaf() &&
2703 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
2704 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
2705 if (Op.Rec != InRec && !InRec->isSubClassOf("ComplexPattern"))
2706 I->error("Operand $" + OpName + "'s register class disagrees"
2707 " between the operand and pattern");
2709 Operands.push_back(Op.Rec);
2711 // Construct the result for the dest-pattern operand list.
2712 TreePatternNode *OpNode = InVal->clone();
2714 // No predicate is useful on the result.
2715 OpNode->clearPredicateFns();
2717 // Promote the xform function to be an explicit node if set.
2718 if (Record *Xform = OpNode->getTransformFn()) {
2719 OpNode->setTransformFn(0);
2720 std::vector<TreePatternNode*> Children;
2721 Children.push_back(OpNode);
2722 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
2725 ResultNodeOperands.push_back(OpNode);
2728 if (!InstInputsCheck.empty())
2729 I->error("Input operand $" + InstInputsCheck.begin()->first +
2730 " occurs in pattern but not in operands list!");
2732 TreePatternNode *ResultPattern =
2733 new TreePatternNode(I->getRecord(), ResultNodeOperands,
2734 GetNumNodeResults(I->getRecord(), *this));
2735 // Copy fully inferred output node type to instruction result pattern.
2736 for (unsigned i = 0; i != NumResults; ++i)
2737 ResultPattern->setType(i, Res0Node->getExtType(i));
2739 // Create and insert the instruction.
2740 // FIXME: InstImpResults should not be part of DAGInstruction.
2741 DAGInstruction TheInst(I, Results, Operands, InstImpResults);
2742 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
2744 // Use a temporary tree pattern to infer all types and make sure that the
2745 // constructed result is correct. This depends on the instruction already
2746 // being inserted into the Instructions map.
2747 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
2748 Temp.InferAllTypes(&I->getNamedNodesMap());
2750 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
2751 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
2756 // If we can, convert the instructions to be patterns that are matched!
2757 for (std::map<Record*, DAGInstruction, RecordPtrCmp>::iterator II =
2758 Instructions.begin(),
2759 E = Instructions.end(); II != E; ++II) {
2760 DAGInstruction &TheInst = II->second;
2761 const TreePattern *I = TheInst.getPattern();
2762 if (I == 0) continue; // No pattern.
2764 // FIXME: Assume only the first tree is the pattern. The others are clobber
2766 TreePatternNode *Pattern = I->getTree(0);
2767 TreePatternNode *SrcPattern;
2768 if (Pattern->getOperator()->getName() == "set") {
2769 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
2771 // Not a set (store or something?)
2772 SrcPattern = Pattern;
2775 Record *Instr = II->first;
2776 AddPatternToMatch(I,
2777 PatternToMatch(Instr,
2778 Instr->getValueAsListInit("Predicates"),
2780 TheInst.getResultPattern(),
2781 TheInst.getImpResults(),
2782 Instr->getValueAsInt("AddedComplexity"),
2788 typedef std::pair<const TreePatternNode*, unsigned> NameRecord;
2790 static void FindNames(const TreePatternNode *P,
2791 std::map<std::string, NameRecord> &Names,
2792 const TreePattern *PatternTop) {
2793 if (!P->getName().empty()) {
2794 NameRecord &Rec = Names[P->getName()];
2795 // If this is the first instance of the name, remember the node.
2796 if (Rec.second++ == 0)
2798 else if (Rec.first->getExtTypes() != P->getExtTypes())
2799 PatternTop->error("repetition of value: $" + P->getName() +
2800 " where different uses have different types!");
2804 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
2805 FindNames(P->getChild(i), Names, PatternTop);
2809 void CodeGenDAGPatterns::AddPatternToMatch(const TreePattern *Pattern,
2810 const PatternToMatch &PTM) {
2811 // Do some sanity checking on the pattern we're about to match.
2813 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this))
2814 Pattern->error("Pattern can never match: " + Reason);
2816 // If the source pattern's root is a complex pattern, that complex pattern
2817 // must specify the nodes it can potentially match.
2818 if (const ComplexPattern *CP =
2819 PTM.getSrcPattern()->getComplexPatternInfo(*this))
2820 if (CP->getRootNodes().empty())
2821 Pattern->error("ComplexPattern at root must specify list of opcodes it"
2825 // Find all of the named values in the input and output, ensure they have the
2827 std::map<std::string, NameRecord> SrcNames, DstNames;
2828 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
2829 FindNames(PTM.getDstPattern(), DstNames, Pattern);
2831 // Scan all of the named values in the destination pattern, rejecting them if
2832 // they don't exist in the input pattern.
2833 for (std::map<std::string, NameRecord>::iterator
2834 I = DstNames.begin(), E = DstNames.end(); I != E; ++I) {
2835 if (SrcNames[I->first].first == 0)
2836 Pattern->error("Pattern has input without matching name in output: $" +
2840 // Scan all of the named values in the source pattern, rejecting them if the
2841 // name isn't used in the dest, and isn't used to tie two values together.
2842 for (std::map<std::string, NameRecord>::iterator
2843 I = SrcNames.begin(), E = SrcNames.end(); I != E; ++I)
2844 if (DstNames[I->first].first == 0 && SrcNames[I->first].second == 1)
2845 Pattern->error("Pattern has dead named input: $" + I->first);
2847 PatternsToMatch.push_back(PTM);
2852 void CodeGenDAGPatterns::InferInstructionFlags() {
2853 const std::vector<const CodeGenInstruction*> &Instructions =
2854 Target.getInstructionsByEnumValue();
2856 // First try to infer flags from the primary instruction pattern, if any.
2857 SmallVector<CodeGenInstruction*, 8> Revisit;
2858 unsigned Errors = 0;
2859 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
2860 CodeGenInstruction &InstInfo =
2861 const_cast<CodeGenInstruction &>(*Instructions[i]);
2863 // Treat neverHasSideEffects = 1 as the equivalent of hasSideEffects = 0.
2864 // This flag is obsolete and will be removed.
2865 if (InstInfo.neverHasSideEffects) {
2866 assert(!InstInfo.hasSideEffects);
2867 InstInfo.hasSideEffects_Unset = false;
2870 // Get the primary instruction pattern.
2871 const TreePattern *Pattern = getInstruction(InstInfo.TheDef).getPattern();
2873 if (InstInfo.hasUndefFlags())
2874 Revisit.push_back(&InstInfo);
2877 InstAnalyzer PatInfo(*this);
2878 PatInfo.Analyze(Pattern);
2879 Errors += InferFromPattern(InstInfo, PatInfo, InstInfo.TheDef);
2882 // Second, look for single-instruction patterns defined outside the
2884 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
2885 const PatternToMatch &PTM = *I;
2887 // We can only infer from single-instruction patterns, otherwise we won't
2888 // know which instruction should get the flags.
2889 SmallVector<Record*, 8> PatInstrs;
2890 getInstructionsInTree(PTM.getDstPattern(), PatInstrs);
2891 if (PatInstrs.size() != 1)
2894 // Get the single instruction.
2895 CodeGenInstruction &InstInfo = Target.getInstruction(PatInstrs.front());
2897 // Only infer properties from the first pattern. We'll verify the others.
2898 if (InstInfo.InferredFrom)
2901 InstAnalyzer PatInfo(*this);
2902 PatInfo.Analyze(&PTM);
2903 Errors += InferFromPattern(InstInfo, PatInfo, PTM.getSrcRecord());
2907 throw "pattern conflicts";
2909 // Revisit instructions with undefined flags and no pattern.
2910 if (Target.guessInstructionProperties()) {
2911 for (unsigned i = 0, e = Revisit.size(); i != e; ++i) {
2912 CodeGenInstruction &InstInfo = *Revisit[i];
2913 if (InstInfo.InferredFrom)
2915 // The mayLoad and mayStore flags default to false.
2916 // Conservatively assume hasSideEffects if it wasn't explicit.
2917 if (InstInfo.hasSideEffects_Unset)
2918 InstInfo.hasSideEffects = true;
2923 // Complain about any flags that are still undefined.
2924 for (unsigned i = 0, e = Revisit.size(); i != e; ++i) {
2925 CodeGenInstruction &InstInfo = *Revisit[i];
2926 if (InstInfo.InferredFrom)
2928 if (InstInfo.hasSideEffects_Unset)
2929 PrintError(InstInfo.TheDef->getLoc(),
2930 "Can't infer hasSideEffects from patterns");
2931 if (InstInfo.mayStore_Unset)
2932 PrintError(InstInfo.TheDef->getLoc(),
2933 "Can't infer mayStore from patterns");
2934 if (InstInfo.mayLoad_Unset)
2935 PrintError(InstInfo.TheDef->getLoc(),
2936 "Can't infer mayLoad from patterns");
2940 /// Given a pattern result with an unresolved type, see if we can find one
2941 /// instruction with an unresolved result type. Force this result type to an
2942 /// arbitrary element if it's possible types to converge results.
2943 static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
2947 // Analyze children.
2948 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2949 if (ForceArbitraryInstResultType(N->getChild(i), TP))
2952 if (!N->getOperator()->isSubClassOf("Instruction"))
2955 // If this type is already concrete or completely unknown we can't do
2957 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
2958 if (N->getExtType(i).isCompletelyUnknown() || N->getExtType(i).isConcrete())
2961 // Otherwise, force its type to the first possibility (an arbitrary choice).
2962 if (N->getExtType(i).MergeInTypeInfo(N->getExtType(i).getTypeList()[0], TP))
2969 void CodeGenDAGPatterns::ParsePatterns() {
2970 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
2972 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
2973 Record *CurPattern = Patterns[i];
2974 DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
2976 // If the pattern references the null_frag, there's nothing to do.
2977 if (hasNullFragReference(Tree))
2980 TreePattern *Pattern = new TreePattern(CurPattern, Tree, true, *this);
2982 // Inline pattern fragments into it.
2983 Pattern->InlinePatternFragments();
2985 ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
2986 if (LI->getSize() == 0) continue; // no pattern.
2988 // Parse the instruction.
2989 TreePattern *Result = new TreePattern(CurPattern, LI, false, *this);
2991 // Inline pattern fragments into it.
2992 Result->InlinePatternFragments();
2994 if (Result->getNumTrees() != 1)
2995 Result->error("Cannot handle instructions producing instructions "
2996 "with temporaries yet!");
2998 bool IterateInference;
2999 bool InferredAllPatternTypes, InferredAllResultTypes;
3001 // Infer as many types as possible. If we cannot infer all of them, we
3002 // can never do anything with this pattern: report it to the user.
3003 InferredAllPatternTypes =
3004 Pattern->InferAllTypes(&Pattern->getNamedNodesMap());
3006 // Infer as many types as possible. If we cannot infer all of them, we
3007 // can never do anything with this pattern: report it to the user.
3008 InferredAllResultTypes =
3009 Result->InferAllTypes(&Pattern->getNamedNodesMap());
3011 IterateInference = false;
3013 // Apply the type of the result to the source pattern. This helps us
3014 // resolve cases where the input type is known to be a pointer type (which
3015 // is considered resolved), but the result knows it needs to be 32- or
3016 // 64-bits. Infer the other way for good measure.
3017 for (unsigned i = 0, e = std::min(Result->getTree(0)->getNumTypes(),
3018 Pattern->getTree(0)->getNumTypes());
3020 IterateInference = Pattern->getTree(0)->
3021 UpdateNodeType(i, Result->getTree(0)->getExtType(i), *Result);
3022 IterateInference |= Result->getTree(0)->
3023 UpdateNodeType(i, Pattern->getTree(0)->getExtType(i), *Result);
3026 // If our iteration has converged and the input pattern's types are fully
3027 // resolved but the result pattern is not fully resolved, we may have a
3028 // situation where we have two instructions in the result pattern and
3029 // the instructions require a common register class, but don't care about
3030 // what actual MVT is used. This is actually a bug in our modelling:
3031 // output patterns should have register classes, not MVTs.
3033 // In any case, to handle this, we just go through and disambiguate some
3034 // arbitrary types to the result pattern's nodes.
3035 if (!IterateInference && InferredAllPatternTypes &&
3036 !InferredAllResultTypes)
3037 IterateInference = ForceArbitraryInstResultType(Result->getTree(0),
3039 } while (IterateInference);
3041 // Verify that we inferred enough types that we can do something with the
3042 // pattern and result. If these fire the user has to add type casts.
3043 if (!InferredAllPatternTypes)
3044 Pattern->error("Could not infer all types in pattern!");
3045 if (!InferredAllResultTypes) {
3047 Result->error("Could not infer all types in pattern result!");
3050 // Validate that the input pattern is correct.
3051 std::map<std::string, TreePatternNode*> InstInputs;
3052 std::map<std::string, TreePatternNode*> InstResults;
3053 std::vector<Record*> InstImpResults;
3054 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
3055 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
3056 InstInputs, InstResults,
3059 // Promote the xform function to be an explicit node if set.
3060 TreePatternNode *DstPattern = Result->getOnlyTree();
3061 std::vector<TreePatternNode*> ResultNodeOperands;
3062 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
3063 TreePatternNode *OpNode = DstPattern->getChild(ii);
3064 if (Record *Xform = OpNode->getTransformFn()) {
3065 OpNode->setTransformFn(0);
3066 std::vector<TreePatternNode*> Children;
3067 Children.push_back(OpNode);
3068 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
3070 ResultNodeOperands.push_back(OpNode);
3072 DstPattern = Result->getOnlyTree();
3073 if (!DstPattern->isLeaf())
3074 DstPattern = new TreePatternNode(DstPattern->getOperator(),
3076 DstPattern->getNumTypes());
3078 for (unsigned i = 0, e = Result->getOnlyTree()->getNumTypes(); i != e; ++i)
3079 DstPattern->setType(i, Result->getOnlyTree()->getExtType(i));
3081 TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
3082 Temp.InferAllTypes();
3085 AddPatternToMatch(Pattern,
3086 PatternToMatch(CurPattern,
3087 CurPattern->getValueAsListInit("Predicates"),
3088 Pattern->getTree(0),
3089 Temp.getOnlyTree(), InstImpResults,
3090 CurPattern->getValueAsInt("AddedComplexity"),
3091 CurPattern->getID()));
3095 /// CombineChildVariants - Given a bunch of permutations of each child of the
3096 /// 'operator' node, put them together in all possible ways.
3097 static void CombineChildVariants(TreePatternNode *Orig,
3098 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
3099 std::vector<TreePatternNode*> &OutVariants,
3100 CodeGenDAGPatterns &CDP,
3101 const MultipleUseVarSet &DepVars) {
3102 // Make sure that each operand has at least one variant to choose from.
3103 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
3104 if (ChildVariants[i].empty())
3107 // The end result is an all-pairs construction of the resultant pattern.
3108 std::vector<unsigned> Idxs;
3109 Idxs.resize(ChildVariants.size());
3113 DEBUG(if (!Idxs.empty()) {
3114 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
3115 for (unsigned i = 0; i < Idxs.size(); ++i) {
3116 errs() << Idxs[i] << " ";
3121 // Create the variant and add it to the output list.
3122 std::vector<TreePatternNode*> NewChildren;
3123 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
3124 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
3125 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren,
3126 Orig->getNumTypes());
3128 // Copy over properties.
3129 R->setName(Orig->getName());
3130 R->setPredicateFns(Orig->getPredicateFns());
3131 R->setTransformFn(Orig->getTransformFn());
3132 for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
3133 R->setType(i, Orig->getExtType(i));
3135 // If this pattern cannot match, do not include it as a variant.
3136 std::string ErrString;
3137 if (!R->canPatternMatch(ErrString, CDP)) {
3140 bool AlreadyExists = false;
3142 // Scan to see if this pattern has already been emitted. We can get
3143 // duplication due to things like commuting:
3144 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
3145 // which are the same pattern. Ignore the dups.
3146 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
3147 if (R->isIsomorphicTo(OutVariants[i], DepVars)) {
3148 AlreadyExists = true;
3155 OutVariants.push_back(R);
3158 // Increment indices to the next permutation by incrementing the
3159 // indicies from last index backward, e.g., generate the sequence
3160 // [0, 0], [0, 1], [1, 0], [1, 1].
3162 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
3163 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
3168 NotDone = (IdxsIdx >= 0);
3172 /// CombineChildVariants - A helper function for binary operators.
3174 static void CombineChildVariants(TreePatternNode *Orig,
3175 const std::vector<TreePatternNode*> &LHS,
3176 const std::vector<TreePatternNode*> &RHS,
3177 std::vector<TreePatternNode*> &OutVariants,
3178 CodeGenDAGPatterns &CDP,
3179 const MultipleUseVarSet &DepVars) {
3180 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3181 ChildVariants.push_back(LHS);
3182 ChildVariants.push_back(RHS);
3183 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
3187 static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
3188 std::vector<TreePatternNode *> &Children) {
3189 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
3190 Record *Operator = N->getOperator();
3192 // Only permit raw nodes.
3193 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
3194 N->getTransformFn()) {
3195 Children.push_back(N);
3199 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
3200 Children.push_back(N->getChild(0));
3202 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
3204 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
3205 Children.push_back(N->getChild(1));
3207 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
3210 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
3211 /// the (potentially recursive) pattern by using algebraic laws.
3213 static void GenerateVariantsOf(TreePatternNode *N,
3214 std::vector<TreePatternNode*> &OutVariants,
3215 CodeGenDAGPatterns &CDP,
3216 const MultipleUseVarSet &DepVars) {
3217 // We cannot permute leaves.
3219 OutVariants.push_back(N);
3223 // Look up interesting info about the node.
3224 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
3226 // If this node is associative, re-associate.
3227 if (NodeInfo.hasProperty(SDNPAssociative)) {
3228 // Re-associate by pulling together all of the linked operators
3229 std::vector<TreePatternNode*> MaximalChildren;
3230 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
3232 // Only handle child sizes of 3. Otherwise we'll end up trying too many
3234 if (MaximalChildren.size() == 3) {
3235 // Find the variants of all of our maximal children.
3236 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
3237 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
3238 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
3239 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
3241 // There are only two ways we can permute the tree:
3242 // (A op B) op C and A op (B op C)
3243 // Within these forms, we can also permute A/B/C.
3245 // Generate legal pair permutations of A/B/C.
3246 std::vector<TreePatternNode*> ABVariants;
3247 std::vector<TreePatternNode*> BAVariants;
3248 std::vector<TreePatternNode*> ACVariants;
3249 std::vector<TreePatternNode*> CAVariants;
3250 std::vector<TreePatternNode*> BCVariants;
3251 std::vector<TreePatternNode*> CBVariants;
3252 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
3253 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
3254 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
3255 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
3256 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
3257 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
3259 // Combine those into the result: (x op x) op x
3260 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
3261 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
3262 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
3263 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
3264 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
3265 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
3267 // Combine those into the result: x op (x op x)
3268 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
3269 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
3270 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
3271 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
3272 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
3273 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
3278 // Compute permutations of all children.
3279 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3280 ChildVariants.resize(N->getNumChildren());
3281 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3282 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
3284 // Build all permutations based on how the children were formed.
3285 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
3287 // If this node is commutative, consider the commuted order.
3288 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
3289 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
3290 assert((N->getNumChildren()==2 || isCommIntrinsic) &&
3291 "Commutative but doesn't have 2 children!");
3292 // Don't count children which are actually register references.
3294 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
3295 TreePatternNode *Child = N->getChild(i);
3296 if (Child->isLeaf())
3297 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
3298 Record *RR = DI->getDef();
3299 if (RR->isSubClassOf("Register"))
3304 // Consider the commuted order.
3305 if (isCommIntrinsic) {
3306 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
3307 // operands are the commutative operands, and there might be more operands
3310 "Commutative intrinsic should have at least 3 childrean!");
3311 std::vector<std::vector<TreePatternNode*> > Variants;
3312 Variants.push_back(ChildVariants[0]); // Intrinsic id.
3313 Variants.push_back(ChildVariants[2]);
3314 Variants.push_back(ChildVariants[1]);
3315 for (unsigned i = 3; i != NC; ++i)
3316 Variants.push_back(ChildVariants[i]);
3317 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
3319 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
3320 OutVariants, CDP, DepVars);
3325 // GenerateVariants - Generate variants. For example, commutative patterns can
3326 // match multiple ways. Add them to PatternsToMatch as well.
3327 void CodeGenDAGPatterns::GenerateVariants() {
3328 DEBUG(errs() << "Generating instruction variants.\n");
3330 // Loop over all of the patterns we've collected, checking to see if we can
3331 // generate variants of the instruction, through the exploitation of
3332 // identities. This permits the target to provide aggressive matching without
3333 // the .td file having to contain tons of variants of instructions.
3335 // Note that this loop adds new patterns to the PatternsToMatch list, but we
3336 // intentionally do not reconsider these. Any variants of added patterns have
3337 // already been added.
3339 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
3340 MultipleUseVarSet DepVars;
3341 std::vector<TreePatternNode*> Variants;
3342 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
3343 DEBUG(errs() << "Dependent/multiply used variables: ");
3344 DEBUG(DumpDepVars(DepVars));
3345 DEBUG(errs() << "\n");
3346 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this,
3349 assert(!Variants.empty() && "Must create at least original variant!");
3350 Variants.erase(Variants.begin()); // Remove the original pattern.
3352 if (Variants.empty()) // No variants for this pattern.
3355 DEBUG(errs() << "FOUND VARIANTS OF: ";
3356 PatternsToMatch[i].getSrcPattern()->dump();
3359 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
3360 TreePatternNode *Variant = Variants[v];
3362 DEBUG(errs() << " VAR#" << v << ": ";
3366 // Scan to see if an instruction or explicit pattern already matches this.
3367 bool AlreadyExists = false;
3368 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
3369 // Skip if the top level predicates do not match.
3370 if (PatternsToMatch[i].getPredicates() !=
3371 PatternsToMatch[p].getPredicates())
3373 // Check to see if this variant already exists.
3374 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),
3376 DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
3377 AlreadyExists = true;
3381 // If we already have it, ignore the variant.
3382 if (AlreadyExists) continue;
3384 // Otherwise, add it to the list of patterns we have.
3386 push_back(PatternToMatch(PatternsToMatch[i].getSrcRecord(),
3387 PatternsToMatch[i].getPredicates(),
3388 Variant, PatternsToMatch[i].getDstPattern(),
3389 PatternsToMatch[i].getDstRegs(),
3390 PatternsToMatch[i].getAddedComplexity(),
3391 Record::getNewUID()));
3394 DEBUG(errs() << "\n");