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());
69 /// hasIntegerTypes - Return true if this TypeSet contains iAny or an
70 /// integer value type.
71 bool EEVT::TypeSet::hasIntegerTypes() const {
72 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
73 if (isInteger(TypeVec[i]))
78 /// hasFloatingPointTypes - Return true if this TypeSet contains an fAny or
79 /// a floating point value type.
80 bool EEVT::TypeSet::hasFloatingPointTypes() const {
81 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
82 if (isFloatingPoint(TypeVec[i]))
87 /// hasVectorTypes - Return true if this TypeSet contains a vAny or a vector
89 bool EEVT::TypeSet::hasVectorTypes() const {
90 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
91 if (isVector(TypeVec[i]))
97 std::string EEVT::TypeSet::getName() const {
98 if (TypeVec.empty()) return "<empty>";
102 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i) {
103 std::string VTName = llvm::getEnumName(TypeVec[i]);
104 // Strip off MVT:: prefix if present.
105 if (VTName.substr(0,5) == "MVT::")
106 VTName = VTName.substr(5);
107 if (i) Result += ':';
111 if (TypeVec.size() == 1)
113 return "{" + Result + "}";
116 /// MergeInTypeInfo - This merges in type information from the specified
117 /// argument. If 'this' changes, it returns true. If the two types are
118 /// contradictory (e.g. merge f32 into i32) then this throws an exception.
119 bool EEVT::TypeSet::MergeInTypeInfo(const EEVT::TypeSet &InVT, TreePattern &TP){
120 if (InVT.isCompletelyUnknown() || *this == InVT)
123 if (isCompletelyUnknown()) {
128 assert(TypeVec.size() >= 1 && InVT.TypeVec.size() >= 1 && "No unknowns");
130 // Handle the abstract cases, seeing if we can resolve them better.
131 switch (TypeVec[0]) {
135 if (InVT.hasIntegerTypes()) {
136 EEVT::TypeSet InCopy(InVT);
137 InCopy.EnforceInteger(TP);
138 InCopy.EnforceScalar(TP);
140 if (InCopy.isConcrete()) {
141 // If the RHS has one integer type, upgrade iPTR to i32.
142 TypeVec[0] = InVT.TypeVec[0];
146 // If the input has multiple scalar integers, this doesn't add any info.
147 if (!InCopy.isCompletelyUnknown())
153 // If the input constraint is iAny/iPTR and this is an integer type list,
154 // remove non-integer types from the list.
155 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
157 bool MadeChange = EnforceInteger(TP);
159 // If we're merging in iPTR/iPTRAny and the node currently has a list of
160 // multiple different integer types, replace them with a single iPTR.
161 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
162 TypeVec.size() != 1) {
164 TypeVec[0] = InVT.TypeVec[0];
171 // If this is a type list and the RHS is a typelist as well, eliminate entries
172 // from this list that aren't in the other one.
173 bool MadeChange = false;
174 TypeSet InputSet(*this);
176 for (unsigned i = 0; i != TypeVec.size(); ++i) {
178 for (unsigned j = 0, e = InVT.TypeVec.size(); j != e; ++j)
179 if (TypeVec[i] == InVT.TypeVec[j]) {
184 if (InInVT) continue;
185 TypeVec.erase(TypeVec.begin()+i--);
189 // If we removed all of our types, we have a type contradiction.
190 if (!TypeVec.empty())
193 // FIXME: Really want an SMLoc here!
194 TP.error("Type inference contradiction found, merging '" +
195 InVT.getName() + "' into '" + InputSet.getName() + "'");
196 return true; // unreachable
199 /// EnforceInteger - Remove all non-integer types from this set.
200 bool EEVT::TypeSet::EnforceInteger(TreePattern &TP) {
201 TypeSet InputSet(*this);
202 bool MadeChange = false;
204 // If we know nothing, then get the full set.
205 if (TypeVec.empty()) {
206 *this = TP.getDAGPatterns().getTargetInfo().getLegalValueTypes();
210 if (!hasFloatingPointTypes())
213 // Filter out all the fp types.
214 for (unsigned i = 0; i != TypeVec.size(); ++i)
215 if (isFloatingPoint(TypeVec[i]))
216 TypeVec.erase(TypeVec.begin()+i--);
219 TP.error("Type inference contradiction found, '" +
220 InputSet.getName() + "' needs to be integer");
224 /// EnforceFloatingPoint - Remove all integer types from this set.
225 bool EEVT::TypeSet::EnforceFloatingPoint(TreePattern &TP) {
226 TypeSet InputSet(*this);
227 bool MadeChange = false;
229 // If we know nothing, then get the full set.
230 if (TypeVec.empty()) {
231 *this = TP.getDAGPatterns().getTargetInfo().getLegalValueTypes();
235 if (!hasIntegerTypes())
238 // Filter out all the fp types.
239 for (unsigned i = 0; i != TypeVec.size(); ++i)
240 if (isInteger(TypeVec[i]))
241 TypeVec.erase(TypeVec.begin()+i--);
244 TP.error("Type inference contradiction found, '" +
245 InputSet.getName() + "' needs to be floating point");
249 /// EnforceScalar - Remove all vector types from this.
250 bool EEVT::TypeSet::EnforceScalar(TreePattern &TP) {
251 TypeSet InputSet(*this);
252 bool MadeChange = false;
254 // If we know nothing, then get the full set.
255 if (TypeVec.empty()) {
256 *this = TP.getDAGPatterns().getTargetInfo().getLegalValueTypes();
260 if (!hasVectorTypes())
263 // Filter out all the vector types.
264 for (unsigned i = 0; i != TypeVec.size(); ++i)
265 if (isVector(TypeVec[i]))
266 TypeVec.erase(TypeVec.begin()+i--);
269 TP.error("Type inference contradiction found, '" +
270 InputSet.getName() + "' needs to be scalar");
274 /// EnforceVector - Remove all vector types from this.
275 bool EEVT::TypeSet::EnforceVector(TreePattern &TP) {
276 TypeSet InputSet(*this);
277 bool MadeChange = false;
279 // If we know nothing, then get the full set.
280 if (TypeVec.empty()) {
281 *this = TP.getDAGPatterns().getTargetInfo().getLegalValueTypes();
285 // Filter out all the scalar types.
286 for (unsigned i = 0; i != TypeVec.size(); ++i)
287 if (!isVector(TypeVec[i]))
288 TypeVec.erase(TypeVec.begin()+i--);
291 TP.error("Type inference contradiction found, '" +
292 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 // This code does not currently handle nodes which have multiple types,
304 // where some types are integer, and some are fp. Assert that this is not
306 assert(!(hasIntegerTypes() && hasFloatingPointTypes()) &&
307 !(Other.hasIntegerTypes() && Other.hasFloatingPointTypes()) &&
308 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
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 (hasIntegerTypes())
312 MadeChange |= Other.EnforceInteger(TP);
313 else if (hasFloatingPointTypes())
314 MadeChange |= Other.EnforceFloatingPoint(TP);
315 if (Other.hasIntegerTypes())
316 MadeChange |= EnforceInteger(TP);
317 else if (Other.hasFloatingPointTypes())
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() && Other.hasVectorTypes())
325 MadeChange |= Other.EnforceScalar(TP);
326 if (hasVectorTypes() && !Other.hasVectorTypes())
327 MadeChange |= EnforceScalar(TP);
329 // FIXME: This is a bone-headed way to do this.
331 // Get the set of legal VTs and filter it based on the known integrality.
332 const CodeGenTarget &CGT = TP.getDAGPatterns().getTargetInfo();
333 TypeSet LegalVTs = CGT.getLegalValueTypes();
335 // TODO: If one or the other side is known to be a specific VT, we could prune
337 if (hasIntegerTypes())
338 LegalVTs.EnforceInteger(TP);
339 else if (hasFloatingPointTypes())
340 LegalVTs.EnforceFloatingPoint(TP);
344 switch (LegalVTs.TypeVec.size()) {
345 case 0: assert(0 && "No legal VTs?");
346 default: // Too many VT's to pick from.
347 // TODO: If the biggest type in LegalVTs is in this set, we could remove it.
348 // If one or the other side is known to be a specific VT, we could prune
352 // Only one VT of this flavor. Cannot ever satisfy the constraints.
353 return MergeInTypeInfo(MVT::Other, TP); // throw
355 // If we have exactly two possible types, the little operand must be the
356 // small one, the big operand should be the big one. This is common with
357 // float/double for example.
358 assert(LegalVTs.TypeVec[0] < LegalVTs.TypeVec[1] && "Should be sorted!");
359 MadeChange |= MergeInTypeInfo(LegalVTs.TypeVec[0], TP);
360 MadeChange |= Other.MergeInTypeInfo(LegalVTs.TypeVec[1], TP);
365 /// EnforceVectorEltTypeIs - 'this' is now constrainted to be a vector type
366 /// whose element is VT.
367 bool EEVT::TypeSet::EnforceVectorEltTypeIs(MVT::SimpleValueType VT,
369 TypeSet InputSet(*this);
370 bool MadeChange = false;
372 // If we know nothing, then get the full set.
373 if (TypeVec.empty()) {
374 *this = TP.getDAGPatterns().getTargetInfo().getLegalValueTypes();
378 // Filter out all the non-vector types and types which don't have the right
380 for (unsigned i = 0; i != TypeVec.size(); ++i)
381 if (!isVector(TypeVec[i]) ||
382 EVT(TypeVec[i]).getVectorElementType().getSimpleVT().SimpleTy != VT) {
383 TypeVec.erase(TypeVec.begin()+i--);
387 if (TypeVec.empty()) // FIXME: Really want an SMLoc here!
388 TP.error("Type inference contradiction found, forcing '" +
389 InputSet.getName() + "' to have a vector element");
393 //===----------------------------------------------------------------------===//
394 // Helpers for working with extended types.
396 bool RecordPtrCmp::operator()(const Record *LHS, const Record *RHS) const {
397 return LHS->getID() < RHS->getID();
400 /// Dependent variable map for CodeGenDAGPattern variant generation
401 typedef std::map<std::string, int> DepVarMap;
403 /// Const iterator shorthand for DepVarMap
404 typedef DepVarMap::const_iterator DepVarMap_citer;
407 void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
409 if (dynamic_cast<DefInit*>(N->getLeafValue()) != NULL) {
410 DepMap[N->getName()]++;
413 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
414 FindDepVarsOf(N->getChild(i), DepMap);
418 //! Find dependent variables within child patterns
421 void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
423 FindDepVarsOf(N, depcounts);
424 for (DepVarMap_citer i = depcounts.begin(); i != depcounts.end(); ++i) {
425 if (i->second > 1) { // std::pair<std::string, int>
426 DepVars.insert(i->first);
431 //! Dump the dependent variable set:
432 void DumpDepVars(MultipleUseVarSet &DepVars) {
433 if (DepVars.empty()) {
434 DEBUG(errs() << "<empty set>");
436 DEBUG(errs() << "[ ");
437 for (MultipleUseVarSet::const_iterator i = DepVars.begin(), e = DepVars.end();
439 DEBUG(errs() << (*i) << " ");
441 DEBUG(errs() << "]");
446 //===----------------------------------------------------------------------===//
447 // PatternToMatch implementation
450 /// getPredicateCheck - Return a single string containing all of this
451 /// pattern's predicates concatenated with "&&" operators.
453 std::string PatternToMatch::getPredicateCheck() const {
454 std::string PredicateCheck;
455 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
456 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
457 Record *Def = Pred->getDef();
458 if (!Def->isSubClassOf("Predicate")) {
462 assert(0 && "Unknown predicate type!");
464 if (!PredicateCheck.empty())
465 PredicateCheck += " && ";
466 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
470 return PredicateCheck;
473 //===----------------------------------------------------------------------===//
474 // SDTypeConstraint implementation
477 SDTypeConstraint::SDTypeConstraint(Record *R) {
478 OperandNo = R->getValueAsInt("OperandNum");
480 if (R->isSubClassOf("SDTCisVT")) {
481 ConstraintType = SDTCisVT;
482 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
483 } else if (R->isSubClassOf("SDTCisPtrTy")) {
484 ConstraintType = SDTCisPtrTy;
485 } else if (R->isSubClassOf("SDTCisInt")) {
486 ConstraintType = SDTCisInt;
487 } else if (R->isSubClassOf("SDTCisFP")) {
488 ConstraintType = SDTCisFP;
489 } else if (R->isSubClassOf("SDTCisVec")) {
490 ConstraintType = SDTCisVec;
491 } else if (R->isSubClassOf("SDTCisSameAs")) {
492 ConstraintType = SDTCisSameAs;
493 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
494 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
495 ConstraintType = SDTCisVTSmallerThanOp;
496 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
497 R->getValueAsInt("OtherOperandNum");
498 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
499 ConstraintType = SDTCisOpSmallerThanOp;
500 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
501 R->getValueAsInt("BigOperandNum");
502 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
503 ConstraintType = SDTCisEltOfVec;
504 x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
506 errs() << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
511 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
512 /// N, which has NumResults results.
513 TreePatternNode *SDTypeConstraint::getOperandNum(unsigned OpNo,
515 unsigned NumResults) const {
516 assert(NumResults <= 1 &&
517 "We only work with nodes with zero or one result so far!");
519 if (OpNo >= (NumResults + N->getNumChildren())) {
520 errs() << "Invalid operand number " << OpNo << " ";
526 if (OpNo < NumResults)
527 return N; // FIXME: need value #
529 return N->getChild(OpNo-NumResults);
532 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
533 /// constraint to the nodes operands. This returns true if it makes a
534 /// change, false otherwise. If a type contradiction is found, throw an
536 bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
537 const SDNodeInfo &NodeInfo,
538 TreePattern &TP) const {
539 unsigned NumResults = NodeInfo.getNumResults();
540 assert(NumResults <= 1 &&
541 "We only work with nodes with zero or one result so far!");
543 // Check that the number of operands is sane. Negative operands -> varargs.
544 if (NodeInfo.getNumOperands() >= 0) {
545 if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands())
546 TP.error(N->getOperator()->getName() + " node requires exactly " +
547 itostr(NodeInfo.getNumOperands()) + " operands!");
550 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NumResults);
552 switch (ConstraintType) {
553 default: assert(0 && "Unknown constraint type!");
555 // Operand must be a particular type.
556 return NodeToApply->UpdateNodeType(x.SDTCisVT_Info.VT, TP);
558 // Operand must be same as target pointer type.
559 return NodeToApply->UpdateNodeType(MVT::iPTR, TP);
561 // Require it to be one of the legal integer VTs.
562 return NodeToApply->getExtType().EnforceInteger(TP);
564 // Require it to be one of the legal fp VTs.
565 return NodeToApply->getExtType().EnforceFloatingPoint(TP);
567 // Require it to be one of the legal vector VTs.
568 return NodeToApply->getExtType().EnforceVector(TP);
570 TreePatternNode *OtherNode =
571 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NumResults);
572 return NodeToApply->UpdateNodeType(OtherNode->getExtType(), TP) |
573 OtherNode->UpdateNodeType(NodeToApply->getExtType(), TP);
575 case SDTCisVTSmallerThanOp: {
576 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
577 // have an integer type that is smaller than the VT.
578 if (!NodeToApply->isLeaf() ||
579 !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
580 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
581 ->isSubClassOf("ValueType"))
582 TP.error(N->getOperator()->getName() + " expects a VT operand!");
583 MVT::SimpleValueType VT =
584 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
586 TP.error(N->getOperator()->getName() + " VT operand must be integer!");
588 TreePatternNode *OtherNode =
589 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N,NumResults);
591 // It must be integer.
592 bool MadeChange = OtherNode->getExtType().EnforceInteger(TP);
594 // This doesn't try to enforce any information on the OtherNode, it just
595 // validates it when information is determined.
596 if (OtherNode->hasTypeSet() && OtherNode->getType() <= VT)
597 OtherNode->UpdateNodeType(MVT::Other, TP); // Throw an error.
600 case SDTCisOpSmallerThanOp: {
601 TreePatternNode *BigOperand =
602 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NumResults);
603 return NodeToApply->getExtType().
604 EnforceSmallerThan(BigOperand->getExtType(), TP);
606 case SDTCisEltOfVec: {
607 TreePatternNode *VecOperand =
608 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NumResults);
609 if (VecOperand->hasTypeSet()) {
610 if (!isVector(VecOperand->getType()))
611 TP.error(N->getOperator()->getName() + " VT operand must be a vector!");
612 EVT IVT = VecOperand->getType();
613 IVT = IVT.getVectorElementType();
614 return NodeToApply->UpdateNodeType(IVT.getSimpleVT().SimpleTy, TP);
617 if (NodeToApply->hasTypeSet() && VecOperand->getExtType().hasVectorTypes()){
618 // Filter vector types out of VecOperand that don't have the right element
620 return VecOperand->getExtType().
621 EnforceVectorEltTypeIs(NodeToApply->getType(), TP);
629 //===----------------------------------------------------------------------===//
630 // SDNodeInfo implementation
632 SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
633 EnumName = R->getValueAsString("Opcode");
634 SDClassName = R->getValueAsString("SDClass");
635 Record *TypeProfile = R->getValueAsDef("TypeProfile");
636 NumResults = TypeProfile->getValueAsInt("NumResults");
637 NumOperands = TypeProfile->getValueAsInt("NumOperands");
639 // Parse the properties.
641 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
642 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
643 if (PropList[i]->getName() == "SDNPCommutative") {
644 Properties |= 1 << SDNPCommutative;
645 } else if (PropList[i]->getName() == "SDNPAssociative") {
646 Properties |= 1 << SDNPAssociative;
647 } else if (PropList[i]->getName() == "SDNPHasChain") {
648 Properties |= 1 << SDNPHasChain;
649 } else if (PropList[i]->getName() == "SDNPOutFlag") {
650 Properties |= 1 << SDNPOutFlag;
651 } else if (PropList[i]->getName() == "SDNPInFlag") {
652 Properties |= 1 << SDNPInFlag;
653 } else if (PropList[i]->getName() == "SDNPOptInFlag") {
654 Properties |= 1 << SDNPOptInFlag;
655 } else if (PropList[i]->getName() == "SDNPMayStore") {
656 Properties |= 1 << SDNPMayStore;
657 } else if (PropList[i]->getName() == "SDNPMayLoad") {
658 Properties |= 1 << SDNPMayLoad;
659 } else if (PropList[i]->getName() == "SDNPSideEffect") {
660 Properties |= 1 << SDNPSideEffect;
661 } else if (PropList[i]->getName() == "SDNPMemOperand") {
662 Properties |= 1 << SDNPMemOperand;
664 errs() << "Unknown SD Node property '" << PropList[i]->getName()
665 << "' on node '" << R->getName() << "'!\n";
671 // Parse the type constraints.
672 std::vector<Record*> ConstraintList =
673 TypeProfile->getValueAsListOfDefs("Constraints");
674 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
677 /// getKnownType - If the type constraints on this node imply a fixed type
678 /// (e.g. all stores return void, etc), then return it as an
679 /// MVT::SimpleValueType. Otherwise, return EEVT::Other.
680 MVT::SimpleValueType SDNodeInfo::getKnownType() const {
681 unsigned NumResults = getNumResults();
682 assert(NumResults <= 1 &&
683 "We only work with nodes with zero or one result so far!");
685 for (unsigned i = 0, e = TypeConstraints.size(); i != e; ++i) {
686 // Make sure that this applies to the correct node result.
687 if (TypeConstraints[i].OperandNo >= NumResults) // FIXME: need value #
690 switch (TypeConstraints[i].ConstraintType) {
692 case SDTypeConstraint::SDTCisVT:
693 return TypeConstraints[i].x.SDTCisVT_Info.VT;
694 case SDTypeConstraint::SDTCisPtrTy:
701 //===----------------------------------------------------------------------===//
702 // TreePatternNode implementation
705 TreePatternNode::~TreePatternNode() {
706 #if 0 // FIXME: implement refcounted tree nodes!
707 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
714 void TreePatternNode::print(raw_ostream &OS) const {
716 OS << *getLeafValue();
718 OS << '(' << getOperator()->getName();
721 if (!isTypeCompletelyUnknown())
722 OS << ':' << getExtType().getName();
725 if (getNumChildren() != 0) {
727 getChild(0)->print(OS);
728 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
730 getChild(i)->print(OS);
736 for (unsigned i = 0, e = PredicateFns.size(); i != e; ++i)
737 OS << "<<P:" << PredicateFns[i] << ">>";
739 OS << "<<X:" << TransformFn->getName() << ">>";
740 if (!getName().empty())
741 OS << ":$" << getName();
744 void TreePatternNode::dump() const {
748 /// isIsomorphicTo - Return true if this node is recursively
749 /// isomorphic to the specified node. For this comparison, the node's
750 /// entire state is considered. The assigned name is ignored, since
751 /// nodes with differing names are considered isomorphic. However, if
752 /// the assigned name is present in the dependent variable set, then
753 /// the assigned name is considered significant and the node is
754 /// isomorphic if the names match.
755 bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
756 const MultipleUseVarSet &DepVars) const {
757 if (N == this) return true;
758 if (N->isLeaf() != isLeaf() || getExtType() != N->getExtType() ||
759 getPredicateFns() != N->getPredicateFns() ||
760 getTransformFn() != N->getTransformFn())
764 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
765 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue())) {
766 return ((DI->getDef() == NDI->getDef())
767 && (DepVars.find(getName()) == DepVars.end()
768 || getName() == N->getName()));
771 return getLeafValue() == N->getLeafValue();
774 if (N->getOperator() != getOperator() ||
775 N->getNumChildren() != getNumChildren()) return false;
776 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
777 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
782 /// clone - Make a copy of this tree and all of its children.
784 TreePatternNode *TreePatternNode::clone() const {
785 TreePatternNode *New;
787 New = new TreePatternNode(getLeafValue());
789 std::vector<TreePatternNode*> CChildren;
790 CChildren.reserve(Children.size());
791 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
792 CChildren.push_back(getChild(i)->clone());
793 New = new TreePatternNode(getOperator(), CChildren);
795 New->setName(getName());
796 New->setType(getExtType());
797 New->setPredicateFns(getPredicateFns());
798 New->setTransformFn(getTransformFn());
802 /// RemoveAllTypes - Recursively strip all the types of this tree.
803 void TreePatternNode::RemoveAllTypes() {
804 setType(EEVT::TypeSet()); // Reset to unknown type.
805 if (isLeaf()) return;
806 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
807 getChild(i)->RemoveAllTypes();
811 /// SubstituteFormalArguments - Replace the formal arguments in this tree
812 /// with actual values specified by ArgMap.
813 void TreePatternNode::
814 SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
815 if (isLeaf()) return;
817 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
818 TreePatternNode *Child = getChild(i);
819 if (Child->isLeaf()) {
820 Init *Val = Child->getLeafValue();
821 if (dynamic_cast<DefInit*>(Val) &&
822 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
823 // We found a use of a formal argument, replace it with its value.
824 TreePatternNode *NewChild = ArgMap[Child->getName()];
825 assert(NewChild && "Couldn't find formal argument!");
826 assert((Child->getPredicateFns().empty() ||
827 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
828 "Non-empty child predicate clobbered!");
829 setChild(i, NewChild);
832 getChild(i)->SubstituteFormalArguments(ArgMap);
838 /// InlinePatternFragments - If this pattern refers to any pattern
839 /// fragments, inline them into place, giving us a pattern without any
840 /// PatFrag references.
841 TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
842 if (isLeaf()) return this; // nothing to do.
843 Record *Op = getOperator();
845 if (!Op->isSubClassOf("PatFrag")) {
846 // Just recursively inline children nodes.
847 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
848 TreePatternNode *Child = getChild(i);
849 TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
851 assert((Child->getPredicateFns().empty() ||
852 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
853 "Non-empty child predicate clobbered!");
855 setChild(i, NewChild);
860 // Otherwise, we found a reference to a fragment. First, look up its
861 // TreePattern record.
862 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
864 // Verify that we are passing the right number of operands.
865 if (Frag->getNumArgs() != Children.size())
866 TP.error("'" + Op->getName() + "' fragment requires " +
867 utostr(Frag->getNumArgs()) + " operands!");
869 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
871 std::string Code = Op->getValueAsCode("Predicate");
873 FragTree->addPredicateFn("Predicate_"+Op->getName());
875 // Resolve formal arguments to their actual value.
876 if (Frag->getNumArgs()) {
877 // Compute the map of formal to actual arguments.
878 std::map<std::string, TreePatternNode*> ArgMap;
879 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
880 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
882 FragTree->SubstituteFormalArguments(ArgMap);
885 FragTree->setName(getName());
886 FragTree->UpdateNodeType(getExtType(), TP);
888 // Transfer in the old predicates.
889 for (unsigned i = 0, e = getPredicateFns().size(); i != e; ++i)
890 FragTree->addPredicateFn(getPredicateFns()[i]);
892 // Get a new copy of this fragment to stitch into here.
893 //delete this; // FIXME: implement refcounting!
895 // The fragment we inlined could have recursive inlining that is needed. See
896 // if there are any pattern fragments in it and inline them as needed.
897 return FragTree->InlinePatternFragments(TP);
900 /// getImplicitType - Check to see if the specified record has an implicit
901 /// type which should be applied to it. This will infer the type of register
902 /// references from the register file information, for example.
904 static EEVT::TypeSet getImplicitType(Record *R, bool NotRegisters,
906 // Check to see if this is a register or a register class.
907 if (R->isSubClassOf("RegisterClass")) {
909 return EEVT::TypeSet(); // Unknown.
910 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
911 return EEVT::TypeSet(T.getRegisterClass(R).getValueTypes());
912 } else if (R->isSubClassOf("PatFrag")) {
913 // Pattern fragment types will be resolved when they are inlined.
914 return EEVT::TypeSet(); // Unknown.
915 } else if (R->isSubClassOf("Register")) {
917 return EEVT::TypeSet(); // Unknown.
918 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
919 return EEVT::TypeSet(T.getRegisterVTs(R));
920 } else if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
921 // Using a VTSDNode or CondCodeSDNode.
922 return EEVT::TypeSet(MVT::Other, TP);
923 } else if (R->isSubClassOf("ComplexPattern")) {
925 return EEVT::TypeSet(); // Unknown.
926 return EEVT::TypeSet(TP.getDAGPatterns().getComplexPattern(R).getValueType(),
928 } else if (R->isSubClassOf("PointerLikeRegClass")) {
929 return EEVT::TypeSet(MVT::iPTR, TP);
930 } else if (R->getName() == "node" || R->getName() == "srcvalue" ||
931 R->getName() == "zero_reg") {
933 return EEVT::TypeSet(); // Unknown.
936 TP.error("Unknown node flavor used in pattern: " + R->getName());
937 return EEVT::TypeSet(MVT::Other, TP);
941 /// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
942 /// CodeGenIntrinsic information for it, otherwise return a null pointer.
943 const CodeGenIntrinsic *TreePatternNode::
944 getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
945 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
946 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
947 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
951 dynamic_cast<IntInit*>(getChild(0)->getLeafValue())->getValue();
952 return &CDP.getIntrinsicInfo(IID);
955 /// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
956 /// return the ComplexPattern information, otherwise return null.
957 const ComplexPattern *
958 TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
959 if (!isLeaf()) return 0;
961 DefInit *DI = dynamic_cast<DefInit*>(getLeafValue());
962 if (DI && DI->getDef()->isSubClassOf("ComplexPattern"))
963 return &CGP.getComplexPattern(DI->getDef());
967 /// NodeHasProperty - Return true if this node has the specified property.
968 bool TreePatternNode::NodeHasProperty(SDNP Property,
969 const CodeGenDAGPatterns &CGP) const {
971 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
972 return CP->hasProperty(Property);
976 Record *Operator = getOperator();
977 if (!Operator->isSubClassOf("SDNode")) return false;
979 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
985 /// TreeHasProperty - Return true if any node in this tree has the specified
987 bool TreePatternNode::TreeHasProperty(SDNP Property,
988 const CodeGenDAGPatterns &CGP) const {
989 if (NodeHasProperty(Property, CGP))
991 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
992 if (getChild(i)->TreeHasProperty(Property, CGP))
997 /// isCommutativeIntrinsic - Return true if the node corresponds to a
998 /// commutative intrinsic.
1000 TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
1001 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
1002 return Int->isCommutative;
1007 /// ApplyTypeConstraints - Apply all of the type constraints relevant to
1008 /// this node and its children in the tree. This returns true if it makes a
1009 /// change, false otherwise. If a type contradiction is found, throw an
1011 bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
1012 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
1014 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
1015 // If it's a regclass or something else known, include the type.
1016 return UpdateNodeType(getImplicitType(DI->getDef(), NotRegisters, TP),TP);
1019 if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
1020 // Int inits are always integers. :)
1021 bool MadeChange = Type.EnforceInteger(TP);
1026 MVT::SimpleValueType VT = getType();
1027 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
1030 unsigned Size = EVT(VT).getSizeInBits();
1031 // Make sure that the value is representable for this type.
1032 if (Size >= 32) return MadeChange;
1034 int Val = (II->getValue() << (32-Size)) >> (32-Size);
1035 if (Val == II->getValue()) return MadeChange;
1037 // If sign-extended doesn't fit, does it fit as unsigned?
1039 unsigned UnsignedVal;
1040 ValueMask = unsigned(~uint32_t(0UL) >> (32-Size));
1041 UnsignedVal = unsigned(II->getValue());
1043 if ((ValueMask & UnsignedVal) == UnsignedVal)
1046 TP.error("Integer value '" + itostr(II->getValue())+
1047 "' is out of range for type '" + getEnumName(getType()) + "'!");
1053 // special handling for set, which isn't really an SDNode.
1054 if (getOperator()->getName() == "set") {
1055 assert (getNumChildren() >= 2 && "Missing RHS of a set?");
1056 unsigned NC = getNumChildren();
1057 bool MadeChange = false;
1058 for (unsigned i = 0; i < NC-1; ++i) {
1059 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1060 MadeChange |= getChild(NC-1)->ApplyTypeConstraints(TP, NotRegisters);
1062 // Types of operands must match.
1063 MadeChange |=getChild(i)->UpdateNodeType(getChild(NC-1)->getExtType(),TP);
1064 MadeChange |=getChild(NC-1)->UpdateNodeType(getChild(i)->getExtType(),TP);
1065 MadeChange |=UpdateNodeType(MVT::isVoid, TP);
1070 if (getOperator()->getName() == "implicit" ||
1071 getOperator()->getName() == "parallel") {
1072 bool MadeChange = false;
1073 for (unsigned i = 0; i < getNumChildren(); ++i)
1074 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1075 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
1079 if (getOperator()->getName() == "COPY_TO_REGCLASS") {
1080 bool MadeChange = false;
1081 MadeChange |= getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1082 MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
1084 // child #1 of COPY_TO_REGCLASS should be a register class. We don't care
1085 // what type it gets, so if it didn't get a concrete type just give it the
1086 // first viable type from the reg class.
1087 if (!getChild(1)->hasTypeSet() &&
1088 !getChild(1)->getExtType().isCompletelyUnknown()) {
1089 MVT::SimpleValueType RCVT = getChild(1)->getExtType().getTypeList()[0];
1090 MadeChange |= getChild(1)->UpdateNodeType(RCVT, TP);
1095 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
1096 bool MadeChange = false;
1098 // Apply the result type to the node.
1099 unsigned NumRetVTs = Int->IS.RetVTs.size();
1100 unsigned NumParamVTs = Int->IS.ParamVTs.size();
1102 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
1103 MadeChange |= UpdateNodeType(Int->IS.RetVTs[i], TP);
1105 if (getNumChildren() != NumParamVTs + NumRetVTs)
1106 TP.error("Intrinsic '" + Int->Name + "' expects " +
1107 utostr(NumParamVTs + NumRetVTs - 1) + " operands, not " +
1108 utostr(getNumChildren() - 1) + " operands!");
1110 // Apply type info to the intrinsic ID.
1111 MadeChange |= getChild(0)->UpdateNodeType(MVT::iPTR, TP);
1113 for (unsigned i = NumRetVTs, e = getNumChildren(); i != e; ++i) {
1114 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i - NumRetVTs];
1115 MadeChange |= getChild(i)->UpdateNodeType(OpVT, TP);
1116 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1121 if (getOperator()->isSubClassOf("SDNode")) {
1122 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
1124 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
1125 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1126 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1127 // Branch, etc. do not produce results and top-level forms in instr pattern
1128 // must have void types.
1129 if (NI.getNumResults() == 0)
1130 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
1135 if (getOperator()->isSubClassOf("Instruction")) {
1136 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
1137 unsigned NumResults = Inst.getNumResults();
1138 assert(NumResults <= 1 &&
1139 "Only supports zero or one result instrs!");
1141 CodeGenInstruction &InstInfo =
1142 CDP.getTargetInfo().getInstruction(getOperator());
1144 EEVT::TypeSet ResultType;
1146 // Apply the result type to the node
1147 if (InstInfo.NumDefs != 0) { // # of elements in (outs) list
1148 Record *ResultNode = Inst.getResult(0);
1150 if (ResultNode->isSubClassOf("PointerLikeRegClass")) {
1151 ResultType = EEVT::TypeSet(MVT::iPTR, TP);
1152 } else if (ResultNode->getName() == "unknown") {
1155 assert(ResultNode->isSubClassOf("RegisterClass") &&
1156 "Operands should be register classes!");
1157 const CodeGenRegisterClass &RC =
1158 CDP.getTargetInfo().getRegisterClass(ResultNode);
1159 ResultType = RC.getValueTypes();
1161 } else if (!InstInfo.ImplicitDefs.empty()) {
1162 // If the instruction has implicit defs, the first one defines the result
1164 Record *FirstImplicitDef = InstInfo.ImplicitDefs[0];
1165 assert(FirstImplicitDef->isSubClassOf("Register"));
1166 const std::vector<MVT::SimpleValueType> &RegVTs =
1167 CDP.getTargetInfo().getRegisterVTs(FirstImplicitDef);
1168 if (RegVTs.size() == 1)
1169 ResultType = EEVT::TypeSet(RegVTs);
1171 ResultType = EEVT::TypeSet(MVT::isVoid, TP);
1173 // Otherwise, the instruction produces no value result.
1174 // FIXME: Model "no result" different than "one result that is void"
1175 ResultType = EEVT::TypeSet(MVT::isVoid, TP);
1178 bool MadeChange = UpdateNodeType(ResultType, TP);
1180 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
1182 if (getOperator()->getName() == "INSERT_SUBREG") {
1183 MadeChange |= UpdateNodeType(getChild(0)->getExtType(), TP);
1184 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
1187 unsigned ChildNo = 0;
1188 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
1189 Record *OperandNode = Inst.getOperand(i);
1191 // If the instruction expects a predicate or optional def operand, we
1192 // codegen this by setting the operand to it's default value if it has a
1193 // non-empty DefaultOps field.
1194 if ((OperandNode->isSubClassOf("PredicateOperand") ||
1195 OperandNode->isSubClassOf("OptionalDefOperand")) &&
1196 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1199 // Verify that we didn't run out of provided operands.
1200 if (ChildNo >= getNumChildren())
1201 TP.error("Instruction '" + getOperator()->getName() +
1202 "' expects more operands than were provided.");
1204 MVT::SimpleValueType VT;
1205 TreePatternNode *Child = getChild(ChildNo++);
1206 if (OperandNode->isSubClassOf("RegisterClass")) {
1207 const CodeGenRegisterClass &RC =
1208 CDP.getTargetInfo().getRegisterClass(OperandNode);
1209 MadeChange |= Child->UpdateNodeType(RC.getValueTypes(), TP);
1210 } else if (OperandNode->isSubClassOf("Operand")) {
1211 VT = getValueType(OperandNode->getValueAsDef("Type"));
1212 MadeChange |= Child->UpdateNodeType(VT, TP);
1213 } else if (OperandNode->isSubClassOf("PointerLikeRegClass")) {
1214 MadeChange |= Child->UpdateNodeType(MVT::iPTR, TP);
1215 } else if (OperandNode->getName() == "unknown") {
1218 assert(0 && "Unknown operand type!");
1221 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
1224 if (ChildNo != getNumChildren())
1225 TP.error("Instruction '" + getOperator()->getName() +
1226 "' was provided too many operands!");
1231 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
1233 // Node transforms always take one operand.
1234 if (getNumChildren() != 1)
1235 TP.error("Node transform '" + getOperator()->getName() +
1236 "' requires one operand!");
1238 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1241 // If either the output or input of the xform does not have exact
1242 // type info. We assume they must be the same. Otherwise, it is perfectly
1243 // legal to transform from one type to a completely different type.
1245 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
1246 bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
1247 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
1254 /// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
1255 /// RHS of a commutative operation, not the on LHS.
1256 static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
1257 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
1259 if (N->isLeaf() && dynamic_cast<IntInit*>(N->getLeafValue()))
1265 /// canPatternMatch - If it is impossible for this pattern to match on this
1266 /// target, fill in Reason and return false. Otherwise, return true. This is
1267 /// used as a sanity check for .td files (to prevent people from writing stuff
1268 /// that can never possibly work), and to prevent the pattern permuter from
1269 /// generating stuff that is useless.
1270 bool TreePatternNode::canPatternMatch(std::string &Reason,
1271 const CodeGenDAGPatterns &CDP) {
1272 if (isLeaf()) return true;
1274 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1275 if (!getChild(i)->canPatternMatch(Reason, CDP))
1278 // If this is an intrinsic, handle cases that would make it not match. For
1279 // example, if an operand is required to be an immediate.
1280 if (getOperator()->isSubClassOf("Intrinsic")) {
1285 // If this node is a commutative operator, check that the LHS isn't an
1287 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
1288 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
1289 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
1290 // Scan all of the operands of the node and make sure that only the last one
1291 // is a constant node, unless the RHS also is.
1292 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
1293 bool Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
1294 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
1295 if (OnlyOnRHSOfCommutative(getChild(i))) {
1296 Reason="Immediate value must be on the RHS of commutative operators!";
1305 //===----------------------------------------------------------------------===//
1306 // TreePattern implementation
1309 TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
1310 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
1311 isInputPattern = isInput;
1312 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
1313 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
1316 TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
1317 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
1318 isInputPattern = isInput;
1319 Trees.push_back(ParseTreePattern(Pat));
1322 TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
1323 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
1324 isInputPattern = isInput;
1325 Trees.push_back(Pat);
1328 void TreePattern::error(const std::string &Msg) const {
1330 throw TGError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
1333 void TreePattern::ComputeNamedNodes() {
1334 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1335 ComputeNamedNodes(Trees[i]);
1338 void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
1339 if (!N->getName().empty())
1340 NamedNodes[N->getName()].push_back(N);
1342 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1343 ComputeNamedNodes(N->getChild(i));
1346 TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
1347 DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
1348 if (!OpDef) error("Pattern has unexpected operator type!");
1349 Record *Operator = OpDef->getDef();
1351 if (Operator->isSubClassOf("ValueType")) {
1352 // If the operator is a ValueType, then this must be "type cast" of a leaf
1354 if (Dag->getNumArgs() != 1)
1355 error("Type cast only takes one operand!");
1357 Init *Arg = Dag->getArg(0);
1358 TreePatternNode *New;
1359 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
1360 Record *R = DI->getDef();
1361 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
1362 Dag->setArg(0, new DagInit(DI, "",
1363 std::vector<std::pair<Init*, std::string> >()));
1364 return ParseTreePattern(Dag);
1368 if (R->getName() == "node") {
1369 if (Dag->getArgName(0).empty())
1370 error("'node' argument requires a name to match with operand list");
1371 Args.push_back(Dag->getArgName(0));
1374 New = new TreePatternNode(DI);
1375 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
1376 New = ParseTreePattern(DI);
1377 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
1378 New = new TreePatternNode(II);
1379 if (!Dag->getArgName(0).empty())
1380 error("Constant int argument should not have a name!");
1381 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
1382 // Turn this into an IntInit.
1383 Init *II = BI->convertInitializerTo(new IntRecTy());
1384 if (II == 0 || !dynamic_cast<IntInit*>(II))
1385 error("Bits value must be constants!");
1387 New = new TreePatternNode(dynamic_cast<IntInit*>(II));
1388 if (!Dag->getArgName(0).empty())
1389 error("Constant int argument should not have a name!");
1392 error("Unknown leaf value for tree pattern!");
1396 // Apply the type cast.
1397 New->UpdateNodeType(getValueType(Operator), *this);
1398 if (New->getNumChildren() == 0)
1399 New->setName(Dag->getArgName(0));
1403 // Verify that this is something that makes sense for an operator.
1404 if (!Operator->isSubClassOf("PatFrag") &&
1405 !Operator->isSubClassOf("SDNode") &&
1406 !Operator->isSubClassOf("Instruction") &&
1407 !Operator->isSubClassOf("SDNodeXForm") &&
1408 !Operator->isSubClassOf("Intrinsic") &&
1409 Operator->getName() != "set" &&
1410 Operator->getName() != "implicit" &&
1411 Operator->getName() != "parallel")
1412 error("Unrecognized node '" + Operator->getName() + "'!");
1414 // Check to see if this is something that is illegal in an input pattern.
1415 if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
1416 Operator->isSubClassOf("SDNodeXForm")))
1417 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
1419 std::vector<TreePatternNode*> Children;
1421 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
1422 Init *Arg = Dag->getArg(i);
1423 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
1424 Children.push_back(ParseTreePattern(DI));
1425 if (Children.back()->getName().empty())
1426 Children.back()->setName(Dag->getArgName(i));
1427 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
1428 Record *R = DefI->getDef();
1429 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
1430 // TreePatternNode if its own.
1431 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
1432 Dag->setArg(i, new DagInit(DefI, "",
1433 std::vector<std::pair<Init*, std::string> >()));
1434 --i; // Revisit this node...
1436 TreePatternNode *Node = new TreePatternNode(DefI);
1437 Node->setName(Dag->getArgName(i));
1438 Children.push_back(Node);
1441 if (R->getName() == "node") {
1442 if (Dag->getArgName(i).empty())
1443 error("'node' argument requires a name to match with operand list");
1444 Args.push_back(Dag->getArgName(i));
1447 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
1448 TreePatternNode *Node = new TreePatternNode(II);
1449 if (!Dag->getArgName(i).empty())
1450 error("Constant int argument should not have a name!");
1451 Children.push_back(Node);
1452 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
1453 // Turn this into an IntInit.
1454 Init *II = BI->convertInitializerTo(new IntRecTy());
1455 if (II == 0 || !dynamic_cast<IntInit*>(II))
1456 error("Bits value must be constants!");
1458 TreePatternNode *Node = new TreePatternNode(dynamic_cast<IntInit*>(II));
1459 if (!Dag->getArgName(i).empty())
1460 error("Constant int argument should not have a name!");
1461 Children.push_back(Node);
1466 error("Unknown leaf value for tree pattern!");
1470 // If the operator is an intrinsic, then this is just syntactic sugar for for
1471 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
1472 // convert the intrinsic name to a number.
1473 if (Operator->isSubClassOf("Intrinsic")) {
1474 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
1475 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
1477 // If this intrinsic returns void, it must have side-effects and thus a
1479 if (Int.IS.RetVTs[0] == MVT::isVoid) {
1480 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
1481 } else if (Int.ModRef != CodeGenIntrinsic::NoMem) {
1482 // Has side-effects, requires chain.
1483 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
1485 // Otherwise, no chain.
1486 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
1489 TreePatternNode *IIDNode = new TreePatternNode(new IntInit(IID));
1490 Children.insert(Children.begin(), IIDNode);
1493 TreePatternNode *Result = new TreePatternNode(Operator, Children);
1494 Result->setName(Dag->getName());
1498 /// InferAllTypes - Infer/propagate as many types throughout the expression
1499 /// patterns as possible. Return true if all types are inferred, false
1500 /// otherwise. Throw an exception if a type contradiction is found.
1502 InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
1503 if (NamedNodes.empty())
1504 ComputeNamedNodes();
1506 bool MadeChange = true;
1507 while (MadeChange) {
1509 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1510 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
1512 // If there are constraints on our named nodes, apply them.
1513 for (StringMap<SmallVector<TreePatternNode*,1> >::iterator
1514 I = NamedNodes.begin(), E = NamedNodes.end(); I != E; ++I) {
1515 SmallVectorImpl<TreePatternNode*> &Nodes = I->second;
1517 // If we have input named node types, propagate their types to the named
1520 // FIXME: Should be error?
1521 assert(InNamedTypes->count(I->getKey()) &&
1522 "Named node in output pattern but not input pattern?");
1524 const SmallVectorImpl<TreePatternNode*> &InNodes =
1525 InNamedTypes->find(I->getKey())->second;
1527 // The input types should be fully resolved by now.
1528 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
1529 // If this node is a register class, and it is the root of the pattern
1530 // then we're mapping something onto an input register. We allow
1531 // changing the type of the input register in this case. This allows
1532 // us to match things like:
1533 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
1534 if (Nodes[i] == Trees[0] && Nodes[i]->isLeaf()) {
1535 DefInit *DI = dynamic_cast<DefInit*>(Nodes[i]->getLeafValue());
1536 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1540 MadeChange |=Nodes[i]->UpdateNodeType(InNodes[0]->getExtType(),*this);
1544 // If there are multiple nodes with the same name, they must all have the
1546 if (I->second.size() > 1) {
1547 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
1548 MadeChange |=Nodes[i]->UpdateNodeType(Nodes[i+1]->getExtType(),*this);
1549 MadeChange |=Nodes[i+1]->UpdateNodeType(Nodes[i]->getExtType(),*this);
1555 bool HasUnresolvedTypes = false;
1556 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1557 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
1558 return !HasUnresolvedTypes;
1561 void TreePattern::print(raw_ostream &OS) const {
1562 OS << getRecord()->getName();
1563 if (!Args.empty()) {
1564 OS << "(" << Args[0];
1565 for (unsigned i = 1, e = Args.size(); i != e; ++i)
1566 OS << ", " << Args[i];
1571 if (Trees.size() > 1)
1573 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
1575 Trees[i]->print(OS);
1579 if (Trees.size() > 1)
1583 void TreePattern::dump() const { print(errs()); }
1585 //===----------------------------------------------------------------------===//
1586 // CodeGenDAGPatterns implementation
1589 CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) : Records(R) {
1590 Intrinsics = LoadIntrinsics(Records, false);
1591 TgtIntrinsics = LoadIntrinsics(Records, true);
1593 ParseNodeTransforms();
1594 ParseComplexPatterns();
1595 ParsePatternFragments();
1596 ParseDefaultOperands();
1597 ParseInstructions();
1600 // Generate variants. For example, commutative patterns can match
1601 // multiple ways. Add them to PatternsToMatch as well.
1604 // Infer instruction flags. For example, we can detect loads,
1605 // stores, and side effects in many cases by examining an
1606 // instruction's pattern.
1607 InferInstructionFlags();
1610 CodeGenDAGPatterns::~CodeGenDAGPatterns() {
1611 for (pf_iterator I = PatternFragments.begin(),
1612 E = PatternFragments.end(); I != E; ++I)
1617 Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
1618 Record *N = Records.getDef(Name);
1619 if (!N || !N->isSubClassOf("SDNode")) {
1620 errs() << "Error getting SDNode '" << Name << "'!\n";
1626 // Parse all of the SDNode definitions for the target, populating SDNodes.
1627 void CodeGenDAGPatterns::ParseNodeInfo() {
1628 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
1629 while (!Nodes.empty()) {
1630 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
1634 // Get the builtin intrinsic nodes.
1635 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
1636 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
1637 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
1640 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
1641 /// map, and emit them to the file as functions.
1642 void CodeGenDAGPatterns::ParseNodeTransforms() {
1643 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
1644 while (!Xforms.empty()) {
1645 Record *XFormNode = Xforms.back();
1646 Record *SDNode = XFormNode->getValueAsDef("Opcode");
1647 std::string Code = XFormNode->getValueAsCode("XFormFunction");
1648 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
1654 void CodeGenDAGPatterns::ParseComplexPatterns() {
1655 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
1656 while (!AMs.empty()) {
1657 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
1663 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
1664 /// file, building up the PatternFragments map. After we've collected them all,
1665 /// inline fragments together as necessary, so that there are no references left
1666 /// inside a pattern fragment to a pattern fragment.
1668 void CodeGenDAGPatterns::ParsePatternFragments() {
1669 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
1671 // First step, parse all of the fragments.
1672 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1673 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
1674 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
1675 PatternFragments[Fragments[i]] = P;
1677 // Validate the argument list, converting it to set, to discard duplicates.
1678 std::vector<std::string> &Args = P->getArgList();
1679 std::set<std::string> OperandsSet(Args.begin(), Args.end());
1681 if (OperandsSet.count(""))
1682 P->error("Cannot have unnamed 'node' values in pattern fragment!");
1684 // Parse the operands list.
1685 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
1686 DefInit *OpsOp = dynamic_cast<DefInit*>(OpsList->getOperator());
1687 // Special cases: ops == outs == ins. Different names are used to
1688 // improve readability.
1690 (OpsOp->getDef()->getName() != "ops" &&
1691 OpsOp->getDef()->getName() != "outs" &&
1692 OpsOp->getDef()->getName() != "ins"))
1693 P->error("Operands list should start with '(ops ... '!");
1695 // Copy over the arguments.
1697 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
1698 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
1699 static_cast<DefInit*>(OpsList->getArg(j))->
1700 getDef()->getName() != "node")
1701 P->error("Operands list should all be 'node' values.");
1702 if (OpsList->getArgName(j).empty())
1703 P->error("Operands list should have names for each operand!");
1704 if (!OperandsSet.count(OpsList->getArgName(j)))
1705 P->error("'" + OpsList->getArgName(j) +
1706 "' does not occur in pattern or was multiply specified!");
1707 OperandsSet.erase(OpsList->getArgName(j));
1708 Args.push_back(OpsList->getArgName(j));
1711 if (!OperandsSet.empty())
1712 P->error("Operands list does not contain an entry for operand '" +
1713 *OperandsSet.begin() + "'!");
1715 // If there is a code init for this fragment, keep track of the fact that
1716 // this fragment uses it.
1717 std::string Code = Fragments[i]->getValueAsCode("Predicate");
1719 P->getOnlyTree()->addPredicateFn("Predicate_"+Fragments[i]->getName());
1721 // If there is a node transformation corresponding to this, keep track of
1723 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
1724 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
1725 P->getOnlyTree()->setTransformFn(Transform);
1728 // Now that we've parsed all of the tree fragments, do a closure on them so
1729 // that there are not references to PatFrags left inside of them.
1730 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1731 TreePattern *ThePat = PatternFragments[Fragments[i]];
1732 ThePat->InlinePatternFragments();
1734 // Infer as many types as possible. Don't worry about it if we don't infer
1735 // all of them, some may depend on the inputs of the pattern.
1737 ThePat->InferAllTypes();
1739 // If this pattern fragment is not supported by this target (no types can
1740 // satisfy its constraints), just ignore it. If the bogus pattern is
1741 // actually used by instructions, the type consistency error will be
1745 // If debugging, print out the pattern fragment result.
1746 DEBUG(ThePat->dump());
1750 void CodeGenDAGPatterns::ParseDefaultOperands() {
1751 std::vector<Record*> DefaultOps[2];
1752 DefaultOps[0] = Records.getAllDerivedDefinitions("PredicateOperand");
1753 DefaultOps[1] = Records.getAllDerivedDefinitions("OptionalDefOperand");
1755 // Find some SDNode.
1756 assert(!SDNodes.empty() && "No SDNodes parsed?");
1757 Init *SomeSDNode = new DefInit(SDNodes.begin()->first);
1759 for (unsigned iter = 0; iter != 2; ++iter) {
1760 for (unsigned i = 0, e = DefaultOps[iter].size(); i != e; ++i) {
1761 DagInit *DefaultInfo = DefaultOps[iter][i]->getValueAsDag("DefaultOps");
1763 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
1764 // SomeSDnode so that we can parse this.
1765 std::vector<std::pair<Init*, std::string> > Ops;
1766 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
1767 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
1768 DefaultInfo->getArgName(op)));
1769 DagInit *DI = new DagInit(SomeSDNode, "", Ops);
1771 // Create a TreePattern to parse this.
1772 TreePattern P(DefaultOps[iter][i], DI, false, *this);
1773 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
1775 // Copy the operands over into a DAGDefaultOperand.
1776 DAGDefaultOperand DefaultOpInfo;
1778 TreePatternNode *T = P.getTree(0);
1779 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
1780 TreePatternNode *TPN = T->getChild(op);
1781 while (TPN->ApplyTypeConstraints(P, false))
1782 /* Resolve all types */;
1784 if (TPN->ContainsUnresolvedType()) {
1786 throw "Value #" + utostr(i) + " of PredicateOperand '" +
1787 DefaultOps[iter][i]->getName() +"' doesn't have a concrete type!";
1789 throw "Value #" + utostr(i) + " of OptionalDefOperand '" +
1790 DefaultOps[iter][i]->getName() +"' doesn't have a concrete type!";
1792 DefaultOpInfo.DefaultOps.push_back(TPN);
1795 // Insert it into the DefaultOperands map so we can find it later.
1796 DefaultOperands[DefaultOps[iter][i]] = DefaultOpInfo;
1801 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
1802 /// instruction input. Return true if this is a real use.
1803 static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
1804 std::map<std::string, TreePatternNode*> &InstInputs,
1805 std::vector<Record*> &InstImpInputs) {
1806 // No name -> not interesting.
1807 if (Pat->getName().empty()) {
1808 if (Pat->isLeaf()) {
1809 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1810 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1811 I->error("Input " + DI->getDef()->getName() + " must be named!");
1812 else if (DI && DI->getDef()->isSubClassOf("Register"))
1813 InstImpInputs.push_back(DI->getDef());
1819 if (Pat->isLeaf()) {
1820 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1821 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
1824 Rec = Pat->getOperator();
1827 // SRCVALUE nodes are ignored.
1828 if (Rec->getName() == "srcvalue")
1831 TreePatternNode *&Slot = InstInputs[Pat->getName()];
1837 if (Slot->isLeaf()) {
1838 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
1840 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
1841 SlotRec = Slot->getOperator();
1844 // Ensure that the inputs agree if we've already seen this input.
1846 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1847 if (Slot->getExtType() != Pat->getExtType())
1848 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1852 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
1853 /// part of "I", the instruction), computing the set of inputs and outputs of
1854 /// the pattern. Report errors if we see anything naughty.
1855 void CodeGenDAGPatterns::
1856 FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
1857 std::map<std::string, TreePatternNode*> &InstInputs,
1858 std::map<std::string, TreePatternNode*>&InstResults,
1859 std::vector<Record*> &InstImpInputs,
1860 std::vector<Record*> &InstImpResults) {
1861 if (Pat->isLeaf()) {
1862 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1863 if (!isUse && Pat->getTransformFn())
1864 I->error("Cannot specify a transform function for a non-input value!");
1868 if (Pat->getOperator()->getName() == "implicit") {
1869 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1870 TreePatternNode *Dest = Pat->getChild(i);
1871 if (!Dest->isLeaf())
1872 I->error("implicitly defined value should be a register!");
1874 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1875 if (!Val || !Val->getDef()->isSubClassOf("Register"))
1876 I->error("implicitly defined value should be a register!");
1877 InstImpResults.push_back(Val->getDef());
1882 if (Pat->getOperator()->getName() != "set") {
1883 // If this is not a set, verify that the children nodes are not void typed,
1885 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1886 if (Pat->getChild(i)->getType() == MVT::isVoid)
1887 I->error("Cannot have void nodes inside of patterns!");
1888 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
1889 InstImpInputs, InstImpResults);
1892 // If this is a non-leaf node with no children, treat it basically as if
1893 // it were a leaf. This handles nodes like (imm).
1894 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1896 if (!isUse && Pat->getTransformFn())
1897 I->error("Cannot specify a transform function for a non-input value!");
1901 // Otherwise, this is a set, validate and collect instruction results.
1902 if (Pat->getNumChildren() == 0)
1903 I->error("set requires operands!");
1905 if (Pat->getTransformFn())
1906 I->error("Cannot specify a transform function on a set node!");
1908 // Check the set destinations.
1909 unsigned NumDests = Pat->getNumChildren()-1;
1910 for (unsigned i = 0; i != NumDests; ++i) {
1911 TreePatternNode *Dest = Pat->getChild(i);
1912 if (!Dest->isLeaf())
1913 I->error("set destination should be a register!");
1915 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1917 I->error("set destination should be a register!");
1919 if (Val->getDef()->isSubClassOf("RegisterClass") ||
1920 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
1921 if (Dest->getName().empty())
1922 I->error("set destination must have a name!");
1923 if (InstResults.count(Dest->getName()))
1924 I->error("cannot set '" + Dest->getName() +"' multiple times");
1925 InstResults[Dest->getName()] = Dest;
1926 } else if (Val->getDef()->isSubClassOf("Register")) {
1927 InstImpResults.push_back(Val->getDef());
1929 I->error("set destination should be a register!");
1933 // Verify and collect info from the computation.
1934 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
1935 InstInputs, InstResults,
1936 InstImpInputs, InstImpResults);
1939 //===----------------------------------------------------------------------===//
1940 // Instruction Analysis
1941 //===----------------------------------------------------------------------===//
1943 class InstAnalyzer {
1944 const CodeGenDAGPatterns &CDP;
1947 bool &HasSideEffects;
1949 InstAnalyzer(const CodeGenDAGPatterns &cdp,
1950 bool &maystore, bool &mayload, bool &hse)
1951 : CDP(cdp), mayStore(maystore), mayLoad(mayload), HasSideEffects(hse){
1954 /// Analyze - Analyze the specified instruction, returning true if the
1955 /// instruction had a pattern.
1956 bool Analyze(Record *InstRecord) {
1957 const TreePattern *Pattern = CDP.getInstruction(InstRecord).getPattern();
1960 return false; // No pattern.
1963 // FIXME: Assume only the first tree is the pattern. The others are clobber
1965 AnalyzeNode(Pattern->getTree(0));
1970 void AnalyzeNode(const TreePatternNode *N) {
1972 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
1973 Record *LeafRec = DI->getDef();
1974 // Handle ComplexPattern leaves.
1975 if (LeafRec->isSubClassOf("ComplexPattern")) {
1976 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
1977 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
1978 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
1979 if (CP.hasProperty(SDNPSideEffect)) HasSideEffects = true;
1985 // Analyze children.
1986 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1987 AnalyzeNode(N->getChild(i));
1989 // Ignore set nodes, which are not SDNodes.
1990 if (N->getOperator()->getName() == "set")
1993 // Get information about the SDNode for the operator.
1994 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N->getOperator());
1996 // Notice properties of the node.
1997 if (OpInfo.hasProperty(SDNPMayStore)) mayStore = true;
1998 if (OpInfo.hasProperty(SDNPMayLoad)) mayLoad = true;
1999 if (OpInfo.hasProperty(SDNPSideEffect)) HasSideEffects = true;
2001 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
2002 // If this is an intrinsic, analyze it.
2003 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
2004 mayLoad = true;// These may load memory.
2006 if (IntInfo->ModRef >= CodeGenIntrinsic::WriteArgMem)
2007 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
2009 if (IntInfo->ModRef >= CodeGenIntrinsic::WriteMem)
2010 // WriteMem intrinsics can have other strange effects.
2011 HasSideEffects = true;
2017 static void InferFromPattern(const CodeGenInstruction &Inst,
2018 bool &MayStore, bool &MayLoad,
2019 bool &HasSideEffects,
2020 const CodeGenDAGPatterns &CDP) {
2021 MayStore = MayLoad = HasSideEffects = false;
2024 InstAnalyzer(CDP, MayStore, MayLoad, HasSideEffects).Analyze(Inst.TheDef);
2026 // InstAnalyzer only correctly analyzes mayStore/mayLoad so far.
2027 if (Inst.mayStore) { // If the .td file explicitly sets mayStore, use it.
2028 // If we decided that this is a store from the pattern, then the .td file
2029 // entry is redundant.
2032 "Warning: mayStore flag explicitly set on instruction '%s'"
2033 " but flag already inferred from pattern.\n",
2034 Inst.TheDef->getName().c_str());
2038 if (Inst.mayLoad) { // If the .td file explicitly sets mayLoad, use it.
2039 // If we decided that this is a load from the pattern, then the .td file
2040 // entry is redundant.
2043 "Warning: mayLoad flag explicitly set on instruction '%s'"
2044 " but flag already inferred from pattern.\n",
2045 Inst.TheDef->getName().c_str());
2049 if (Inst.neverHasSideEffects) {
2051 fprintf(stderr, "Warning: neverHasSideEffects set on instruction '%s' "
2052 "which already has a pattern\n", Inst.TheDef->getName().c_str());
2053 HasSideEffects = false;
2056 if (Inst.hasSideEffects) {
2058 fprintf(stderr, "Warning: hasSideEffects set on instruction '%s' "
2059 "which already inferred this.\n", Inst.TheDef->getName().c_str());
2060 HasSideEffects = true;
2064 /// ParseInstructions - Parse all of the instructions, inlining and resolving
2065 /// any fragments involved. This populates the Instructions list with fully
2066 /// resolved instructions.
2067 void CodeGenDAGPatterns::ParseInstructions() {
2068 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
2070 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
2073 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
2074 LI = Instrs[i]->getValueAsListInit("Pattern");
2076 // If there is no pattern, only collect minimal information about the
2077 // instruction for its operand list. We have to assume that there is one
2078 // result, as we have no detailed info.
2079 if (!LI || LI->getSize() == 0) {
2080 std::vector<Record*> Results;
2081 std::vector<Record*> Operands;
2083 CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
2085 if (InstInfo.OperandList.size() != 0) {
2086 if (InstInfo.NumDefs == 0) {
2087 // These produce no results
2088 for (unsigned j = 0, e = InstInfo.OperandList.size(); j < e; ++j)
2089 Operands.push_back(InstInfo.OperandList[j].Rec);
2091 // Assume the first operand is the result.
2092 Results.push_back(InstInfo.OperandList[0].Rec);
2094 // The rest are inputs.
2095 for (unsigned j = 1, e = InstInfo.OperandList.size(); j < e; ++j)
2096 Operands.push_back(InstInfo.OperandList[j].Rec);
2100 // Create and insert the instruction.
2101 std::vector<Record*> ImpResults;
2102 std::vector<Record*> ImpOperands;
2103 Instructions.insert(std::make_pair(Instrs[i],
2104 DAGInstruction(0, Results, Operands, ImpResults,
2106 continue; // no pattern.
2109 // Parse the instruction.
2110 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
2111 // Inline pattern fragments into it.
2112 I->InlinePatternFragments();
2114 // Infer as many types as possible. If we cannot infer all of them, we can
2115 // never do anything with this instruction pattern: report it to the user.
2116 if (!I->InferAllTypes())
2117 I->error("Could not infer all types in pattern!");
2119 // InstInputs - Keep track of all of the inputs of the instruction, along
2120 // with the record they are declared as.
2121 std::map<std::string, TreePatternNode*> InstInputs;
2123 // InstResults - Keep track of all the virtual registers that are 'set'
2124 // in the instruction, including what reg class they are.
2125 std::map<std::string, TreePatternNode*> InstResults;
2127 std::vector<Record*> InstImpInputs;
2128 std::vector<Record*> InstImpResults;
2130 // Verify that the top-level forms in the instruction are of void type, and
2131 // fill in the InstResults map.
2132 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
2133 TreePatternNode *Pat = I->getTree(j);
2134 if (!Pat->hasTypeSet() || Pat->getType() != MVT::isVoid)
2135 I->error("Top-level forms in instruction pattern should have"
2138 // Find inputs and outputs, and verify the structure of the uses/defs.
2139 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
2140 InstImpInputs, InstImpResults);
2143 // Now that we have inputs and outputs of the pattern, inspect the operands
2144 // list for the instruction. This determines the order that operands are
2145 // added to the machine instruction the node corresponds to.
2146 unsigned NumResults = InstResults.size();
2148 // Parse the operands list from the (ops) list, validating it.
2149 assert(I->getArgList().empty() && "Args list should still be empty here!");
2150 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]);
2152 // Check that all of the results occur first in the list.
2153 std::vector<Record*> Results;
2154 TreePatternNode *Res0Node = NULL;
2155 for (unsigned i = 0; i != NumResults; ++i) {
2156 if (i == CGI.OperandList.size())
2157 I->error("'" + InstResults.begin()->first +
2158 "' set but does not appear in operand list!");
2159 const std::string &OpName = CGI.OperandList[i].Name;
2161 // Check that it exists in InstResults.
2162 TreePatternNode *RNode = InstResults[OpName];
2164 I->error("Operand $" + OpName + " does not exist in operand list!");
2168 Record *R = dynamic_cast<DefInit*>(RNode->getLeafValue())->getDef();
2170 I->error("Operand $" + OpName + " should be a set destination: all "
2171 "outputs must occur before inputs in operand list!");
2173 if (CGI.OperandList[i].Rec != R)
2174 I->error("Operand $" + OpName + " class mismatch!");
2176 // Remember the return type.
2177 Results.push_back(CGI.OperandList[i].Rec);
2179 // Okay, this one checks out.
2180 InstResults.erase(OpName);
2183 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
2184 // the copy while we're checking the inputs.
2185 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
2187 std::vector<TreePatternNode*> ResultNodeOperands;
2188 std::vector<Record*> Operands;
2189 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
2190 CodeGenInstruction::OperandInfo &Op = CGI.OperandList[i];
2191 const std::string &OpName = Op.Name;
2193 I->error("Operand #" + utostr(i) + " in operands list has no name!");
2195 if (!InstInputsCheck.count(OpName)) {
2196 // If this is an predicate operand or optional def operand with an
2197 // DefaultOps set filled in, we can ignore this. When we codegen it,
2198 // we will do so as always executed.
2199 if (Op.Rec->isSubClassOf("PredicateOperand") ||
2200 Op.Rec->isSubClassOf("OptionalDefOperand")) {
2201 // Does it have a non-empty DefaultOps field? If so, ignore this
2203 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
2206 I->error("Operand $" + OpName +
2207 " does not appear in the instruction pattern");
2209 TreePatternNode *InVal = InstInputsCheck[OpName];
2210 InstInputsCheck.erase(OpName); // It occurred, remove from map.
2212 if (InVal->isLeaf() &&
2213 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
2214 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
2215 if (Op.Rec != InRec && !InRec->isSubClassOf("ComplexPattern"))
2216 I->error("Operand $" + OpName + "'s register class disagrees"
2217 " between the operand and pattern");
2219 Operands.push_back(Op.Rec);
2221 // Construct the result for the dest-pattern operand list.
2222 TreePatternNode *OpNode = InVal->clone();
2224 // No predicate is useful on the result.
2225 OpNode->clearPredicateFns();
2227 // Promote the xform function to be an explicit node if set.
2228 if (Record *Xform = OpNode->getTransformFn()) {
2229 OpNode->setTransformFn(0);
2230 std::vector<TreePatternNode*> Children;
2231 Children.push_back(OpNode);
2232 OpNode = new TreePatternNode(Xform, Children);
2235 ResultNodeOperands.push_back(OpNode);
2238 if (!InstInputsCheck.empty())
2239 I->error("Input operand $" + InstInputsCheck.begin()->first +
2240 " occurs in pattern but not in operands list!");
2242 TreePatternNode *ResultPattern =
2243 new TreePatternNode(I->getRecord(), ResultNodeOperands);
2244 // Copy fully inferred output node type to instruction result pattern.
2246 ResultPattern->setType(Res0Node->getExtType());
2248 // Create and insert the instruction.
2249 // FIXME: InstImpResults and InstImpInputs should not be part of
2251 DAGInstruction TheInst(I, Results, Operands, InstImpResults, InstImpInputs);
2252 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
2254 // Use a temporary tree pattern to infer all types and make sure that the
2255 // constructed result is correct. This depends on the instruction already
2256 // being inserted into the Instructions map.
2257 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
2258 Temp.InferAllTypes(&I->getNamedNodesMap());
2260 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
2261 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
2266 // If we can, convert the instructions to be patterns that are matched!
2267 for (std::map<Record*, DAGInstruction, RecordPtrCmp>::iterator II =
2268 Instructions.begin(),
2269 E = Instructions.end(); II != E; ++II) {
2270 DAGInstruction &TheInst = II->second;
2271 const TreePattern *I = TheInst.getPattern();
2272 if (I == 0) continue; // No pattern.
2274 // FIXME: Assume only the first tree is the pattern. The others are clobber
2276 TreePatternNode *Pattern = I->getTree(0);
2277 TreePatternNode *SrcPattern;
2278 if (Pattern->getOperator()->getName() == "set") {
2279 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
2281 // Not a set (store or something?)
2282 SrcPattern = Pattern;
2285 Record *Instr = II->first;
2286 AddPatternToMatch(I,
2287 PatternToMatch(Instr->getValueAsListInit("Predicates"),
2289 TheInst.getResultPattern(),
2290 TheInst.getImpResults(),
2291 Instr->getValueAsInt("AddedComplexity"),
2297 typedef std::pair<const TreePatternNode*, unsigned> NameRecord;
2299 static void FindNames(const TreePatternNode *P,
2300 std::map<std::string, NameRecord> &Names,
2301 const TreePattern *PatternTop) {
2302 if (!P->getName().empty()) {
2303 NameRecord &Rec = Names[P->getName()];
2304 // If this is the first instance of the name, remember the node.
2305 if (Rec.second++ == 0)
2307 else if (Rec.first->getType() != P->getType())
2308 PatternTop->error("repetition of value: $" + P->getName() +
2309 " where different uses have different types!");
2313 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
2314 FindNames(P->getChild(i), Names, PatternTop);
2318 void CodeGenDAGPatterns::AddPatternToMatch(const TreePattern *Pattern,
2319 const PatternToMatch &PTM) {
2320 // Do some sanity checking on the pattern we're about to match.
2322 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this))
2323 Pattern->error("Pattern can never match: " + Reason);
2325 // If the source pattern's root is a complex pattern, that complex pattern
2326 // must specify the nodes it can potentially match.
2327 if (const ComplexPattern *CP =
2328 PTM.getSrcPattern()->getComplexPatternInfo(*this))
2329 if (CP->getRootNodes().empty())
2330 Pattern->error("ComplexPattern at root must specify list of opcodes it"
2334 // Find all of the named values in the input and output, ensure they have the
2336 std::map<std::string, NameRecord> SrcNames, DstNames;
2337 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
2338 FindNames(PTM.getDstPattern(), DstNames, Pattern);
2340 // Scan all of the named values in the destination pattern, rejecting them if
2341 // they don't exist in the input pattern.
2342 for (std::map<std::string, NameRecord>::iterator
2343 I = DstNames.begin(), E = DstNames.end(); I != E; ++I) {
2344 if (SrcNames[I->first].first == 0)
2345 Pattern->error("Pattern has input without matching name in output: $" +
2349 // Scan all of the named values in the source pattern, rejecting them if the
2350 // name isn't used in the dest, and isn't used to tie two values together.
2351 for (std::map<std::string, NameRecord>::iterator
2352 I = SrcNames.begin(), E = SrcNames.end(); I != E; ++I)
2353 if (DstNames[I->first].first == 0 && SrcNames[I->first].second == 1)
2354 Pattern->error("Pattern has dead named input: $" + I->first);
2356 PatternsToMatch.push_back(PTM);
2361 void CodeGenDAGPatterns::InferInstructionFlags() {
2362 const std::vector<const CodeGenInstruction*> &Instructions =
2363 Target.getInstructionsByEnumValue();
2364 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
2365 CodeGenInstruction &InstInfo =
2366 const_cast<CodeGenInstruction &>(*Instructions[i]);
2367 // Determine properties of the instruction from its pattern.
2368 bool MayStore, MayLoad, HasSideEffects;
2369 InferFromPattern(InstInfo, MayStore, MayLoad, HasSideEffects, *this);
2370 InstInfo.mayStore = MayStore;
2371 InstInfo.mayLoad = MayLoad;
2372 InstInfo.hasSideEffects = HasSideEffects;
2376 /// Given a pattern result with an unresolved type, see if we can find one
2377 /// instruction with an unresolved result type. Force this result type to an
2378 /// arbitrary element if it's possible types to converge results.
2379 static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
2383 // Analyze children.
2384 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2385 if (ForceArbitraryInstResultType(N->getChild(i), TP))
2388 if (!N->getOperator()->isSubClassOf("Instruction"))
2391 // If this type is already concrete or completely unknown we can't do
2393 if (N->getExtType().isCompletelyUnknown() || N->getExtType().isConcrete())
2396 // Otherwise, force its type to the first possibility (an arbitrary choice).
2397 return N->getExtType().MergeInTypeInfo(N->getExtType().getTypeList()[0], TP);
2400 void CodeGenDAGPatterns::ParsePatterns() {
2401 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
2403 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
2404 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
2405 DefInit *OpDef = dynamic_cast<DefInit*>(Tree->getOperator());
2406 Record *Operator = OpDef->getDef();
2407 TreePattern *Pattern;
2408 if (Operator->getName() != "parallel")
2409 Pattern = new TreePattern(Patterns[i], Tree, true, *this);
2411 std::vector<Init*> Values;
2413 for (unsigned j = 0, ee = Tree->getNumArgs(); j != ee; ++j) {
2414 Values.push_back(Tree->getArg(j));
2415 TypedInit *TArg = dynamic_cast<TypedInit*>(Tree->getArg(j));
2417 errs() << "In dag: " << Tree->getAsString();
2418 errs() << " -- Untyped argument in pattern\n";
2419 assert(0 && "Untyped argument in pattern");
2422 ListTy = resolveTypes(ListTy, TArg->getType());
2424 errs() << "In dag: " << Tree->getAsString();
2425 errs() << " -- Incompatible types in pattern arguments\n";
2426 assert(0 && "Incompatible types in pattern arguments");
2430 ListTy = TArg->getType();
2433 ListInit *LI = new ListInit(Values, new ListRecTy(ListTy));
2434 Pattern = new TreePattern(Patterns[i], LI, true, *this);
2437 // Inline pattern fragments into it.
2438 Pattern->InlinePatternFragments();
2440 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
2441 if (LI->getSize() == 0) continue; // no pattern.
2443 // Parse the instruction.
2444 TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
2446 // Inline pattern fragments into it.
2447 Result->InlinePatternFragments();
2449 if (Result->getNumTrees() != 1)
2450 Result->error("Cannot handle instructions producing instructions "
2451 "with temporaries yet!");
2453 bool IterateInference;
2454 bool InferredAllPatternTypes, InferredAllResultTypes;
2456 // Infer as many types as possible. If we cannot infer all of them, we
2457 // can never do anything with this pattern: report it to the user.
2458 InferredAllPatternTypes =
2459 Pattern->InferAllTypes(&Pattern->getNamedNodesMap());
2461 // Infer as many types as possible. If we cannot infer all of them, we
2462 // can never do anything with this pattern: report it to the user.
2463 InferredAllResultTypes =
2464 Result->InferAllTypes(&Pattern->getNamedNodesMap());
2466 IterateInference = false;
2468 // Apply the type of the result to the source pattern. This helps us
2469 // resolve cases where the input type is known to be a pointer type (which
2470 // is considered resolved), but the result knows it needs to be 32- or
2471 // 64-bits. Infer the other way for good measure.
2472 if (!Result->getTree(0)->getExtType().isVoid() &&
2473 !Pattern->getTree(0)->getExtType().isVoid()) {
2474 IterateInference = Pattern->getTree(0)->
2475 UpdateNodeType(Result->getTree(0)->getExtType(), *Result);
2476 IterateInference |= Result->getTree(0)->
2477 UpdateNodeType(Pattern->getTree(0)->getExtType(), *Result);
2480 // If our iteration has converged and the input pattern's types are fully
2481 // resolved but the result pattern is not fully resolved, we may have a
2482 // situation where we have two instructions in the result pattern and
2483 // the instructions require a common register class, but don't care about
2484 // what actual MVT is used. This is actually a bug in our modelling:
2485 // output patterns should have register classes, not MVTs.
2487 // In any case, to handle this, we just go through and disambiguate some
2488 // arbitrary types to the result pattern's nodes.
2489 if (!IterateInference && InferredAllPatternTypes &&
2490 !InferredAllResultTypes)
2491 IterateInference = ForceArbitraryInstResultType(Result->getTree(0),
2493 } while (IterateInference);
2495 // Verify that we inferred enough types that we can do something with the
2496 // pattern and result. If these fire the user has to add type casts.
2497 if (!InferredAllPatternTypes)
2498 Pattern->error("Could not infer all types in pattern!");
2499 if (!InferredAllResultTypes) {
2501 Result->error("Could not infer all types in pattern result!");
2504 // Validate that the input pattern is correct.
2505 std::map<std::string, TreePatternNode*> InstInputs;
2506 std::map<std::string, TreePatternNode*> InstResults;
2507 std::vector<Record*> InstImpInputs;
2508 std::vector<Record*> InstImpResults;
2509 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
2510 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
2511 InstInputs, InstResults,
2512 InstImpInputs, InstImpResults);
2514 // Promote the xform function to be an explicit node if set.
2515 TreePatternNode *DstPattern = Result->getOnlyTree();
2516 std::vector<TreePatternNode*> ResultNodeOperands;
2517 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
2518 TreePatternNode *OpNode = DstPattern->getChild(ii);
2519 if (Record *Xform = OpNode->getTransformFn()) {
2520 OpNode->setTransformFn(0);
2521 std::vector<TreePatternNode*> Children;
2522 Children.push_back(OpNode);
2523 OpNode = new TreePatternNode(Xform, Children);
2525 ResultNodeOperands.push_back(OpNode);
2527 DstPattern = Result->getOnlyTree();
2528 if (!DstPattern->isLeaf())
2529 DstPattern = new TreePatternNode(DstPattern->getOperator(),
2530 ResultNodeOperands);
2531 DstPattern->setType(Result->getOnlyTree()->getExtType());
2532 TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
2533 Temp.InferAllTypes();
2536 AddPatternToMatch(Pattern,
2537 PatternToMatch(Patterns[i]->getValueAsListInit("Predicates"),
2538 Pattern->getTree(0),
2539 Temp.getOnlyTree(), InstImpResults,
2540 Patterns[i]->getValueAsInt("AddedComplexity"),
2541 Patterns[i]->getID()));
2545 /// CombineChildVariants - Given a bunch of permutations of each child of the
2546 /// 'operator' node, put them together in all possible ways.
2547 static void CombineChildVariants(TreePatternNode *Orig,
2548 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
2549 std::vector<TreePatternNode*> &OutVariants,
2550 CodeGenDAGPatterns &CDP,
2551 const MultipleUseVarSet &DepVars) {
2552 // Make sure that each operand has at least one variant to choose from.
2553 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2554 if (ChildVariants[i].empty())
2557 // The end result is an all-pairs construction of the resultant pattern.
2558 std::vector<unsigned> Idxs;
2559 Idxs.resize(ChildVariants.size());
2563 DEBUG(if (!Idxs.empty()) {
2564 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
2565 for (unsigned i = 0; i < Idxs.size(); ++i) {
2566 errs() << Idxs[i] << " ";
2571 // Create the variant and add it to the output list.
2572 std::vector<TreePatternNode*> NewChildren;
2573 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2574 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
2575 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
2577 // Copy over properties.
2578 R->setName(Orig->getName());
2579 R->setPredicateFns(Orig->getPredicateFns());
2580 R->setTransformFn(Orig->getTransformFn());
2581 R->setType(Orig->getExtType());
2583 // If this pattern cannot match, do not include it as a variant.
2584 std::string ErrString;
2585 if (!R->canPatternMatch(ErrString, CDP)) {
2588 bool AlreadyExists = false;
2590 // Scan to see if this pattern has already been emitted. We can get
2591 // duplication due to things like commuting:
2592 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
2593 // which are the same pattern. Ignore the dups.
2594 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
2595 if (R->isIsomorphicTo(OutVariants[i], DepVars)) {
2596 AlreadyExists = true;
2603 OutVariants.push_back(R);
2606 // Increment indices to the next permutation by incrementing the
2607 // indicies from last index backward, e.g., generate the sequence
2608 // [0, 0], [0, 1], [1, 0], [1, 1].
2610 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
2611 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
2616 NotDone = (IdxsIdx >= 0);
2620 /// CombineChildVariants - A helper function for binary operators.
2622 static void CombineChildVariants(TreePatternNode *Orig,
2623 const std::vector<TreePatternNode*> &LHS,
2624 const std::vector<TreePatternNode*> &RHS,
2625 std::vector<TreePatternNode*> &OutVariants,
2626 CodeGenDAGPatterns &CDP,
2627 const MultipleUseVarSet &DepVars) {
2628 std::vector<std::vector<TreePatternNode*> > ChildVariants;
2629 ChildVariants.push_back(LHS);
2630 ChildVariants.push_back(RHS);
2631 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
2635 static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
2636 std::vector<TreePatternNode *> &Children) {
2637 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
2638 Record *Operator = N->getOperator();
2640 // Only permit raw nodes.
2641 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
2642 N->getTransformFn()) {
2643 Children.push_back(N);
2647 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
2648 Children.push_back(N->getChild(0));
2650 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
2652 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
2653 Children.push_back(N->getChild(1));
2655 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
2658 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
2659 /// the (potentially recursive) pattern by using algebraic laws.
2661 static void GenerateVariantsOf(TreePatternNode *N,
2662 std::vector<TreePatternNode*> &OutVariants,
2663 CodeGenDAGPatterns &CDP,
2664 const MultipleUseVarSet &DepVars) {
2665 // We cannot permute leaves.
2667 OutVariants.push_back(N);
2671 // Look up interesting info about the node.
2672 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
2674 // If this node is associative, re-associate.
2675 if (NodeInfo.hasProperty(SDNPAssociative)) {
2676 // Re-associate by pulling together all of the linked operators
2677 std::vector<TreePatternNode*> MaximalChildren;
2678 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
2680 // Only handle child sizes of 3. Otherwise we'll end up trying too many
2682 if (MaximalChildren.size() == 3) {
2683 // Find the variants of all of our maximal children.
2684 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
2685 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
2686 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
2687 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
2689 // There are only two ways we can permute the tree:
2690 // (A op B) op C and A op (B op C)
2691 // Within these forms, we can also permute A/B/C.
2693 // Generate legal pair permutations of A/B/C.
2694 std::vector<TreePatternNode*> ABVariants;
2695 std::vector<TreePatternNode*> BAVariants;
2696 std::vector<TreePatternNode*> ACVariants;
2697 std::vector<TreePatternNode*> CAVariants;
2698 std::vector<TreePatternNode*> BCVariants;
2699 std::vector<TreePatternNode*> CBVariants;
2700 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
2701 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
2702 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
2703 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
2704 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
2705 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
2707 // Combine those into the result: (x op x) op x
2708 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
2709 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
2710 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
2711 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
2712 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
2713 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
2715 // Combine those into the result: x op (x op x)
2716 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
2717 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
2718 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
2719 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
2720 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
2721 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
2726 // Compute permutations of all children.
2727 std::vector<std::vector<TreePatternNode*> > ChildVariants;
2728 ChildVariants.resize(N->getNumChildren());
2729 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2730 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
2732 // Build all permutations based on how the children were formed.
2733 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
2735 // If this node is commutative, consider the commuted order.
2736 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
2737 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
2738 assert((N->getNumChildren()==2 || isCommIntrinsic) &&
2739 "Commutative but doesn't have 2 children!");
2740 // Don't count children which are actually register references.
2742 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2743 TreePatternNode *Child = N->getChild(i);
2744 if (Child->isLeaf())
2745 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2746 Record *RR = DI->getDef();
2747 if (RR->isSubClassOf("Register"))
2752 // Consider the commuted order.
2753 if (isCommIntrinsic) {
2754 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
2755 // operands are the commutative operands, and there might be more operands
2758 "Commutative intrinsic should have at least 3 childrean!");
2759 std::vector<std::vector<TreePatternNode*> > Variants;
2760 Variants.push_back(ChildVariants[0]); // Intrinsic id.
2761 Variants.push_back(ChildVariants[2]);
2762 Variants.push_back(ChildVariants[1]);
2763 for (unsigned i = 3; i != NC; ++i)
2764 Variants.push_back(ChildVariants[i]);
2765 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
2767 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
2768 OutVariants, CDP, DepVars);
2773 // GenerateVariants - Generate variants. For example, commutative patterns can
2774 // match multiple ways. Add them to PatternsToMatch as well.
2775 void CodeGenDAGPatterns::GenerateVariants() {
2776 DEBUG(errs() << "Generating instruction variants.\n");
2778 // Loop over all of the patterns we've collected, checking to see if we can
2779 // generate variants of the instruction, through the exploitation of
2780 // identities. This permits the target to provide aggressive matching without
2781 // the .td file having to contain tons of variants of instructions.
2783 // Note that this loop adds new patterns to the PatternsToMatch list, but we
2784 // intentionally do not reconsider these. Any variants of added patterns have
2785 // already been added.
2787 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
2788 MultipleUseVarSet DepVars;
2789 std::vector<TreePatternNode*> Variants;
2790 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
2791 DEBUG(errs() << "Dependent/multiply used variables: ");
2792 DEBUG(DumpDepVars(DepVars));
2793 DEBUG(errs() << "\n");
2794 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this, DepVars);
2796 assert(!Variants.empty() && "Must create at least original variant!");
2797 Variants.erase(Variants.begin()); // Remove the original pattern.
2799 if (Variants.empty()) // No variants for this pattern.
2802 DEBUG(errs() << "FOUND VARIANTS OF: ";
2803 PatternsToMatch[i].getSrcPattern()->dump();
2806 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
2807 TreePatternNode *Variant = Variants[v];
2809 DEBUG(errs() << " VAR#" << v << ": ";
2813 // Scan to see if an instruction or explicit pattern already matches this.
2814 bool AlreadyExists = false;
2815 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
2816 // Skip if the top level predicates do not match.
2817 if (PatternsToMatch[i].getPredicates() !=
2818 PatternsToMatch[p].getPredicates())
2820 // Check to see if this variant already exists.
2821 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(), DepVars)) {
2822 DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
2823 AlreadyExists = true;
2827 // If we already have it, ignore the variant.
2828 if (AlreadyExists) continue;
2830 // Otherwise, add it to the list of patterns we have.
2832 push_back(PatternToMatch(PatternsToMatch[i].getPredicates(),
2833 Variant, PatternsToMatch[i].getDstPattern(),
2834 PatternsToMatch[i].getDstRegs(),
2835 PatternsToMatch[i].getAddedComplexity(),
2836 Record::getNewUID()));
2839 DEBUG(errs() << "\n");