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();
32 static inline bool isFloatingPoint(MVT::SimpleValueType VT) {
33 return EVT(VT).isFloatingPoint();
36 static inline bool isVector(MVT::SimpleValueType VT) {
37 return EVT(VT).isVector();
40 EEVT::TypeSet::TypeSet(MVT::SimpleValueType VT, TreePattern &TP) {
43 else if (VT == MVT::fAny)
44 EnforceFloatingPoint(TP);
45 else if (VT == MVT::vAny)
48 assert((VT < MVT::LAST_VALUETYPE || VT == MVT::iPTR ||
49 VT == MVT::iPTRAny) && "Not a concrete type!");
50 TypeVec.push_back(VT);
55 EEVT::TypeSet::TypeSet(const std::vector<MVT::SimpleValueType> &VTList) {
56 assert(!VTList.empty() && "empty list?");
57 TypeVec.append(VTList.begin(), VTList.end());
60 assert(VTList[0] != MVT::iAny && VTList[0] != MVT::vAny &&
61 VTList[0] != MVT::fAny);
64 array_pod_sort(TypeVec.begin(), TypeVec.end());
65 TypeVec.erase(std::unique(TypeVec.begin(), TypeVec.end()), TypeVec.end());
68 /// FillWithPossibleTypes - Set to all legal types and return true, only valid
69 /// on completely unknown type sets.
70 bool EEVT::TypeSet::FillWithPossibleTypes(TreePattern &TP) {
71 assert(isCompletelyUnknown());
72 *this = TP.getDAGPatterns().getTargetInfo().getLegalValueTypes();
76 /// hasIntegerTypes - Return true if this TypeSet contains iAny or an
77 /// integer value type.
78 bool EEVT::TypeSet::hasIntegerTypes() const {
79 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
80 if (isInteger(TypeVec[i]))
85 /// hasFloatingPointTypes - Return true if this TypeSet contains an fAny or
86 /// a floating point value type.
87 bool EEVT::TypeSet::hasFloatingPointTypes() const {
88 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
89 if (isFloatingPoint(TypeVec[i]))
94 /// hasVectorTypes - Return true if this TypeSet contains a vAny or a vector
96 bool EEVT::TypeSet::hasVectorTypes() const {
97 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
98 if (isVector(TypeVec[i]))
104 std::string EEVT::TypeSet::getName() const {
105 if (TypeVec.empty()) return "<empty>";
109 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i) {
110 std::string VTName = llvm::getEnumName(TypeVec[i]);
111 // Strip off MVT:: prefix if present.
112 if (VTName.substr(0,5) == "MVT::")
113 VTName = VTName.substr(5);
114 if (i) Result += ':';
118 if (TypeVec.size() == 1)
120 return "{" + Result + "}";
123 /// MergeInTypeInfo - This merges in type information from the specified
124 /// argument. If 'this' changes, it returns true. If the two types are
125 /// contradictory (e.g. merge f32 into i32) then this throws an exception.
126 bool EEVT::TypeSet::MergeInTypeInfo(const EEVT::TypeSet &InVT, TreePattern &TP){
127 if (InVT.isCompletelyUnknown() || *this == InVT)
130 if (isCompletelyUnknown()) {
135 assert(TypeVec.size() >= 1 && InVT.TypeVec.size() >= 1 && "No unknowns");
137 // Handle the abstract cases, seeing if we can resolve them better.
138 switch (TypeVec[0]) {
142 if (InVT.hasIntegerTypes()) {
143 EEVT::TypeSet InCopy(InVT);
144 InCopy.EnforceInteger(TP);
145 InCopy.EnforceScalar(TP);
147 if (InCopy.isConcrete()) {
148 // If the RHS has one integer type, upgrade iPTR to i32.
149 TypeVec[0] = InVT.TypeVec[0];
153 // If the input has multiple scalar integers, this doesn't add any info.
154 if (!InCopy.isCompletelyUnknown())
160 // If the input constraint is iAny/iPTR and this is an integer type list,
161 // remove non-integer types from the list.
162 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
164 bool MadeChange = EnforceInteger(TP);
166 // If we're merging in iPTR/iPTRAny and the node currently has a list of
167 // multiple different integer types, replace them with a single iPTR.
168 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
169 TypeVec.size() != 1) {
171 TypeVec[0] = InVT.TypeVec[0];
178 // If this is a type list and the RHS is a typelist as well, eliminate entries
179 // from this list that aren't in the other one.
180 bool MadeChange = false;
181 TypeSet InputSet(*this);
183 for (unsigned i = 0; i != TypeVec.size(); ++i) {
185 for (unsigned j = 0, e = InVT.TypeVec.size(); j != e; ++j)
186 if (TypeVec[i] == InVT.TypeVec[j]) {
191 if (InInVT) continue;
192 TypeVec.erase(TypeVec.begin()+i--);
196 // If we removed all of our types, we have a type contradiction.
197 if (!TypeVec.empty())
200 // FIXME: Really want an SMLoc here!
201 TP.error("Type inference contradiction found, merging '" +
202 InVT.getName() + "' into '" + InputSet.getName() + "'");
203 return true; // unreachable
206 /// EnforceInteger - Remove all non-integer types from this set.
207 bool EEVT::TypeSet::EnforceInteger(TreePattern &TP) {
208 TypeSet InputSet(*this);
209 bool MadeChange = false;
211 // If we know nothing, then get the full set.
213 MadeChange = FillWithPossibleTypes(TP);
215 if (!hasFloatingPointTypes())
218 // Filter out all the fp types.
219 for (unsigned i = 0; i != TypeVec.size(); ++i)
220 if (isFloatingPoint(TypeVec[i]))
221 TypeVec.erase(TypeVec.begin()+i--);
224 TP.error("Type inference contradiction found, '" +
225 InputSet.getName() + "' needs to be integer");
229 /// EnforceFloatingPoint - Remove all integer types from this set.
230 bool EEVT::TypeSet::EnforceFloatingPoint(TreePattern &TP) {
231 TypeSet InputSet(*this);
232 bool MadeChange = false;
234 // If we know nothing, then get the full set.
236 MadeChange = FillWithPossibleTypes(TP);
238 if (!hasIntegerTypes())
241 // Filter out all the fp types.
242 for (unsigned i = 0; i != TypeVec.size(); ++i)
243 if (isInteger(TypeVec[i]))
244 TypeVec.erase(TypeVec.begin()+i--);
247 TP.error("Type inference contradiction found, '" +
248 InputSet.getName() + "' needs to be floating point");
252 /// EnforceScalar - Remove all vector types from this.
253 bool EEVT::TypeSet::EnforceScalar(TreePattern &TP) {
254 TypeSet InputSet(*this);
255 bool MadeChange = false;
257 // If we know nothing, then get the full set.
259 MadeChange = FillWithPossibleTypes(TP);
261 if (!hasVectorTypes())
264 // Filter out all the vector types.
265 for (unsigned i = 0; i != TypeVec.size(); ++i)
266 if (isVector(TypeVec[i]))
267 TypeVec.erase(TypeVec.begin()+i--);
270 TP.error("Type inference contradiction found, '" +
271 InputSet.getName() + "' needs to be scalar");
275 /// EnforceVector - Remove all vector types from this.
276 bool EEVT::TypeSet::EnforceVector(TreePattern &TP) {
277 TypeSet InputSet(*this);
278 bool MadeChange = false;
280 // If we know nothing, then get the full set.
282 MadeChange = FillWithPossibleTypes(TP);
284 // Filter out all the scalar types.
285 for (unsigned i = 0; i != TypeVec.size(); ++i)
286 if (!isVector(TypeVec[i]))
287 TypeVec.erase(TypeVec.begin()+i--);
290 TP.error("Type inference contradiction found, '" +
291 InputSet.getName() + "' needs to be a vector");
297 /// EnforceSmallerThan - 'this' must be a smaller VT than Other. Update
298 /// this an other based on this information.
299 bool EEVT::TypeSet::EnforceSmallerThan(EEVT::TypeSet &Other, TreePattern &TP) {
300 // Both operands must be integer or FP, but we don't care which.
301 bool MadeChange = false;
303 if (isCompletelyUnknown())
304 MadeChange = FillWithPossibleTypes(TP);
306 if (Other.isCompletelyUnknown())
307 MadeChange = Other.FillWithPossibleTypes(TP);
309 // If one side is known to be integer or known to be FP but the other side has
310 // no information, get at least the type integrality info in there.
311 if (!hasFloatingPointTypes())
312 MadeChange |= Other.EnforceInteger(TP);
313 else if (!hasIntegerTypes())
314 MadeChange |= Other.EnforceFloatingPoint(TP);
315 if (!Other.hasFloatingPointTypes())
316 MadeChange |= EnforceInteger(TP);
317 else if (!Other.hasIntegerTypes())
318 MadeChange |= EnforceFloatingPoint(TP);
320 assert(!isCompletelyUnknown() && !Other.isCompletelyUnknown() &&
321 "Should have a type list now");
323 // If one contains vectors but the other doesn't pull vectors out.
324 if (!hasVectorTypes())
325 MadeChange |= Other.EnforceScalar(TP);
326 if (!hasVectorTypes())
327 MadeChange |= EnforceScalar(TP);
329 // This code does not currently handle nodes which have multiple types,
330 // where some types are integer, and some are fp. Assert that this is not
332 assert(!(hasIntegerTypes() && hasFloatingPointTypes()) &&
333 !(Other.hasIntegerTypes() && Other.hasFloatingPointTypes()) &&
334 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
336 // Okay, find the smallest type from the current set and remove it from the
338 MVT::SimpleValueType Smallest = TypeVec[0];
339 for (unsigned i = 1, e = TypeVec.size(); i != e; ++i)
340 if (TypeVec[i] < Smallest)
341 Smallest = TypeVec[i];
343 // If this is the only type in the large set, the constraint can never be
345 if (Other.TypeVec.size() == 1 && Other.TypeVec[0] == Smallest)
346 TP.error("Type inference contradiction found, '" +
347 Other.getName() + "' has nothing larger than '" + getName() +"'!");
349 SmallVector<MVT::SimpleValueType, 2>::iterator TVI =
350 std::find(Other.TypeVec.begin(), Other.TypeVec.end(), Smallest);
351 if (TVI != Other.TypeVec.end()) {
352 Other.TypeVec.erase(TVI);
356 // Okay, find the largest type in the Other set and remove it from the
358 MVT::SimpleValueType Largest = Other.TypeVec[0];
359 for (unsigned i = 1, e = Other.TypeVec.size(); i != e; ++i)
360 if (Other.TypeVec[i] > Largest)
361 Largest = Other.TypeVec[i];
363 // If this is the only type in the small set, the constraint can never be
365 if (TypeVec.size() == 1 && TypeVec[0] == Largest)
366 TP.error("Type inference contradiction found, '" +
367 getName() + "' has nothing smaller than '" + Other.getName()+"'!");
369 TVI = std::find(TypeVec.begin(), TypeVec.end(), Largest);
370 if (TVI != TypeVec.end()) {
378 /// EnforceVectorEltTypeIs - 'this' is now constrainted to be a vector type
379 /// whose element is VT.
380 bool EEVT::TypeSet::EnforceVectorEltTypeIs(MVT::SimpleValueType VT,
382 TypeSet InputSet(*this);
383 bool MadeChange = false;
385 // If we know nothing, then get the full set.
387 MadeChange = FillWithPossibleTypes(TP);
389 // Filter out all the non-vector types and types which don't have the right
391 for (unsigned i = 0; i != TypeVec.size(); ++i)
392 if (!isVector(TypeVec[i]) ||
393 EVT(TypeVec[i]).getVectorElementType().getSimpleVT().SimpleTy != VT) {
394 TypeVec.erase(TypeVec.begin()+i--);
398 if (TypeVec.empty()) // FIXME: Really want an SMLoc here!
399 TP.error("Type inference contradiction found, forcing '" +
400 InputSet.getName() + "' to have a vector element");
404 //===----------------------------------------------------------------------===//
405 // Helpers for working with extended types.
407 bool RecordPtrCmp::operator()(const Record *LHS, const Record *RHS) const {
408 return LHS->getID() < RHS->getID();
411 /// Dependent variable map for CodeGenDAGPattern variant generation
412 typedef std::map<std::string, int> DepVarMap;
414 /// Const iterator shorthand for DepVarMap
415 typedef DepVarMap::const_iterator DepVarMap_citer;
418 void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
420 if (dynamic_cast<DefInit*>(N->getLeafValue()) != NULL) {
421 DepMap[N->getName()]++;
424 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
425 FindDepVarsOf(N->getChild(i), DepMap);
429 //! Find dependent variables within child patterns
432 void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
434 FindDepVarsOf(N, depcounts);
435 for (DepVarMap_citer i = depcounts.begin(); i != depcounts.end(); ++i) {
436 if (i->second > 1) { // std::pair<std::string, int>
437 DepVars.insert(i->first);
442 //! Dump the dependent variable set:
443 void DumpDepVars(MultipleUseVarSet &DepVars) {
444 if (DepVars.empty()) {
445 DEBUG(errs() << "<empty set>");
447 DEBUG(errs() << "[ ");
448 for (MultipleUseVarSet::const_iterator i = DepVars.begin(), e = DepVars.end();
450 DEBUG(errs() << (*i) << " ");
452 DEBUG(errs() << "]");
457 //===----------------------------------------------------------------------===//
458 // PatternToMatch implementation
461 /// getPredicateCheck - Return a single string containing all of this
462 /// pattern's predicates concatenated with "&&" operators.
464 std::string PatternToMatch::getPredicateCheck() const {
465 std::string PredicateCheck;
466 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
467 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
468 Record *Def = Pred->getDef();
469 if (!Def->isSubClassOf("Predicate")) {
473 assert(0 && "Unknown predicate type!");
475 if (!PredicateCheck.empty())
476 PredicateCheck += " && ";
477 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
481 return PredicateCheck;
484 //===----------------------------------------------------------------------===//
485 // SDTypeConstraint implementation
488 SDTypeConstraint::SDTypeConstraint(Record *R) {
489 OperandNo = R->getValueAsInt("OperandNum");
491 if (R->isSubClassOf("SDTCisVT")) {
492 ConstraintType = SDTCisVT;
493 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
494 } else if (R->isSubClassOf("SDTCisPtrTy")) {
495 ConstraintType = SDTCisPtrTy;
496 } else if (R->isSubClassOf("SDTCisInt")) {
497 ConstraintType = SDTCisInt;
498 } else if (R->isSubClassOf("SDTCisFP")) {
499 ConstraintType = SDTCisFP;
500 } else if (R->isSubClassOf("SDTCisVec")) {
501 ConstraintType = SDTCisVec;
502 } else if (R->isSubClassOf("SDTCisSameAs")) {
503 ConstraintType = SDTCisSameAs;
504 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
505 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
506 ConstraintType = SDTCisVTSmallerThanOp;
507 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
508 R->getValueAsInt("OtherOperandNum");
509 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
510 ConstraintType = SDTCisOpSmallerThanOp;
511 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
512 R->getValueAsInt("BigOperandNum");
513 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
514 ConstraintType = SDTCisEltOfVec;
515 x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
517 errs() << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
522 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
523 /// N, which has NumResults results.
524 TreePatternNode *SDTypeConstraint::getOperandNum(unsigned OpNo,
526 unsigned NumResults) const {
527 assert(NumResults <= 1 &&
528 "We only work with nodes with zero or one result so far!");
530 if (OpNo >= (NumResults + N->getNumChildren())) {
531 errs() << "Invalid operand number " << OpNo << " ";
537 if (OpNo < NumResults)
538 return N; // FIXME: need value #
540 return N->getChild(OpNo-NumResults);
543 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
544 /// constraint to the nodes operands. This returns true if it makes a
545 /// change, false otherwise. If a type contradiction is found, throw an
547 bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
548 const SDNodeInfo &NodeInfo,
549 TreePattern &TP) const {
550 unsigned NumResults = NodeInfo.getNumResults();
551 assert(NumResults <= 1 &&
552 "We only work with nodes with zero or one result so far!");
554 // Check that the number of operands is sane. Negative operands -> varargs.
555 if (NodeInfo.getNumOperands() >= 0) {
556 if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands())
557 TP.error(N->getOperator()->getName() + " node requires exactly " +
558 itostr(NodeInfo.getNumOperands()) + " operands!");
561 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NumResults);
563 switch (ConstraintType) {
564 default: assert(0 && "Unknown constraint type!");
566 // Operand must be a particular type.
567 return NodeToApply->UpdateNodeType(x.SDTCisVT_Info.VT, TP);
569 // Operand must be same as target pointer type.
570 return NodeToApply->UpdateNodeType(MVT::iPTR, TP);
572 // Require it to be one of the legal integer VTs.
573 return NodeToApply->getExtType().EnforceInteger(TP);
575 // Require it to be one of the legal fp VTs.
576 return NodeToApply->getExtType().EnforceFloatingPoint(TP);
578 // Require it to be one of the legal vector VTs.
579 return NodeToApply->getExtType().EnforceVector(TP);
581 TreePatternNode *OtherNode =
582 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NumResults);
583 return NodeToApply->UpdateNodeType(OtherNode->getExtType(), TP) |
584 OtherNode->UpdateNodeType(NodeToApply->getExtType(), TP);
586 case SDTCisVTSmallerThanOp: {
587 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
588 // have an integer type that is smaller than the VT.
589 if (!NodeToApply->isLeaf() ||
590 !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
591 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
592 ->isSubClassOf("ValueType"))
593 TP.error(N->getOperator()->getName() + " expects a VT operand!");
594 MVT::SimpleValueType VT =
595 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
597 TP.error(N->getOperator()->getName() + " VT operand must be integer!");
599 TreePatternNode *OtherNode =
600 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N,NumResults);
602 // It must be integer.
603 bool MadeChange = OtherNode->getExtType().EnforceInteger(TP);
605 // This doesn't try to enforce any information on the OtherNode, it just
606 // validates it when information is determined.
607 if (OtherNode->hasTypeSet() && OtherNode->getType() <= VT)
608 OtherNode->UpdateNodeType(MVT::Other, TP); // Throw an error.
611 case SDTCisOpSmallerThanOp: {
612 TreePatternNode *BigOperand =
613 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NumResults);
614 return NodeToApply->getExtType().
615 EnforceSmallerThan(BigOperand->getExtType(), TP);
617 case SDTCisEltOfVec: {
618 TreePatternNode *VecOperand =
619 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NumResults);
620 if (VecOperand->hasTypeSet()) {
621 if (!isVector(VecOperand->getType()))
622 TP.error(N->getOperator()->getName() + " VT operand must be a vector!");
623 EVT IVT = VecOperand->getType();
624 IVT = IVT.getVectorElementType();
625 return NodeToApply->UpdateNodeType(IVT.getSimpleVT().SimpleTy, TP);
628 if (NodeToApply->hasTypeSet() && VecOperand->getExtType().hasVectorTypes()){
629 // Filter vector types out of VecOperand that don't have the right element
631 return VecOperand->getExtType().
632 EnforceVectorEltTypeIs(NodeToApply->getType(), TP);
640 //===----------------------------------------------------------------------===//
641 // SDNodeInfo implementation
643 SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
644 EnumName = R->getValueAsString("Opcode");
645 SDClassName = R->getValueAsString("SDClass");
646 Record *TypeProfile = R->getValueAsDef("TypeProfile");
647 NumResults = TypeProfile->getValueAsInt("NumResults");
648 NumOperands = TypeProfile->getValueAsInt("NumOperands");
650 // Parse the properties.
652 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
653 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
654 if (PropList[i]->getName() == "SDNPCommutative") {
655 Properties |= 1 << SDNPCommutative;
656 } else if (PropList[i]->getName() == "SDNPAssociative") {
657 Properties |= 1 << SDNPAssociative;
658 } else if (PropList[i]->getName() == "SDNPHasChain") {
659 Properties |= 1 << SDNPHasChain;
660 } else if (PropList[i]->getName() == "SDNPOutFlag") {
661 Properties |= 1 << SDNPOutFlag;
662 } else if (PropList[i]->getName() == "SDNPInFlag") {
663 Properties |= 1 << SDNPInFlag;
664 } else if (PropList[i]->getName() == "SDNPOptInFlag") {
665 Properties |= 1 << SDNPOptInFlag;
666 } else if (PropList[i]->getName() == "SDNPMayStore") {
667 Properties |= 1 << SDNPMayStore;
668 } else if (PropList[i]->getName() == "SDNPMayLoad") {
669 Properties |= 1 << SDNPMayLoad;
670 } else if (PropList[i]->getName() == "SDNPSideEffect") {
671 Properties |= 1 << SDNPSideEffect;
672 } else if (PropList[i]->getName() == "SDNPMemOperand") {
673 Properties |= 1 << SDNPMemOperand;
674 } else if (PropList[i]->getName() == "SDNPVariadic") {
675 Properties |= 1 << SDNPVariadic;
677 errs() << "Unknown SD Node property '" << PropList[i]->getName()
678 << "' on node '" << R->getName() << "'!\n";
684 // Parse the type constraints.
685 std::vector<Record*> ConstraintList =
686 TypeProfile->getValueAsListOfDefs("Constraints");
687 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
690 /// getKnownType - If the type constraints on this node imply a fixed type
691 /// (e.g. all stores return void, etc), then return it as an
692 /// MVT::SimpleValueType. Otherwise, return EEVT::Other.
693 MVT::SimpleValueType SDNodeInfo::getKnownType() const {
694 unsigned NumResults = getNumResults();
695 assert(NumResults <= 1 &&
696 "We only work with nodes with zero or one result so far!");
698 for (unsigned i = 0, e = TypeConstraints.size(); i != e; ++i) {
699 // Make sure that this applies to the correct node result.
700 if (TypeConstraints[i].OperandNo >= NumResults) // FIXME: need value #
703 switch (TypeConstraints[i].ConstraintType) {
705 case SDTypeConstraint::SDTCisVT:
706 return TypeConstraints[i].x.SDTCisVT_Info.VT;
707 case SDTypeConstraint::SDTCisPtrTy:
714 //===----------------------------------------------------------------------===//
715 // TreePatternNode implementation
718 TreePatternNode::~TreePatternNode() {
719 #if 0 // FIXME: implement refcounted tree nodes!
720 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
727 void TreePatternNode::print(raw_ostream &OS) const {
729 OS << *getLeafValue();
731 OS << '(' << getOperator()->getName();
734 if (!isTypeCompletelyUnknown())
735 OS << ':' << getExtType().getName();
738 if (getNumChildren() != 0) {
740 getChild(0)->print(OS);
741 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
743 getChild(i)->print(OS);
749 for (unsigned i = 0, e = PredicateFns.size(); i != e; ++i)
750 OS << "<<P:" << PredicateFns[i] << ">>";
752 OS << "<<X:" << TransformFn->getName() << ">>";
753 if (!getName().empty())
754 OS << ":$" << getName();
757 void TreePatternNode::dump() const {
761 /// isIsomorphicTo - Return true if this node is recursively
762 /// isomorphic to the specified node. For this comparison, the node's
763 /// entire state is considered. The assigned name is ignored, since
764 /// nodes with differing names are considered isomorphic. However, if
765 /// the assigned name is present in the dependent variable set, then
766 /// the assigned name is considered significant and the node is
767 /// isomorphic if the names match.
768 bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
769 const MultipleUseVarSet &DepVars) const {
770 if (N == this) return true;
771 if (N->isLeaf() != isLeaf() || getExtType() != N->getExtType() ||
772 getPredicateFns() != N->getPredicateFns() ||
773 getTransformFn() != N->getTransformFn())
777 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
778 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue())) {
779 return ((DI->getDef() == NDI->getDef())
780 && (DepVars.find(getName()) == DepVars.end()
781 || getName() == N->getName()));
784 return getLeafValue() == N->getLeafValue();
787 if (N->getOperator() != getOperator() ||
788 N->getNumChildren() != getNumChildren()) return false;
789 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
790 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
795 /// clone - Make a copy of this tree and all of its children.
797 TreePatternNode *TreePatternNode::clone() const {
798 TreePatternNode *New;
800 New = new TreePatternNode(getLeafValue());
802 std::vector<TreePatternNode*> CChildren;
803 CChildren.reserve(Children.size());
804 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
805 CChildren.push_back(getChild(i)->clone());
806 New = new TreePatternNode(getOperator(), CChildren);
808 New->setName(getName());
809 New->setType(getExtType());
810 New->setPredicateFns(getPredicateFns());
811 New->setTransformFn(getTransformFn());
815 /// RemoveAllTypes - Recursively strip all the types of this tree.
816 void TreePatternNode::RemoveAllTypes() {
817 setType(EEVT::TypeSet()); // Reset to unknown type.
818 if (isLeaf()) return;
819 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
820 getChild(i)->RemoveAllTypes();
824 /// SubstituteFormalArguments - Replace the formal arguments in this tree
825 /// with actual values specified by ArgMap.
826 void TreePatternNode::
827 SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
828 if (isLeaf()) return;
830 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
831 TreePatternNode *Child = getChild(i);
832 if (Child->isLeaf()) {
833 Init *Val = Child->getLeafValue();
834 if (dynamic_cast<DefInit*>(Val) &&
835 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
836 // We found a use of a formal argument, replace it with its value.
837 TreePatternNode *NewChild = ArgMap[Child->getName()];
838 assert(NewChild && "Couldn't find formal argument!");
839 assert((Child->getPredicateFns().empty() ||
840 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
841 "Non-empty child predicate clobbered!");
842 setChild(i, NewChild);
845 getChild(i)->SubstituteFormalArguments(ArgMap);
851 /// InlinePatternFragments - If this pattern refers to any pattern
852 /// fragments, inline them into place, giving us a pattern without any
853 /// PatFrag references.
854 TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
855 if (isLeaf()) return this; // nothing to do.
856 Record *Op = getOperator();
858 if (!Op->isSubClassOf("PatFrag")) {
859 // Just recursively inline children nodes.
860 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
861 TreePatternNode *Child = getChild(i);
862 TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
864 assert((Child->getPredicateFns().empty() ||
865 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
866 "Non-empty child predicate clobbered!");
868 setChild(i, NewChild);
873 // Otherwise, we found a reference to a fragment. First, look up its
874 // TreePattern record.
875 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
877 // Verify that we are passing the right number of operands.
878 if (Frag->getNumArgs() != Children.size())
879 TP.error("'" + Op->getName() + "' fragment requires " +
880 utostr(Frag->getNumArgs()) + " operands!");
882 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
884 std::string Code = Op->getValueAsCode("Predicate");
886 FragTree->addPredicateFn("Predicate_"+Op->getName());
888 // Resolve formal arguments to their actual value.
889 if (Frag->getNumArgs()) {
890 // Compute the map of formal to actual arguments.
891 std::map<std::string, TreePatternNode*> ArgMap;
892 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
893 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
895 FragTree->SubstituteFormalArguments(ArgMap);
898 FragTree->setName(getName());
899 FragTree->UpdateNodeType(getExtType(), TP);
901 // Transfer in the old predicates.
902 for (unsigned i = 0, e = getPredicateFns().size(); i != e; ++i)
903 FragTree->addPredicateFn(getPredicateFns()[i]);
905 // Get a new copy of this fragment to stitch into here.
906 //delete this; // FIXME: implement refcounting!
908 // The fragment we inlined could have recursive inlining that is needed. See
909 // if there are any pattern fragments in it and inline them as needed.
910 return FragTree->InlinePatternFragments(TP);
913 /// getImplicitType - Check to see if the specified record has an implicit
914 /// type which should be applied to it. This will infer the type of register
915 /// references from the register file information, for example.
917 static EEVT::TypeSet getImplicitType(Record *R, bool NotRegisters,
919 // Check to see if this is a register or a register class.
920 if (R->isSubClassOf("RegisterClass")) {
922 return EEVT::TypeSet(); // Unknown.
923 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
924 return EEVT::TypeSet(T.getRegisterClass(R).getValueTypes());
925 } else if (R->isSubClassOf("PatFrag")) {
926 // Pattern fragment types will be resolved when they are inlined.
927 return EEVT::TypeSet(); // Unknown.
928 } else if (R->isSubClassOf("Register")) {
930 return EEVT::TypeSet(); // Unknown.
931 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
932 return EEVT::TypeSet(T.getRegisterVTs(R));
933 } else if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
934 // Using a VTSDNode or CondCodeSDNode.
935 return EEVT::TypeSet(MVT::Other, TP);
936 } else if (R->isSubClassOf("ComplexPattern")) {
938 return EEVT::TypeSet(); // Unknown.
939 return EEVT::TypeSet(TP.getDAGPatterns().getComplexPattern(R).getValueType(),
941 } else if (R->isSubClassOf("PointerLikeRegClass")) {
942 return EEVT::TypeSet(MVT::iPTR, TP);
943 } else if (R->getName() == "node" || R->getName() == "srcvalue" ||
944 R->getName() == "zero_reg") {
946 return EEVT::TypeSet(); // Unknown.
949 TP.error("Unknown node flavor used in pattern: " + R->getName());
950 return EEVT::TypeSet(MVT::Other, TP);
954 /// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
955 /// CodeGenIntrinsic information for it, otherwise return a null pointer.
956 const CodeGenIntrinsic *TreePatternNode::
957 getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
958 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
959 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
960 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
964 dynamic_cast<IntInit*>(getChild(0)->getLeafValue())->getValue();
965 return &CDP.getIntrinsicInfo(IID);
968 /// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
969 /// return the ComplexPattern information, otherwise return null.
970 const ComplexPattern *
971 TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
972 if (!isLeaf()) return 0;
974 DefInit *DI = dynamic_cast<DefInit*>(getLeafValue());
975 if (DI && DI->getDef()->isSubClassOf("ComplexPattern"))
976 return &CGP.getComplexPattern(DI->getDef());
980 /// NodeHasProperty - Return true if this node has the specified property.
981 bool TreePatternNode::NodeHasProperty(SDNP Property,
982 const CodeGenDAGPatterns &CGP) const {
984 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
985 return CP->hasProperty(Property);
989 Record *Operator = getOperator();
990 if (!Operator->isSubClassOf("SDNode")) return false;
992 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
998 /// TreeHasProperty - Return true if any node in this tree has the specified
1000 bool TreePatternNode::TreeHasProperty(SDNP Property,
1001 const CodeGenDAGPatterns &CGP) const {
1002 if (NodeHasProperty(Property, CGP))
1004 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1005 if (getChild(i)->TreeHasProperty(Property, CGP))
1010 /// isCommutativeIntrinsic - Return true if the node corresponds to a
1011 /// commutative intrinsic.
1013 TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
1014 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
1015 return Int->isCommutative;
1020 /// ApplyTypeConstraints - Apply all of the type constraints relevant to
1021 /// this node and its children in the tree. This returns true if it makes a
1022 /// change, false otherwise. If a type contradiction is found, throw an
1024 bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
1025 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
1027 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
1028 // If it's a regclass or something else known, include the type.
1029 return UpdateNodeType(getImplicitType(DI->getDef(), NotRegisters, TP),TP);
1032 if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
1033 // Int inits are always integers. :)
1034 bool MadeChange = Type.EnforceInteger(TP);
1039 MVT::SimpleValueType VT = getType();
1040 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
1043 unsigned Size = EVT(VT).getSizeInBits();
1044 // Make sure that the value is representable for this type.
1045 if (Size >= 32) return MadeChange;
1047 int Val = (II->getValue() << (32-Size)) >> (32-Size);
1048 if (Val == II->getValue()) return MadeChange;
1050 // If sign-extended doesn't fit, does it fit as unsigned?
1052 unsigned UnsignedVal;
1053 ValueMask = unsigned(~uint32_t(0UL) >> (32-Size));
1054 UnsignedVal = unsigned(II->getValue());
1056 if ((ValueMask & UnsignedVal) == UnsignedVal)
1059 TP.error("Integer value '" + itostr(II->getValue())+
1060 "' is out of range for type '" + getEnumName(getType()) + "'!");
1066 // special handling for set, which isn't really an SDNode.
1067 if (getOperator()->getName() == "set") {
1068 assert (getNumChildren() >= 2 && "Missing RHS of a set?");
1069 unsigned NC = getNumChildren();
1070 bool MadeChange = false;
1071 for (unsigned i = 0; i < NC-1; ++i) {
1072 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1073 MadeChange |= getChild(NC-1)->ApplyTypeConstraints(TP, NotRegisters);
1075 // Types of operands must match.
1076 MadeChange |=getChild(i)->UpdateNodeType(getChild(NC-1)->getExtType(),TP);
1077 MadeChange |=getChild(NC-1)->UpdateNodeType(getChild(i)->getExtType(),TP);
1078 MadeChange |=UpdateNodeType(MVT::isVoid, TP);
1083 if (getOperator()->getName() == "implicit" ||
1084 getOperator()->getName() == "parallel") {
1085 bool MadeChange = false;
1086 for (unsigned i = 0; i < getNumChildren(); ++i)
1087 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1088 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
1092 if (getOperator()->getName() == "COPY_TO_REGCLASS") {
1093 bool MadeChange = false;
1094 MadeChange |= getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1095 MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
1097 // child #1 of COPY_TO_REGCLASS should be a register class. We don't care
1098 // what type it gets, so if it didn't get a concrete type just give it the
1099 // first viable type from the reg class.
1100 if (!getChild(1)->hasTypeSet() &&
1101 !getChild(1)->getExtType().isCompletelyUnknown()) {
1102 MVT::SimpleValueType RCVT = getChild(1)->getExtType().getTypeList()[0];
1103 MadeChange |= getChild(1)->UpdateNodeType(RCVT, TP);
1108 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
1109 bool MadeChange = false;
1111 // Apply the result type to the node.
1112 unsigned NumRetVTs = Int->IS.RetVTs.size();
1113 unsigned NumParamVTs = Int->IS.ParamVTs.size();
1115 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
1116 MadeChange |= UpdateNodeType(Int->IS.RetVTs[i], TP);
1118 if (getNumChildren() != NumParamVTs + NumRetVTs)
1119 TP.error("Intrinsic '" + Int->Name + "' expects " +
1120 utostr(NumParamVTs + NumRetVTs - 1) + " operands, not " +
1121 utostr(getNumChildren() - 1) + " operands!");
1123 // Apply type info to the intrinsic ID.
1124 MadeChange |= getChild(0)->UpdateNodeType(MVT::iPTR, TP);
1126 for (unsigned i = NumRetVTs, e = getNumChildren(); i != e; ++i) {
1127 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i - NumRetVTs];
1128 MadeChange |= getChild(i)->UpdateNodeType(OpVT, TP);
1129 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1134 if (getOperator()->isSubClassOf("SDNode")) {
1135 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
1137 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
1138 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1139 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1140 // Branch, etc. do not produce results and top-level forms in instr pattern
1141 // must have void types.
1142 if (NI.getNumResults() == 0)
1143 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
1148 if (getOperator()->isSubClassOf("Instruction")) {
1149 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
1150 assert(Inst.getNumResults() <= 1 &&
1151 "Only supports zero or one result instrs!");
1153 CodeGenInstruction &InstInfo =
1154 CDP.getTargetInfo().getInstruction(getOperator());
1156 EEVT::TypeSet ResultType;
1158 // Apply the result type to the node
1159 if (InstInfo.NumDefs != 0) { // # of elements in (outs) list
1160 Record *ResultNode = Inst.getResult(0);
1162 if (ResultNode->isSubClassOf("PointerLikeRegClass")) {
1163 ResultType = EEVT::TypeSet(MVT::iPTR, TP);
1164 } else if (ResultNode->getName() == "unknown") {
1167 assert(ResultNode->isSubClassOf("RegisterClass") &&
1168 "Operands should be register classes!");
1169 const CodeGenRegisterClass &RC =
1170 CDP.getTargetInfo().getRegisterClass(ResultNode);
1171 ResultType = RC.getValueTypes();
1173 } else if (!InstInfo.ImplicitDefs.empty()) {
1174 // If the instruction has implicit defs, the first one defines the result
1176 Record *FirstImplicitDef = InstInfo.ImplicitDefs[0];
1177 assert(FirstImplicitDef->isSubClassOf("Register"));
1178 const std::vector<MVT::SimpleValueType> &RegVTs =
1179 CDP.getTargetInfo().getRegisterVTs(FirstImplicitDef);
1180 if (RegVTs.size() == 1)
1181 ResultType = EEVT::TypeSet(RegVTs);
1183 ResultType = EEVT::TypeSet(MVT::isVoid, TP);
1185 // Otherwise, the instruction produces no value result.
1186 // FIXME: Model "no result" different than "one result that is void"
1187 ResultType = EEVT::TypeSet(MVT::isVoid, TP);
1190 bool MadeChange = UpdateNodeType(ResultType, TP);
1192 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
1194 if (getOperator()->getName() == "INSERT_SUBREG") {
1195 MadeChange |= UpdateNodeType(getChild(0)->getExtType(), TP);
1196 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
1199 unsigned ChildNo = 0;
1200 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
1201 Record *OperandNode = Inst.getOperand(i);
1203 // If the instruction expects a predicate or optional def operand, we
1204 // codegen this by setting the operand to it's default value if it has a
1205 // non-empty DefaultOps field.
1206 if ((OperandNode->isSubClassOf("PredicateOperand") ||
1207 OperandNode->isSubClassOf("OptionalDefOperand")) &&
1208 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1211 // Verify that we didn't run out of provided operands.
1212 if (ChildNo >= getNumChildren())
1213 TP.error("Instruction '" + getOperator()->getName() +
1214 "' expects more operands than were provided.");
1216 MVT::SimpleValueType VT;
1217 TreePatternNode *Child = getChild(ChildNo++);
1218 if (OperandNode->isSubClassOf("RegisterClass")) {
1219 const CodeGenRegisterClass &RC =
1220 CDP.getTargetInfo().getRegisterClass(OperandNode);
1221 MadeChange |= Child->UpdateNodeType(RC.getValueTypes(), TP);
1222 } else if (OperandNode->isSubClassOf("Operand")) {
1223 VT = getValueType(OperandNode->getValueAsDef("Type"));
1224 MadeChange |= Child->UpdateNodeType(VT, TP);
1225 } else if (OperandNode->isSubClassOf("PointerLikeRegClass")) {
1226 MadeChange |= Child->UpdateNodeType(MVT::iPTR, TP);
1227 } else if (OperandNode->getName() == "unknown") {
1230 assert(0 && "Unknown operand type!");
1233 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
1236 if (ChildNo != getNumChildren())
1237 TP.error("Instruction '" + getOperator()->getName() +
1238 "' was provided too many operands!");
1243 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
1245 // Node transforms always take one operand.
1246 if (getNumChildren() != 1)
1247 TP.error("Node transform '" + getOperator()->getName() +
1248 "' requires one operand!");
1250 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1253 // If either the output or input of the xform does not have exact
1254 // type info. We assume they must be the same. Otherwise, it is perfectly
1255 // legal to transform from one type to a completely different type.
1257 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
1258 bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
1259 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
1266 /// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
1267 /// RHS of a commutative operation, not the on LHS.
1268 static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
1269 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
1271 if (N->isLeaf() && dynamic_cast<IntInit*>(N->getLeafValue()))
1277 /// canPatternMatch - If it is impossible for this pattern to match on this
1278 /// target, fill in Reason and return false. Otherwise, return true. This is
1279 /// used as a sanity check for .td files (to prevent people from writing stuff
1280 /// that can never possibly work), and to prevent the pattern permuter from
1281 /// generating stuff that is useless.
1282 bool TreePatternNode::canPatternMatch(std::string &Reason,
1283 const CodeGenDAGPatterns &CDP) {
1284 if (isLeaf()) return true;
1286 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1287 if (!getChild(i)->canPatternMatch(Reason, CDP))
1290 // If this is an intrinsic, handle cases that would make it not match. For
1291 // example, if an operand is required to be an immediate.
1292 if (getOperator()->isSubClassOf("Intrinsic")) {
1297 // If this node is a commutative operator, check that the LHS isn't an
1299 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
1300 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
1301 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
1302 // Scan all of the operands of the node and make sure that only the last one
1303 // is a constant node, unless the RHS also is.
1304 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
1305 bool Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
1306 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
1307 if (OnlyOnRHSOfCommutative(getChild(i))) {
1308 Reason="Immediate value must be on the RHS of commutative operators!";
1317 //===----------------------------------------------------------------------===//
1318 // TreePattern implementation
1321 TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
1322 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
1323 isInputPattern = isInput;
1324 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
1325 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
1328 TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
1329 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
1330 isInputPattern = isInput;
1331 Trees.push_back(ParseTreePattern(Pat));
1334 TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
1335 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
1336 isInputPattern = isInput;
1337 Trees.push_back(Pat);
1340 void TreePattern::error(const std::string &Msg) const {
1342 throw TGError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
1345 void TreePattern::ComputeNamedNodes() {
1346 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1347 ComputeNamedNodes(Trees[i]);
1350 void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
1351 if (!N->getName().empty())
1352 NamedNodes[N->getName()].push_back(N);
1354 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1355 ComputeNamedNodes(N->getChild(i));
1358 TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
1359 DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
1360 if (!OpDef) error("Pattern has unexpected operator type!");
1361 Record *Operator = OpDef->getDef();
1363 if (Operator->isSubClassOf("ValueType")) {
1364 // If the operator is a ValueType, then this must be "type cast" of a leaf
1366 if (Dag->getNumArgs() != 1)
1367 error("Type cast only takes one operand!");
1369 Init *Arg = Dag->getArg(0);
1370 TreePatternNode *New;
1371 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
1372 Record *R = DI->getDef();
1373 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
1374 Dag->setArg(0, new DagInit(DI, "",
1375 std::vector<std::pair<Init*, std::string> >()));
1376 return ParseTreePattern(Dag);
1380 if (R->getName() == "node") {
1381 if (Dag->getArgName(0).empty())
1382 error("'node' argument requires a name to match with operand list");
1383 Args.push_back(Dag->getArgName(0));
1386 New = new TreePatternNode(DI);
1387 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
1388 New = ParseTreePattern(DI);
1389 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
1390 New = new TreePatternNode(II);
1391 if (!Dag->getArgName(0).empty())
1392 error("Constant int argument should not have a name!");
1393 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
1394 // Turn this into an IntInit.
1395 Init *II = BI->convertInitializerTo(new IntRecTy());
1396 if (II == 0 || !dynamic_cast<IntInit*>(II))
1397 error("Bits value must be constants!");
1399 New = new TreePatternNode(dynamic_cast<IntInit*>(II));
1400 if (!Dag->getArgName(0).empty())
1401 error("Constant int argument should not have a name!");
1404 error("Unknown leaf value for tree pattern!");
1408 // Apply the type cast.
1409 New->UpdateNodeType(getValueType(Operator), *this);
1410 if (New->getNumChildren() == 0)
1411 New->setName(Dag->getArgName(0));
1415 // Verify that this is something that makes sense for an operator.
1416 if (!Operator->isSubClassOf("PatFrag") &&
1417 !Operator->isSubClassOf("SDNode") &&
1418 !Operator->isSubClassOf("Instruction") &&
1419 !Operator->isSubClassOf("SDNodeXForm") &&
1420 !Operator->isSubClassOf("Intrinsic") &&
1421 Operator->getName() != "set" &&
1422 Operator->getName() != "implicit" &&
1423 Operator->getName() != "parallel")
1424 error("Unrecognized node '" + Operator->getName() + "'!");
1426 // Check to see if this is something that is illegal in an input pattern.
1427 if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
1428 Operator->isSubClassOf("SDNodeXForm")))
1429 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
1431 std::vector<TreePatternNode*> Children;
1433 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
1434 Init *Arg = Dag->getArg(i);
1435 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
1436 Children.push_back(ParseTreePattern(DI));
1437 if (Children.back()->getName().empty())
1438 Children.back()->setName(Dag->getArgName(i));
1439 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
1440 Record *R = DefI->getDef();
1441 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
1442 // TreePatternNode if its own.
1443 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
1444 Dag->setArg(i, new DagInit(DefI, "",
1445 std::vector<std::pair<Init*, std::string> >()));
1446 --i; // Revisit this node...
1448 TreePatternNode *Node = new TreePatternNode(DefI);
1449 Node->setName(Dag->getArgName(i));
1450 Children.push_back(Node);
1453 if (R->getName() == "node") {
1454 if (Dag->getArgName(i).empty())
1455 error("'node' argument requires a name to match with operand list");
1456 Args.push_back(Dag->getArgName(i));
1459 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
1460 TreePatternNode *Node = new TreePatternNode(II);
1461 if (!Dag->getArgName(i).empty())
1462 error("Constant int argument should not have a name!");
1463 Children.push_back(Node);
1464 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
1465 // Turn this into an IntInit.
1466 Init *II = BI->convertInitializerTo(new IntRecTy());
1467 if (II == 0 || !dynamic_cast<IntInit*>(II))
1468 error("Bits value must be constants!");
1470 TreePatternNode *Node = new TreePatternNode(dynamic_cast<IntInit*>(II));
1471 if (!Dag->getArgName(i).empty())
1472 error("Constant int argument should not have a name!");
1473 Children.push_back(Node);
1478 error("Unknown leaf value for tree pattern!");
1482 // If the operator is an intrinsic, then this is just syntactic sugar for for
1483 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
1484 // convert the intrinsic name to a number.
1485 if (Operator->isSubClassOf("Intrinsic")) {
1486 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
1487 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
1489 // If this intrinsic returns void, it must have side-effects and thus a
1491 if (Int.IS.RetVTs[0] == MVT::isVoid) {
1492 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
1493 } else if (Int.ModRef != CodeGenIntrinsic::NoMem) {
1494 // Has side-effects, requires chain.
1495 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
1497 // Otherwise, no chain.
1498 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
1501 TreePatternNode *IIDNode = new TreePatternNode(new IntInit(IID));
1502 Children.insert(Children.begin(), IIDNode);
1505 TreePatternNode *Result = new TreePatternNode(Operator, Children);
1506 Result->setName(Dag->getName());
1510 /// InferAllTypes - Infer/propagate as many types throughout the expression
1511 /// patterns as possible. Return true if all types are inferred, false
1512 /// otherwise. Throw an exception if a type contradiction is found.
1514 InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
1515 if (NamedNodes.empty())
1516 ComputeNamedNodes();
1518 bool MadeChange = true;
1519 while (MadeChange) {
1521 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1522 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
1524 // If there are constraints on our named nodes, apply them.
1525 for (StringMap<SmallVector<TreePatternNode*,1> >::iterator
1526 I = NamedNodes.begin(), E = NamedNodes.end(); I != E; ++I) {
1527 SmallVectorImpl<TreePatternNode*> &Nodes = I->second;
1529 // If we have input named node types, propagate their types to the named
1532 // FIXME: Should be error?
1533 assert(InNamedTypes->count(I->getKey()) &&
1534 "Named node in output pattern but not input pattern?");
1536 const SmallVectorImpl<TreePatternNode*> &InNodes =
1537 InNamedTypes->find(I->getKey())->second;
1539 // The input types should be fully resolved by now.
1540 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
1541 // If this node is a register class, and it is the root of the pattern
1542 // then we're mapping something onto an input register. We allow
1543 // changing the type of the input register in this case. This allows
1544 // us to match things like:
1545 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
1546 if (Nodes[i] == Trees[0] && Nodes[i]->isLeaf()) {
1547 DefInit *DI = dynamic_cast<DefInit*>(Nodes[i]->getLeafValue());
1548 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1552 MadeChange |=Nodes[i]->UpdateNodeType(InNodes[0]->getExtType(),*this);
1556 // If there are multiple nodes with the same name, they must all have the
1558 if (I->second.size() > 1) {
1559 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
1560 MadeChange |=Nodes[i]->UpdateNodeType(Nodes[i+1]->getExtType(),*this);
1561 MadeChange |=Nodes[i+1]->UpdateNodeType(Nodes[i]->getExtType(),*this);
1567 bool HasUnresolvedTypes = false;
1568 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1569 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
1570 return !HasUnresolvedTypes;
1573 void TreePattern::print(raw_ostream &OS) const {
1574 OS << getRecord()->getName();
1575 if (!Args.empty()) {
1576 OS << "(" << Args[0];
1577 for (unsigned i = 1, e = Args.size(); i != e; ++i)
1578 OS << ", " << Args[i];
1583 if (Trees.size() > 1)
1585 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
1587 Trees[i]->print(OS);
1591 if (Trees.size() > 1)
1595 void TreePattern::dump() const { print(errs()); }
1597 //===----------------------------------------------------------------------===//
1598 // CodeGenDAGPatterns implementation
1601 CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) : Records(R) {
1602 Intrinsics = LoadIntrinsics(Records, false);
1603 TgtIntrinsics = LoadIntrinsics(Records, true);
1605 ParseNodeTransforms();
1606 ParseComplexPatterns();
1607 ParsePatternFragments();
1608 ParseDefaultOperands();
1609 ParseInstructions();
1612 // Generate variants. For example, commutative patterns can match
1613 // multiple ways. Add them to PatternsToMatch as well.
1616 // Infer instruction flags. For example, we can detect loads,
1617 // stores, and side effects in many cases by examining an
1618 // instruction's pattern.
1619 InferInstructionFlags();
1622 CodeGenDAGPatterns::~CodeGenDAGPatterns() {
1623 for (pf_iterator I = PatternFragments.begin(),
1624 E = PatternFragments.end(); I != E; ++I)
1629 Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
1630 Record *N = Records.getDef(Name);
1631 if (!N || !N->isSubClassOf("SDNode")) {
1632 errs() << "Error getting SDNode '" << Name << "'!\n";
1638 // Parse all of the SDNode definitions for the target, populating SDNodes.
1639 void CodeGenDAGPatterns::ParseNodeInfo() {
1640 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
1641 while (!Nodes.empty()) {
1642 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
1646 // Get the builtin intrinsic nodes.
1647 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
1648 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
1649 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
1652 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
1653 /// map, and emit them to the file as functions.
1654 void CodeGenDAGPatterns::ParseNodeTransforms() {
1655 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
1656 while (!Xforms.empty()) {
1657 Record *XFormNode = Xforms.back();
1658 Record *SDNode = XFormNode->getValueAsDef("Opcode");
1659 std::string Code = XFormNode->getValueAsCode("XFormFunction");
1660 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
1666 void CodeGenDAGPatterns::ParseComplexPatterns() {
1667 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
1668 while (!AMs.empty()) {
1669 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
1675 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
1676 /// file, building up the PatternFragments map. After we've collected them all,
1677 /// inline fragments together as necessary, so that there are no references left
1678 /// inside a pattern fragment to a pattern fragment.
1680 void CodeGenDAGPatterns::ParsePatternFragments() {
1681 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
1683 // First step, parse all of the fragments.
1684 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1685 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
1686 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
1687 PatternFragments[Fragments[i]] = P;
1689 // Validate the argument list, converting it to set, to discard duplicates.
1690 std::vector<std::string> &Args = P->getArgList();
1691 std::set<std::string> OperandsSet(Args.begin(), Args.end());
1693 if (OperandsSet.count(""))
1694 P->error("Cannot have unnamed 'node' values in pattern fragment!");
1696 // Parse the operands list.
1697 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
1698 DefInit *OpsOp = dynamic_cast<DefInit*>(OpsList->getOperator());
1699 // Special cases: ops == outs == ins. Different names are used to
1700 // improve readability.
1702 (OpsOp->getDef()->getName() != "ops" &&
1703 OpsOp->getDef()->getName() != "outs" &&
1704 OpsOp->getDef()->getName() != "ins"))
1705 P->error("Operands list should start with '(ops ... '!");
1707 // Copy over the arguments.
1709 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
1710 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
1711 static_cast<DefInit*>(OpsList->getArg(j))->
1712 getDef()->getName() != "node")
1713 P->error("Operands list should all be 'node' values.");
1714 if (OpsList->getArgName(j).empty())
1715 P->error("Operands list should have names for each operand!");
1716 if (!OperandsSet.count(OpsList->getArgName(j)))
1717 P->error("'" + OpsList->getArgName(j) +
1718 "' does not occur in pattern or was multiply specified!");
1719 OperandsSet.erase(OpsList->getArgName(j));
1720 Args.push_back(OpsList->getArgName(j));
1723 if (!OperandsSet.empty())
1724 P->error("Operands list does not contain an entry for operand '" +
1725 *OperandsSet.begin() + "'!");
1727 // If there is a code init for this fragment, keep track of the fact that
1728 // this fragment uses it.
1729 std::string Code = Fragments[i]->getValueAsCode("Predicate");
1731 P->getOnlyTree()->addPredicateFn("Predicate_"+Fragments[i]->getName());
1733 // If there is a node transformation corresponding to this, keep track of
1735 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
1736 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
1737 P->getOnlyTree()->setTransformFn(Transform);
1740 // Now that we've parsed all of the tree fragments, do a closure on them so
1741 // that there are not references to PatFrags left inside of them.
1742 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1743 TreePattern *ThePat = PatternFragments[Fragments[i]];
1744 ThePat->InlinePatternFragments();
1746 // Infer as many types as possible. Don't worry about it if we don't infer
1747 // all of them, some may depend on the inputs of the pattern.
1749 ThePat->InferAllTypes();
1751 // If this pattern fragment is not supported by this target (no types can
1752 // satisfy its constraints), just ignore it. If the bogus pattern is
1753 // actually used by instructions, the type consistency error will be
1757 // If debugging, print out the pattern fragment result.
1758 DEBUG(ThePat->dump());
1762 void CodeGenDAGPatterns::ParseDefaultOperands() {
1763 std::vector<Record*> DefaultOps[2];
1764 DefaultOps[0] = Records.getAllDerivedDefinitions("PredicateOperand");
1765 DefaultOps[1] = Records.getAllDerivedDefinitions("OptionalDefOperand");
1767 // Find some SDNode.
1768 assert(!SDNodes.empty() && "No SDNodes parsed?");
1769 Init *SomeSDNode = new DefInit(SDNodes.begin()->first);
1771 for (unsigned iter = 0; iter != 2; ++iter) {
1772 for (unsigned i = 0, e = DefaultOps[iter].size(); i != e; ++i) {
1773 DagInit *DefaultInfo = DefaultOps[iter][i]->getValueAsDag("DefaultOps");
1775 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
1776 // SomeSDnode so that we can parse this.
1777 std::vector<std::pair<Init*, std::string> > Ops;
1778 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
1779 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
1780 DefaultInfo->getArgName(op)));
1781 DagInit *DI = new DagInit(SomeSDNode, "", Ops);
1783 // Create a TreePattern to parse this.
1784 TreePattern P(DefaultOps[iter][i], DI, false, *this);
1785 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
1787 // Copy the operands over into a DAGDefaultOperand.
1788 DAGDefaultOperand DefaultOpInfo;
1790 TreePatternNode *T = P.getTree(0);
1791 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
1792 TreePatternNode *TPN = T->getChild(op);
1793 while (TPN->ApplyTypeConstraints(P, false))
1794 /* Resolve all types */;
1796 if (TPN->ContainsUnresolvedType()) {
1798 throw "Value #" + utostr(i) + " of PredicateOperand '" +
1799 DefaultOps[iter][i]->getName() +"' doesn't have a concrete type!";
1801 throw "Value #" + utostr(i) + " of OptionalDefOperand '" +
1802 DefaultOps[iter][i]->getName() +"' doesn't have a concrete type!";
1804 DefaultOpInfo.DefaultOps.push_back(TPN);
1807 // Insert it into the DefaultOperands map so we can find it later.
1808 DefaultOperands[DefaultOps[iter][i]] = DefaultOpInfo;
1813 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
1814 /// instruction input. Return true if this is a real use.
1815 static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
1816 std::map<std::string, TreePatternNode*> &InstInputs,
1817 std::vector<Record*> &InstImpInputs) {
1818 // No name -> not interesting.
1819 if (Pat->getName().empty()) {
1820 if (Pat->isLeaf()) {
1821 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1822 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1823 I->error("Input " + DI->getDef()->getName() + " must be named!");
1824 else if (DI && DI->getDef()->isSubClassOf("Register"))
1825 InstImpInputs.push_back(DI->getDef());
1831 if (Pat->isLeaf()) {
1832 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1833 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
1836 Rec = Pat->getOperator();
1839 // SRCVALUE nodes are ignored.
1840 if (Rec->getName() == "srcvalue")
1843 TreePatternNode *&Slot = InstInputs[Pat->getName()];
1849 if (Slot->isLeaf()) {
1850 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
1852 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
1853 SlotRec = Slot->getOperator();
1856 // Ensure that the inputs agree if we've already seen this input.
1858 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1859 if (Slot->getExtType() != Pat->getExtType())
1860 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1864 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
1865 /// part of "I", the instruction), computing the set of inputs and outputs of
1866 /// the pattern. Report errors if we see anything naughty.
1867 void CodeGenDAGPatterns::
1868 FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
1869 std::map<std::string, TreePatternNode*> &InstInputs,
1870 std::map<std::string, TreePatternNode*>&InstResults,
1871 std::vector<Record*> &InstImpInputs,
1872 std::vector<Record*> &InstImpResults) {
1873 if (Pat->isLeaf()) {
1874 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1875 if (!isUse && Pat->getTransformFn())
1876 I->error("Cannot specify a transform function for a non-input value!");
1880 if (Pat->getOperator()->getName() == "implicit") {
1881 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1882 TreePatternNode *Dest = Pat->getChild(i);
1883 if (!Dest->isLeaf())
1884 I->error("implicitly defined value should be a register!");
1886 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1887 if (!Val || !Val->getDef()->isSubClassOf("Register"))
1888 I->error("implicitly defined value should be a register!");
1889 InstImpResults.push_back(Val->getDef());
1894 if (Pat->getOperator()->getName() != "set") {
1895 // If this is not a set, verify that the children nodes are not void typed,
1897 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1898 if (Pat->getChild(i)->getType() == MVT::isVoid)
1899 I->error("Cannot have void nodes inside of patterns!");
1900 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
1901 InstImpInputs, InstImpResults);
1904 // If this is a non-leaf node with no children, treat it basically as if
1905 // it were a leaf. This handles nodes like (imm).
1906 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1908 if (!isUse && Pat->getTransformFn())
1909 I->error("Cannot specify a transform function for a non-input value!");
1913 // Otherwise, this is a set, validate and collect instruction results.
1914 if (Pat->getNumChildren() == 0)
1915 I->error("set requires operands!");
1917 if (Pat->getTransformFn())
1918 I->error("Cannot specify a transform function on a set node!");
1920 // Check the set destinations.
1921 unsigned NumDests = Pat->getNumChildren()-1;
1922 for (unsigned i = 0; i != NumDests; ++i) {
1923 TreePatternNode *Dest = Pat->getChild(i);
1924 if (!Dest->isLeaf())
1925 I->error("set destination should be a register!");
1927 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1929 I->error("set destination should be a register!");
1931 if (Val->getDef()->isSubClassOf("RegisterClass") ||
1932 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
1933 if (Dest->getName().empty())
1934 I->error("set destination must have a name!");
1935 if (InstResults.count(Dest->getName()))
1936 I->error("cannot set '" + Dest->getName() +"' multiple times");
1937 InstResults[Dest->getName()] = Dest;
1938 } else if (Val->getDef()->isSubClassOf("Register")) {
1939 InstImpResults.push_back(Val->getDef());
1941 I->error("set destination should be a register!");
1945 // Verify and collect info from the computation.
1946 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
1947 InstInputs, InstResults,
1948 InstImpInputs, InstImpResults);
1951 //===----------------------------------------------------------------------===//
1952 // Instruction Analysis
1953 //===----------------------------------------------------------------------===//
1955 class InstAnalyzer {
1956 const CodeGenDAGPatterns &CDP;
1959 bool &HasSideEffects;
1961 InstAnalyzer(const CodeGenDAGPatterns &cdp,
1962 bool &maystore, bool &mayload, bool &hse)
1963 : CDP(cdp), mayStore(maystore), mayLoad(mayload), HasSideEffects(hse){
1966 /// Analyze - Analyze the specified instruction, returning true if the
1967 /// instruction had a pattern.
1968 bool Analyze(Record *InstRecord) {
1969 const TreePattern *Pattern = CDP.getInstruction(InstRecord).getPattern();
1972 return false; // No pattern.
1975 // FIXME: Assume only the first tree is the pattern. The others are clobber
1977 AnalyzeNode(Pattern->getTree(0));
1982 void AnalyzeNode(const TreePatternNode *N) {
1984 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
1985 Record *LeafRec = DI->getDef();
1986 // Handle ComplexPattern leaves.
1987 if (LeafRec->isSubClassOf("ComplexPattern")) {
1988 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
1989 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
1990 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
1991 if (CP.hasProperty(SDNPSideEffect)) HasSideEffects = true;
1997 // Analyze children.
1998 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1999 AnalyzeNode(N->getChild(i));
2001 // Ignore set nodes, which are not SDNodes.
2002 if (N->getOperator()->getName() == "set")
2005 // Get information about the SDNode for the operator.
2006 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N->getOperator());
2008 // Notice properties of the node.
2009 if (OpInfo.hasProperty(SDNPMayStore)) mayStore = true;
2010 if (OpInfo.hasProperty(SDNPMayLoad)) mayLoad = true;
2011 if (OpInfo.hasProperty(SDNPSideEffect)) HasSideEffects = true;
2013 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
2014 // If this is an intrinsic, analyze it.
2015 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
2016 mayLoad = true;// These may load memory.
2018 if (IntInfo->ModRef >= CodeGenIntrinsic::WriteArgMem)
2019 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
2021 if (IntInfo->ModRef >= CodeGenIntrinsic::WriteMem)
2022 // WriteMem intrinsics can have other strange effects.
2023 HasSideEffects = true;
2029 static void InferFromPattern(const CodeGenInstruction &Inst,
2030 bool &MayStore, bool &MayLoad,
2031 bool &HasSideEffects,
2032 const CodeGenDAGPatterns &CDP) {
2033 MayStore = MayLoad = HasSideEffects = false;
2036 InstAnalyzer(CDP, MayStore, MayLoad, HasSideEffects).Analyze(Inst.TheDef);
2038 // InstAnalyzer only correctly analyzes mayStore/mayLoad so far.
2039 if (Inst.mayStore) { // If the .td file explicitly sets mayStore, use it.
2040 // If we decided that this is a store from the pattern, then the .td file
2041 // entry is redundant.
2044 "Warning: mayStore flag explicitly set on instruction '%s'"
2045 " but flag already inferred from pattern.\n",
2046 Inst.TheDef->getName().c_str());
2050 if (Inst.mayLoad) { // If the .td file explicitly sets mayLoad, use it.
2051 // If we decided that this is a load from the pattern, then the .td file
2052 // entry is redundant.
2055 "Warning: mayLoad flag explicitly set on instruction '%s'"
2056 " but flag already inferred from pattern.\n",
2057 Inst.TheDef->getName().c_str());
2061 if (Inst.neverHasSideEffects) {
2063 fprintf(stderr, "Warning: neverHasSideEffects set on instruction '%s' "
2064 "which already has a pattern\n", Inst.TheDef->getName().c_str());
2065 HasSideEffects = false;
2068 if (Inst.hasSideEffects) {
2070 fprintf(stderr, "Warning: hasSideEffects set on instruction '%s' "
2071 "which already inferred this.\n", Inst.TheDef->getName().c_str());
2072 HasSideEffects = true;
2076 /// ParseInstructions - Parse all of the instructions, inlining and resolving
2077 /// any fragments involved. This populates the Instructions list with fully
2078 /// resolved instructions.
2079 void CodeGenDAGPatterns::ParseInstructions() {
2080 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
2082 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
2085 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
2086 LI = Instrs[i]->getValueAsListInit("Pattern");
2088 // If there is no pattern, only collect minimal information about the
2089 // instruction for its operand list. We have to assume that there is one
2090 // result, as we have no detailed info.
2091 if (!LI || LI->getSize() == 0) {
2092 std::vector<Record*> Results;
2093 std::vector<Record*> Operands;
2095 CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
2097 if (InstInfo.OperandList.size() != 0) {
2098 if (InstInfo.NumDefs == 0) {
2099 // These produce no results
2100 for (unsigned j = 0, e = InstInfo.OperandList.size(); j < e; ++j)
2101 Operands.push_back(InstInfo.OperandList[j].Rec);
2103 // Assume the first operand is the result.
2104 Results.push_back(InstInfo.OperandList[0].Rec);
2106 // The rest are inputs.
2107 for (unsigned j = 1, e = InstInfo.OperandList.size(); j < e; ++j)
2108 Operands.push_back(InstInfo.OperandList[j].Rec);
2112 // Create and insert the instruction.
2113 std::vector<Record*> ImpResults;
2114 std::vector<Record*> ImpOperands;
2115 Instructions.insert(std::make_pair(Instrs[i],
2116 DAGInstruction(0, Results, Operands, ImpResults,
2118 continue; // no pattern.
2121 // Parse the instruction.
2122 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
2123 // Inline pattern fragments into it.
2124 I->InlinePatternFragments();
2126 // Infer as many types as possible. If we cannot infer all of them, we can
2127 // never do anything with this instruction pattern: report it to the user.
2128 if (!I->InferAllTypes())
2129 I->error("Could not infer all types in pattern!");
2131 // InstInputs - Keep track of all of the inputs of the instruction, along
2132 // with the record they are declared as.
2133 std::map<std::string, TreePatternNode*> InstInputs;
2135 // InstResults - Keep track of all the virtual registers that are 'set'
2136 // in the instruction, including what reg class they are.
2137 std::map<std::string, TreePatternNode*> InstResults;
2139 std::vector<Record*> InstImpInputs;
2140 std::vector<Record*> InstImpResults;
2142 // Verify that the top-level forms in the instruction are of void type, and
2143 // fill in the InstResults map.
2144 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
2145 TreePatternNode *Pat = I->getTree(j);
2146 if (!Pat->hasTypeSet() || Pat->getType() != MVT::isVoid)
2147 I->error("Top-level forms in instruction pattern should have"
2150 // Find inputs and outputs, and verify the structure of the uses/defs.
2151 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
2152 InstImpInputs, InstImpResults);
2155 // Now that we have inputs and outputs of the pattern, inspect the operands
2156 // list for the instruction. This determines the order that operands are
2157 // added to the machine instruction the node corresponds to.
2158 unsigned NumResults = InstResults.size();
2160 // Parse the operands list from the (ops) list, validating it.
2161 assert(I->getArgList().empty() && "Args list should still be empty here!");
2162 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]);
2164 // Check that all of the results occur first in the list.
2165 std::vector<Record*> Results;
2166 TreePatternNode *Res0Node = NULL;
2167 for (unsigned i = 0; i != NumResults; ++i) {
2168 if (i == CGI.OperandList.size())
2169 I->error("'" + InstResults.begin()->first +
2170 "' set but does not appear in operand list!");
2171 const std::string &OpName = CGI.OperandList[i].Name;
2173 // Check that it exists in InstResults.
2174 TreePatternNode *RNode = InstResults[OpName];
2176 I->error("Operand $" + OpName + " does not exist in operand list!");
2180 Record *R = dynamic_cast<DefInit*>(RNode->getLeafValue())->getDef();
2182 I->error("Operand $" + OpName + " should be a set destination: all "
2183 "outputs must occur before inputs in operand list!");
2185 if (CGI.OperandList[i].Rec != R)
2186 I->error("Operand $" + OpName + " class mismatch!");
2188 // Remember the return type.
2189 Results.push_back(CGI.OperandList[i].Rec);
2191 // Okay, this one checks out.
2192 InstResults.erase(OpName);
2195 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
2196 // the copy while we're checking the inputs.
2197 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
2199 std::vector<TreePatternNode*> ResultNodeOperands;
2200 std::vector<Record*> Operands;
2201 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
2202 CodeGenInstruction::OperandInfo &Op = CGI.OperandList[i];
2203 const std::string &OpName = Op.Name;
2205 I->error("Operand #" + utostr(i) + " in operands list has no name!");
2207 if (!InstInputsCheck.count(OpName)) {
2208 // If this is an predicate operand or optional def operand with an
2209 // DefaultOps set filled in, we can ignore this. When we codegen it,
2210 // we will do so as always executed.
2211 if (Op.Rec->isSubClassOf("PredicateOperand") ||
2212 Op.Rec->isSubClassOf("OptionalDefOperand")) {
2213 // Does it have a non-empty DefaultOps field? If so, ignore this
2215 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
2218 I->error("Operand $" + OpName +
2219 " does not appear in the instruction pattern");
2221 TreePatternNode *InVal = InstInputsCheck[OpName];
2222 InstInputsCheck.erase(OpName); // It occurred, remove from map.
2224 if (InVal->isLeaf() &&
2225 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
2226 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
2227 if (Op.Rec != InRec && !InRec->isSubClassOf("ComplexPattern"))
2228 I->error("Operand $" + OpName + "'s register class disagrees"
2229 " between the operand and pattern");
2231 Operands.push_back(Op.Rec);
2233 // Construct the result for the dest-pattern operand list.
2234 TreePatternNode *OpNode = InVal->clone();
2236 // No predicate is useful on the result.
2237 OpNode->clearPredicateFns();
2239 // Promote the xform function to be an explicit node if set.
2240 if (Record *Xform = OpNode->getTransformFn()) {
2241 OpNode->setTransformFn(0);
2242 std::vector<TreePatternNode*> Children;
2243 Children.push_back(OpNode);
2244 OpNode = new TreePatternNode(Xform, Children);
2247 ResultNodeOperands.push_back(OpNode);
2250 if (!InstInputsCheck.empty())
2251 I->error("Input operand $" + InstInputsCheck.begin()->first +
2252 " occurs in pattern but not in operands list!");
2254 TreePatternNode *ResultPattern =
2255 new TreePatternNode(I->getRecord(), ResultNodeOperands);
2256 // Copy fully inferred output node type to instruction result pattern.
2258 ResultPattern->setType(Res0Node->getExtType());
2260 // Create and insert the instruction.
2261 // FIXME: InstImpResults and InstImpInputs should not be part of
2263 DAGInstruction TheInst(I, Results, Operands, InstImpResults, InstImpInputs);
2264 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
2266 // Use a temporary tree pattern to infer all types and make sure that the
2267 // constructed result is correct. This depends on the instruction already
2268 // being inserted into the Instructions map.
2269 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
2270 Temp.InferAllTypes(&I->getNamedNodesMap());
2272 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
2273 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
2278 // If we can, convert the instructions to be patterns that are matched!
2279 for (std::map<Record*, DAGInstruction, RecordPtrCmp>::iterator II =
2280 Instructions.begin(),
2281 E = Instructions.end(); II != E; ++II) {
2282 DAGInstruction &TheInst = II->second;
2283 const TreePattern *I = TheInst.getPattern();
2284 if (I == 0) continue; // No pattern.
2286 // FIXME: Assume only the first tree is the pattern. The others are clobber
2288 TreePatternNode *Pattern = I->getTree(0);
2289 TreePatternNode *SrcPattern;
2290 if (Pattern->getOperator()->getName() == "set") {
2291 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
2293 // Not a set (store or something?)
2294 SrcPattern = Pattern;
2297 Record *Instr = II->first;
2298 AddPatternToMatch(I,
2299 PatternToMatch(Instr->getValueAsListInit("Predicates"),
2301 TheInst.getResultPattern(),
2302 TheInst.getImpResults(),
2303 Instr->getValueAsInt("AddedComplexity"),
2309 typedef std::pair<const TreePatternNode*, unsigned> NameRecord;
2311 static void FindNames(const TreePatternNode *P,
2312 std::map<std::string, NameRecord> &Names,
2313 const TreePattern *PatternTop) {
2314 if (!P->getName().empty()) {
2315 NameRecord &Rec = Names[P->getName()];
2316 // If this is the first instance of the name, remember the node.
2317 if (Rec.second++ == 0)
2319 else if (Rec.first->getType() != P->getType())
2320 PatternTop->error("repetition of value: $" + P->getName() +
2321 " where different uses have different types!");
2325 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
2326 FindNames(P->getChild(i), Names, PatternTop);
2330 void CodeGenDAGPatterns::AddPatternToMatch(const TreePattern *Pattern,
2331 const PatternToMatch &PTM) {
2332 // Do some sanity checking on the pattern we're about to match.
2334 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this))
2335 Pattern->error("Pattern can never match: " + Reason);
2337 // If the source pattern's root is a complex pattern, that complex pattern
2338 // must specify the nodes it can potentially match.
2339 if (const ComplexPattern *CP =
2340 PTM.getSrcPattern()->getComplexPatternInfo(*this))
2341 if (CP->getRootNodes().empty())
2342 Pattern->error("ComplexPattern at root must specify list of opcodes it"
2346 // Find all of the named values in the input and output, ensure they have the
2348 std::map<std::string, NameRecord> SrcNames, DstNames;
2349 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
2350 FindNames(PTM.getDstPattern(), DstNames, Pattern);
2352 // Scan all of the named values in the destination pattern, rejecting them if
2353 // they don't exist in the input pattern.
2354 for (std::map<std::string, NameRecord>::iterator
2355 I = DstNames.begin(), E = DstNames.end(); I != E; ++I) {
2356 if (SrcNames[I->first].first == 0)
2357 Pattern->error("Pattern has input without matching name in output: $" +
2361 // Scan all of the named values in the source pattern, rejecting them if the
2362 // name isn't used in the dest, and isn't used to tie two values together.
2363 for (std::map<std::string, NameRecord>::iterator
2364 I = SrcNames.begin(), E = SrcNames.end(); I != E; ++I)
2365 if (DstNames[I->first].first == 0 && SrcNames[I->first].second == 1)
2366 Pattern->error("Pattern has dead named input: $" + I->first);
2368 PatternsToMatch.push_back(PTM);
2373 void CodeGenDAGPatterns::InferInstructionFlags() {
2374 const std::vector<const CodeGenInstruction*> &Instructions =
2375 Target.getInstructionsByEnumValue();
2376 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
2377 CodeGenInstruction &InstInfo =
2378 const_cast<CodeGenInstruction &>(*Instructions[i]);
2379 // Determine properties of the instruction from its pattern.
2380 bool MayStore, MayLoad, HasSideEffects;
2381 InferFromPattern(InstInfo, MayStore, MayLoad, HasSideEffects, *this);
2382 InstInfo.mayStore = MayStore;
2383 InstInfo.mayLoad = MayLoad;
2384 InstInfo.hasSideEffects = HasSideEffects;
2388 /// Given a pattern result with an unresolved type, see if we can find one
2389 /// instruction with an unresolved result type. Force this result type to an
2390 /// arbitrary element if it's possible types to converge results.
2391 static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
2395 // Analyze children.
2396 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2397 if (ForceArbitraryInstResultType(N->getChild(i), TP))
2400 if (!N->getOperator()->isSubClassOf("Instruction"))
2403 // If this type is already concrete or completely unknown we can't do
2405 if (N->getExtType().isCompletelyUnknown() || N->getExtType().isConcrete())
2408 // Otherwise, force its type to the first possibility (an arbitrary choice).
2409 return N->getExtType().MergeInTypeInfo(N->getExtType().getTypeList()[0], TP);
2412 void CodeGenDAGPatterns::ParsePatterns() {
2413 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
2415 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
2416 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
2417 DefInit *OpDef = dynamic_cast<DefInit*>(Tree->getOperator());
2418 Record *Operator = OpDef->getDef();
2419 TreePattern *Pattern;
2420 if (Operator->getName() != "parallel")
2421 Pattern = new TreePattern(Patterns[i], Tree, true, *this);
2423 std::vector<Init*> Values;
2425 for (unsigned j = 0, ee = Tree->getNumArgs(); j != ee; ++j) {
2426 Values.push_back(Tree->getArg(j));
2427 TypedInit *TArg = dynamic_cast<TypedInit*>(Tree->getArg(j));
2429 errs() << "In dag: " << Tree->getAsString();
2430 errs() << " -- Untyped argument in pattern\n";
2431 assert(0 && "Untyped argument in pattern");
2434 ListTy = resolveTypes(ListTy, TArg->getType());
2436 errs() << "In dag: " << Tree->getAsString();
2437 errs() << " -- Incompatible types in pattern arguments\n";
2438 assert(0 && "Incompatible types in pattern arguments");
2442 ListTy = TArg->getType();
2445 ListInit *LI = new ListInit(Values, new ListRecTy(ListTy));
2446 Pattern = new TreePattern(Patterns[i], LI, true, *this);
2449 // Inline pattern fragments into it.
2450 Pattern->InlinePatternFragments();
2452 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
2453 if (LI->getSize() == 0) continue; // no pattern.
2455 // Parse the instruction.
2456 TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
2458 // Inline pattern fragments into it.
2459 Result->InlinePatternFragments();
2461 if (Result->getNumTrees() != 1)
2462 Result->error("Cannot handle instructions producing instructions "
2463 "with temporaries yet!");
2465 bool IterateInference;
2466 bool InferredAllPatternTypes, InferredAllResultTypes;
2468 // Infer as many types as possible. If we cannot infer all of them, we
2469 // can never do anything with this pattern: report it to the user.
2470 InferredAllPatternTypes =
2471 Pattern->InferAllTypes(&Pattern->getNamedNodesMap());
2473 // Infer as many types as possible. If we cannot infer all of them, we
2474 // can never do anything with this pattern: report it to the user.
2475 InferredAllResultTypes =
2476 Result->InferAllTypes(&Pattern->getNamedNodesMap());
2478 IterateInference = false;
2480 // Apply the type of the result to the source pattern. This helps us
2481 // resolve cases where the input type is known to be a pointer type (which
2482 // is considered resolved), but the result knows it needs to be 32- or
2483 // 64-bits. Infer the other way for good measure.
2484 if (!Result->getTree(0)->getExtType().isVoid() &&
2485 !Pattern->getTree(0)->getExtType().isVoid()) {
2486 IterateInference = Pattern->getTree(0)->
2487 UpdateNodeType(Result->getTree(0)->getExtType(), *Result);
2488 IterateInference |= Result->getTree(0)->
2489 UpdateNodeType(Pattern->getTree(0)->getExtType(), *Result);
2492 // If our iteration has converged and the input pattern's types are fully
2493 // resolved but the result pattern is not fully resolved, we may have a
2494 // situation where we have two instructions in the result pattern and
2495 // the instructions require a common register class, but don't care about
2496 // what actual MVT is used. This is actually a bug in our modelling:
2497 // output patterns should have register classes, not MVTs.
2499 // In any case, to handle this, we just go through and disambiguate some
2500 // arbitrary types to the result pattern's nodes.
2501 if (!IterateInference && InferredAllPatternTypes &&
2502 !InferredAllResultTypes)
2503 IterateInference = ForceArbitraryInstResultType(Result->getTree(0),
2505 } while (IterateInference);
2507 // Verify that we inferred enough types that we can do something with the
2508 // pattern and result. If these fire the user has to add type casts.
2509 if (!InferredAllPatternTypes)
2510 Pattern->error("Could not infer all types in pattern!");
2511 if (!InferredAllResultTypes) {
2513 Result->error("Could not infer all types in pattern result!");
2516 // Validate that the input pattern is correct.
2517 std::map<std::string, TreePatternNode*> InstInputs;
2518 std::map<std::string, TreePatternNode*> InstResults;
2519 std::vector<Record*> InstImpInputs;
2520 std::vector<Record*> InstImpResults;
2521 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
2522 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
2523 InstInputs, InstResults,
2524 InstImpInputs, InstImpResults);
2526 // Promote the xform function to be an explicit node if set.
2527 TreePatternNode *DstPattern = Result->getOnlyTree();
2528 std::vector<TreePatternNode*> ResultNodeOperands;
2529 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
2530 TreePatternNode *OpNode = DstPattern->getChild(ii);
2531 if (Record *Xform = OpNode->getTransformFn()) {
2532 OpNode->setTransformFn(0);
2533 std::vector<TreePatternNode*> Children;
2534 Children.push_back(OpNode);
2535 OpNode = new TreePatternNode(Xform, Children);
2537 ResultNodeOperands.push_back(OpNode);
2539 DstPattern = Result->getOnlyTree();
2540 if (!DstPattern->isLeaf())
2541 DstPattern = new TreePatternNode(DstPattern->getOperator(),
2542 ResultNodeOperands);
2543 DstPattern->setType(Result->getOnlyTree()->getExtType());
2544 TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
2545 Temp.InferAllTypes();
2548 AddPatternToMatch(Pattern,
2549 PatternToMatch(Patterns[i]->getValueAsListInit("Predicates"),
2550 Pattern->getTree(0),
2551 Temp.getOnlyTree(), InstImpResults,
2552 Patterns[i]->getValueAsInt("AddedComplexity"),
2553 Patterns[i]->getID()));
2557 /// CombineChildVariants - Given a bunch of permutations of each child of the
2558 /// 'operator' node, put them together in all possible ways.
2559 static void CombineChildVariants(TreePatternNode *Orig,
2560 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
2561 std::vector<TreePatternNode*> &OutVariants,
2562 CodeGenDAGPatterns &CDP,
2563 const MultipleUseVarSet &DepVars) {
2564 // Make sure that each operand has at least one variant to choose from.
2565 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2566 if (ChildVariants[i].empty())
2569 // The end result is an all-pairs construction of the resultant pattern.
2570 std::vector<unsigned> Idxs;
2571 Idxs.resize(ChildVariants.size());
2575 DEBUG(if (!Idxs.empty()) {
2576 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
2577 for (unsigned i = 0; i < Idxs.size(); ++i) {
2578 errs() << Idxs[i] << " ";
2583 // Create the variant and add it to the output list.
2584 std::vector<TreePatternNode*> NewChildren;
2585 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2586 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
2587 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
2589 // Copy over properties.
2590 R->setName(Orig->getName());
2591 R->setPredicateFns(Orig->getPredicateFns());
2592 R->setTransformFn(Orig->getTransformFn());
2593 R->setType(Orig->getExtType());
2595 // If this pattern cannot match, do not include it as a variant.
2596 std::string ErrString;
2597 if (!R->canPatternMatch(ErrString, CDP)) {
2600 bool AlreadyExists = false;
2602 // Scan to see if this pattern has already been emitted. We can get
2603 // duplication due to things like commuting:
2604 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
2605 // which are the same pattern. Ignore the dups.
2606 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
2607 if (R->isIsomorphicTo(OutVariants[i], DepVars)) {
2608 AlreadyExists = true;
2615 OutVariants.push_back(R);
2618 // Increment indices to the next permutation by incrementing the
2619 // indicies from last index backward, e.g., generate the sequence
2620 // [0, 0], [0, 1], [1, 0], [1, 1].
2622 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
2623 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
2628 NotDone = (IdxsIdx >= 0);
2632 /// CombineChildVariants - A helper function for binary operators.
2634 static void CombineChildVariants(TreePatternNode *Orig,
2635 const std::vector<TreePatternNode*> &LHS,
2636 const std::vector<TreePatternNode*> &RHS,
2637 std::vector<TreePatternNode*> &OutVariants,
2638 CodeGenDAGPatterns &CDP,
2639 const MultipleUseVarSet &DepVars) {
2640 std::vector<std::vector<TreePatternNode*> > ChildVariants;
2641 ChildVariants.push_back(LHS);
2642 ChildVariants.push_back(RHS);
2643 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
2647 static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
2648 std::vector<TreePatternNode *> &Children) {
2649 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
2650 Record *Operator = N->getOperator();
2652 // Only permit raw nodes.
2653 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
2654 N->getTransformFn()) {
2655 Children.push_back(N);
2659 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
2660 Children.push_back(N->getChild(0));
2662 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
2664 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
2665 Children.push_back(N->getChild(1));
2667 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
2670 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
2671 /// the (potentially recursive) pattern by using algebraic laws.
2673 static void GenerateVariantsOf(TreePatternNode *N,
2674 std::vector<TreePatternNode*> &OutVariants,
2675 CodeGenDAGPatterns &CDP,
2676 const MultipleUseVarSet &DepVars) {
2677 // We cannot permute leaves.
2679 OutVariants.push_back(N);
2683 // Look up interesting info about the node.
2684 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
2686 // If this node is associative, re-associate.
2687 if (NodeInfo.hasProperty(SDNPAssociative)) {
2688 // Re-associate by pulling together all of the linked operators
2689 std::vector<TreePatternNode*> MaximalChildren;
2690 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
2692 // Only handle child sizes of 3. Otherwise we'll end up trying too many
2694 if (MaximalChildren.size() == 3) {
2695 // Find the variants of all of our maximal children.
2696 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
2697 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
2698 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
2699 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
2701 // There are only two ways we can permute the tree:
2702 // (A op B) op C and A op (B op C)
2703 // Within these forms, we can also permute A/B/C.
2705 // Generate legal pair permutations of A/B/C.
2706 std::vector<TreePatternNode*> ABVariants;
2707 std::vector<TreePatternNode*> BAVariants;
2708 std::vector<TreePatternNode*> ACVariants;
2709 std::vector<TreePatternNode*> CAVariants;
2710 std::vector<TreePatternNode*> BCVariants;
2711 std::vector<TreePatternNode*> CBVariants;
2712 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
2713 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
2714 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
2715 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
2716 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
2717 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
2719 // Combine those into the result: (x op x) op x
2720 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
2721 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
2722 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
2723 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
2724 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
2725 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
2727 // Combine those into the result: x op (x op x)
2728 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
2729 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
2730 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
2731 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
2732 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
2733 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
2738 // Compute permutations of all children.
2739 std::vector<std::vector<TreePatternNode*> > ChildVariants;
2740 ChildVariants.resize(N->getNumChildren());
2741 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2742 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
2744 // Build all permutations based on how the children were formed.
2745 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
2747 // If this node is commutative, consider the commuted order.
2748 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
2749 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
2750 assert((N->getNumChildren()==2 || isCommIntrinsic) &&
2751 "Commutative but doesn't have 2 children!");
2752 // Don't count children which are actually register references.
2754 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2755 TreePatternNode *Child = N->getChild(i);
2756 if (Child->isLeaf())
2757 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2758 Record *RR = DI->getDef();
2759 if (RR->isSubClassOf("Register"))
2764 // Consider the commuted order.
2765 if (isCommIntrinsic) {
2766 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
2767 // operands are the commutative operands, and there might be more operands
2770 "Commutative intrinsic should have at least 3 childrean!");
2771 std::vector<std::vector<TreePatternNode*> > Variants;
2772 Variants.push_back(ChildVariants[0]); // Intrinsic id.
2773 Variants.push_back(ChildVariants[2]);
2774 Variants.push_back(ChildVariants[1]);
2775 for (unsigned i = 3; i != NC; ++i)
2776 Variants.push_back(ChildVariants[i]);
2777 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
2779 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
2780 OutVariants, CDP, DepVars);
2785 // GenerateVariants - Generate variants. For example, commutative patterns can
2786 // match multiple ways. Add them to PatternsToMatch as well.
2787 void CodeGenDAGPatterns::GenerateVariants() {
2788 DEBUG(errs() << "Generating instruction variants.\n");
2790 // Loop over all of the patterns we've collected, checking to see if we can
2791 // generate variants of the instruction, through the exploitation of
2792 // identities. This permits the target to provide aggressive matching without
2793 // the .td file having to contain tons of variants of instructions.
2795 // Note that this loop adds new patterns to the PatternsToMatch list, but we
2796 // intentionally do not reconsider these. Any variants of added patterns have
2797 // already been added.
2799 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
2800 MultipleUseVarSet DepVars;
2801 std::vector<TreePatternNode*> Variants;
2802 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
2803 DEBUG(errs() << "Dependent/multiply used variables: ");
2804 DEBUG(DumpDepVars(DepVars));
2805 DEBUG(errs() << "\n");
2806 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this, DepVars);
2808 assert(!Variants.empty() && "Must create at least original variant!");
2809 Variants.erase(Variants.begin()); // Remove the original pattern.
2811 if (Variants.empty()) // No variants for this pattern.
2814 DEBUG(errs() << "FOUND VARIANTS OF: ";
2815 PatternsToMatch[i].getSrcPattern()->dump();
2818 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
2819 TreePatternNode *Variant = Variants[v];
2821 DEBUG(errs() << " VAR#" << v << ": ";
2825 // Scan to see if an instruction or explicit pattern already matches this.
2826 bool AlreadyExists = false;
2827 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
2828 // Skip if the top level predicates do not match.
2829 if (PatternsToMatch[i].getPredicates() !=
2830 PatternsToMatch[p].getPredicates())
2832 // Check to see if this variant already exists.
2833 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(), DepVars)) {
2834 DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
2835 AlreadyExists = true;
2839 // If we already have it, ignore the variant.
2840 if (AlreadyExists) continue;
2842 // Otherwise, add it to the list of patterns we have.
2844 push_back(PatternToMatch(PatternsToMatch[i].getPredicates(),
2845 Variant, PatternsToMatch[i].getDstPattern(),
2846 PatternsToMatch[i].getDstRegs(),
2847 PatternsToMatch[i].getAddedComplexity(),
2848 Record::getNewUID()));
2851 DEBUG(errs() << "\n");