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;
675 errs() << "Unknown SD Node property '" << PropList[i]->getName()
676 << "' on node '" << R->getName() << "'!\n";
682 // Parse the type constraints.
683 std::vector<Record*> ConstraintList =
684 TypeProfile->getValueAsListOfDefs("Constraints");
685 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
688 /// getKnownType - If the type constraints on this node imply a fixed type
689 /// (e.g. all stores return void, etc), then return it as an
690 /// MVT::SimpleValueType. Otherwise, return EEVT::Other.
691 MVT::SimpleValueType SDNodeInfo::getKnownType() const {
692 unsigned NumResults = getNumResults();
693 assert(NumResults <= 1 &&
694 "We only work with nodes with zero or one result so far!");
696 for (unsigned i = 0, e = TypeConstraints.size(); i != e; ++i) {
697 // Make sure that this applies to the correct node result.
698 if (TypeConstraints[i].OperandNo >= NumResults) // FIXME: need value #
701 switch (TypeConstraints[i].ConstraintType) {
703 case SDTypeConstraint::SDTCisVT:
704 return TypeConstraints[i].x.SDTCisVT_Info.VT;
705 case SDTypeConstraint::SDTCisPtrTy:
712 //===----------------------------------------------------------------------===//
713 // TreePatternNode implementation
716 TreePatternNode::~TreePatternNode() {
717 #if 0 // FIXME: implement refcounted tree nodes!
718 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
725 void TreePatternNode::print(raw_ostream &OS) const {
727 OS << *getLeafValue();
729 OS << '(' << getOperator()->getName();
732 if (!isTypeCompletelyUnknown())
733 OS << ':' << getExtType().getName();
736 if (getNumChildren() != 0) {
738 getChild(0)->print(OS);
739 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
741 getChild(i)->print(OS);
747 for (unsigned i = 0, e = PredicateFns.size(); i != e; ++i)
748 OS << "<<P:" << PredicateFns[i] << ">>";
750 OS << "<<X:" << TransformFn->getName() << ">>";
751 if (!getName().empty())
752 OS << ":$" << getName();
755 void TreePatternNode::dump() const {
759 /// isIsomorphicTo - Return true if this node is recursively
760 /// isomorphic to the specified node. For this comparison, the node's
761 /// entire state is considered. The assigned name is ignored, since
762 /// nodes with differing names are considered isomorphic. However, if
763 /// the assigned name is present in the dependent variable set, then
764 /// the assigned name is considered significant and the node is
765 /// isomorphic if the names match.
766 bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
767 const MultipleUseVarSet &DepVars) const {
768 if (N == this) return true;
769 if (N->isLeaf() != isLeaf() || getExtType() != N->getExtType() ||
770 getPredicateFns() != N->getPredicateFns() ||
771 getTransformFn() != N->getTransformFn())
775 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
776 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue())) {
777 return ((DI->getDef() == NDI->getDef())
778 && (DepVars.find(getName()) == DepVars.end()
779 || getName() == N->getName()));
782 return getLeafValue() == N->getLeafValue();
785 if (N->getOperator() != getOperator() ||
786 N->getNumChildren() != getNumChildren()) return false;
787 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
788 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
793 /// clone - Make a copy of this tree and all of its children.
795 TreePatternNode *TreePatternNode::clone() const {
796 TreePatternNode *New;
798 New = new TreePatternNode(getLeafValue());
800 std::vector<TreePatternNode*> CChildren;
801 CChildren.reserve(Children.size());
802 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
803 CChildren.push_back(getChild(i)->clone());
804 New = new TreePatternNode(getOperator(), CChildren);
806 New->setName(getName());
807 New->setType(getExtType());
808 New->setPredicateFns(getPredicateFns());
809 New->setTransformFn(getTransformFn());
813 /// RemoveAllTypes - Recursively strip all the types of this tree.
814 void TreePatternNode::RemoveAllTypes() {
815 setType(EEVT::TypeSet()); // Reset to unknown type.
816 if (isLeaf()) return;
817 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
818 getChild(i)->RemoveAllTypes();
822 /// SubstituteFormalArguments - Replace the formal arguments in this tree
823 /// with actual values specified by ArgMap.
824 void TreePatternNode::
825 SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
826 if (isLeaf()) return;
828 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
829 TreePatternNode *Child = getChild(i);
830 if (Child->isLeaf()) {
831 Init *Val = Child->getLeafValue();
832 if (dynamic_cast<DefInit*>(Val) &&
833 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
834 // We found a use of a formal argument, replace it with its value.
835 TreePatternNode *NewChild = ArgMap[Child->getName()];
836 assert(NewChild && "Couldn't find formal argument!");
837 assert((Child->getPredicateFns().empty() ||
838 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
839 "Non-empty child predicate clobbered!");
840 setChild(i, NewChild);
843 getChild(i)->SubstituteFormalArguments(ArgMap);
849 /// InlinePatternFragments - If this pattern refers to any pattern
850 /// fragments, inline them into place, giving us a pattern without any
851 /// PatFrag references.
852 TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
853 if (isLeaf()) return this; // nothing to do.
854 Record *Op = getOperator();
856 if (!Op->isSubClassOf("PatFrag")) {
857 // Just recursively inline children nodes.
858 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
859 TreePatternNode *Child = getChild(i);
860 TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
862 assert((Child->getPredicateFns().empty() ||
863 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
864 "Non-empty child predicate clobbered!");
866 setChild(i, NewChild);
871 // Otherwise, we found a reference to a fragment. First, look up its
872 // TreePattern record.
873 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
875 // Verify that we are passing the right number of operands.
876 if (Frag->getNumArgs() != Children.size())
877 TP.error("'" + Op->getName() + "' fragment requires " +
878 utostr(Frag->getNumArgs()) + " operands!");
880 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
882 std::string Code = Op->getValueAsCode("Predicate");
884 FragTree->addPredicateFn("Predicate_"+Op->getName());
886 // Resolve formal arguments to their actual value.
887 if (Frag->getNumArgs()) {
888 // Compute the map of formal to actual arguments.
889 std::map<std::string, TreePatternNode*> ArgMap;
890 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
891 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
893 FragTree->SubstituteFormalArguments(ArgMap);
896 FragTree->setName(getName());
897 FragTree->UpdateNodeType(getExtType(), TP);
899 // Transfer in the old predicates.
900 for (unsigned i = 0, e = getPredicateFns().size(); i != e; ++i)
901 FragTree->addPredicateFn(getPredicateFns()[i]);
903 // Get a new copy of this fragment to stitch into here.
904 //delete this; // FIXME: implement refcounting!
906 // The fragment we inlined could have recursive inlining that is needed. See
907 // if there are any pattern fragments in it and inline them as needed.
908 return FragTree->InlinePatternFragments(TP);
911 /// getImplicitType - Check to see if the specified record has an implicit
912 /// type which should be applied to it. This will infer the type of register
913 /// references from the register file information, for example.
915 static EEVT::TypeSet getImplicitType(Record *R, bool NotRegisters,
917 // Check to see if this is a register or a register class.
918 if (R->isSubClassOf("RegisterClass")) {
920 return EEVT::TypeSet(); // Unknown.
921 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
922 return EEVT::TypeSet(T.getRegisterClass(R).getValueTypes());
923 } else if (R->isSubClassOf("PatFrag")) {
924 // Pattern fragment types will be resolved when they are inlined.
925 return EEVT::TypeSet(); // Unknown.
926 } else if (R->isSubClassOf("Register")) {
928 return EEVT::TypeSet(); // Unknown.
929 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
930 return EEVT::TypeSet(T.getRegisterVTs(R));
931 } else if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
932 // Using a VTSDNode or CondCodeSDNode.
933 return EEVT::TypeSet(MVT::Other, TP);
934 } else if (R->isSubClassOf("ComplexPattern")) {
936 return EEVT::TypeSet(); // Unknown.
937 return EEVT::TypeSet(TP.getDAGPatterns().getComplexPattern(R).getValueType(),
939 } else if (R->isSubClassOf("PointerLikeRegClass")) {
940 return EEVT::TypeSet(MVT::iPTR, TP);
941 } else if (R->getName() == "node" || R->getName() == "srcvalue" ||
942 R->getName() == "zero_reg") {
944 return EEVT::TypeSet(); // Unknown.
947 TP.error("Unknown node flavor used in pattern: " + R->getName());
948 return EEVT::TypeSet(MVT::Other, TP);
952 /// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
953 /// CodeGenIntrinsic information for it, otherwise return a null pointer.
954 const CodeGenIntrinsic *TreePatternNode::
955 getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
956 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
957 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
958 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
962 dynamic_cast<IntInit*>(getChild(0)->getLeafValue())->getValue();
963 return &CDP.getIntrinsicInfo(IID);
966 /// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
967 /// return the ComplexPattern information, otherwise return null.
968 const ComplexPattern *
969 TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
970 if (!isLeaf()) return 0;
972 DefInit *DI = dynamic_cast<DefInit*>(getLeafValue());
973 if (DI && DI->getDef()->isSubClassOf("ComplexPattern"))
974 return &CGP.getComplexPattern(DI->getDef());
978 /// NodeHasProperty - Return true if this node has the specified property.
979 bool TreePatternNode::NodeHasProperty(SDNP Property,
980 const CodeGenDAGPatterns &CGP) const {
982 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
983 return CP->hasProperty(Property);
987 Record *Operator = getOperator();
988 if (!Operator->isSubClassOf("SDNode")) return false;
990 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
996 /// TreeHasProperty - Return true if any node in this tree has the specified
998 bool TreePatternNode::TreeHasProperty(SDNP Property,
999 const CodeGenDAGPatterns &CGP) const {
1000 if (NodeHasProperty(Property, CGP))
1002 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1003 if (getChild(i)->TreeHasProperty(Property, CGP))
1008 /// isCommutativeIntrinsic - Return true if the node corresponds to a
1009 /// commutative intrinsic.
1011 TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
1012 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
1013 return Int->isCommutative;
1018 /// ApplyTypeConstraints - Apply all of the type constraints relevant to
1019 /// this node and its children in the tree. This returns true if it makes a
1020 /// change, false otherwise. If a type contradiction is found, throw an
1022 bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
1023 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
1025 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
1026 // If it's a regclass or something else known, include the type.
1027 return UpdateNodeType(getImplicitType(DI->getDef(), NotRegisters, TP),TP);
1030 if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
1031 // Int inits are always integers. :)
1032 bool MadeChange = Type.EnforceInteger(TP);
1037 MVT::SimpleValueType VT = getType();
1038 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
1041 unsigned Size = EVT(VT).getSizeInBits();
1042 // Make sure that the value is representable for this type.
1043 if (Size >= 32) return MadeChange;
1045 int Val = (II->getValue() << (32-Size)) >> (32-Size);
1046 if (Val == II->getValue()) return MadeChange;
1048 // If sign-extended doesn't fit, does it fit as unsigned?
1050 unsigned UnsignedVal;
1051 ValueMask = unsigned(~uint32_t(0UL) >> (32-Size));
1052 UnsignedVal = unsigned(II->getValue());
1054 if ((ValueMask & UnsignedVal) == UnsignedVal)
1057 TP.error("Integer value '" + itostr(II->getValue())+
1058 "' is out of range for type '" + getEnumName(getType()) + "'!");
1064 // special handling for set, which isn't really an SDNode.
1065 if (getOperator()->getName() == "set") {
1066 assert (getNumChildren() >= 2 && "Missing RHS of a set?");
1067 unsigned NC = getNumChildren();
1068 bool MadeChange = false;
1069 for (unsigned i = 0; i < NC-1; ++i) {
1070 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1071 MadeChange |= getChild(NC-1)->ApplyTypeConstraints(TP, NotRegisters);
1073 // Types of operands must match.
1074 MadeChange |=getChild(i)->UpdateNodeType(getChild(NC-1)->getExtType(),TP);
1075 MadeChange |=getChild(NC-1)->UpdateNodeType(getChild(i)->getExtType(),TP);
1076 MadeChange |=UpdateNodeType(MVT::isVoid, TP);
1081 if (getOperator()->getName() == "implicit" ||
1082 getOperator()->getName() == "parallel") {
1083 bool MadeChange = false;
1084 for (unsigned i = 0; i < getNumChildren(); ++i)
1085 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1086 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
1090 if (getOperator()->getName() == "COPY_TO_REGCLASS") {
1091 bool MadeChange = false;
1092 MadeChange |= getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1093 MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
1095 // child #1 of COPY_TO_REGCLASS should be a register class. We don't care
1096 // what type it gets, so if it didn't get a concrete type just give it the
1097 // first viable type from the reg class.
1098 if (!getChild(1)->hasTypeSet() &&
1099 !getChild(1)->getExtType().isCompletelyUnknown()) {
1100 MVT::SimpleValueType RCVT = getChild(1)->getExtType().getTypeList()[0];
1101 MadeChange |= getChild(1)->UpdateNodeType(RCVT, TP);
1106 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
1107 bool MadeChange = false;
1109 // Apply the result type to the node.
1110 unsigned NumRetVTs = Int->IS.RetVTs.size();
1111 unsigned NumParamVTs = Int->IS.ParamVTs.size();
1113 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
1114 MadeChange |= UpdateNodeType(Int->IS.RetVTs[i], TP);
1116 if (getNumChildren() != NumParamVTs + NumRetVTs)
1117 TP.error("Intrinsic '" + Int->Name + "' expects " +
1118 utostr(NumParamVTs + NumRetVTs - 1) + " operands, not " +
1119 utostr(getNumChildren() - 1) + " operands!");
1121 // Apply type info to the intrinsic ID.
1122 MadeChange |= getChild(0)->UpdateNodeType(MVT::iPTR, TP);
1124 for (unsigned i = NumRetVTs, e = getNumChildren(); i != e; ++i) {
1125 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i - NumRetVTs];
1126 MadeChange |= getChild(i)->UpdateNodeType(OpVT, TP);
1127 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1132 if (getOperator()->isSubClassOf("SDNode")) {
1133 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
1135 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
1136 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1137 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1138 // Branch, etc. do not produce results and top-level forms in instr pattern
1139 // must have void types.
1140 if (NI.getNumResults() == 0)
1141 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
1146 if (getOperator()->isSubClassOf("Instruction")) {
1147 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
1148 assert(Inst.getNumResults() <= 1 &&
1149 "Only supports zero or one result instrs!");
1151 CodeGenInstruction &InstInfo =
1152 CDP.getTargetInfo().getInstruction(getOperator());
1154 EEVT::TypeSet ResultType;
1156 // Apply the result type to the node
1157 if (InstInfo.NumDefs != 0) { // # of elements in (outs) list
1158 Record *ResultNode = Inst.getResult(0);
1160 if (ResultNode->isSubClassOf("PointerLikeRegClass")) {
1161 ResultType = EEVT::TypeSet(MVT::iPTR, TP);
1162 } else if (ResultNode->getName() == "unknown") {
1165 assert(ResultNode->isSubClassOf("RegisterClass") &&
1166 "Operands should be register classes!");
1167 const CodeGenRegisterClass &RC =
1168 CDP.getTargetInfo().getRegisterClass(ResultNode);
1169 ResultType = RC.getValueTypes();
1171 } else if (!InstInfo.ImplicitDefs.empty()) {
1172 // If the instruction has implicit defs, the first one defines the result
1174 Record *FirstImplicitDef = InstInfo.ImplicitDefs[0];
1175 assert(FirstImplicitDef->isSubClassOf("Register"));
1176 const std::vector<MVT::SimpleValueType> &RegVTs =
1177 CDP.getTargetInfo().getRegisterVTs(FirstImplicitDef);
1178 if (RegVTs.size() == 1)
1179 ResultType = EEVT::TypeSet(RegVTs);
1181 ResultType = EEVT::TypeSet(MVT::isVoid, TP);
1183 // Otherwise, the instruction produces no value result.
1184 // FIXME: Model "no result" different than "one result that is void"
1185 ResultType = EEVT::TypeSet(MVT::isVoid, TP);
1188 bool MadeChange = UpdateNodeType(ResultType, TP);
1190 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
1192 if (getOperator()->getName() == "INSERT_SUBREG") {
1193 MadeChange |= UpdateNodeType(getChild(0)->getExtType(), TP);
1194 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
1197 unsigned ChildNo = 0;
1198 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
1199 Record *OperandNode = Inst.getOperand(i);
1201 // If the instruction expects a predicate or optional def operand, we
1202 // codegen this by setting the operand to it's default value if it has a
1203 // non-empty DefaultOps field.
1204 if ((OperandNode->isSubClassOf("PredicateOperand") ||
1205 OperandNode->isSubClassOf("OptionalDefOperand")) &&
1206 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1209 // Verify that we didn't run out of provided operands.
1210 if (ChildNo >= getNumChildren())
1211 TP.error("Instruction '" + getOperator()->getName() +
1212 "' expects more operands than were provided.");
1214 MVT::SimpleValueType VT;
1215 TreePatternNode *Child = getChild(ChildNo++);
1216 if (OperandNode->isSubClassOf("RegisterClass")) {
1217 const CodeGenRegisterClass &RC =
1218 CDP.getTargetInfo().getRegisterClass(OperandNode);
1219 MadeChange |= Child->UpdateNodeType(RC.getValueTypes(), TP);
1220 } else if (OperandNode->isSubClassOf("Operand")) {
1221 VT = getValueType(OperandNode->getValueAsDef("Type"));
1222 MadeChange |= Child->UpdateNodeType(VT, TP);
1223 } else if (OperandNode->isSubClassOf("PointerLikeRegClass")) {
1224 MadeChange |= Child->UpdateNodeType(MVT::iPTR, TP);
1225 } else if (OperandNode->getName() == "unknown") {
1228 assert(0 && "Unknown operand type!");
1231 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
1234 if (ChildNo != getNumChildren())
1235 TP.error("Instruction '" + getOperator()->getName() +
1236 "' was provided too many operands!");
1241 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
1243 // Node transforms always take one operand.
1244 if (getNumChildren() != 1)
1245 TP.error("Node transform '" + getOperator()->getName() +
1246 "' requires one operand!");
1248 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1251 // If either the output or input of the xform does not have exact
1252 // type info. We assume they must be the same. Otherwise, it is perfectly
1253 // legal to transform from one type to a completely different type.
1255 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
1256 bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
1257 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
1264 /// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
1265 /// RHS of a commutative operation, not the on LHS.
1266 static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
1267 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
1269 if (N->isLeaf() && dynamic_cast<IntInit*>(N->getLeafValue()))
1275 /// canPatternMatch - If it is impossible for this pattern to match on this
1276 /// target, fill in Reason and return false. Otherwise, return true. This is
1277 /// used as a sanity check for .td files (to prevent people from writing stuff
1278 /// that can never possibly work), and to prevent the pattern permuter from
1279 /// generating stuff that is useless.
1280 bool TreePatternNode::canPatternMatch(std::string &Reason,
1281 const CodeGenDAGPatterns &CDP) {
1282 if (isLeaf()) return true;
1284 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1285 if (!getChild(i)->canPatternMatch(Reason, CDP))
1288 // If this is an intrinsic, handle cases that would make it not match. For
1289 // example, if an operand is required to be an immediate.
1290 if (getOperator()->isSubClassOf("Intrinsic")) {
1295 // If this node is a commutative operator, check that the LHS isn't an
1297 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
1298 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
1299 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
1300 // Scan all of the operands of the node and make sure that only the last one
1301 // is a constant node, unless the RHS also is.
1302 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
1303 bool Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
1304 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
1305 if (OnlyOnRHSOfCommutative(getChild(i))) {
1306 Reason="Immediate value must be on the RHS of commutative operators!";
1315 //===----------------------------------------------------------------------===//
1316 // TreePattern implementation
1319 TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
1320 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
1321 isInputPattern = isInput;
1322 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
1323 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
1326 TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
1327 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
1328 isInputPattern = isInput;
1329 Trees.push_back(ParseTreePattern(Pat));
1332 TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
1333 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
1334 isInputPattern = isInput;
1335 Trees.push_back(Pat);
1338 void TreePattern::error(const std::string &Msg) const {
1340 throw TGError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
1343 void TreePattern::ComputeNamedNodes() {
1344 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1345 ComputeNamedNodes(Trees[i]);
1348 void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
1349 if (!N->getName().empty())
1350 NamedNodes[N->getName()].push_back(N);
1352 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1353 ComputeNamedNodes(N->getChild(i));
1356 TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
1357 DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
1358 if (!OpDef) error("Pattern has unexpected operator type!");
1359 Record *Operator = OpDef->getDef();
1361 if (Operator->isSubClassOf("ValueType")) {
1362 // If the operator is a ValueType, then this must be "type cast" of a leaf
1364 if (Dag->getNumArgs() != 1)
1365 error("Type cast only takes one operand!");
1367 Init *Arg = Dag->getArg(0);
1368 TreePatternNode *New;
1369 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
1370 Record *R = DI->getDef();
1371 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
1372 Dag->setArg(0, new DagInit(DI, "",
1373 std::vector<std::pair<Init*, std::string> >()));
1374 return ParseTreePattern(Dag);
1378 if (R->getName() == "node") {
1379 if (Dag->getArgName(0).empty())
1380 error("'node' argument requires a name to match with operand list");
1381 Args.push_back(Dag->getArgName(0));
1384 New = new TreePatternNode(DI);
1385 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
1386 New = ParseTreePattern(DI);
1387 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
1388 New = new TreePatternNode(II);
1389 if (!Dag->getArgName(0).empty())
1390 error("Constant int argument should not have a name!");
1391 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
1392 // Turn this into an IntInit.
1393 Init *II = BI->convertInitializerTo(new IntRecTy());
1394 if (II == 0 || !dynamic_cast<IntInit*>(II))
1395 error("Bits value must be constants!");
1397 New = new TreePatternNode(dynamic_cast<IntInit*>(II));
1398 if (!Dag->getArgName(0).empty())
1399 error("Constant int argument should not have a name!");
1402 error("Unknown leaf value for tree pattern!");
1406 // Apply the type cast.
1407 New->UpdateNodeType(getValueType(Operator), *this);
1408 if (New->getNumChildren() == 0)
1409 New->setName(Dag->getArgName(0));
1413 // Verify that this is something that makes sense for an operator.
1414 if (!Operator->isSubClassOf("PatFrag") &&
1415 !Operator->isSubClassOf("SDNode") &&
1416 !Operator->isSubClassOf("Instruction") &&
1417 !Operator->isSubClassOf("SDNodeXForm") &&
1418 !Operator->isSubClassOf("Intrinsic") &&
1419 Operator->getName() != "set" &&
1420 Operator->getName() != "implicit" &&
1421 Operator->getName() != "parallel")
1422 error("Unrecognized node '" + Operator->getName() + "'!");
1424 // Check to see if this is something that is illegal in an input pattern.
1425 if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
1426 Operator->isSubClassOf("SDNodeXForm")))
1427 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
1429 std::vector<TreePatternNode*> Children;
1431 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
1432 Init *Arg = Dag->getArg(i);
1433 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
1434 Children.push_back(ParseTreePattern(DI));
1435 if (Children.back()->getName().empty())
1436 Children.back()->setName(Dag->getArgName(i));
1437 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
1438 Record *R = DefI->getDef();
1439 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
1440 // TreePatternNode if its own.
1441 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
1442 Dag->setArg(i, new DagInit(DefI, "",
1443 std::vector<std::pair<Init*, std::string> >()));
1444 --i; // Revisit this node...
1446 TreePatternNode *Node = new TreePatternNode(DefI);
1447 Node->setName(Dag->getArgName(i));
1448 Children.push_back(Node);
1451 if (R->getName() == "node") {
1452 if (Dag->getArgName(i).empty())
1453 error("'node' argument requires a name to match with operand list");
1454 Args.push_back(Dag->getArgName(i));
1457 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
1458 TreePatternNode *Node = new TreePatternNode(II);
1459 if (!Dag->getArgName(i).empty())
1460 error("Constant int argument should not have a name!");
1461 Children.push_back(Node);
1462 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
1463 // Turn this into an IntInit.
1464 Init *II = BI->convertInitializerTo(new IntRecTy());
1465 if (II == 0 || !dynamic_cast<IntInit*>(II))
1466 error("Bits value must be constants!");
1468 TreePatternNode *Node = new TreePatternNode(dynamic_cast<IntInit*>(II));
1469 if (!Dag->getArgName(i).empty())
1470 error("Constant int argument should not have a name!");
1471 Children.push_back(Node);
1476 error("Unknown leaf value for tree pattern!");
1480 // If the operator is an intrinsic, then this is just syntactic sugar for for
1481 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
1482 // convert the intrinsic name to a number.
1483 if (Operator->isSubClassOf("Intrinsic")) {
1484 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
1485 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
1487 // If this intrinsic returns void, it must have side-effects and thus a
1489 if (Int.IS.RetVTs[0] == MVT::isVoid) {
1490 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
1491 } else if (Int.ModRef != CodeGenIntrinsic::NoMem) {
1492 // Has side-effects, requires chain.
1493 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
1495 // Otherwise, no chain.
1496 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
1499 TreePatternNode *IIDNode = new TreePatternNode(new IntInit(IID));
1500 Children.insert(Children.begin(), IIDNode);
1503 TreePatternNode *Result = new TreePatternNode(Operator, Children);
1504 Result->setName(Dag->getName());
1508 /// InferAllTypes - Infer/propagate as many types throughout the expression
1509 /// patterns as possible. Return true if all types are inferred, false
1510 /// otherwise. Throw an exception if a type contradiction is found.
1512 InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
1513 if (NamedNodes.empty())
1514 ComputeNamedNodes();
1516 bool MadeChange = true;
1517 while (MadeChange) {
1519 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1520 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
1522 // If there are constraints on our named nodes, apply them.
1523 for (StringMap<SmallVector<TreePatternNode*,1> >::iterator
1524 I = NamedNodes.begin(), E = NamedNodes.end(); I != E; ++I) {
1525 SmallVectorImpl<TreePatternNode*> &Nodes = I->second;
1527 // If we have input named node types, propagate their types to the named
1530 // FIXME: Should be error?
1531 assert(InNamedTypes->count(I->getKey()) &&
1532 "Named node in output pattern but not input pattern?");
1534 const SmallVectorImpl<TreePatternNode*> &InNodes =
1535 InNamedTypes->find(I->getKey())->second;
1537 // The input types should be fully resolved by now.
1538 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
1539 // If this node is a register class, and it is the root of the pattern
1540 // then we're mapping something onto an input register. We allow
1541 // changing the type of the input register in this case. This allows
1542 // us to match things like:
1543 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
1544 if (Nodes[i] == Trees[0] && Nodes[i]->isLeaf()) {
1545 DefInit *DI = dynamic_cast<DefInit*>(Nodes[i]->getLeafValue());
1546 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1550 MadeChange |=Nodes[i]->UpdateNodeType(InNodes[0]->getExtType(),*this);
1554 // If there are multiple nodes with the same name, they must all have the
1556 if (I->second.size() > 1) {
1557 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
1558 MadeChange |=Nodes[i]->UpdateNodeType(Nodes[i+1]->getExtType(),*this);
1559 MadeChange |=Nodes[i+1]->UpdateNodeType(Nodes[i]->getExtType(),*this);
1565 bool HasUnresolvedTypes = false;
1566 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1567 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
1568 return !HasUnresolvedTypes;
1571 void TreePattern::print(raw_ostream &OS) const {
1572 OS << getRecord()->getName();
1573 if (!Args.empty()) {
1574 OS << "(" << Args[0];
1575 for (unsigned i = 1, e = Args.size(); i != e; ++i)
1576 OS << ", " << Args[i];
1581 if (Trees.size() > 1)
1583 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
1585 Trees[i]->print(OS);
1589 if (Trees.size() > 1)
1593 void TreePattern::dump() const { print(errs()); }
1595 //===----------------------------------------------------------------------===//
1596 // CodeGenDAGPatterns implementation
1599 CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) : Records(R) {
1600 Intrinsics = LoadIntrinsics(Records, false);
1601 TgtIntrinsics = LoadIntrinsics(Records, true);
1603 ParseNodeTransforms();
1604 ParseComplexPatterns();
1605 ParsePatternFragments();
1606 ParseDefaultOperands();
1607 ParseInstructions();
1610 // Generate variants. For example, commutative patterns can match
1611 // multiple ways. Add them to PatternsToMatch as well.
1614 // Infer instruction flags. For example, we can detect loads,
1615 // stores, and side effects in many cases by examining an
1616 // instruction's pattern.
1617 InferInstructionFlags();
1620 CodeGenDAGPatterns::~CodeGenDAGPatterns() {
1621 for (pf_iterator I = PatternFragments.begin(),
1622 E = PatternFragments.end(); I != E; ++I)
1627 Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
1628 Record *N = Records.getDef(Name);
1629 if (!N || !N->isSubClassOf("SDNode")) {
1630 errs() << "Error getting SDNode '" << Name << "'!\n";
1636 // Parse all of the SDNode definitions for the target, populating SDNodes.
1637 void CodeGenDAGPatterns::ParseNodeInfo() {
1638 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
1639 while (!Nodes.empty()) {
1640 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
1644 // Get the builtin intrinsic nodes.
1645 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
1646 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
1647 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
1650 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
1651 /// map, and emit them to the file as functions.
1652 void CodeGenDAGPatterns::ParseNodeTransforms() {
1653 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
1654 while (!Xforms.empty()) {
1655 Record *XFormNode = Xforms.back();
1656 Record *SDNode = XFormNode->getValueAsDef("Opcode");
1657 std::string Code = XFormNode->getValueAsCode("XFormFunction");
1658 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
1664 void CodeGenDAGPatterns::ParseComplexPatterns() {
1665 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
1666 while (!AMs.empty()) {
1667 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
1673 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
1674 /// file, building up the PatternFragments map. After we've collected them all,
1675 /// inline fragments together as necessary, so that there are no references left
1676 /// inside a pattern fragment to a pattern fragment.
1678 void CodeGenDAGPatterns::ParsePatternFragments() {
1679 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
1681 // First step, parse all of the fragments.
1682 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1683 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
1684 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
1685 PatternFragments[Fragments[i]] = P;
1687 // Validate the argument list, converting it to set, to discard duplicates.
1688 std::vector<std::string> &Args = P->getArgList();
1689 std::set<std::string> OperandsSet(Args.begin(), Args.end());
1691 if (OperandsSet.count(""))
1692 P->error("Cannot have unnamed 'node' values in pattern fragment!");
1694 // Parse the operands list.
1695 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
1696 DefInit *OpsOp = dynamic_cast<DefInit*>(OpsList->getOperator());
1697 // Special cases: ops == outs == ins. Different names are used to
1698 // improve readability.
1700 (OpsOp->getDef()->getName() != "ops" &&
1701 OpsOp->getDef()->getName() != "outs" &&
1702 OpsOp->getDef()->getName() != "ins"))
1703 P->error("Operands list should start with '(ops ... '!");
1705 // Copy over the arguments.
1707 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
1708 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
1709 static_cast<DefInit*>(OpsList->getArg(j))->
1710 getDef()->getName() != "node")
1711 P->error("Operands list should all be 'node' values.");
1712 if (OpsList->getArgName(j).empty())
1713 P->error("Operands list should have names for each operand!");
1714 if (!OperandsSet.count(OpsList->getArgName(j)))
1715 P->error("'" + OpsList->getArgName(j) +
1716 "' does not occur in pattern or was multiply specified!");
1717 OperandsSet.erase(OpsList->getArgName(j));
1718 Args.push_back(OpsList->getArgName(j));
1721 if (!OperandsSet.empty())
1722 P->error("Operands list does not contain an entry for operand '" +
1723 *OperandsSet.begin() + "'!");
1725 // If there is a code init for this fragment, keep track of the fact that
1726 // this fragment uses it.
1727 std::string Code = Fragments[i]->getValueAsCode("Predicate");
1729 P->getOnlyTree()->addPredicateFn("Predicate_"+Fragments[i]->getName());
1731 // If there is a node transformation corresponding to this, keep track of
1733 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
1734 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
1735 P->getOnlyTree()->setTransformFn(Transform);
1738 // Now that we've parsed all of the tree fragments, do a closure on them so
1739 // that there are not references to PatFrags left inside of them.
1740 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1741 TreePattern *ThePat = PatternFragments[Fragments[i]];
1742 ThePat->InlinePatternFragments();
1744 // Infer as many types as possible. Don't worry about it if we don't infer
1745 // all of them, some may depend on the inputs of the pattern.
1747 ThePat->InferAllTypes();
1749 // If this pattern fragment is not supported by this target (no types can
1750 // satisfy its constraints), just ignore it. If the bogus pattern is
1751 // actually used by instructions, the type consistency error will be
1755 // If debugging, print out the pattern fragment result.
1756 DEBUG(ThePat->dump());
1760 void CodeGenDAGPatterns::ParseDefaultOperands() {
1761 std::vector<Record*> DefaultOps[2];
1762 DefaultOps[0] = Records.getAllDerivedDefinitions("PredicateOperand");
1763 DefaultOps[1] = Records.getAllDerivedDefinitions("OptionalDefOperand");
1765 // Find some SDNode.
1766 assert(!SDNodes.empty() && "No SDNodes parsed?");
1767 Init *SomeSDNode = new DefInit(SDNodes.begin()->first);
1769 for (unsigned iter = 0; iter != 2; ++iter) {
1770 for (unsigned i = 0, e = DefaultOps[iter].size(); i != e; ++i) {
1771 DagInit *DefaultInfo = DefaultOps[iter][i]->getValueAsDag("DefaultOps");
1773 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
1774 // SomeSDnode so that we can parse this.
1775 std::vector<std::pair<Init*, std::string> > Ops;
1776 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
1777 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
1778 DefaultInfo->getArgName(op)));
1779 DagInit *DI = new DagInit(SomeSDNode, "", Ops);
1781 // Create a TreePattern to parse this.
1782 TreePattern P(DefaultOps[iter][i], DI, false, *this);
1783 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
1785 // Copy the operands over into a DAGDefaultOperand.
1786 DAGDefaultOperand DefaultOpInfo;
1788 TreePatternNode *T = P.getTree(0);
1789 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
1790 TreePatternNode *TPN = T->getChild(op);
1791 while (TPN->ApplyTypeConstraints(P, false))
1792 /* Resolve all types */;
1794 if (TPN->ContainsUnresolvedType()) {
1796 throw "Value #" + utostr(i) + " of PredicateOperand '" +
1797 DefaultOps[iter][i]->getName() +"' doesn't have a concrete type!";
1799 throw "Value #" + utostr(i) + " of OptionalDefOperand '" +
1800 DefaultOps[iter][i]->getName() +"' doesn't have a concrete type!";
1802 DefaultOpInfo.DefaultOps.push_back(TPN);
1805 // Insert it into the DefaultOperands map so we can find it later.
1806 DefaultOperands[DefaultOps[iter][i]] = DefaultOpInfo;
1811 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
1812 /// instruction input. Return true if this is a real use.
1813 static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
1814 std::map<std::string, TreePatternNode*> &InstInputs,
1815 std::vector<Record*> &InstImpInputs) {
1816 // No name -> not interesting.
1817 if (Pat->getName().empty()) {
1818 if (Pat->isLeaf()) {
1819 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1820 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1821 I->error("Input " + DI->getDef()->getName() + " must be named!");
1822 else if (DI && DI->getDef()->isSubClassOf("Register"))
1823 InstImpInputs.push_back(DI->getDef());
1829 if (Pat->isLeaf()) {
1830 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1831 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
1834 Rec = Pat->getOperator();
1837 // SRCVALUE nodes are ignored.
1838 if (Rec->getName() == "srcvalue")
1841 TreePatternNode *&Slot = InstInputs[Pat->getName()];
1847 if (Slot->isLeaf()) {
1848 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
1850 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
1851 SlotRec = Slot->getOperator();
1854 // Ensure that the inputs agree if we've already seen this input.
1856 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1857 if (Slot->getExtType() != Pat->getExtType())
1858 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1862 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
1863 /// part of "I", the instruction), computing the set of inputs and outputs of
1864 /// the pattern. Report errors if we see anything naughty.
1865 void CodeGenDAGPatterns::
1866 FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
1867 std::map<std::string, TreePatternNode*> &InstInputs,
1868 std::map<std::string, TreePatternNode*>&InstResults,
1869 std::vector<Record*> &InstImpInputs,
1870 std::vector<Record*> &InstImpResults) {
1871 if (Pat->isLeaf()) {
1872 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1873 if (!isUse && Pat->getTransformFn())
1874 I->error("Cannot specify a transform function for a non-input value!");
1878 if (Pat->getOperator()->getName() == "implicit") {
1879 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1880 TreePatternNode *Dest = Pat->getChild(i);
1881 if (!Dest->isLeaf())
1882 I->error("implicitly defined value should be a register!");
1884 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1885 if (!Val || !Val->getDef()->isSubClassOf("Register"))
1886 I->error("implicitly defined value should be a register!");
1887 InstImpResults.push_back(Val->getDef());
1892 if (Pat->getOperator()->getName() != "set") {
1893 // If this is not a set, verify that the children nodes are not void typed,
1895 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1896 if (Pat->getChild(i)->getType() == MVT::isVoid)
1897 I->error("Cannot have void nodes inside of patterns!");
1898 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
1899 InstImpInputs, InstImpResults);
1902 // If this is a non-leaf node with no children, treat it basically as if
1903 // it were a leaf. This handles nodes like (imm).
1904 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1906 if (!isUse && Pat->getTransformFn())
1907 I->error("Cannot specify a transform function for a non-input value!");
1911 // Otherwise, this is a set, validate and collect instruction results.
1912 if (Pat->getNumChildren() == 0)
1913 I->error("set requires operands!");
1915 if (Pat->getTransformFn())
1916 I->error("Cannot specify a transform function on a set node!");
1918 // Check the set destinations.
1919 unsigned NumDests = Pat->getNumChildren()-1;
1920 for (unsigned i = 0; i != NumDests; ++i) {
1921 TreePatternNode *Dest = Pat->getChild(i);
1922 if (!Dest->isLeaf())
1923 I->error("set destination should be a register!");
1925 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1927 I->error("set destination should be a register!");
1929 if (Val->getDef()->isSubClassOf("RegisterClass") ||
1930 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
1931 if (Dest->getName().empty())
1932 I->error("set destination must have a name!");
1933 if (InstResults.count(Dest->getName()))
1934 I->error("cannot set '" + Dest->getName() +"' multiple times");
1935 InstResults[Dest->getName()] = Dest;
1936 } else if (Val->getDef()->isSubClassOf("Register")) {
1937 InstImpResults.push_back(Val->getDef());
1939 I->error("set destination should be a register!");
1943 // Verify and collect info from the computation.
1944 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
1945 InstInputs, InstResults,
1946 InstImpInputs, InstImpResults);
1949 //===----------------------------------------------------------------------===//
1950 // Instruction Analysis
1951 //===----------------------------------------------------------------------===//
1953 class InstAnalyzer {
1954 const CodeGenDAGPatterns &CDP;
1957 bool &HasSideEffects;
1959 InstAnalyzer(const CodeGenDAGPatterns &cdp,
1960 bool &maystore, bool &mayload, bool &hse)
1961 : CDP(cdp), mayStore(maystore), mayLoad(mayload), HasSideEffects(hse){
1964 /// Analyze - Analyze the specified instruction, returning true if the
1965 /// instruction had a pattern.
1966 bool Analyze(Record *InstRecord) {
1967 const TreePattern *Pattern = CDP.getInstruction(InstRecord).getPattern();
1970 return false; // No pattern.
1973 // FIXME: Assume only the first tree is the pattern. The others are clobber
1975 AnalyzeNode(Pattern->getTree(0));
1980 void AnalyzeNode(const TreePatternNode *N) {
1982 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
1983 Record *LeafRec = DI->getDef();
1984 // Handle ComplexPattern leaves.
1985 if (LeafRec->isSubClassOf("ComplexPattern")) {
1986 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
1987 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
1988 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
1989 if (CP.hasProperty(SDNPSideEffect)) HasSideEffects = true;
1995 // Analyze children.
1996 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1997 AnalyzeNode(N->getChild(i));
1999 // Ignore set nodes, which are not SDNodes.
2000 if (N->getOperator()->getName() == "set")
2003 // Get information about the SDNode for the operator.
2004 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N->getOperator());
2006 // Notice properties of the node.
2007 if (OpInfo.hasProperty(SDNPMayStore)) mayStore = true;
2008 if (OpInfo.hasProperty(SDNPMayLoad)) mayLoad = true;
2009 if (OpInfo.hasProperty(SDNPSideEffect)) HasSideEffects = true;
2011 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
2012 // If this is an intrinsic, analyze it.
2013 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
2014 mayLoad = true;// These may load memory.
2016 if (IntInfo->ModRef >= CodeGenIntrinsic::WriteArgMem)
2017 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
2019 if (IntInfo->ModRef >= CodeGenIntrinsic::WriteMem)
2020 // WriteMem intrinsics can have other strange effects.
2021 HasSideEffects = true;
2027 static void InferFromPattern(const CodeGenInstruction &Inst,
2028 bool &MayStore, bool &MayLoad,
2029 bool &HasSideEffects,
2030 const CodeGenDAGPatterns &CDP) {
2031 MayStore = MayLoad = HasSideEffects = false;
2034 InstAnalyzer(CDP, MayStore, MayLoad, HasSideEffects).Analyze(Inst.TheDef);
2036 // InstAnalyzer only correctly analyzes mayStore/mayLoad so far.
2037 if (Inst.mayStore) { // If the .td file explicitly sets mayStore, use it.
2038 // If we decided that this is a store from the pattern, then the .td file
2039 // entry is redundant.
2042 "Warning: mayStore flag explicitly set on instruction '%s'"
2043 " but flag already inferred from pattern.\n",
2044 Inst.TheDef->getName().c_str());
2048 if (Inst.mayLoad) { // If the .td file explicitly sets mayLoad, use it.
2049 // If we decided that this is a load from the pattern, then the .td file
2050 // entry is redundant.
2053 "Warning: mayLoad flag explicitly set on instruction '%s'"
2054 " but flag already inferred from pattern.\n",
2055 Inst.TheDef->getName().c_str());
2059 if (Inst.neverHasSideEffects) {
2061 fprintf(stderr, "Warning: neverHasSideEffects set on instruction '%s' "
2062 "which already has a pattern\n", Inst.TheDef->getName().c_str());
2063 HasSideEffects = false;
2066 if (Inst.hasSideEffects) {
2068 fprintf(stderr, "Warning: hasSideEffects set on instruction '%s' "
2069 "which already inferred this.\n", Inst.TheDef->getName().c_str());
2070 HasSideEffects = true;
2074 /// ParseInstructions - Parse all of the instructions, inlining and resolving
2075 /// any fragments involved. This populates the Instructions list with fully
2076 /// resolved instructions.
2077 void CodeGenDAGPatterns::ParseInstructions() {
2078 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
2080 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
2083 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
2084 LI = Instrs[i]->getValueAsListInit("Pattern");
2086 // If there is no pattern, only collect minimal information about the
2087 // instruction for its operand list. We have to assume that there is one
2088 // result, as we have no detailed info.
2089 if (!LI || LI->getSize() == 0) {
2090 std::vector<Record*> Results;
2091 std::vector<Record*> Operands;
2093 CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
2095 if (InstInfo.OperandList.size() != 0) {
2096 if (InstInfo.NumDefs == 0) {
2097 // These produce no results
2098 for (unsigned j = 0, e = InstInfo.OperandList.size(); j < e; ++j)
2099 Operands.push_back(InstInfo.OperandList[j].Rec);
2101 // Assume the first operand is the result.
2102 Results.push_back(InstInfo.OperandList[0].Rec);
2104 // The rest are inputs.
2105 for (unsigned j = 1, e = InstInfo.OperandList.size(); j < e; ++j)
2106 Operands.push_back(InstInfo.OperandList[j].Rec);
2110 // Create and insert the instruction.
2111 std::vector<Record*> ImpResults;
2112 std::vector<Record*> ImpOperands;
2113 Instructions.insert(std::make_pair(Instrs[i],
2114 DAGInstruction(0, Results, Operands, ImpResults,
2116 continue; // no pattern.
2119 // Parse the instruction.
2120 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
2121 // Inline pattern fragments into it.
2122 I->InlinePatternFragments();
2124 // Infer as many types as possible. If we cannot infer all of them, we can
2125 // never do anything with this instruction pattern: report it to the user.
2126 if (!I->InferAllTypes())
2127 I->error("Could not infer all types in pattern!");
2129 // InstInputs - Keep track of all of the inputs of the instruction, along
2130 // with the record they are declared as.
2131 std::map<std::string, TreePatternNode*> InstInputs;
2133 // InstResults - Keep track of all the virtual registers that are 'set'
2134 // in the instruction, including what reg class they are.
2135 std::map<std::string, TreePatternNode*> InstResults;
2137 std::vector<Record*> InstImpInputs;
2138 std::vector<Record*> InstImpResults;
2140 // Verify that the top-level forms in the instruction are of void type, and
2141 // fill in the InstResults map.
2142 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
2143 TreePatternNode *Pat = I->getTree(j);
2144 if (!Pat->hasTypeSet() || Pat->getType() != MVT::isVoid)
2145 I->error("Top-level forms in instruction pattern should have"
2148 // Find inputs and outputs, and verify the structure of the uses/defs.
2149 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
2150 InstImpInputs, InstImpResults);
2153 // Now that we have inputs and outputs of the pattern, inspect the operands
2154 // list for the instruction. This determines the order that operands are
2155 // added to the machine instruction the node corresponds to.
2156 unsigned NumResults = InstResults.size();
2158 // Parse the operands list from the (ops) list, validating it.
2159 assert(I->getArgList().empty() && "Args list should still be empty here!");
2160 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]);
2162 // Check that all of the results occur first in the list.
2163 std::vector<Record*> Results;
2164 TreePatternNode *Res0Node = NULL;
2165 for (unsigned i = 0; i != NumResults; ++i) {
2166 if (i == CGI.OperandList.size())
2167 I->error("'" + InstResults.begin()->first +
2168 "' set but does not appear in operand list!");
2169 const std::string &OpName = CGI.OperandList[i].Name;
2171 // Check that it exists in InstResults.
2172 TreePatternNode *RNode = InstResults[OpName];
2174 I->error("Operand $" + OpName + " does not exist in operand list!");
2178 Record *R = dynamic_cast<DefInit*>(RNode->getLeafValue())->getDef();
2180 I->error("Operand $" + OpName + " should be a set destination: all "
2181 "outputs must occur before inputs in operand list!");
2183 if (CGI.OperandList[i].Rec != R)
2184 I->error("Operand $" + OpName + " class mismatch!");
2186 // Remember the return type.
2187 Results.push_back(CGI.OperandList[i].Rec);
2189 // Okay, this one checks out.
2190 InstResults.erase(OpName);
2193 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
2194 // the copy while we're checking the inputs.
2195 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
2197 std::vector<TreePatternNode*> ResultNodeOperands;
2198 std::vector<Record*> Operands;
2199 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
2200 CodeGenInstruction::OperandInfo &Op = CGI.OperandList[i];
2201 const std::string &OpName = Op.Name;
2203 I->error("Operand #" + utostr(i) + " in operands list has no name!");
2205 if (!InstInputsCheck.count(OpName)) {
2206 // If this is an predicate operand or optional def operand with an
2207 // DefaultOps set filled in, we can ignore this. When we codegen it,
2208 // we will do so as always executed.
2209 if (Op.Rec->isSubClassOf("PredicateOperand") ||
2210 Op.Rec->isSubClassOf("OptionalDefOperand")) {
2211 // Does it have a non-empty DefaultOps field? If so, ignore this
2213 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
2216 I->error("Operand $" + OpName +
2217 " does not appear in the instruction pattern");
2219 TreePatternNode *InVal = InstInputsCheck[OpName];
2220 InstInputsCheck.erase(OpName); // It occurred, remove from map.
2222 if (InVal->isLeaf() &&
2223 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
2224 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
2225 if (Op.Rec != InRec && !InRec->isSubClassOf("ComplexPattern"))
2226 I->error("Operand $" + OpName + "'s register class disagrees"
2227 " between the operand and pattern");
2229 Operands.push_back(Op.Rec);
2231 // Construct the result for the dest-pattern operand list.
2232 TreePatternNode *OpNode = InVal->clone();
2234 // No predicate is useful on the result.
2235 OpNode->clearPredicateFns();
2237 // Promote the xform function to be an explicit node if set.
2238 if (Record *Xform = OpNode->getTransformFn()) {
2239 OpNode->setTransformFn(0);
2240 std::vector<TreePatternNode*> Children;
2241 Children.push_back(OpNode);
2242 OpNode = new TreePatternNode(Xform, Children);
2245 ResultNodeOperands.push_back(OpNode);
2248 if (!InstInputsCheck.empty())
2249 I->error("Input operand $" + InstInputsCheck.begin()->first +
2250 " occurs in pattern but not in operands list!");
2252 TreePatternNode *ResultPattern =
2253 new TreePatternNode(I->getRecord(), ResultNodeOperands);
2254 // Copy fully inferred output node type to instruction result pattern.
2256 ResultPattern->setType(Res0Node->getExtType());
2258 // Create and insert the instruction.
2259 // FIXME: InstImpResults and InstImpInputs should not be part of
2261 DAGInstruction TheInst(I, Results, Operands, InstImpResults, InstImpInputs);
2262 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
2264 // Use a temporary tree pattern to infer all types and make sure that the
2265 // constructed result is correct. This depends on the instruction already
2266 // being inserted into the Instructions map.
2267 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
2268 Temp.InferAllTypes(&I->getNamedNodesMap());
2270 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
2271 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
2276 // If we can, convert the instructions to be patterns that are matched!
2277 for (std::map<Record*, DAGInstruction, RecordPtrCmp>::iterator II =
2278 Instructions.begin(),
2279 E = Instructions.end(); II != E; ++II) {
2280 DAGInstruction &TheInst = II->second;
2281 const TreePattern *I = TheInst.getPattern();
2282 if (I == 0) continue; // No pattern.
2284 // FIXME: Assume only the first tree is the pattern. The others are clobber
2286 TreePatternNode *Pattern = I->getTree(0);
2287 TreePatternNode *SrcPattern;
2288 if (Pattern->getOperator()->getName() == "set") {
2289 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
2291 // Not a set (store or something?)
2292 SrcPattern = Pattern;
2295 Record *Instr = II->first;
2296 AddPatternToMatch(I,
2297 PatternToMatch(Instr->getValueAsListInit("Predicates"),
2299 TheInst.getResultPattern(),
2300 TheInst.getImpResults(),
2301 Instr->getValueAsInt("AddedComplexity"),
2307 typedef std::pair<const TreePatternNode*, unsigned> NameRecord;
2309 static void FindNames(const TreePatternNode *P,
2310 std::map<std::string, NameRecord> &Names,
2311 const TreePattern *PatternTop) {
2312 if (!P->getName().empty()) {
2313 NameRecord &Rec = Names[P->getName()];
2314 // If this is the first instance of the name, remember the node.
2315 if (Rec.second++ == 0)
2317 else if (Rec.first->getType() != P->getType())
2318 PatternTop->error("repetition of value: $" + P->getName() +
2319 " where different uses have different types!");
2323 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
2324 FindNames(P->getChild(i), Names, PatternTop);
2328 void CodeGenDAGPatterns::AddPatternToMatch(const TreePattern *Pattern,
2329 const PatternToMatch &PTM) {
2330 // Do some sanity checking on the pattern we're about to match.
2332 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this))
2333 Pattern->error("Pattern can never match: " + Reason);
2335 // If the source pattern's root is a complex pattern, that complex pattern
2336 // must specify the nodes it can potentially match.
2337 if (const ComplexPattern *CP =
2338 PTM.getSrcPattern()->getComplexPatternInfo(*this))
2339 if (CP->getRootNodes().empty())
2340 Pattern->error("ComplexPattern at root must specify list of opcodes it"
2344 // Find all of the named values in the input and output, ensure they have the
2346 std::map<std::string, NameRecord> SrcNames, DstNames;
2347 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
2348 FindNames(PTM.getDstPattern(), DstNames, Pattern);
2350 // Scan all of the named values in the destination pattern, rejecting them if
2351 // they don't exist in the input pattern.
2352 for (std::map<std::string, NameRecord>::iterator
2353 I = DstNames.begin(), E = DstNames.end(); I != E; ++I) {
2354 if (SrcNames[I->first].first == 0)
2355 Pattern->error("Pattern has input without matching name in output: $" +
2359 // Scan all of the named values in the source pattern, rejecting them if the
2360 // name isn't used in the dest, and isn't used to tie two values together.
2361 for (std::map<std::string, NameRecord>::iterator
2362 I = SrcNames.begin(), E = SrcNames.end(); I != E; ++I)
2363 if (DstNames[I->first].first == 0 && SrcNames[I->first].second == 1)
2364 Pattern->error("Pattern has dead named input: $" + I->first);
2366 PatternsToMatch.push_back(PTM);
2371 void CodeGenDAGPatterns::InferInstructionFlags() {
2372 const std::vector<const CodeGenInstruction*> &Instructions =
2373 Target.getInstructionsByEnumValue();
2374 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
2375 CodeGenInstruction &InstInfo =
2376 const_cast<CodeGenInstruction &>(*Instructions[i]);
2377 // Determine properties of the instruction from its pattern.
2378 bool MayStore, MayLoad, HasSideEffects;
2379 InferFromPattern(InstInfo, MayStore, MayLoad, HasSideEffects, *this);
2380 InstInfo.mayStore = MayStore;
2381 InstInfo.mayLoad = MayLoad;
2382 InstInfo.hasSideEffects = HasSideEffects;
2386 /// Given a pattern result with an unresolved type, see if we can find one
2387 /// instruction with an unresolved result type. Force this result type to an
2388 /// arbitrary element if it's possible types to converge results.
2389 static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
2393 // Analyze children.
2394 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2395 if (ForceArbitraryInstResultType(N->getChild(i), TP))
2398 if (!N->getOperator()->isSubClassOf("Instruction"))
2401 // If this type is already concrete or completely unknown we can't do
2403 if (N->getExtType().isCompletelyUnknown() || N->getExtType().isConcrete())
2406 // Otherwise, force its type to the first possibility (an arbitrary choice).
2407 return N->getExtType().MergeInTypeInfo(N->getExtType().getTypeList()[0], TP);
2410 void CodeGenDAGPatterns::ParsePatterns() {
2411 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
2413 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
2414 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
2415 DefInit *OpDef = dynamic_cast<DefInit*>(Tree->getOperator());
2416 Record *Operator = OpDef->getDef();
2417 TreePattern *Pattern;
2418 if (Operator->getName() != "parallel")
2419 Pattern = new TreePattern(Patterns[i], Tree, true, *this);
2421 std::vector<Init*> Values;
2423 for (unsigned j = 0, ee = Tree->getNumArgs(); j != ee; ++j) {
2424 Values.push_back(Tree->getArg(j));
2425 TypedInit *TArg = dynamic_cast<TypedInit*>(Tree->getArg(j));
2427 errs() << "In dag: " << Tree->getAsString();
2428 errs() << " -- Untyped argument in pattern\n";
2429 assert(0 && "Untyped argument in pattern");
2432 ListTy = resolveTypes(ListTy, TArg->getType());
2434 errs() << "In dag: " << Tree->getAsString();
2435 errs() << " -- Incompatible types in pattern arguments\n";
2436 assert(0 && "Incompatible types in pattern arguments");
2440 ListTy = TArg->getType();
2443 ListInit *LI = new ListInit(Values, new ListRecTy(ListTy));
2444 Pattern = new TreePattern(Patterns[i], LI, true, *this);
2447 // Inline pattern fragments into it.
2448 Pattern->InlinePatternFragments();
2450 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
2451 if (LI->getSize() == 0) continue; // no pattern.
2453 // Parse the instruction.
2454 TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
2456 // Inline pattern fragments into it.
2457 Result->InlinePatternFragments();
2459 if (Result->getNumTrees() != 1)
2460 Result->error("Cannot handle instructions producing instructions "
2461 "with temporaries yet!");
2463 bool IterateInference;
2464 bool InferredAllPatternTypes, InferredAllResultTypes;
2466 // Infer as many types as possible. If we cannot infer all of them, we
2467 // can never do anything with this pattern: report it to the user.
2468 InferredAllPatternTypes =
2469 Pattern->InferAllTypes(&Pattern->getNamedNodesMap());
2471 // Infer as many types as possible. If we cannot infer all of them, we
2472 // can never do anything with this pattern: report it to the user.
2473 InferredAllResultTypes =
2474 Result->InferAllTypes(&Pattern->getNamedNodesMap());
2476 IterateInference = false;
2478 // Apply the type of the result to the source pattern. This helps us
2479 // resolve cases where the input type is known to be a pointer type (which
2480 // is considered resolved), but the result knows it needs to be 32- or
2481 // 64-bits. Infer the other way for good measure.
2482 if (!Result->getTree(0)->getExtType().isVoid() &&
2483 !Pattern->getTree(0)->getExtType().isVoid()) {
2484 IterateInference = Pattern->getTree(0)->
2485 UpdateNodeType(Result->getTree(0)->getExtType(), *Result);
2486 IterateInference |= Result->getTree(0)->
2487 UpdateNodeType(Pattern->getTree(0)->getExtType(), *Result);
2490 // If our iteration has converged and the input pattern's types are fully
2491 // resolved but the result pattern is not fully resolved, we may have a
2492 // situation where we have two instructions in the result pattern and
2493 // the instructions require a common register class, but don't care about
2494 // what actual MVT is used. This is actually a bug in our modelling:
2495 // output patterns should have register classes, not MVTs.
2497 // In any case, to handle this, we just go through and disambiguate some
2498 // arbitrary types to the result pattern's nodes.
2499 if (!IterateInference && InferredAllPatternTypes &&
2500 !InferredAllResultTypes)
2501 IterateInference = ForceArbitraryInstResultType(Result->getTree(0),
2503 } while (IterateInference);
2505 // Verify that we inferred enough types that we can do something with the
2506 // pattern and result. If these fire the user has to add type casts.
2507 if (!InferredAllPatternTypes)
2508 Pattern->error("Could not infer all types in pattern!");
2509 if (!InferredAllResultTypes) {
2511 Result->error("Could not infer all types in pattern result!");
2514 // Validate that the input pattern is correct.
2515 std::map<std::string, TreePatternNode*> InstInputs;
2516 std::map<std::string, TreePatternNode*> InstResults;
2517 std::vector<Record*> InstImpInputs;
2518 std::vector<Record*> InstImpResults;
2519 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
2520 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
2521 InstInputs, InstResults,
2522 InstImpInputs, InstImpResults);
2524 // Promote the xform function to be an explicit node if set.
2525 TreePatternNode *DstPattern = Result->getOnlyTree();
2526 std::vector<TreePatternNode*> ResultNodeOperands;
2527 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
2528 TreePatternNode *OpNode = DstPattern->getChild(ii);
2529 if (Record *Xform = OpNode->getTransformFn()) {
2530 OpNode->setTransformFn(0);
2531 std::vector<TreePatternNode*> Children;
2532 Children.push_back(OpNode);
2533 OpNode = new TreePatternNode(Xform, Children);
2535 ResultNodeOperands.push_back(OpNode);
2537 DstPattern = Result->getOnlyTree();
2538 if (!DstPattern->isLeaf())
2539 DstPattern = new TreePatternNode(DstPattern->getOperator(),
2540 ResultNodeOperands);
2541 DstPattern->setType(Result->getOnlyTree()->getExtType());
2542 TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
2543 Temp.InferAllTypes();
2546 AddPatternToMatch(Pattern,
2547 PatternToMatch(Patterns[i]->getValueAsListInit("Predicates"),
2548 Pattern->getTree(0),
2549 Temp.getOnlyTree(), InstImpResults,
2550 Patterns[i]->getValueAsInt("AddedComplexity"),
2551 Patterns[i]->getID()));
2555 /// CombineChildVariants - Given a bunch of permutations of each child of the
2556 /// 'operator' node, put them together in all possible ways.
2557 static void CombineChildVariants(TreePatternNode *Orig,
2558 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
2559 std::vector<TreePatternNode*> &OutVariants,
2560 CodeGenDAGPatterns &CDP,
2561 const MultipleUseVarSet &DepVars) {
2562 // Make sure that each operand has at least one variant to choose from.
2563 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2564 if (ChildVariants[i].empty())
2567 // The end result is an all-pairs construction of the resultant pattern.
2568 std::vector<unsigned> Idxs;
2569 Idxs.resize(ChildVariants.size());
2573 DEBUG(if (!Idxs.empty()) {
2574 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
2575 for (unsigned i = 0; i < Idxs.size(); ++i) {
2576 errs() << Idxs[i] << " ";
2581 // Create the variant and add it to the output list.
2582 std::vector<TreePatternNode*> NewChildren;
2583 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2584 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
2585 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
2587 // Copy over properties.
2588 R->setName(Orig->getName());
2589 R->setPredicateFns(Orig->getPredicateFns());
2590 R->setTransformFn(Orig->getTransformFn());
2591 R->setType(Orig->getExtType());
2593 // If this pattern cannot match, do not include it as a variant.
2594 std::string ErrString;
2595 if (!R->canPatternMatch(ErrString, CDP)) {
2598 bool AlreadyExists = false;
2600 // Scan to see if this pattern has already been emitted. We can get
2601 // duplication due to things like commuting:
2602 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
2603 // which are the same pattern. Ignore the dups.
2604 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
2605 if (R->isIsomorphicTo(OutVariants[i], DepVars)) {
2606 AlreadyExists = true;
2613 OutVariants.push_back(R);
2616 // Increment indices to the next permutation by incrementing the
2617 // indicies from last index backward, e.g., generate the sequence
2618 // [0, 0], [0, 1], [1, 0], [1, 1].
2620 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
2621 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
2626 NotDone = (IdxsIdx >= 0);
2630 /// CombineChildVariants - A helper function for binary operators.
2632 static void CombineChildVariants(TreePatternNode *Orig,
2633 const std::vector<TreePatternNode*> &LHS,
2634 const std::vector<TreePatternNode*> &RHS,
2635 std::vector<TreePatternNode*> &OutVariants,
2636 CodeGenDAGPatterns &CDP,
2637 const MultipleUseVarSet &DepVars) {
2638 std::vector<std::vector<TreePatternNode*> > ChildVariants;
2639 ChildVariants.push_back(LHS);
2640 ChildVariants.push_back(RHS);
2641 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
2645 static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
2646 std::vector<TreePatternNode *> &Children) {
2647 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
2648 Record *Operator = N->getOperator();
2650 // Only permit raw nodes.
2651 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
2652 N->getTransformFn()) {
2653 Children.push_back(N);
2657 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
2658 Children.push_back(N->getChild(0));
2660 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
2662 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
2663 Children.push_back(N->getChild(1));
2665 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
2668 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
2669 /// the (potentially recursive) pattern by using algebraic laws.
2671 static void GenerateVariantsOf(TreePatternNode *N,
2672 std::vector<TreePatternNode*> &OutVariants,
2673 CodeGenDAGPatterns &CDP,
2674 const MultipleUseVarSet &DepVars) {
2675 // We cannot permute leaves.
2677 OutVariants.push_back(N);
2681 // Look up interesting info about the node.
2682 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
2684 // If this node is associative, re-associate.
2685 if (NodeInfo.hasProperty(SDNPAssociative)) {
2686 // Re-associate by pulling together all of the linked operators
2687 std::vector<TreePatternNode*> MaximalChildren;
2688 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
2690 // Only handle child sizes of 3. Otherwise we'll end up trying too many
2692 if (MaximalChildren.size() == 3) {
2693 // Find the variants of all of our maximal children.
2694 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
2695 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
2696 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
2697 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
2699 // There are only two ways we can permute the tree:
2700 // (A op B) op C and A op (B op C)
2701 // Within these forms, we can also permute A/B/C.
2703 // Generate legal pair permutations of A/B/C.
2704 std::vector<TreePatternNode*> ABVariants;
2705 std::vector<TreePatternNode*> BAVariants;
2706 std::vector<TreePatternNode*> ACVariants;
2707 std::vector<TreePatternNode*> CAVariants;
2708 std::vector<TreePatternNode*> BCVariants;
2709 std::vector<TreePatternNode*> CBVariants;
2710 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
2711 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
2712 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
2713 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
2714 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
2715 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
2717 // Combine those into the result: (x op x) op x
2718 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
2719 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
2720 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
2721 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
2722 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
2723 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
2725 // Combine those into the result: x op (x op x)
2726 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
2727 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
2728 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
2729 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
2730 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
2731 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
2736 // Compute permutations of all children.
2737 std::vector<std::vector<TreePatternNode*> > ChildVariants;
2738 ChildVariants.resize(N->getNumChildren());
2739 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2740 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
2742 // Build all permutations based on how the children were formed.
2743 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
2745 // If this node is commutative, consider the commuted order.
2746 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
2747 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
2748 assert((N->getNumChildren()==2 || isCommIntrinsic) &&
2749 "Commutative but doesn't have 2 children!");
2750 // Don't count children which are actually register references.
2752 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2753 TreePatternNode *Child = N->getChild(i);
2754 if (Child->isLeaf())
2755 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2756 Record *RR = DI->getDef();
2757 if (RR->isSubClassOf("Register"))
2762 // Consider the commuted order.
2763 if (isCommIntrinsic) {
2764 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
2765 // operands are the commutative operands, and there might be more operands
2768 "Commutative intrinsic should have at least 3 childrean!");
2769 std::vector<std::vector<TreePatternNode*> > Variants;
2770 Variants.push_back(ChildVariants[0]); // Intrinsic id.
2771 Variants.push_back(ChildVariants[2]);
2772 Variants.push_back(ChildVariants[1]);
2773 for (unsigned i = 3; i != NC; ++i)
2774 Variants.push_back(ChildVariants[i]);
2775 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
2777 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
2778 OutVariants, CDP, DepVars);
2783 // GenerateVariants - Generate variants. For example, commutative patterns can
2784 // match multiple ways. Add them to PatternsToMatch as well.
2785 void CodeGenDAGPatterns::GenerateVariants() {
2786 DEBUG(errs() << "Generating instruction variants.\n");
2788 // Loop over all of the patterns we've collected, checking to see if we can
2789 // generate variants of the instruction, through the exploitation of
2790 // identities. This permits the target to provide aggressive matching without
2791 // the .td file having to contain tons of variants of instructions.
2793 // Note that this loop adds new patterns to the PatternsToMatch list, but we
2794 // intentionally do not reconsider these. Any variants of added patterns have
2795 // already been added.
2797 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
2798 MultipleUseVarSet DepVars;
2799 std::vector<TreePatternNode*> Variants;
2800 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
2801 DEBUG(errs() << "Dependent/multiply used variables: ");
2802 DEBUG(DumpDepVars(DepVars));
2803 DEBUG(errs() << "\n");
2804 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this, DepVars);
2806 assert(!Variants.empty() && "Must create at least original variant!");
2807 Variants.erase(Variants.begin()); // Remove the original pattern.
2809 if (Variants.empty()) // No variants for this pattern.
2812 DEBUG(errs() << "FOUND VARIANTS OF: ";
2813 PatternsToMatch[i].getSrcPattern()->dump();
2816 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
2817 TreePatternNode *Variant = Variants[v];
2819 DEBUG(errs() << " VAR#" << v << ": ";
2823 // Scan to see if an instruction or explicit pattern already matches this.
2824 bool AlreadyExists = false;
2825 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
2826 // Skip if the top level predicates do not match.
2827 if (PatternsToMatch[i].getPredicates() !=
2828 PatternsToMatch[p].getPredicates())
2830 // Check to see if this variant already exists.
2831 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(), DepVars)) {
2832 DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
2833 AlreadyExists = true;
2837 // If we already have it, ignore the variant.
2838 if (AlreadyExists) continue;
2840 // Otherwise, add it to the list of patterns we have.
2842 push_back(PatternToMatch(PatternsToMatch[i].getPredicates(),
2843 Variant, PatternsToMatch[i].getDstPattern(),
2844 PatternsToMatch[i].getDstRegs(),
2845 PatternsToMatch[i].getAddedComplexity(),
2846 Record::getNewUID()));
2849 DEBUG(errs() << "\n");