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"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/Support/Debug.h"
24 //===----------------------------------------------------------------------===//
25 // EEVT::TypeSet Implementation
26 //===----------------------------------------------------------------------===//
28 static inline bool isInteger(MVT::SimpleValueType VT) {
29 return EVT(VT).isInteger();
31 static inline bool isFloatingPoint(MVT::SimpleValueType VT) {
32 return EVT(VT).isFloatingPoint();
34 static inline bool isVector(MVT::SimpleValueType VT) {
35 return EVT(VT).isVector();
37 static inline bool isScalar(MVT::SimpleValueType VT) {
38 return !EVT(VT).isVector();
41 EEVT::TypeSet::TypeSet(MVT::SimpleValueType VT, TreePattern &TP) {
44 else if (VT == MVT::fAny)
45 EnforceFloatingPoint(TP);
46 else if (VT == MVT::vAny)
49 assert((VT < MVT::LAST_VALUETYPE || VT == MVT::iPTR ||
50 VT == MVT::iPTRAny) && "Not a concrete type!");
51 TypeVec.push_back(VT);
56 EEVT::TypeSet::TypeSet(const std::vector<MVT::SimpleValueType> &VTList) {
57 assert(!VTList.empty() && "empty list?");
58 TypeVec.append(VTList.begin(), VTList.end());
61 assert(VTList[0] != MVT::iAny && VTList[0] != MVT::vAny &&
62 VTList[0] != MVT::fAny);
64 // Verify no duplicates.
65 array_pod_sort(TypeVec.begin(), TypeVec.end());
66 assert(std::unique(TypeVec.begin(), TypeVec.end()) == TypeVec.end());
69 /// FillWithPossibleTypes - Set to all legal types and return true, only valid
70 /// on completely unknown type sets.
71 bool EEVT::TypeSet::FillWithPossibleTypes(TreePattern &TP,
72 bool (*Pred)(MVT::SimpleValueType),
73 const char *PredicateName) {
74 assert(isCompletelyUnknown());
75 const std::vector<MVT::SimpleValueType> &LegalTypes =
76 TP.getDAGPatterns().getTargetInfo().getLegalValueTypes();
78 for (unsigned i = 0, e = LegalTypes.size(); i != e; ++i)
79 if (Pred == 0 || Pred(LegalTypes[i]))
80 TypeVec.push_back(LegalTypes[i]);
82 // If we have nothing that matches the predicate, bail out.
84 TP.error("Type inference contradiction found, no " +
85 std::string(PredicateName) + " types found");
86 // No need to sort with one element.
87 if (TypeVec.size() == 1) return true;
90 array_pod_sort(TypeVec.begin(), TypeVec.end());
91 TypeVec.erase(std::unique(TypeVec.begin(), TypeVec.end()), TypeVec.end());
96 /// hasIntegerTypes - Return true if this TypeSet contains iAny or an
97 /// integer value type.
98 bool EEVT::TypeSet::hasIntegerTypes() const {
99 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
100 if (isInteger(TypeVec[i]))
105 /// hasFloatingPointTypes - Return true if this TypeSet contains an fAny or
106 /// a floating point value type.
107 bool EEVT::TypeSet::hasFloatingPointTypes() const {
108 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
109 if (isFloatingPoint(TypeVec[i]))
114 /// hasVectorTypes - Return true if this TypeSet contains a vAny or a vector
116 bool EEVT::TypeSet::hasVectorTypes() const {
117 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
118 if (isVector(TypeVec[i]))
124 std::string EEVT::TypeSet::getName() const {
125 if (TypeVec.empty()) return "<empty>";
129 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i) {
130 std::string VTName = llvm::getEnumName(TypeVec[i]);
131 // Strip off MVT:: prefix if present.
132 if (VTName.substr(0,5) == "MVT::")
133 VTName = VTName.substr(5);
134 if (i) Result += ':';
138 if (TypeVec.size() == 1)
140 return "{" + Result + "}";
143 /// MergeInTypeInfo - This merges in type information from the specified
144 /// argument. If 'this' changes, it returns true. If the two types are
145 /// contradictory (e.g. merge f32 into i32) then this throws an exception.
146 bool EEVT::TypeSet::MergeInTypeInfo(const EEVT::TypeSet &InVT, TreePattern &TP){
147 if (InVT.isCompletelyUnknown() || *this == InVT)
150 if (isCompletelyUnknown()) {
155 assert(TypeVec.size() >= 1 && InVT.TypeVec.size() >= 1 && "No unknowns");
157 // Handle the abstract cases, seeing if we can resolve them better.
158 switch (TypeVec[0]) {
162 if (InVT.hasIntegerTypes()) {
163 EEVT::TypeSet InCopy(InVT);
164 InCopy.EnforceInteger(TP);
165 InCopy.EnforceScalar(TP);
167 if (InCopy.isConcrete()) {
168 // If the RHS has one integer type, upgrade iPTR to i32.
169 TypeVec[0] = InVT.TypeVec[0];
173 // If the input has multiple scalar integers, this doesn't add any info.
174 if (!InCopy.isCompletelyUnknown())
180 // If the input constraint is iAny/iPTR and this is an integer type list,
181 // remove non-integer types from the list.
182 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
184 bool MadeChange = EnforceInteger(TP);
186 // If we're merging in iPTR/iPTRAny and the node currently has a list of
187 // multiple different integer types, replace them with a single iPTR.
188 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
189 TypeVec.size() != 1) {
191 TypeVec[0] = InVT.TypeVec[0];
198 // If this is a type list and the RHS is a typelist as well, eliminate entries
199 // from this list that aren't in the other one.
200 bool MadeChange = false;
201 TypeSet InputSet(*this);
203 for (unsigned i = 0; i != TypeVec.size(); ++i) {
205 for (unsigned j = 0, e = InVT.TypeVec.size(); j != e; ++j)
206 if (TypeVec[i] == InVT.TypeVec[j]) {
211 if (InInVT) continue;
212 TypeVec.erase(TypeVec.begin()+i--);
216 // If we removed all of our types, we have a type contradiction.
217 if (!TypeVec.empty())
220 // FIXME: Really want an SMLoc here!
221 TP.error("Type inference contradiction found, merging '" +
222 InVT.getName() + "' into '" + InputSet.getName() + "'");
223 return true; // unreachable
226 /// EnforceInteger - Remove all non-integer types from this set.
227 bool EEVT::TypeSet::EnforceInteger(TreePattern &TP) {
228 // If we know nothing, then get the full set.
230 return FillWithPossibleTypes(TP, isInteger, "integer");
231 if (!hasFloatingPointTypes())
234 TypeSet InputSet(*this);
236 // Filter out all the fp types.
237 for (unsigned i = 0; i != TypeVec.size(); ++i)
238 if (!isInteger(TypeVec[i]))
239 TypeVec.erase(TypeVec.begin()+i--);
242 TP.error("Type inference contradiction found, '" +
243 InputSet.getName() + "' needs to be integer");
247 /// EnforceFloatingPoint - Remove all integer types from this set.
248 bool EEVT::TypeSet::EnforceFloatingPoint(TreePattern &TP) {
249 // If we know nothing, then get the full set.
251 return FillWithPossibleTypes(TP, isFloatingPoint, "floating point");
253 if (!hasIntegerTypes())
256 TypeSet InputSet(*this);
258 // Filter out all the fp types.
259 for (unsigned i = 0; i != TypeVec.size(); ++i)
260 if (!isFloatingPoint(TypeVec[i]))
261 TypeVec.erase(TypeVec.begin()+i--);
264 TP.error("Type inference contradiction found, '" +
265 InputSet.getName() + "' needs to be floating point");
269 /// EnforceScalar - Remove all vector types from this.
270 bool EEVT::TypeSet::EnforceScalar(TreePattern &TP) {
271 // If we know nothing, then get the full set.
273 return FillWithPossibleTypes(TP, isScalar, "scalar");
275 if (!hasVectorTypes())
278 TypeSet InputSet(*this);
280 // Filter out all the vector types.
281 for (unsigned i = 0; i != TypeVec.size(); ++i)
282 if (!isScalar(TypeVec[i]))
283 TypeVec.erase(TypeVec.begin()+i--);
286 TP.error("Type inference contradiction found, '" +
287 InputSet.getName() + "' needs to be scalar");
291 /// EnforceVector - Remove all vector types from this.
292 bool EEVT::TypeSet::EnforceVector(TreePattern &TP) {
293 // If we know nothing, then get the full set.
295 return FillWithPossibleTypes(TP, isVector, "vector");
297 TypeSet InputSet(*this);
298 bool MadeChange = false;
300 // Filter out all the scalar types.
301 for (unsigned i = 0; i != TypeVec.size(); ++i)
302 if (!isVector(TypeVec[i])) {
303 TypeVec.erase(TypeVec.begin()+i--);
308 TP.error("Type inference contradiction found, '" +
309 InputSet.getName() + "' needs to be a vector");
315 /// EnforceSmallerThan - 'this' must be a smaller VT than Other. Update
316 /// this an other based on this information.
317 bool EEVT::TypeSet::EnforceSmallerThan(EEVT::TypeSet &Other, TreePattern &TP) {
318 // Both operands must be integer or FP, but we don't care which.
319 bool MadeChange = false;
321 if (isCompletelyUnknown())
322 MadeChange = FillWithPossibleTypes(TP);
324 if (Other.isCompletelyUnknown())
325 MadeChange = Other.FillWithPossibleTypes(TP);
327 // If one side is known to be integer or known to be FP but the other side has
328 // no information, get at least the type integrality info in there.
329 if (!hasFloatingPointTypes())
330 MadeChange |= Other.EnforceInteger(TP);
331 else if (!hasIntegerTypes())
332 MadeChange |= Other.EnforceFloatingPoint(TP);
333 if (!Other.hasFloatingPointTypes())
334 MadeChange |= EnforceInteger(TP);
335 else if (!Other.hasIntegerTypes())
336 MadeChange |= EnforceFloatingPoint(TP);
338 assert(!isCompletelyUnknown() && !Other.isCompletelyUnknown() &&
339 "Should have a type list now");
341 // If one contains vectors but the other doesn't pull vectors out.
342 if (!hasVectorTypes())
343 MadeChange |= Other.EnforceScalar(TP);
344 if (!hasVectorTypes())
345 MadeChange |= EnforceScalar(TP);
347 // This code does not currently handle nodes which have multiple types,
348 // where some types are integer, and some are fp. Assert that this is not
350 assert(!(hasIntegerTypes() && hasFloatingPointTypes()) &&
351 !(Other.hasIntegerTypes() && Other.hasFloatingPointTypes()) &&
352 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
354 // Okay, find the smallest type from the current set and remove it from the
356 MVT::SimpleValueType Smallest = TypeVec[0];
357 for (unsigned i = 1, e = TypeVec.size(); i != e; ++i)
358 if (TypeVec[i] < Smallest)
359 Smallest = TypeVec[i];
361 // If this is the only type in the large set, the constraint can never be
363 if (Other.TypeVec.size() == 1 && Other.TypeVec[0] == Smallest)
364 TP.error("Type inference contradiction found, '" +
365 Other.getName() + "' has nothing larger than '" + getName() +"'!");
367 SmallVector<MVT::SimpleValueType, 2>::iterator TVI =
368 std::find(Other.TypeVec.begin(), Other.TypeVec.end(), Smallest);
369 if (TVI != Other.TypeVec.end()) {
370 Other.TypeVec.erase(TVI);
374 // Okay, find the largest type in the Other set and remove it from the
376 MVT::SimpleValueType Largest = Other.TypeVec[0];
377 for (unsigned i = 1, e = Other.TypeVec.size(); i != e; ++i)
378 if (Other.TypeVec[i] > Largest)
379 Largest = Other.TypeVec[i];
381 // If this is the only type in the small set, the constraint can never be
383 if (TypeVec.size() == 1 && TypeVec[0] == Largest)
384 TP.error("Type inference contradiction found, '" +
385 getName() + "' has nothing smaller than '" + Other.getName()+"'!");
387 TVI = std::find(TypeVec.begin(), TypeVec.end(), Largest);
388 if (TVI != TypeVec.end()) {
396 /// EnforceVectorEltTypeIs - 'this' is now constrainted to be a vector type
397 /// whose element is specified by VTOperand.
398 bool EEVT::TypeSet::EnforceVectorEltTypeIs(EEVT::TypeSet &VTOperand,
400 // "This" must be a vector and "VTOperand" must be a scalar.
401 bool MadeChange = false;
402 MadeChange |= EnforceVector(TP);
403 MadeChange |= VTOperand.EnforceScalar(TP);
405 // If we know the vector type, it forces the scalar to agree.
407 EVT IVT = getConcrete();
408 IVT = IVT.getVectorElementType();
410 VTOperand.MergeInTypeInfo(IVT.getSimpleVT().SimpleTy, TP);
413 // If the scalar type is known, filter out vector types whose element types
415 if (!VTOperand.isConcrete())
418 MVT::SimpleValueType VT = VTOperand.getConcrete();
420 TypeSet InputSet(*this);
422 // Filter out all the types which don't have the right element type.
423 for (unsigned i = 0; i != TypeVec.size(); ++i) {
424 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
425 if (EVT(TypeVec[i]).getVectorElementType().getSimpleVT().SimpleTy != VT) {
426 TypeVec.erase(TypeVec.begin()+i--);
431 if (TypeVec.empty()) // FIXME: Really want an SMLoc here!
432 TP.error("Type inference contradiction found, forcing '" +
433 InputSet.getName() + "' to have a vector element");
437 /// EnforceVectorSubVectorTypeIs - 'this' is now constrainted to be a
438 /// vector type specified by VTOperand.
439 bool EEVT::TypeSet::EnforceVectorSubVectorTypeIs(EEVT::TypeSet &VTOperand,
441 // "This" must be a vector and "VTOperand" must be a vector.
442 bool MadeChange = false;
443 MadeChange |= EnforceVector(TP);
444 MadeChange |= VTOperand.EnforceVector(TP);
446 // "This" must be larger than "VTOperand."
447 MadeChange |= VTOperand.EnforceSmallerThan(*this, TP);
449 // If we know the vector type, it forces the scalar types to agree.
451 EVT IVT = getConcrete();
452 IVT = IVT.getVectorElementType();
454 EEVT::TypeSet EltTypeSet(IVT.getSimpleVT().SimpleTy, TP);
455 MadeChange |= VTOperand.EnforceVectorEltTypeIs(EltTypeSet, TP);
456 } else if (VTOperand.isConcrete()) {
457 EVT IVT = VTOperand.getConcrete();
458 IVT = IVT.getVectorElementType();
460 EEVT::TypeSet EltTypeSet(IVT.getSimpleVT().SimpleTy, TP);
461 MadeChange |= EnforceVectorEltTypeIs(EltTypeSet, TP);
467 //===----------------------------------------------------------------------===//
468 // Helpers for working with extended types.
470 bool RecordPtrCmp::operator()(const Record *LHS, const Record *RHS) const {
471 return LHS->getID() < RHS->getID();
474 /// Dependent variable map for CodeGenDAGPattern variant generation
475 typedef std::map<std::string, int> DepVarMap;
477 /// Const iterator shorthand for DepVarMap
478 typedef DepVarMap::const_iterator DepVarMap_citer;
481 void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
483 if (dynamic_cast<DefInit*>(N->getLeafValue()) != NULL) {
484 DepMap[N->getName()]++;
487 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
488 FindDepVarsOf(N->getChild(i), DepMap);
492 //! Find dependent variables within child patterns
495 void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
497 FindDepVarsOf(N, depcounts);
498 for (DepVarMap_citer i = depcounts.begin(); i != depcounts.end(); ++i) {
499 if (i->second > 1) { // std::pair<std::string, int>
500 DepVars.insert(i->first);
505 //! Dump the dependent variable set:
507 void DumpDepVars(MultipleUseVarSet &DepVars) {
508 if (DepVars.empty()) {
509 DEBUG(errs() << "<empty set>");
511 DEBUG(errs() << "[ ");
512 for (MultipleUseVarSet::const_iterator i = DepVars.begin(),
513 e = DepVars.end(); i != e; ++i) {
514 DEBUG(errs() << (*i) << " ");
516 DEBUG(errs() << "]");
523 //===----------------------------------------------------------------------===//
524 // PatternToMatch implementation
528 /// getPatternSize - Return the 'size' of this pattern. We want to match large
529 /// patterns before small ones. This is used to determine the size of a
531 static unsigned getPatternSize(const TreePatternNode *P,
532 const CodeGenDAGPatterns &CGP) {
533 unsigned Size = 3; // The node itself.
534 // If the root node is a ConstantSDNode, increases its size.
535 // e.g. (set R32:$dst, 0).
536 if (P->isLeaf() && dynamic_cast<IntInit*>(P->getLeafValue()))
539 // FIXME: This is a hack to statically increase the priority of patterns
540 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
541 // Later we can allow complexity / cost for each pattern to be (optionally)
542 // specified. To get best possible pattern match we'll need to dynamically
543 // calculate the complexity of all patterns a dag can potentially map to.
544 const ComplexPattern *AM = P->getComplexPatternInfo(CGP);
546 Size += AM->getNumOperands() * 3;
548 // If this node has some predicate function that must match, it adds to the
549 // complexity of this node.
550 if (!P->getPredicateFns().empty())
553 // Count children in the count if they are also nodes.
554 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
555 TreePatternNode *Child = P->getChild(i);
556 if (!Child->isLeaf() && Child->getNumTypes() &&
557 Child->getType(0) != MVT::Other)
558 Size += getPatternSize(Child, CGP);
559 else if (Child->isLeaf()) {
560 if (dynamic_cast<IntInit*>(Child->getLeafValue()))
561 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
562 else if (Child->getComplexPatternInfo(CGP))
563 Size += getPatternSize(Child, CGP);
564 else if (!Child->getPredicateFns().empty())
572 /// Compute the complexity metric for the input pattern. This roughly
573 /// corresponds to the number of nodes that are covered.
574 unsigned PatternToMatch::
575 getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
576 return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();
580 /// getPredicateCheck - Return a single string containing all of this
581 /// pattern's predicates concatenated with "&&" operators.
583 std::string PatternToMatch::getPredicateCheck() const {
584 std::string PredicateCheck;
585 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
586 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
587 Record *Def = Pred->getDef();
588 if (!Def->isSubClassOf("Predicate")) {
592 assert(0 && "Unknown predicate type!");
594 if (!PredicateCheck.empty())
595 PredicateCheck += " && ";
596 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
600 return PredicateCheck;
603 //===----------------------------------------------------------------------===//
604 // SDTypeConstraint implementation
607 SDTypeConstraint::SDTypeConstraint(Record *R) {
608 OperandNo = R->getValueAsInt("OperandNum");
610 if (R->isSubClassOf("SDTCisVT")) {
611 ConstraintType = SDTCisVT;
612 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
613 if (x.SDTCisVT_Info.VT == MVT::isVoid)
614 throw TGError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
616 } else if (R->isSubClassOf("SDTCisPtrTy")) {
617 ConstraintType = SDTCisPtrTy;
618 } else if (R->isSubClassOf("SDTCisInt")) {
619 ConstraintType = SDTCisInt;
620 } else if (R->isSubClassOf("SDTCisFP")) {
621 ConstraintType = SDTCisFP;
622 } else if (R->isSubClassOf("SDTCisVec")) {
623 ConstraintType = SDTCisVec;
624 } else if (R->isSubClassOf("SDTCisSameAs")) {
625 ConstraintType = SDTCisSameAs;
626 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
627 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
628 ConstraintType = SDTCisVTSmallerThanOp;
629 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
630 R->getValueAsInt("OtherOperandNum");
631 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
632 ConstraintType = SDTCisOpSmallerThanOp;
633 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
634 R->getValueAsInt("BigOperandNum");
635 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
636 ConstraintType = SDTCisEltOfVec;
637 x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
638 } else if (R->isSubClassOf("SDTCisSubVecOfVec")) {
639 ConstraintType = SDTCisSubVecOfVec;
640 x.SDTCisSubVecOfVec_Info.OtherOperandNum =
641 R->getValueAsInt("OtherOpNum");
643 errs() << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
648 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
649 /// N, and the result number in ResNo.
650 static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
651 const SDNodeInfo &NodeInfo,
653 unsigned NumResults = NodeInfo.getNumResults();
654 if (OpNo < NumResults) {
661 if (OpNo >= N->getNumChildren()) {
662 errs() << "Invalid operand number in type constraint "
663 << (OpNo+NumResults) << " ";
669 return N->getChild(OpNo);
672 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
673 /// constraint to the nodes operands. This returns true if it makes a
674 /// change, false otherwise. If a type contradiction is found, throw an
676 bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
677 const SDNodeInfo &NodeInfo,
678 TreePattern &TP) const {
679 unsigned ResNo = 0; // The result number being referenced.
680 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
682 switch (ConstraintType) {
683 default: assert(0 && "Unknown constraint type!");
685 // Operand must be a particular type.
686 return NodeToApply->UpdateNodeType(ResNo, x.SDTCisVT_Info.VT, TP);
688 // Operand must be same as target pointer type.
689 return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
691 // Require it to be one of the legal integer VTs.
692 return NodeToApply->getExtType(ResNo).EnforceInteger(TP);
694 // Require it to be one of the legal fp VTs.
695 return NodeToApply->getExtType(ResNo).EnforceFloatingPoint(TP);
697 // Require it to be one of the legal vector VTs.
698 return NodeToApply->getExtType(ResNo).EnforceVector(TP);
701 TreePatternNode *OtherNode =
702 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
703 return NodeToApply->UpdateNodeType(OResNo, OtherNode->getExtType(ResNo),TP)|
704 OtherNode->UpdateNodeType(ResNo,NodeToApply->getExtType(OResNo),TP);
706 case SDTCisVTSmallerThanOp: {
707 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
708 // have an integer type that is smaller than the VT.
709 if (!NodeToApply->isLeaf() ||
710 !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
711 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
712 ->isSubClassOf("ValueType"))
713 TP.error(N->getOperator()->getName() + " expects a VT operand!");
714 MVT::SimpleValueType VT =
715 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
717 EEVT::TypeSet TypeListTmp(VT, TP);
720 TreePatternNode *OtherNode =
721 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
724 return TypeListTmp.EnforceSmallerThan(OtherNode->getExtType(OResNo), TP);
726 case SDTCisOpSmallerThanOp: {
728 TreePatternNode *BigOperand =
729 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
731 return NodeToApply->getExtType(ResNo).
732 EnforceSmallerThan(BigOperand->getExtType(BResNo), TP);
734 case SDTCisEltOfVec: {
736 TreePatternNode *VecOperand =
737 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
740 // Filter vector types out of VecOperand that don't have the right element
742 return VecOperand->getExtType(VResNo).
743 EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), TP);
745 case SDTCisSubVecOfVec: {
747 TreePatternNode *BigVecOperand =
748 getOperandNum(x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo,
751 // Filter vector types out of BigVecOperand that don't have the
752 // right subvector type.
753 return BigVecOperand->getExtType(VResNo).
754 EnforceVectorSubVectorTypeIs(NodeToApply->getExtType(ResNo), TP);
760 //===----------------------------------------------------------------------===//
761 // SDNodeInfo implementation
763 SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
764 EnumName = R->getValueAsString("Opcode");
765 SDClassName = R->getValueAsString("SDClass");
766 Record *TypeProfile = R->getValueAsDef("TypeProfile");
767 NumResults = TypeProfile->getValueAsInt("NumResults");
768 NumOperands = TypeProfile->getValueAsInt("NumOperands");
770 // Parse the properties.
772 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
773 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
774 if (PropList[i]->getName() == "SDNPCommutative") {
775 Properties |= 1 << SDNPCommutative;
776 } else if (PropList[i]->getName() == "SDNPAssociative") {
777 Properties |= 1 << SDNPAssociative;
778 } else if (PropList[i]->getName() == "SDNPHasChain") {
779 Properties |= 1 << SDNPHasChain;
780 } else if (PropList[i]->getName() == "SDNPOutGlue") {
781 Properties |= 1 << SDNPOutGlue;
782 } else if (PropList[i]->getName() == "SDNPInGlue") {
783 Properties |= 1 << SDNPInGlue;
784 } else if (PropList[i]->getName() == "SDNPOptInGlue") {
785 Properties |= 1 << SDNPOptInGlue;
786 } else if (PropList[i]->getName() == "SDNPMayStore") {
787 Properties |= 1 << SDNPMayStore;
788 } else if (PropList[i]->getName() == "SDNPMayLoad") {
789 Properties |= 1 << SDNPMayLoad;
790 } else if (PropList[i]->getName() == "SDNPSideEffect") {
791 Properties |= 1 << SDNPSideEffect;
792 } else if (PropList[i]->getName() == "SDNPMemOperand") {
793 Properties |= 1 << SDNPMemOperand;
794 } else if (PropList[i]->getName() == "SDNPVariadic") {
795 Properties |= 1 << SDNPVariadic;
797 errs() << "Unknown SD Node property '" << PropList[i]->getName()
798 << "' on node '" << R->getName() << "'!\n";
804 // Parse the type constraints.
805 std::vector<Record*> ConstraintList =
806 TypeProfile->getValueAsListOfDefs("Constraints");
807 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
810 /// getKnownType - If the type constraints on this node imply a fixed type
811 /// (e.g. all stores return void, etc), then return it as an
812 /// MVT::SimpleValueType. Otherwise, return EEVT::Other.
813 MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
814 unsigned NumResults = getNumResults();
815 assert(NumResults <= 1 &&
816 "We only work with nodes with zero or one result so far!");
817 assert(ResNo == 0 && "Only handles single result nodes so far");
819 for (unsigned i = 0, e = TypeConstraints.size(); i != e; ++i) {
820 // Make sure that this applies to the correct node result.
821 if (TypeConstraints[i].OperandNo >= NumResults) // FIXME: need value #
824 switch (TypeConstraints[i].ConstraintType) {
826 case SDTypeConstraint::SDTCisVT:
827 return TypeConstraints[i].x.SDTCisVT_Info.VT;
828 case SDTypeConstraint::SDTCisPtrTy:
835 //===----------------------------------------------------------------------===//
836 // TreePatternNode implementation
839 TreePatternNode::~TreePatternNode() {
840 #if 0 // FIXME: implement refcounted tree nodes!
841 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
846 static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
847 if (Operator->getName() == "set" ||
848 Operator->getName() == "implicit")
849 return 0; // All return nothing.
851 if (Operator->isSubClassOf("Intrinsic"))
852 return CDP.getIntrinsic(Operator).IS.RetVTs.size();
854 if (Operator->isSubClassOf("SDNode"))
855 return CDP.getSDNodeInfo(Operator).getNumResults();
857 if (Operator->isSubClassOf("PatFrag")) {
858 // If we've already parsed this pattern fragment, get it. Otherwise, handle
859 // the forward reference case where one pattern fragment references another
860 // before it is processed.
861 if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator))
862 return PFRec->getOnlyTree()->getNumTypes();
864 // Get the result tree.
865 DagInit *Tree = Operator->getValueAsDag("Fragment");
867 if (Tree && dynamic_cast<DefInit*>(Tree->getOperator()))
868 Op = dynamic_cast<DefInit*>(Tree->getOperator())->getDef();
869 assert(Op && "Invalid Fragment");
870 return GetNumNodeResults(Op, CDP);
873 if (Operator->isSubClassOf("Instruction")) {
874 CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
876 // FIXME: Should allow access to all the results here.
877 unsigned NumDefsToAdd = InstInfo.Operands.NumDefs ? 1 : 0;
879 // Add on one implicit def if it has a resolvable type.
880 if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
885 if (Operator->isSubClassOf("SDNodeXForm"))
886 return 1; // FIXME: Generalize SDNodeXForm
889 errs() << "Unhandled node in GetNumNodeResults\n";
893 void TreePatternNode::print(raw_ostream &OS) const {
895 OS << *getLeafValue();
897 OS << '(' << getOperator()->getName();
899 for (unsigned i = 0, e = Types.size(); i != e; ++i)
900 OS << ':' << getExtType(i).getName();
903 if (getNumChildren() != 0) {
905 getChild(0)->print(OS);
906 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
908 getChild(i)->print(OS);
914 for (unsigned i = 0, e = PredicateFns.size(); i != e; ++i)
915 OS << "<<P:" << PredicateFns[i] << ">>";
917 OS << "<<X:" << TransformFn->getName() << ">>";
918 if (!getName().empty())
919 OS << ":$" << getName();
922 void TreePatternNode::dump() const {
926 /// isIsomorphicTo - Return true if this node is recursively
927 /// isomorphic to the specified node. For this comparison, the node's
928 /// entire state is considered. The assigned name is ignored, since
929 /// nodes with differing names are considered isomorphic. However, if
930 /// the assigned name is present in the dependent variable set, then
931 /// the assigned name is considered significant and the node is
932 /// isomorphic if the names match.
933 bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
934 const MultipleUseVarSet &DepVars) const {
935 if (N == this) return true;
936 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
937 getPredicateFns() != N->getPredicateFns() ||
938 getTransformFn() != N->getTransformFn())
942 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
943 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue())) {
944 return ((DI->getDef() == NDI->getDef())
945 && (DepVars.find(getName()) == DepVars.end()
946 || getName() == N->getName()));
949 return getLeafValue() == N->getLeafValue();
952 if (N->getOperator() != getOperator() ||
953 N->getNumChildren() != getNumChildren()) return false;
954 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
955 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
960 /// clone - Make a copy of this tree and all of its children.
962 TreePatternNode *TreePatternNode::clone() const {
963 TreePatternNode *New;
965 New = new TreePatternNode(getLeafValue(), getNumTypes());
967 std::vector<TreePatternNode*> CChildren;
968 CChildren.reserve(Children.size());
969 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
970 CChildren.push_back(getChild(i)->clone());
971 New = new TreePatternNode(getOperator(), CChildren, getNumTypes());
973 New->setName(getName());
975 New->setPredicateFns(getPredicateFns());
976 New->setTransformFn(getTransformFn());
980 /// RemoveAllTypes - Recursively strip all the types of this tree.
981 void TreePatternNode::RemoveAllTypes() {
982 for (unsigned i = 0, e = Types.size(); i != e; ++i)
983 Types[i] = EEVT::TypeSet(); // Reset to unknown type.
984 if (isLeaf()) return;
985 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
986 getChild(i)->RemoveAllTypes();
990 /// SubstituteFormalArguments - Replace the formal arguments in this tree
991 /// with actual values specified by ArgMap.
992 void TreePatternNode::
993 SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
994 if (isLeaf()) return;
996 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
997 TreePatternNode *Child = getChild(i);
998 if (Child->isLeaf()) {
999 Init *Val = Child->getLeafValue();
1000 if (dynamic_cast<DefInit*>(Val) &&
1001 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
1002 // We found a use of a formal argument, replace it with its value.
1003 TreePatternNode *NewChild = ArgMap[Child->getName()];
1004 assert(NewChild && "Couldn't find formal argument!");
1005 assert((Child->getPredicateFns().empty() ||
1006 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1007 "Non-empty child predicate clobbered!");
1008 setChild(i, NewChild);
1011 getChild(i)->SubstituteFormalArguments(ArgMap);
1017 /// InlinePatternFragments - If this pattern refers to any pattern
1018 /// fragments, inline them into place, giving us a pattern without any
1019 /// PatFrag references.
1020 TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
1021 if (isLeaf()) return this; // nothing to do.
1022 Record *Op = getOperator();
1024 if (!Op->isSubClassOf("PatFrag")) {
1025 // Just recursively inline children nodes.
1026 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1027 TreePatternNode *Child = getChild(i);
1028 TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
1030 assert((Child->getPredicateFns().empty() ||
1031 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1032 "Non-empty child predicate clobbered!");
1034 setChild(i, NewChild);
1039 // Otherwise, we found a reference to a fragment. First, look up its
1040 // TreePattern record.
1041 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
1043 // Verify that we are passing the right number of operands.
1044 if (Frag->getNumArgs() != Children.size())
1045 TP.error("'" + Op->getName() + "' fragment requires " +
1046 utostr(Frag->getNumArgs()) + " operands!");
1048 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
1050 std::string Code = Op->getValueAsCode("Predicate");
1052 FragTree->addPredicateFn("Predicate_"+Op->getName());
1054 // Resolve formal arguments to their actual value.
1055 if (Frag->getNumArgs()) {
1056 // Compute the map of formal to actual arguments.
1057 std::map<std::string, TreePatternNode*> ArgMap;
1058 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
1059 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
1061 FragTree->SubstituteFormalArguments(ArgMap);
1064 FragTree->setName(getName());
1065 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1066 FragTree->UpdateNodeType(i, getExtType(i), TP);
1068 // Transfer in the old predicates.
1069 for (unsigned i = 0, e = getPredicateFns().size(); i != e; ++i)
1070 FragTree->addPredicateFn(getPredicateFns()[i]);
1072 // Get a new copy of this fragment to stitch into here.
1073 //delete this; // FIXME: implement refcounting!
1075 // The fragment we inlined could have recursive inlining that is needed. See
1076 // if there are any pattern fragments in it and inline them as needed.
1077 return FragTree->InlinePatternFragments(TP);
1080 /// getImplicitType - Check to see if the specified record has an implicit
1081 /// type which should be applied to it. This will infer the type of register
1082 /// references from the register file information, for example.
1084 static EEVT::TypeSet getImplicitType(Record *R, unsigned ResNo,
1085 bool NotRegisters, TreePattern &TP) {
1086 // Check to see if this is a register or a register class.
1087 if (R->isSubClassOf("RegisterClass")) {
1088 assert(ResNo == 0 && "Regclass ref only has one result!");
1090 return EEVT::TypeSet(); // Unknown.
1091 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1092 return EEVT::TypeSet(T.getRegisterClass(R).getValueTypes());
1095 if (R->isSubClassOf("PatFrag")) {
1096 assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
1097 // Pattern fragment types will be resolved when they are inlined.
1098 return EEVT::TypeSet(); // Unknown.
1101 if (R->isSubClassOf("Register")) {
1102 assert(ResNo == 0 && "Registers only produce one result!");
1104 return EEVT::TypeSet(); // Unknown.
1105 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1106 return EEVT::TypeSet(T.getRegisterVTs(R));
1109 if (R->isSubClassOf("SubRegIndex")) {
1110 assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
1111 return EEVT::TypeSet();
1114 if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
1115 assert(ResNo == 0 && "This node only has one result!");
1116 // Using a VTSDNode or CondCodeSDNode.
1117 return EEVT::TypeSet(MVT::Other, TP);
1120 if (R->isSubClassOf("ComplexPattern")) {
1121 assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
1123 return EEVT::TypeSet(); // Unknown.
1124 return EEVT::TypeSet(TP.getDAGPatterns().getComplexPattern(R).getValueType(),
1127 if (R->isSubClassOf("PointerLikeRegClass")) {
1128 assert(ResNo == 0 && "Regclass can only have one result!");
1129 return EEVT::TypeSet(MVT::iPTR, TP);
1132 if (R->getName() == "node" || R->getName() == "srcvalue" ||
1133 R->getName() == "zero_reg") {
1135 return EEVT::TypeSet(); // Unknown.
1138 TP.error("Unknown node flavor used in pattern: " + R->getName());
1139 return EEVT::TypeSet(MVT::Other, TP);
1143 /// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
1144 /// CodeGenIntrinsic information for it, otherwise return a null pointer.
1145 const CodeGenIntrinsic *TreePatternNode::
1146 getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
1147 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
1148 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
1149 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
1153 dynamic_cast<IntInit*>(getChild(0)->getLeafValue())->getValue();
1154 return &CDP.getIntrinsicInfo(IID);
1157 /// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
1158 /// return the ComplexPattern information, otherwise return null.
1159 const ComplexPattern *
1160 TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
1161 if (!isLeaf()) return 0;
1163 DefInit *DI = dynamic_cast<DefInit*>(getLeafValue());
1164 if (DI && DI->getDef()->isSubClassOf("ComplexPattern"))
1165 return &CGP.getComplexPattern(DI->getDef());
1169 /// NodeHasProperty - Return true if this node has the specified property.
1170 bool TreePatternNode::NodeHasProperty(SDNP Property,
1171 const CodeGenDAGPatterns &CGP) const {
1173 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1174 return CP->hasProperty(Property);
1178 Record *Operator = getOperator();
1179 if (!Operator->isSubClassOf("SDNode")) return false;
1181 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
1187 /// TreeHasProperty - Return true if any node in this tree has the specified
1189 bool TreePatternNode::TreeHasProperty(SDNP Property,
1190 const CodeGenDAGPatterns &CGP) const {
1191 if (NodeHasProperty(Property, CGP))
1193 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1194 if (getChild(i)->TreeHasProperty(Property, CGP))
1199 /// isCommutativeIntrinsic - Return true if the node corresponds to a
1200 /// commutative intrinsic.
1202 TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
1203 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
1204 return Int->isCommutative;
1209 /// ApplyTypeConstraints - Apply all of the type constraints relevant to
1210 /// this node and its children in the tree. This returns true if it makes a
1211 /// change, false otherwise. If a type contradiction is found, throw an
1213 bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
1214 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
1216 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
1217 // If it's a regclass or something else known, include the type.
1218 bool MadeChange = false;
1219 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1220 MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
1221 NotRegisters, TP), TP);
1225 if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
1226 assert(Types.size() == 1 && "Invalid IntInit");
1228 // Int inits are always integers. :)
1229 bool MadeChange = Types[0].EnforceInteger(TP);
1231 if (!Types[0].isConcrete())
1234 MVT::SimpleValueType VT = getType(0);
1235 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
1238 unsigned Size = EVT(VT).getSizeInBits();
1239 // Make sure that the value is representable for this type.
1240 if (Size >= 32) return MadeChange;
1242 int Val = (II->getValue() << (32-Size)) >> (32-Size);
1243 if (Val == II->getValue()) return MadeChange;
1245 // If sign-extended doesn't fit, does it fit as unsigned?
1247 unsigned UnsignedVal;
1248 ValueMask = unsigned(~uint32_t(0UL) >> (32-Size));
1249 UnsignedVal = unsigned(II->getValue());
1251 if ((ValueMask & UnsignedVal) == UnsignedVal)
1254 TP.error("Integer value '" + itostr(II->getValue())+
1255 "' is out of range for type '" + getEnumName(getType(0)) + "'!");
1261 // special handling for set, which isn't really an SDNode.
1262 if (getOperator()->getName() == "set") {
1263 assert(getNumTypes() == 0 && "Set doesn't produce a value");
1264 assert(getNumChildren() >= 2 && "Missing RHS of a set?");
1265 unsigned NC = getNumChildren();
1267 TreePatternNode *SetVal = getChild(NC-1);
1268 bool MadeChange = SetVal->ApplyTypeConstraints(TP, NotRegisters);
1270 for (unsigned i = 0; i < NC-1; ++i) {
1271 TreePatternNode *Child = getChild(i);
1272 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
1274 // Types of operands must match.
1275 MadeChange |= Child->UpdateNodeType(0, SetVal->getExtType(i), TP);
1276 MadeChange |= SetVal->UpdateNodeType(i, Child->getExtType(0), TP);
1281 if (getOperator()->getName() == "implicit") {
1282 assert(getNumTypes() == 0 && "Node doesn't produce a value");
1284 bool MadeChange = false;
1285 for (unsigned i = 0; i < getNumChildren(); ++i)
1286 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1290 if (getOperator()->getName() == "COPY_TO_REGCLASS") {
1291 bool MadeChange = false;
1292 MadeChange |= getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1293 MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
1295 assert(getChild(0)->getNumTypes() == 1 &&
1296 getChild(1)->getNumTypes() == 1 && "Unhandled case");
1298 // child #1 of COPY_TO_REGCLASS should be a register class. We don't care
1299 // what type it gets, so if it didn't get a concrete type just give it the
1300 // first viable type from the reg class.
1301 if (!getChild(1)->hasTypeSet(0) &&
1302 !getChild(1)->getExtType(0).isCompletelyUnknown()) {
1303 MVT::SimpleValueType RCVT = getChild(1)->getExtType(0).getTypeList()[0];
1304 MadeChange |= getChild(1)->UpdateNodeType(0, RCVT, TP);
1309 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
1310 bool MadeChange = false;
1312 // Apply the result type to the node.
1313 unsigned NumRetVTs = Int->IS.RetVTs.size();
1314 unsigned NumParamVTs = Int->IS.ParamVTs.size();
1316 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
1317 MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
1319 if (getNumChildren() != NumParamVTs + 1)
1320 TP.error("Intrinsic '" + Int->Name + "' expects " +
1321 utostr(NumParamVTs) + " operands, not " +
1322 utostr(getNumChildren() - 1) + " operands!");
1324 // Apply type info to the intrinsic ID.
1325 MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
1327 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
1328 MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
1330 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
1331 assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
1332 MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
1337 if (getOperator()->isSubClassOf("SDNode")) {
1338 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
1340 // Check that the number of operands is sane. Negative operands -> varargs.
1341 if (NI.getNumOperands() >= 0 &&
1342 getNumChildren() != (unsigned)NI.getNumOperands())
1343 TP.error(getOperator()->getName() + " node requires exactly " +
1344 itostr(NI.getNumOperands()) + " operands!");
1346 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
1347 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1348 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1352 if (getOperator()->isSubClassOf("Instruction")) {
1353 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
1354 CodeGenInstruction &InstInfo =
1355 CDP.getTargetInfo().getInstruction(getOperator());
1357 bool MadeChange = false;
1359 // Apply the result types to the node, these come from the things in the
1360 // (outs) list of the instruction.
1361 // FIXME: Cap at one result so far.
1362 unsigned NumResultsToAdd = InstInfo.Operands.NumDefs ? 1 : 0;
1363 for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo) {
1364 Record *ResultNode = Inst.getResult(ResNo);
1366 if (ResultNode->isSubClassOf("PointerLikeRegClass")) {
1367 MadeChange |= UpdateNodeType(ResNo, MVT::iPTR, TP);
1368 } else if (ResultNode->getName() == "unknown") {
1371 assert(ResultNode->isSubClassOf("RegisterClass") &&
1372 "Operands should be register classes!");
1373 const CodeGenRegisterClass &RC =
1374 CDP.getTargetInfo().getRegisterClass(ResultNode);
1375 MadeChange |= UpdateNodeType(ResNo, RC.getValueTypes(), TP);
1379 // If the instruction has implicit defs, we apply the first one as a result.
1380 // FIXME: This sucks, it should apply all implicit defs.
1381 if (!InstInfo.ImplicitDefs.empty()) {
1382 unsigned ResNo = NumResultsToAdd;
1384 // FIXME: Generalize to multiple possible types and multiple possible
1386 MVT::SimpleValueType VT =
1387 InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
1389 if (VT != MVT::Other)
1390 MadeChange |= UpdateNodeType(ResNo, VT, TP);
1393 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
1395 if (getOperator()->getName() == "INSERT_SUBREG") {
1396 assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
1397 MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
1398 MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
1401 unsigned ChildNo = 0;
1402 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
1403 Record *OperandNode = Inst.getOperand(i);
1405 // If the instruction expects a predicate or optional def operand, we
1406 // codegen this by setting the operand to it's default value if it has a
1407 // non-empty DefaultOps field.
1408 if ((OperandNode->isSubClassOf("PredicateOperand") ||
1409 OperandNode->isSubClassOf("OptionalDefOperand")) &&
1410 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1413 // Verify that we didn't run out of provided operands.
1414 if (ChildNo >= getNumChildren())
1415 TP.error("Instruction '" + getOperator()->getName() +
1416 "' expects more operands than were provided.");
1418 MVT::SimpleValueType VT;
1419 TreePatternNode *Child = getChild(ChildNo++);
1420 unsigned ChildResNo = 0; // Instructions always use res #0 of their op.
1422 if (OperandNode->isSubClassOf("RegisterClass")) {
1423 const CodeGenRegisterClass &RC =
1424 CDP.getTargetInfo().getRegisterClass(OperandNode);
1425 MadeChange |= Child->UpdateNodeType(ChildResNo, RC.getValueTypes(), TP);
1426 } else if (OperandNode->isSubClassOf("Operand")) {
1427 VT = getValueType(OperandNode->getValueAsDef("Type"));
1428 MadeChange |= Child->UpdateNodeType(ChildResNo, VT, TP);
1429 } else if (OperandNode->isSubClassOf("PointerLikeRegClass")) {
1430 MadeChange |= Child->UpdateNodeType(ChildResNo, MVT::iPTR, TP);
1431 } else if (OperandNode->getName() == "unknown") {
1434 assert(0 && "Unknown operand type!");
1437 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
1440 if (ChildNo != getNumChildren())
1441 TP.error("Instruction '" + getOperator()->getName() +
1442 "' was provided too many operands!");
1447 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
1449 // Node transforms always take one operand.
1450 if (getNumChildren() != 1)
1451 TP.error("Node transform '" + getOperator()->getName() +
1452 "' requires one operand!");
1454 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1457 // If either the output or input of the xform does not have exact
1458 // type info. We assume they must be the same. Otherwise, it is perfectly
1459 // legal to transform from one type to a completely different type.
1461 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
1462 bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
1463 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
1470 /// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
1471 /// RHS of a commutative operation, not the on LHS.
1472 static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
1473 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
1475 if (N->isLeaf() && dynamic_cast<IntInit*>(N->getLeafValue()))
1481 /// canPatternMatch - If it is impossible for this pattern to match on this
1482 /// target, fill in Reason and return false. Otherwise, return true. This is
1483 /// used as a sanity check for .td files (to prevent people from writing stuff
1484 /// that can never possibly work), and to prevent the pattern permuter from
1485 /// generating stuff that is useless.
1486 bool TreePatternNode::canPatternMatch(std::string &Reason,
1487 const CodeGenDAGPatterns &CDP) {
1488 if (isLeaf()) return true;
1490 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1491 if (!getChild(i)->canPatternMatch(Reason, CDP))
1494 // If this is an intrinsic, handle cases that would make it not match. For
1495 // example, if an operand is required to be an immediate.
1496 if (getOperator()->isSubClassOf("Intrinsic")) {
1501 // If this node is a commutative operator, check that the LHS isn't an
1503 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
1504 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
1505 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
1506 // Scan all of the operands of the node and make sure that only the last one
1507 // is a constant node, unless the RHS also is.
1508 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
1509 bool Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
1510 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
1511 if (OnlyOnRHSOfCommutative(getChild(i))) {
1512 Reason="Immediate value must be on the RHS of commutative operators!";
1521 //===----------------------------------------------------------------------===//
1522 // TreePattern implementation
1525 TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
1526 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
1527 isInputPattern = isInput;
1528 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
1529 Trees.push_back(ParseTreePattern(RawPat->getElement(i), ""));
1532 TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
1533 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
1534 isInputPattern = isInput;
1535 Trees.push_back(ParseTreePattern(Pat, ""));
1538 TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
1539 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
1540 isInputPattern = isInput;
1541 Trees.push_back(Pat);
1544 void TreePattern::error(const std::string &Msg) const {
1546 throw TGError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
1549 void TreePattern::ComputeNamedNodes() {
1550 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1551 ComputeNamedNodes(Trees[i]);
1554 void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
1555 if (!N->getName().empty())
1556 NamedNodes[N->getName()].push_back(N);
1558 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1559 ComputeNamedNodes(N->getChild(i));
1563 TreePatternNode *TreePattern::ParseTreePattern(Init *TheInit, StringRef OpName){
1564 if (DefInit *DI = dynamic_cast<DefInit*>(TheInit)) {
1565 Record *R = DI->getDef();
1567 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
1568 // TreePatternNode if its own. For example:
1569 /// (foo GPR, imm) -> (foo GPR, (imm))
1570 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag"))
1571 return ParseTreePattern(new DagInit(DI, "",
1572 std::vector<std::pair<Init*, std::string> >()),
1576 TreePatternNode *Res = new TreePatternNode(DI, 1);
1577 if (R->getName() == "node" && !OpName.empty()) {
1579 error("'node' argument requires a name to match with operand list");
1580 Args.push_back(OpName);
1583 Res->setName(OpName);
1587 if (IntInit *II = dynamic_cast<IntInit*>(TheInit)) {
1588 if (!OpName.empty())
1589 error("Constant int argument should not have a name!");
1590 return new TreePatternNode(II, 1);
1593 if (BitsInit *BI = dynamic_cast<BitsInit*>(TheInit)) {
1594 // Turn this into an IntInit.
1595 Init *II = BI->convertInitializerTo(new IntRecTy());
1596 if (II == 0 || !dynamic_cast<IntInit*>(II))
1597 error("Bits value must be constants!");
1598 return ParseTreePattern(II, OpName);
1601 DagInit *Dag = dynamic_cast<DagInit*>(TheInit);
1604 error("Pattern has unexpected init kind!");
1606 DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
1607 if (!OpDef) error("Pattern has unexpected operator type!");
1608 Record *Operator = OpDef->getDef();
1610 if (Operator->isSubClassOf("ValueType")) {
1611 // If the operator is a ValueType, then this must be "type cast" of a leaf
1613 if (Dag->getNumArgs() != 1)
1614 error("Type cast only takes one operand!");
1616 TreePatternNode *New = ParseTreePattern(Dag->getArg(0), Dag->getArgName(0));
1618 // Apply the type cast.
1619 assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
1620 New->UpdateNodeType(0, getValueType(Operator), *this);
1622 if (!OpName.empty())
1623 error("ValueType cast should not have a name!");
1627 // Verify that this is something that makes sense for an operator.
1628 if (!Operator->isSubClassOf("PatFrag") &&
1629 !Operator->isSubClassOf("SDNode") &&
1630 !Operator->isSubClassOf("Instruction") &&
1631 !Operator->isSubClassOf("SDNodeXForm") &&
1632 !Operator->isSubClassOf("Intrinsic") &&
1633 Operator->getName() != "set" &&
1634 Operator->getName() != "implicit")
1635 error("Unrecognized node '" + Operator->getName() + "'!");
1637 // Check to see if this is something that is illegal in an input pattern.
1638 if (isInputPattern) {
1639 if (Operator->isSubClassOf("Instruction") ||
1640 Operator->isSubClassOf("SDNodeXForm"))
1641 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
1643 if (Operator->isSubClassOf("Intrinsic"))
1644 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
1646 if (Operator->isSubClassOf("SDNode") &&
1647 Operator->getName() != "imm" &&
1648 Operator->getName() != "fpimm" &&
1649 Operator->getName() != "tglobaltlsaddr" &&
1650 Operator->getName() != "tconstpool" &&
1651 Operator->getName() != "tjumptable" &&
1652 Operator->getName() != "tframeindex" &&
1653 Operator->getName() != "texternalsym" &&
1654 Operator->getName() != "tblockaddress" &&
1655 Operator->getName() != "tglobaladdr" &&
1656 Operator->getName() != "bb" &&
1657 Operator->getName() != "vt")
1658 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
1661 std::vector<TreePatternNode*> Children;
1663 // Parse all the operands.
1664 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
1665 Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgName(i)));
1667 // If the operator is an intrinsic, then this is just syntactic sugar for for
1668 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
1669 // convert the intrinsic name to a number.
1670 if (Operator->isSubClassOf("Intrinsic")) {
1671 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
1672 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
1674 // If this intrinsic returns void, it must have side-effects and thus a
1676 if (Int.IS.RetVTs.empty())
1677 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
1678 else if (Int.ModRef != CodeGenIntrinsic::NoMem)
1679 // Has side-effects, requires chain.
1680 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
1681 else // Otherwise, no chain.
1682 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
1684 TreePatternNode *IIDNode = new TreePatternNode(new IntInit(IID), 1);
1685 Children.insert(Children.begin(), IIDNode);
1688 unsigned NumResults = GetNumNodeResults(Operator, CDP);
1689 TreePatternNode *Result = new TreePatternNode(Operator, Children, NumResults);
1690 Result->setName(OpName);
1692 if (!Dag->getName().empty()) {
1693 assert(Result->getName().empty());
1694 Result->setName(Dag->getName());
1699 /// SimplifyTree - See if we can simplify this tree to eliminate something that
1700 /// will never match in favor of something obvious that will. This is here
1701 /// strictly as a convenience to target authors because it allows them to write
1702 /// more type generic things and have useless type casts fold away.
1704 /// This returns true if any change is made.
1705 static bool SimplifyTree(TreePatternNode *&N) {
1709 // If we have a bitconvert with a resolved type and if the source and
1710 // destination types are the same, then the bitconvert is useless, remove it.
1711 if (N->getOperator()->getName() == "bitconvert" &&
1712 N->getExtType(0).isConcrete() &&
1713 N->getExtType(0) == N->getChild(0)->getExtType(0) &&
1714 N->getName().empty()) {
1720 // Walk all children.
1721 bool MadeChange = false;
1722 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
1723 TreePatternNode *Child = N->getChild(i);
1724 MadeChange |= SimplifyTree(Child);
1725 N->setChild(i, Child);
1732 /// InferAllTypes - Infer/propagate as many types throughout the expression
1733 /// patterns as possible. Return true if all types are inferred, false
1734 /// otherwise. Throw an exception if a type contradiction is found.
1736 InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
1737 if (NamedNodes.empty())
1738 ComputeNamedNodes();
1740 bool MadeChange = true;
1741 while (MadeChange) {
1743 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
1744 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
1745 MadeChange |= SimplifyTree(Trees[i]);
1748 // If there are constraints on our named nodes, apply them.
1749 for (StringMap<SmallVector<TreePatternNode*,1> >::iterator
1750 I = NamedNodes.begin(), E = NamedNodes.end(); I != E; ++I) {
1751 SmallVectorImpl<TreePatternNode*> &Nodes = I->second;
1753 // If we have input named node types, propagate their types to the named
1756 // FIXME: Should be error?
1757 assert(InNamedTypes->count(I->getKey()) &&
1758 "Named node in output pattern but not input pattern?");
1760 const SmallVectorImpl<TreePatternNode*> &InNodes =
1761 InNamedTypes->find(I->getKey())->second;
1763 // The input types should be fully resolved by now.
1764 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
1765 // If this node is a register class, and it is the root of the pattern
1766 // then we're mapping something onto an input register. We allow
1767 // changing the type of the input register in this case. This allows
1768 // us to match things like:
1769 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
1770 if (Nodes[i] == Trees[0] && Nodes[i]->isLeaf()) {
1771 DefInit *DI = dynamic_cast<DefInit*>(Nodes[i]->getLeafValue());
1772 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1776 assert(Nodes[i]->getNumTypes() == 1 &&
1777 InNodes[0]->getNumTypes() == 1 &&
1778 "FIXME: cannot name multiple result nodes yet");
1779 MadeChange |= Nodes[i]->UpdateNodeType(0, InNodes[0]->getExtType(0),
1784 // If there are multiple nodes with the same name, they must all have the
1786 if (I->second.size() > 1) {
1787 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
1788 TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
1789 assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
1790 "FIXME: cannot name multiple result nodes yet");
1792 MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
1793 MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
1799 bool HasUnresolvedTypes = false;
1800 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1801 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
1802 return !HasUnresolvedTypes;
1805 void TreePattern::print(raw_ostream &OS) const {
1806 OS << getRecord()->getName();
1807 if (!Args.empty()) {
1808 OS << "(" << Args[0];
1809 for (unsigned i = 1, e = Args.size(); i != e; ++i)
1810 OS << ", " << Args[i];
1815 if (Trees.size() > 1)
1817 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
1819 Trees[i]->print(OS);
1823 if (Trees.size() > 1)
1827 void TreePattern::dump() const { print(errs()); }
1829 //===----------------------------------------------------------------------===//
1830 // CodeGenDAGPatterns implementation
1833 CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) :
1834 Records(R), Target(R) {
1836 Intrinsics = LoadIntrinsics(Records, false);
1837 TgtIntrinsics = LoadIntrinsics(Records, true);
1839 ParseNodeTransforms();
1840 ParseComplexPatterns();
1841 ParsePatternFragments();
1842 ParseDefaultOperands();
1843 ParseInstructions();
1846 // Generate variants. For example, commutative patterns can match
1847 // multiple ways. Add them to PatternsToMatch as well.
1850 // Infer instruction flags. For example, we can detect loads,
1851 // stores, and side effects in many cases by examining an
1852 // instruction's pattern.
1853 InferInstructionFlags();
1856 CodeGenDAGPatterns::~CodeGenDAGPatterns() {
1857 for (pf_iterator I = PatternFragments.begin(),
1858 E = PatternFragments.end(); I != E; ++I)
1863 Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
1864 Record *N = Records.getDef(Name);
1865 if (!N || !N->isSubClassOf("SDNode")) {
1866 errs() << "Error getting SDNode '" << Name << "'!\n";
1872 // Parse all of the SDNode definitions for the target, populating SDNodes.
1873 void CodeGenDAGPatterns::ParseNodeInfo() {
1874 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
1875 while (!Nodes.empty()) {
1876 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
1880 // Get the builtin intrinsic nodes.
1881 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
1882 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
1883 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
1886 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
1887 /// map, and emit them to the file as functions.
1888 void CodeGenDAGPatterns::ParseNodeTransforms() {
1889 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
1890 while (!Xforms.empty()) {
1891 Record *XFormNode = Xforms.back();
1892 Record *SDNode = XFormNode->getValueAsDef("Opcode");
1893 std::string Code = XFormNode->getValueAsCode("XFormFunction");
1894 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
1900 void CodeGenDAGPatterns::ParseComplexPatterns() {
1901 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
1902 while (!AMs.empty()) {
1903 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
1909 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
1910 /// file, building up the PatternFragments map. After we've collected them all,
1911 /// inline fragments together as necessary, so that there are no references left
1912 /// inside a pattern fragment to a pattern fragment.
1914 void CodeGenDAGPatterns::ParsePatternFragments() {
1915 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
1917 // First step, parse all of the fragments.
1918 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1919 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
1920 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
1921 PatternFragments[Fragments[i]] = P;
1923 // Validate the argument list, converting it to set, to discard duplicates.
1924 std::vector<std::string> &Args = P->getArgList();
1925 std::set<std::string> OperandsSet(Args.begin(), Args.end());
1927 if (OperandsSet.count(""))
1928 P->error("Cannot have unnamed 'node' values in pattern fragment!");
1930 // Parse the operands list.
1931 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
1932 DefInit *OpsOp = dynamic_cast<DefInit*>(OpsList->getOperator());
1933 // Special cases: ops == outs == ins. Different names are used to
1934 // improve readability.
1936 (OpsOp->getDef()->getName() != "ops" &&
1937 OpsOp->getDef()->getName() != "outs" &&
1938 OpsOp->getDef()->getName() != "ins"))
1939 P->error("Operands list should start with '(ops ... '!");
1941 // Copy over the arguments.
1943 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
1944 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
1945 static_cast<DefInit*>(OpsList->getArg(j))->
1946 getDef()->getName() != "node")
1947 P->error("Operands list should all be 'node' values.");
1948 if (OpsList->getArgName(j).empty())
1949 P->error("Operands list should have names for each operand!");
1950 if (!OperandsSet.count(OpsList->getArgName(j)))
1951 P->error("'" + OpsList->getArgName(j) +
1952 "' does not occur in pattern or was multiply specified!");
1953 OperandsSet.erase(OpsList->getArgName(j));
1954 Args.push_back(OpsList->getArgName(j));
1957 if (!OperandsSet.empty())
1958 P->error("Operands list does not contain an entry for operand '" +
1959 *OperandsSet.begin() + "'!");
1961 // If there is a code init for this fragment, keep track of the fact that
1962 // this fragment uses it.
1963 std::string Code = Fragments[i]->getValueAsCode("Predicate");
1965 P->getOnlyTree()->addPredicateFn("Predicate_"+Fragments[i]->getName());
1967 // If there is a node transformation corresponding to this, keep track of
1969 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
1970 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
1971 P->getOnlyTree()->setTransformFn(Transform);
1974 // Now that we've parsed all of the tree fragments, do a closure on them so
1975 // that there are not references to PatFrags left inside of them.
1976 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1977 TreePattern *ThePat = PatternFragments[Fragments[i]];
1978 ThePat->InlinePatternFragments();
1980 // Infer as many types as possible. Don't worry about it if we don't infer
1981 // all of them, some may depend on the inputs of the pattern.
1983 ThePat->InferAllTypes();
1985 // If this pattern fragment is not supported by this target (no types can
1986 // satisfy its constraints), just ignore it. If the bogus pattern is
1987 // actually used by instructions, the type consistency error will be
1991 // If debugging, print out the pattern fragment result.
1992 DEBUG(ThePat->dump());
1996 void CodeGenDAGPatterns::ParseDefaultOperands() {
1997 std::vector<Record*> DefaultOps[2];
1998 DefaultOps[0] = Records.getAllDerivedDefinitions("PredicateOperand");
1999 DefaultOps[1] = Records.getAllDerivedDefinitions("OptionalDefOperand");
2001 // Find some SDNode.
2002 assert(!SDNodes.empty() && "No SDNodes parsed?");
2003 Init *SomeSDNode = new DefInit(SDNodes.begin()->first);
2005 for (unsigned iter = 0; iter != 2; ++iter) {
2006 for (unsigned i = 0, e = DefaultOps[iter].size(); i != e; ++i) {
2007 DagInit *DefaultInfo = DefaultOps[iter][i]->getValueAsDag("DefaultOps");
2009 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
2010 // SomeSDnode so that we can parse this.
2011 std::vector<std::pair<Init*, std::string> > Ops;
2012 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
2013 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
2014 DefaultInfo->getArgName(op)));
2015 DagInit *DI = new DagInit(SomeSDNode, "", Ops);
2017 // Create a TreePattern to parse this.
2018 TreePattern P(DefaultOps[iter][i], DI, false, *this);
2019 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
2021 // Copy the operands over into a DAGDefaultOperand.
2022 DAGDefaultOperand DefaultOpInfo;
2024 TreePatternNode *T = P.getTree(0);
2025 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
2026 TreePatternNode *TPN = T->getChild(op);
2027 while (TPN->ApplyTypeConstraints(P, false))
2028 /* Resolve all types */;
2030 if (TPN->ContainsUnresolvedType()) {
2032 throw "Value #" + utostr(i) + " of PredicateOperand '" +
2033 DefaultOps[iter][i]->getName() +"' doesn't have a concrete type!";
2035 throw "Value #" + utostr(i) + " of OptionalDefOperand '" +
2036 DefaultOps[iter][i]->getName() +"' doesn't have a concrete type!";
2038 DefaultOpInfo.DefaultOps.push_back(TPN);
2041 // Insert it into the DefaultOperands map so we can find it later.
2042 DefaultOperands[DefaultOps[iter][i]] = DefaultOpInfo;
2047 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
2048 /// instruction input. Return true if this is a real use.
2049 static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
2050 std::map<std::string, TreePatternNode*> &InstInputs) {
2051 // No name -> not interesting.
2052 if (Pat->getName().empty()) {
2053 if (Pat->isLeaf()) {
2054 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
2055 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
2056 I->error("Input " + DI->getDef()->getName() + " must be named!");
2062 if (Pat->isLeaf()) {
2063 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
2064 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
2067 Rec = Pat->getOperator();
2070 // SRCVALUE nodes are ignored.
2071 if (Rec->getName() == "srcvalue")
2074 TreePatternNode *&Slot = InstInputs[Pat->getName()];
2080 if (Slot->isLeaf()) {
2081 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
2083 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
2084 SlotRec = Slot->getOperator();
2087 // Ensure that the inputs agree if we've already seen this input.
2089 I->error("All $" + Pat->getName() + " inputs must agree with each other");
2090 if (Slot->getExtTypes() != Pat->getExtTypes())
2091 I->error("All $" + Pat->getName() + " inputs must agree with each other");
2095 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
2096 /// part of "I", the instruction), computing the set of inputs and outputs of
2097 /// the pattern. Report errors if we see anything naughty.
2098 void CodeGenDAGPatterns::
2099 FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
2100 std::map<std::string, TreePatternNode*> &InstInputs,
2101 std::map<std::string, TreePatternNode*>&InstResults,
2102 std::vector<Record*> &InstImpResults) {
2103 if (Pat->isLeaf()) {
2104 bool isUse = HandleUse(I, Pat, InstInputs);
2105 if (!isUse && Pat->getTransformFn())
2106 I->error("Cannot specify a transform function for a non-input value!");
2110 if (Pat->getOperator()->getName() == "implicit") {
2111 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2112 TreePatternNode *Dest = Pat->getChild(i);
2113 if (!Dest->isLeaf())
2114 I->error("implicitly defined value should be a register!");
2116 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
2117 if (!Val || !Val->getDef()->isSubClassOf("Register"))
2118 I->error("implicitly defined value should be a register!");
2119 InstImpResults.push_back(Val->getDef());
2124 if (Pat->getOperator()->getName() != "set") {
2125 // If this is not a set, verify that the children nodes are not void typed,
2127 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2128 if (Pat->getChild(i)->getNumTypes() == 0)
2129 I->error("Cannot have void nodes inside of patterns!");
2130 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
2134 // If this is a non-leaf node with no children, treat it basically as if
2135 // it were a leaf. This handles nodes like (imm).
2136 bool isUse = HandleUse(I, Pat, InstInputs);
2138 if (!isUse && Pat->getTransformFn())
2139 I->error("Cannot specify a transform function for a non-input value!");
2143 // Otherwise, this is a set, validate and collect instruction results.
2144 if (Pat->getNumChildren() == 0)
2145 I->error("set requires operands!");
2147 if (Pat->getTransformFn())
2148 I->error("Cannot specify a transform function on a set node!");
2150 // Check the set destinations.
2151 unsigned NumDests = Pat->getNumChildren()-1;
2152 for (unsigned i = 0; i != NumDests; ++i) {
2153 TreePatternNode *Dest = Pat->getChild(i);
2154 if (!Dest->isLeaf())
2155 I->error("set destination should be a register!");
2157 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
2159 I->error("set destination should be a register!");
2161 if (Val->getDef()->isSubClassOf("RegisterClass") ||
2162 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
2163 if (Dest->getName().empty())
2164 I->error("set destination must have a name!");
2165 if (InstResults.count(Dest->getName()))
2166 I->error("cannot set '" + Dest->getName() +"' multiple times");
2167 InstResults[Dest->getName()] = Dest;
2168 } else if (Val->getDef()->isSubClassOf("Register")) {
2169 InstImpResults.push_back(Val->getDef());
2171 I->error("set destination should be a register!");
2175 // Verify and collect info from the computation.
2176 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
2177 InstInputs, InstResults, InstImpResults);
2180 //===----------------------------------------------------------------------===//
2181 // Instruction Analysis
2182 //===----------------------------------------------------------------------===//
2184 class InstAnalyzer {
2185 const CodeGenDAGPatterns &CDP;
2188 bool &HasSideEffects;
2191 InstAnalyzer(const CodeGenDAGPatterns &cdp,
2192 bool &maystore, bool &mayload, bool &hse, bool &isv)
2193 : CDP(cdp), mayStore(maystore), mayLoad(mayload), HasSideEffects(hse),
2197 /// Analyze - Analyze the specified instruction, returning true if the
2198 /// instruction had a pattern.
2199 bool Analyze(Record *InstRecord) {
2200 const TreePattern *Pattern = CDP.getInstruction(InstRecord).getPattern();
2203 return false; // No pattern.
2206 // FIXME: Assume only the first tree is the pattern. The others are clobber
2208 AnalyzeNode(Pattern->getTree(0));
2213 void AnalyzeNode(const TreePatternNode *N) {
2215 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
2216 Record *LeafRec = DI->getDef();
2217 // Handle ComplexPattern leaves.
2218 if (LeafRec->isSubClassOf("ComplexPattern")) {
2219 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
2220 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
2221 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
2222 if (CP.hasProperty(SDNPSideEffect)) HasSideEffects = true;
2228 // Analyze children.
2229 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2230 AnalyzeNode(N->getChild(i));
2232 // Ignore set nodes, which are not SDNodes.
2233 if (N->getOperator()->getName() == "set")
2236 // Get information about the SDNode for the operator.
2237 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N->getOperator());
2239 // Notice properties of the node.
2240 if (OpInfo.hasProperty(SDNPMayStore)) mayStore = true;
2241 if (OpInfo.hasProperty(SDNPMayLoad)) mayLoad = true;
2242 if (OpInfo.hasProperty(SDNPSideEffect)) HasSideEffects = true;
2243 if (OpInfo.hasProperty(SDNPVariadic)) IsVariadic = true;
2245 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
2246 // If this is an intrinsic, analyze it.
2247 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
2248 mayLoad = true;// These may load memory.
2250 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteArgMem)
2251 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
2253 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem)
2254 // WriteMem intrinsics can have other strange effects.
2255 HasSideEffects = true;
2261 static void InferFromPattern(const CodeGenInstruction &Inst,
2262 bool &MayStore, bool &MayLoad,
2263 bool &HasSideEffects, bool &IsVariadic,
2264 const CodeGenDAGPatterns &CDP) {
2265 MayStore = MayLoad = HasSideEffects = IsVariadic = false;
2268 InstAnalyzer(CDP, MayStore, MayLoad, HasSideEffects, IsVariadic)
2269 .Analyze(Inst.TheDef);
2271 // InstAnalyzer only correctly analyzes mayStore/mayLoad so far.
2272 if (Inst.mayStore) { // If the .td file explicitly sets mayStore, use it.
2273 // If we decided that this is a store from the pattern, then the .td file
2274 // entry is redundant.
2277 "Warning: mayStore flag explicitly set on instruction '%s'"
2278 " but flag already inferred from pattern.\n",
2279 Inst.TheDef->getName().c_str());
2283 if (Inst.mayLoad) { // If the .td file explicitly sets mayLoad, use it.
2284 // If we decided that this is a load from the pattern, then the .td file
2285 // entry is redundant.
2288 "Warning: mayLoad flag explicitly set on instruction '%s'"
2289 " but flag already inferred from pattern.\n",
2290 Inst.TheDef->getName().c_str());
2294 if (Inst.neverHasSideEffects) {
2296 fprintf(stderr, "Warning: neverHasSideEffects set on instruction '%s' "
2297 "which already has a pattern\n", Inst.TheDef->getName().c_str());
2298 HasSideEffects = false;
2301 if (Inst.hasSideEffects) {
2303 fprintf(stderr, "Warning: hasSideEffects set on instruction '%s' "
2304 "which already inferred this.\n", Inst.TheDef->getName().c_str());
2305 HasSideEffects = true;
2308 if (Inst.Operands.isVariadic)
2309 IsVariadic = true; // Can warn if we want.
2312 /// ParseInstructions - Parse all of the instructions, inlining and resolving
2313 /// any fragments involved. This populates the Instructions list with fully
2314 /// resolved instructions.
2315 void CodeGenDAGPatterns::ParseInstructions() {
2316 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
2318 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
2321 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
2322 LI = Instrs[i]->getValueAsListInit("Pattern");
2324 // If there is no pattern, only collect minimal information about the
2325 // instruction for its operand list. We have to assume that there is one
2326 // result, as we have no detailed info.
2327 if (!LI || LI->getSize() == 0) {
2328 std::vector<Record*> Results;
2329 std::vector<Record*> Operands;
2331 CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
2333 if (InstInfo.Operands.size() != 0) {
2334 if (InstInfo.Operands.NumDefs == 0) {
2335 // These produce no results
2336 for (unsigned j = 0, e = InstInfo.Operands.size(); j < e; ++j)
2337 Operands.push_back(InstInfo.Operands[j].Rec);
2339 // Assume the first operand is the result.
2340 Results.push_back(InstInfo.Operands[0].Rec);
2342 // The rest are inputs.
2343 for (unsigned j = 1, e = InstInfo.Operands.size(); j < e; ++j)
2344 Operands.push_back(InstInfo.Operands[j].Rec);
2348 // Create and insert the instruction.
2349 std::vector<Record*> ImpResults;
2350 Instructions.insert(std::make_pair(Instrs[i],
2351 DAGInstruction(0, Results, Operands, ImpResults)));
2352 continue; // no pattern.
2355 // Parse the instruction.
2356 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
2357 // Inline pattern fragments into it.
2358 I->InlinePatternFragments();
2360 // Infer as many types as possible. If we cannot infer all of them, we can
2361 // never do anything with this instruction pattern: report it to the user.
2362 if (!I->InferAllTypes())
2363 I->error("Could not infer all types in pattern!");
2365 // InstInputs - Keep track of all of the inputs of the instruction, along
2366 // with the record they are declared as.
2367 std::map<std::string, TreePatternNode*> InstInputs;
2369 // InstResults - Keep track of all the virtual registers that are 'set'
2370 // in the instruction, including what reg class they are.
2371 std::map<std::string, TreePatternNode*> InstResults;
2373 std::vector<Record*> InstImpResults;
2375 // Verify that the top-level forms in the instruction are of void type, and
2376 // fill in the InstResults map.
2377 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
2378 TreePatternNode *Pat = I->getTree(j);
2379 if (Pat->getNumTypes() != 0)
2380 I->error("Top-level forms in instruction pattern should have"
2383 // Find inputs and outputs, and verify the structure of the uses/defs.
2384 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
2388 // Now that we have inputs and outputs of the pattern, inspect the operands
2389 // list for the instruction. This determines the order that operands are
2390 // added to the machine instruction the node corresponds to.
2391 unsigned NumResults = InstResults.size();
2393 // Parse the operands list from the (ops) list, validating it.
2394 assert(I->getArgList().empty() && "Args list should still be empty here!");
2395 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]);
2397 // Check that all of the results occur first in the list.
2398 std::vector<Record*> Results;
2399 TreePatternNode *Res0Node = 0;
2400 for (unsigned i = 0; i != NumResults; ++i) {
2401 if (i == CGI.Operands.size())
2402 I->error("'" + InstResults.begin()->first +
2403 "' set but does not appear in operand list!");
2404 const std::string &OpName = CGI.Operands[i].Name;
2406 // Check that it exists in InstResults.
2407 TreePatternNode *RNode = InstResults[OpName];
2409 I->error("Operand $" + OpName + " does not exist in operand list!");
2413 Record *R = dynamic_cast<DefInit*>(RNode->getLeafValue())->getDef();
2415 I->error("Operand $" + OpName + " should be a set destination: all "
2416 "outputs must occur before inputs in operand list!");
2418 if (CGI.Operands[i].Rec != R)
2419 I->error("Operand $" + OpName + " class mismatch!");
2421 // Remember the return type.
2422 Results.push_back(CGI.Operands[i].Rec);
2424 // Okay, this one checks out.
2425 InstResults.erase(OpName);
2428 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
2429 // the copy while we're checking the inputs.
2430 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
2432 std::vector<TreePatternNode*> ResultNodeOperands;
2433 std::vector<Record*> Operands;
2434 for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
2435 CGIOperandList::OperandInfo &Op = CGI.Operands[i];
2436 const std::string &OpName = Op.Name;
2438 I->error("Operand #" + utostr(i) + " in operands list has no name!");
2440 if (!InstInputsCheck.count(OpName)) {
2441 // If this is an predicate operand or optional def operand with an
2442 // DefaultOps set filled in, we can ignore this. When we codegen it,
2443 // we will do so as always executed.
2444 if (Op.Rec->isSubClassOf("PredicateOperand") ||
2445 Op.Rec->isSubClassOf("OptionalDefOperand")) {
2446 // Does it have a non-empty DefaultOps field? If so, ignore this
2448 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
2451 I->error("Operand $" + OpName +
2452 " does not appear in the instruction pattern");
2454 TreePatternNode *InVal = InstInputsCheck[OpName];
2455 InstInputsCheck.erase(OpName); // It occurred, remove from map.
2457 if (InVal->isLeaf() &&
2458 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
2459 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
2460 if (Op.Rec != InRec && !InRec->isSubClassOf("ComplexPattern"))
2461 I->error("Operand $" + OpName + "'s register class disagrees"
2462 " between the operand and pattern");
2464 Operands.push_back(Op.Rec);
2466 // Construct the result for the dest-pattern operand list.
2467 TreePatternNode *OpNode = InVal->clone();
2469 // No predicate is useful on the result.
2470 OpNode->clearPredicateFns();
2472 // Promote the xform function to be an explicit node if set.
2473 if (Record *Xform = OpNode->getTransformFn()) {
2474 OpNode->setTransformFn(0);
2475 std::vector<TreePatternNode*> Children;
2476 Children.push_back(OpNode);
2477 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
2480 ResultNodeOperands.push_back(OpNode);
2483 if (!InstInputsCheck.empty())
2484 I->error("Input operand $" + InstInputsCheck.begin()->first +
2485 " occurs in pattern but not in operands list!");
2487 TreePatternNode *ResultPattern =
2488 new TreePatternNode(I->getRecord(), ResultNodeOperands,
2489 GetNumNodeResults(I->getRecord(), *this));
2490 // Copy fully inferred output node type to instruction result pattern.
2491 for (unsigned i = 0; i != NumResults; ++i)
2492 ResultPattern->setType(i, Res0Node->getExtType(i));
2494 // Create and insert the instruction.
2495 // FIXME: InstImpResults should not be part of DAGInstruction.
2496 DAGInstruction TheInst(I, Results, Operands, InstImpResults);
2497 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
2499 // Use a temporary tree pattern to infer all types and make sure that the
2500 // constructed result is correct. This depends on the instruction already
2501 // being inserted into the Instructions map.
2502 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
2503 Temp.InferAllTypes(&I->getNamedNodesMap());
2505 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
2506 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
2511 // If we can, convert the instructions to be patterns that are matched!
2512 for (std::map<Record*, DAGInstruction, RecordPtrCmp>::iterator II =
2513 Instructions.begin(),
2514 E = Instructions.end(); II != E; ++II) {
2515 DAGInstruction &TheInst = II->second;
2516 const TreePattern *I = TheInst.getPattern();
2517 if (I == 0) continue; // No pattern.
2519 // FIXME: Assume only the first tree is the pattern. The others are clobber
2521 TreePatternNode *Pattern = I->getTree(0);
2522 TreePatternNode *SrcPattern;
2523 if (Pattern->getOperator()->getName() == "set") {
2524 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
2526 // Not a set (store or something?)
2527 SrcPattern = Pattern;
2530 Record *Instr = II->first;
2531 AddPatternToMatch(I,
2532 PatternToMatch(Instr,
2533 Instr->getValueAsListInit("Predicates"),
2535 TheInst.getResultPattern(),
2536 TheInst.getImpResults(),
2537 Instr->getValueAsInt("AddedComplexity"),
2543 typedef std::pair<const TreePatternNode*, unsigned> NameRecord;
2545 static void FindNames(const TreePatternNode *P,
2546 std::map<std::string, NameRecord> &Names,
2547 const TreePattern *PatternTop) {
2548 if (!P->getName().empty()) {
2549 NameRecord &Rec = Names[P->getName()];
2550 // If this is the first instance of the name, remember the node.
2551 if (Rec.second++ == 0)
2553 else if (Rec.first->getExtTypes() != P->getExtTypes())
2554 PatternTop->error("repetition of value: $" + P->getName() +
2555 " where different uses have different types!");
2559 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
2560 FindNames(P->getChild(i), Names, PatternTop);
2564 void CodeGenDAGPatterns::AddPatternToMatch(const TreePattern *Pattern,
2565 const PatternToMatch &PTM) {
2566 // Do some sanity checking on the pattern we're about to match.
2568 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this))
2569 Pattern->error("Pattern can never match: " + Reason);
2571 // If the source pattern's root is a complex pattern, that complex pattern
2572 // must specify the nodes it can potentially match.
2573 if (const ComplexPattern *CP =
2574 PTM.getSrcPattern()->getComplexPatternInfo(*this))
2575 if (CP->getRootNodes().empty())
2576 Pattern->error("ComplexPattern at root must specify list of opcodes it"
2580 // Find all of the named values in the input and output, ensure they have the
2582 std::map<std::string, NameRecord> SrcNames, DstNames;
2583 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
2584 FindNames(PTM.getDstPattern(), DstNames, Pattern);
2586 // Scan all of the named values in the destination pattern, rejecting them if
2587 // they don't exist in the input pattern.
2588 for (std::map<std::string, NameRecord>::iterator
2589 I = DstNames.begin(), E = DstNames.end(); I != E; ++I) {
2590 if (SrcNames[I->first].first == 0)
2591 Pattern->error("Pattern has input without matching name in output: $" +
2595 // Scan all of the named values in the source pattern, rejecting them if the
2596 // name isn't used in the dest, and isn't used to tie two values together.
2597 for (std::map<std::string, NameRecord>::iterator
2598 I = SrcNames.begin(), E = SrcNames.end(); I != E; ++I)
2599 if (DstNames[I->first].first == 0 && SrcNames[I->first].second == 1)
2600 Pattern->error("Pattern has dead named input: $" + I->first);
2602 PatternsToMatch.push_back(PTM);
2607 void CodeGenDAGPatterns::InferInstructionFlags() {
2608 const std::vector<const CodeGenInstruction*> &Instructions =
2609 Target.getInstructionsByEnumValue();
2610 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
2611 CodeGenInstruction &InstInfo =
2612 const_cast<CodeGenInstruction &>(*Instructions[i]);
2613 // Determine properties of the instruction from its pattern.
2614 bool MayStore, MayLoad, HasSideEffects, IsVariadic;
2615 InferFromPattern(InstInfo, MayStore, MayLoad, HasSideEffects, IsVariadic,
2617 InstInfo.mayStore = MayStore;
2618 InstInfo.mayLoad = MayLoad;
2619 InstInfo.hasSideEffects = HasSideEffects;
2620 InstInfo.Operands.isVariadic = IsVariadic;
2624 /// Given a pattern result with an unresolved type, see if we can find one
2625 /// instruction with an unresolved result type. Force this result type to an
2626 /// arbitrary element if it's possible types to converge results.
2627 static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
2631 // Analyze children.
2632 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2633 if (ForceArbitraryInstResultType(N->getChild(i), TP))
2636 if (!N->getOperator()->isSubClassOf("Instruction"))
2639 // If this type is already concrete or completely unknown we can't do
2641 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
2642 if (N->getExtType(i).isCompletelyUnknown() || N->getExtType(i).isConcrete())
2645 // Otherwise, force its type to the first possibility (an arbitrary choice).
2646 if (N->getExtType(i).MergeInTypeInfo(N->getExtType(i).getTypeList()[0], TP))
2653 void CodeGenDAGPatterns::ParsePatterns() {
2654 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
2656 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
2657 Record *CurPattern = Patterns[i];
2658 DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
2659 TreePattern *Pattern = new TreePattern(CurPattern, Tree, true, *this);
2661 // Inline pattern fragments into it.
2662 Pattern->InlinePatternFragments();
2664 ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
2665 if (LI->getSize() == 0) continue; // no pattern.
2667 // Parse the instruction.
2668 TreePattern *Result = new TreePattern(CurPattern, LI, false, *this);
2670 // Inline pattern fragments into it.
2671 Result->InlinePatternFragments();
2673 if (Result->getNumTrees() != 1)
2674 Result->error("Cannot handle instructions producing instructions "
2675 "with temporaries yet!");
2677 bool IterateInference;
2678 bool InferredAllPatternTypes, InferredAllResultTypes;
2680 // Infer as many types as possible. If we cannot infer all of them, we
2681 // can never do anything with this pattern: report it to the user.
2682 InferredAllPatternTypes =
2683 Pattern->InferAllTypes(&Pattern->getNamedNodesMap());
2685 // Infer as many types as possible. If we cannot infer all of them, we
2686 // can never do anything with this pattern: report it to the user.
2687 InferredAllResultTypes =
2688 Result->InferAllTypes(&Pattern->getNamedNodesMap());
2690 IterateInference = false;
2692 // Apply the type of the result to the source pattern. This helps us
2693 // resolve cases where the input type is known to be a pointer type (which
2694 // is considered resolved), but the result knows it needs to be 32- or
2695 // 64-bits. Infer the other way for good measure.
2696 for (unsigned i = 0, e = std::min(Result->getTree(0)->getNumTypes(),
2697 Pattern->getTree(0)->getNumTypes());
2699 IterateInference = Pattern->getTree(0)->
2700 UpdateNodeType(i, Result->getTree(0)->getExtType(i), *Result);
2701 IterateInference |= Result->getTree(0)->
2702 UpdateNodeType(i, Pattern->getTree(0)->getExtType(i), *Result);
2705 // If our iteration has converged and the input pattern's types are fully
2706 // resolved but the result pattern is not fully resolved, we may have a
2707 // situation where we have two instructions in the result pattern and
2708 // the instructions require a common register class, but don't care about
2709 // what actual MVT is used. This is actually a bug in our modelling:
2710 // output patterns should have register classes, not MVTs.
2712 // In any case, to handle this, we just go through and disambiguate some
2713 // arbitrary types to the result pattern's nodes.
2714 if (!IterateInference && InferredAllPatternTypes &&
2715 !InferredAllResultTypes)
2716 IterateInference = ForceArbitraryInstResultType(Result->getTree(0),
2718 } while (IterateInference);
2720 // Verify that we inferred enough types that we can do something with the
2721 // pattern and result. If these fire the user has to add type casts.
2722 if (!InferredAllPatternTypes)
2723 Pattern->error("Could not infer all types in pattern!");
2724 if (!InferredAllResultTypes) {
2726 Result->error("Could not infer all types in pattern result!");
2729 // Validate that the input pattern is correct.
2730 std::map<std::string, TreePatternNode*> InstInputs;
2731 std::map<std::string, TreePatternNode*> InstResults;
2732 std::vector<Record*> InstImpResults;
2733 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
2734 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
2735 InstInputs, InstResults,
2738 // Promote the xform function to be an explicit node if set.
2739 TreePatternNode *DstPattern = Result->getOnlyTree();
2740 std::vector<TreePatternNode*> ResultNodeOperands;
2741 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
2742 TreePatternNode *OpNode = DstPattern->getChild(ii);
2743 if (Record *Xform = OpNode->getTransformFn()) {
2744 OpNode->setTransformFn(0);
2745 std::vector<TreePatternNode*> Children;
2746 Children.push_back(OpNode);
2747 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
2749 ResultNodeOperands.push_back(OpNode);
2751 DstPattern = Result->getOnlyTree();
2752 if (!DstPattern->isLeaf())
2753 DstPattern = new TreePatternNode(DstPattern->getOperator(),
2755 DstPattern->getNumTypes());
2757 for (unsigned i = 0, e = Result->getOnlyTree()->getNumTypes(); i != e; ++i)
2758 DstPattern->setType(i, Result->getOnlyTree()->getExtType(i));
2760 TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
2761 Temp.InferAllTypes();
2764 AddPatternToMatch(Pattern,
2765 PatternToMatch(CurPattern,
2766 CurPattern->getValueAsListInit("Predicates"),
2767 Pattern->getTree(0),
2768 Temp.getOnlyTree(), InstImpResults,
2769 CurPattern->getValueAsInt("AddedComplexity"),
2770 CurPattern->getID()));
2774 /// CombineChildVariants - Given a bunch of permutations of each child of the
2775 /// 'operator' node, put them together in all possible ways.
2776 static void CombineChildVariants(TreePatternNode *Orig,
2777 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
2778 std::vector<TreePatternNode*> &OutVariants,
2779 CodeGenDAGPatterns &CDP,
2780 const MultipleUseVarSet &DepVars) {
2781 // Make sure that each operand has at least one variant to choose from.
2782 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2783 if (ChildVariants[i].empty())
2786 // The end result is an all-pairs construction of the resultant pattern.
2787 std::vector<unsigned> Idxs;
2788 Idxs.resize(ChildVariants.size());
2792 DEBUG(if (!Idxs.empty()) {
2793 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
2794 for (unsigned i = 0; i < Idxs.size(); ++i) {
2795 errs() << Idxs[i] << " ";
2800 // Create the variant and add it to the output list.
2801 std::vector<TreePatternNode*> NewChildren;
2802 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2803 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
2804 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren,
2805 Orig->getNumTypes());
2807 // Copy over properties.
2808 R->setName(Orig->getName());
2809 R->setPredicateFns(Orig->getPredicateFns());
2810 R->setTransformFn(Orig->getTransformFn());
2811 for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
2812 R->setType(i, Orig->getExtType(i));
2814 // If this pattern cannot match, do not include it as a variant.
2815 std::string ErrString;
2816 if (!R->canPatternMatch(ErrString, CDP)) {
2819 bool AlreadyExists = false;
2821 // Scan to see if this pattern has already been emitted. We can get
2822 // duplication due to things like commuting:
2823 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
2824 // which are the same pattern. Ignore the dups.
2825 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
2826 if (R->isIsomorphicTo(OutVariants[i], DepVars)) {
2827 AlreadyExists = true;
2834 OutVariants.push_back(R);
2837 // Increment indices to the next permutation by incrementing the
2838 // indicies from last index backward, e.g., generate the sequence
2839 // [0, 0], [0, 1], [1, 0], [1, 1].
2841 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
2842 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
2847 NotDone = (IdxsIdx >= 0);
2851 /// CombineChildVariants - A helper function for binary operators.
2853 static void CombineChildVariants(TreePatternNode *Orig,
2854 const std::vector<TreePatternNode*> &LHS,
2855 const std::vector<TreePatternNode*> &RHS,
2856 std::vector<TreePatternNode*> &OutVariants,
2857 CodeGenDAGPatterns &CDP,
2858 const MultipleUseVarSet &DepVars) {
2859 std::vector<std::vector<TreePatternNode*> > ChildVariants;
2860 ChildVariants.push_back(LHS);
2861 ChildVariants.push_back(RHS);
2862 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
2866 static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
2867 std::vector<TreePatternNode *> &Children) {
2868 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
2869 Record *Operator = N->getOperator();
2871 // Only permit raw nodes.
2872 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
2873 N->getTransformFn()) {
2874 Children.push_back(N);
2878 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
2879 Children.push_back(N->getChild(0));
2881 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
2883 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
2884 Children.push_back(N->getChild(1));
2886 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
2889 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
2890 /// the (potentially recursive) pattern by using algebraic laws.
2892 static void GenerateVariantsOf(TreePatternNode *N,
2893 std::vector<TreePatternNode*> &OutVariants,
2894 CodeGenDAGPatterns &CDP,
2895 const MultipleUseVarSet &DepVars) {
2896 // We cannot permute leaves.
2898 OutVariants.push_back(N);
2902 // Look up interesting info about the node.
2903 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
2905 // If this node is associative, re-associate.
2906 if (NodeInfo.hasProperty(SDNPAssociative)) {
2907 // Re-associate by pulling together all of the linked operators
2908 std::vector<TreePatternNode*> MaximalChildren;
2909 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
2911 // Only handle child sizes of 3. Otherwise we'll end up trying too many
2913 if (MaximalChildren.size() == 3) {
2914 // Find the variants of all of our maximal children.
2915 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
2916 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
2917 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
2918 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
2920 // There are only two ways we can permute the tree:
2921 // (A op B) op C and A op (B op C)
2922 // Within these forms, we can also permute A/B/C.
2924 // Generate legal pair permutations of A/B/C.
2925 std::vector<TreePatternNode*> ABVariants;
2926 std::vector<TreePatternNode*> BAVariants;
2927 std::vector<TreePatternNode*> ACVariants;
2928 std::vector<TreePatternNode*> CAVariants;
2929 std::vector<TreePatternNode*> BCVariants;
2930 std::vector<TreePatternNode*> CBVariants;
2931 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
2932 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
2933 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
2934 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
2935 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
2936 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
2938 // Combine those into the result: (x op x) op x
2939 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
2940 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
2941 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
2942 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
2943 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
2944 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
2946 // Combine those into the result: x op (x op x)
2947 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
2948 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
2949 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
2950 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
2951 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
2952 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
2957 // Compute permutations of all children.
2958 std::vector<std::vector<TreePatternNode*> > ChildVariants;
2959 ChildVariants.resize(N->getNumChildren());
2960 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2961 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
2963 // Build all permutations based on how the children were formed.
2964 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
2966 // If this node is commutative, consider the commuted order.
2967 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
2968 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
2969 assert((N->getNumChildren()==2 || isCommIntrinsic) &&
2970 "Commutative but doesn't have 2 children!");
2971 // Don't count children which are actually register references.
2973 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2974 TreePatternNode *Child = N->getChild(i);
2975 if (Child->isLeaf())
2976 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2977 Record *RR = DI->getDef();
2978 if (RR->isSubClassOf("Register"))
2983 // Consider the commuted order.
2984 if (isCommIntrinsic) {
2985 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
2986 // operands are the commutative operands, and there might be more operands
2989 "Commutative intrinsic should have at least 3 childrean!");
2990 std::vector<std::vector<TreePatternNode*> > Variants;
2991 Variants.push_back(ChildVariants[0]); // Intrinsic id.
2992 Variants.push_back(ChildVariants[2]);
2993 Variants.push_back(ChildVariants[1]);
2994 for (unsigned i = 3; i != NC; ++i)
2995 Variants.push_back(ChildVariants[i]);
2996 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
2998 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
2999 OutVariants, CDP, DepVars);
3004 // GenerateVariants - Generate variants. For example, commutative patterns can
3005 // match multiple ways. Add them to PatternsToMatch as well.
3006 void CodeGenDAGPatterns::GenerateVariants() {
3007 DEBUG(errs() << "Generating instruction variants.\n");
3009 // Loop over all of the patterns we've collected, checking to see if we can
3010 // generate variants of the instruction, through the exploitation of
3011 // identities. This permits the target to provide aggressive matching without
3012 // the .td file having to contain tons of variants of instructions.
3014 // Note that this loop adds new patterns to the PatternsToMatch list, but we
3015 // intentionally do not reconsider these. Any variants of added patterns have
3016 // already been added.
3018 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
3019 MultipleUseVarSet DepVars;
3020 std::vector<TreePatternNode*> Variants;
3021 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
3022 DEBUG(errs() << "Dependent/multiply used variables: ");
3023 DEBUG(DumpDepVars(DepVars));
3024 DEBUG(errs() << "\n");
3025 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this,
3028 assert(!Variants.empty() && "Must create at least original variant!");
3029 Variants.erase(Variants.begin()); // Remove the original pattern.
3031 if (Variants.empty()) // No variants for this pattern.
3034 DEBUG(errs() << "FOUND VARIANTS OF: ";
3035 PatternsToMatch[i].getSrcPattern()->dump();
3038 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
3039 TreePatternNode *Variant = Variants[v];
3041 DEBUG(errs() << " VAR#" << v << ": ";
3045 // Scan to see if an instruction or explicit pattern already matches this.
3046 bool AlreadyExists = false;
3047 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
3048 // Skip if the top level predicates do not match.
3049 if (PatternsToMatch[i].getPredicates() !=
3050 PatternsToMatch[p].getPredicates())
3052 // Check to see if this variant already exists.
3053 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),
3055 DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
3056 AlreadyExists = true;
3060 // If we already have it, ignore the variant.
3061 if (AlreadyExists) continue;
3063 // Otherwise, add it to the list of patterns we have.
3065 push_back(PatternToMatch(PatternsToMatch[i].getSrcRecord(),
3066 PatternsToMatch[i].getPredicates(),
3067 Variant, PatternsToMatch[i].getDstPattern(),
3068 PatternsToMatch[i].getDstRegs(),
3069 PatternsToMatch[i].getAddedComplexity(),
3070 Record::getNewUID()));
3073 DEBUG(errs() << "\n");