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 // FIXME: Remove EEVT::isUnknown!
30 static inline bool isInteger(MVT::SimpleValueType VT) {
31 return EVT(VT).isInteger();
34 static inline bool isFloatingPoint(MVT::SimpleValueType VT) {
35 return EVT(VT).isFloatingPoint();
38 static inline bool isVector(MVT::SimpleValueType VT) {
39 return EVT(VT).isVector();
42 EEVT::TypeSet::TypeSet(MVT::SimpleValueType VT, TreePattern &TP) {
45 else if (VT == MVT::fAny)
46 EnforceFloatingPoint(TP);
47 else if (VT == MVT::vAny)
50 assert((VT < MVT::LAST_VALUETYPE || VT == MVT::iPTR ||
51 VT == MVT::iPTRAny) && "Not a concrete type!");
52 TypeVec.push_back(VT);
57 EEVT::TypeSet::TypeSet(const std::vector<MVT::SimpleValueType> &VTList) {
58 assert(!VTList.empty() && "empty list?");
59 TypeVec.append(VTList.begin(), VTList.end());
62 assert(VTList[0] != MVT::iAny && VTList[0] != MVT::vAny &&
63 VTList[0] != MVT::fAny);
66 array_pod_sort(TypeVec.begin(), TypeVec.end());
67 TypeVec.erase(std::unique(TypeVec.begin(), TypeVec.end()), TypeVec.end());
71 /// hasIntegerTypes - Return true if this TypeSet contains iAny or an
72 /// integer value type.
73 bool EEVT::TypeSet::hasIntegerTypes() const {
74 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
75 if (isInteger(TypeVec[i]))
80 /// hasFloatingPointTypes - Return true if this TypeSet contains an fAny or
81 /// a floating point value type.
82 bool EEVT::TypeSet::hasFloatingPointTypes() const {
83 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
84 if (isFloatingPoint(TypeVec[i]))
89 /// hasVectorTypes - Return true if this TypeSet contains a vAny or a vector
91 bool EEVT::TypeSet::hasVectorTypes() const {
92 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
93 if (isVector(TypeVec[i]))
99 std::string EEVT::TypeSet::getName() const {
100 if (TypeVec.empty()) return "isUnknown";
104 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i) {
105 std::string VTName = llvm::getEnumName(TypeVec[i]);
106 // Strip off MVT:: prefix if present.
107 if (VTName.substr(0,5) == "MVT::")
108 VTName = VTName.substr(5);
109 if (i) Result += ':';
113 if (TypeVec.size() == 1)
115 return "{" + Result + "}";
118 /// MergeInTypeInfo - This merges in type information from the specified
119 /// argument. If 'this' changes, it returns true. If the two types are
120 /// contradictory (e.g. merge f32 into i32) then this throws an exception.
121 bool EEVT::TypeSet::MergeInTypeInfo(const EEVT::TypeSet &InVT, TreePattern &TP){
122 if (InVT.isCompletelyUnknown() || *this == InVT)
125 if (isCompletelyUnknown()) {
130 assert(TypeVec.size() >= 1 && InVT.TypeVec.size() >= 1 && "No unknowns");
132 // Handle the abstract cases, seeing if we can resolve them better.
133 switch (TypeVec[0]) {
137 if (InVT.hasIntegerTypes()) {
138 EEVT::TypeSet InCopy(InVT);
139 InCopy.EnforceInteger(TP);
140 InCopy.EnforceScalar(TP);
142 if (InCopy.isConcrete()) {
143 // If the RHS has one integer type, upgrade iPTR to i32.
144 TypeVec[0] = InVT.TypeVec[0];
148 // If the input has multiple scalar integers, this doesn't add any info.
149 if (!InCopy.isCompletelyUnknown())
155 // If the input constraint is iAny/iPTR and this is an integer type list,
156 // remove non-integer types from the list.
157 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
159 bool MadeChange = EnforceInteger(TP);
161 // If we're merging in iPTR/iPTRAny and the node currently has a list of
162 // multiple different integer types, replace them with a single iPTR.
163 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
164 TypeVec.size() != 1) {
166 TypeVec[0] = InVT.TypeVec[0];
173 // If this is a type list and the RHS is a typelist as well, eliminate entries
174 // from this list that aren't in the other one.
175 bool MadeChange = false;
176 TypeSet InputSet(*this);
178 for (unsigned i = 0; i != TypeVec.size(); ++i) {
180 for (unsigned j = 0, e = InVT.TypeVec.size(); j != e; ++j)
181 if (TypeVec[i] == InVT.TypeVec[j]) {
186 if (InInVT) continue;
187 TypeVec.erase(TypeVec.begin()+i--);
191 // If we removed all of our types, we have a type contradiction.
192 if (!TypeVec.empty())
195 // FIXME: Really want an SMLoc here!
196 TP.error("Type inference contradiction found, merging '" +
197 InVT.getName() + "' into '" + InputSet.getName() + "'");
198 return true; // unreachable
201 /// EnforceInteger - Remove all non-integer types from this set.
202 bool EEVT::TypeSet::EnforceInteger(TreePattern &TP) {
203 TypeSet InputSet(*this);
204 bool MadeChange = false;
206 // If we know nothing, then get the full set.
207 if (TypeVec.empty()) {
208 *this = TP.getDAGPatterns().getTargetInfo().getLegalValueTypes();
212 if (!hasFloatingPointTypes())
215 // Filter out all the fp types.
216 for (unsigned i = 0; i != TypeVec.size(); ++i)
217 if (isFloatingPoint(TypeVec[i]))
218 TypeVec.erase(TypeVec.begin()+i--);
221 TP.error("Type inference contradiction found, '" +
222 InputSet.getName() + "' needs to be integer");
226 /// EnforceFloatingPoint - Remove all integer types from this set.
227 bool EEVT::TypeSet::EnforceFloatingPoint(TreePattern &TP) {
228 TypeSet InputSet(*this);
229 bool MadeChange = false;
231 // If we know nothing, then get the full set.
232 if (TypeVec.empty()) {
233 *this = TP.getDAGPatterns().getTargetInfo().getLegalValueTypes();
237 if (!hasIntegerTypes())
240 // Filter out all the fp types.
241 for (unsigned i = 0; i != TypeVec.size(); ++i)
242 if (isInteger(TypeVec[i]))
243 TypeVec.erase(TypeVec.begin()+i--);
246 TP.error("Type inference contradiction found, '" +
247 InputSet.getName() + "' needs to be floating point");
251 /// EnforceScalar - Remove all vector types from this.
252 bool EEVT::TypeSet::EnforceScalar(TreePattern &TP) {
253 TypeSet InputSet(*this);
254 bool MadeChange = false;
256 // If we know nothing, then get the full set.
257 if (TypeVec.empty()) {
258 *this = TP.getDAGPatterns().getTargetInfo().getLegalValueTypes();
262 if (!hasVectorTypes())
265 // Filter out all the vector types.
266 for (unsigned i = 0; i != TypeVec.size(); ++i)
267 if (isVector(TypeVec[i]))
268 TypeVec.erase(TypeVec.begin()+i--);
271 TP.error("Type inference contradiction found, '" +
272 InputSet.getName() + "' needs to be scalar");
276 /// EnforceVector - Remove all vector types from this.
277 bool EEVT::TypeSet::EnforceVector(TreePattern &TP) {
278 TypeSet InputSet(*this);
279 bool MadeChange = false;
281 // If we know nothing, then get the full set.
282 if (TypeVec.empty()) {
283 *this = TP.getDAGPatterns().getTargetInfo().getLegalValueTypes();
287 // Filter out all the scalar types.
288 for (unsigned i = 0; i != TypeVec.size(); ++i)
289 if (!isVector(TypeVec[i]))
290 TypeVec.erase(TypeVec.begin()+i--);
293 TP.error("Type inference contradiction found, '" +
294 InputSet.getName() + "' needs to be a vector");
299 /// EnforceSmallerThan - 'this' must be a smaller VT than Other. Update
300 /// this an other based on this information.
301 bool EEVT::TypeSet::EnforceSmallerThan(EEVT::TypeSet &Other, TreePattern &TP) {
302 // Both operands must be integer or FP, but we don't care which.
303 bool MadeChange = false;
305 // This code does not currently handle nodes which have multiple types,
306 // where some types are integer, and some are fp. Assert that this is not
308 assert(!(hasIntegerTypes() && hasFloatingPointTypes()) &&
309 !(Other.hasIntegerTypes() && Other.hasFloatingPointTypes()) &&
310 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
311 // If one side is known to be integer or known to be FP but the other side has
312 // no information, get at least the type integrality info in there.
313 if (hasIntegerTypes())
314 MadeChange |= Other.EnforceInteger(TP);
315 else if (hasFloatingPointTypes())
316 MadeChange |= Other.EnforceFloatingPoint(TP);
317 if (Other.hasIntegerTypes())
318 MadeChange |= EnforceInteger(TP);
319 else if (Other.hasFloatingPointTypes())
320 MadeChange |= EnforceFloatingPoint(TP);
322 assert(!isCompletelyUnknown() && !Other.isCompletelyUnknown() &&
323 "Should have a type list now");
325 // If one contains vectors but the other doesn't pull vectors out.
326 if (!hasVectorTypes() && Other.hasVectorTypes())
327 MadeChange |= Other.EnforceScalar(TP);
328 if (hasVectorTypes() && !Other.hasVectorTypes())
329 MadeChange |= EnforceScalar(TP);
331 // FIXME: This is a bone-headed way to do this.
333 // Get the set of legal VTs and filter it based on the known integrality.
334 const CodeGenTarget &CGT = TP.getDAGPatterns().getTargetInfo();
335 TypeSet LegalVTs = CGT.getLegalValueTypes();
337 // TODO: If one or the other side is known to be a specific VT, we could prune
339 if (hasIntegerTypes())
340 LegalVTs.EnforceInteger(TP);
341 else if (hasFloatingPointTypes())
342 LegalVTs.EnforceFloatingPoint(TP);
346 switch (LegalVTs.TypeVec.size()) {
347 case 0: assert(0 && "No legal VTs?");
348 default: // Too many VT's to pick from.
349 // TODO: If the biggest type in LegalVTs is in this set, we could remove it.
350 // If one or the other side is known to be a specific VT, we could prune
354 // Only one VT of this flavor. Cannot ever satisfy the constraints.
355 return MergeInTypeInfo(MVT::Other, TP); // throw
357 // If we have exactly two possible types, the little operand must be the
358 // small one, the big operand should be the big one. This is common with
359 // float/double for example.
360 assert(LegalVTs.TypeVec[0] < LegalVTs.TypeVec[1] && "Should be sorted!");
361 MadeChange |= MergeInTypeInfo(LegalVTs.TypeVec[0], TP);
362 MadeChange |= Other.MergeInTypeInfo(LegalVTs.TypeVec[1], TP);
367 /// EnforceVectorEltTypeIs - 'this' is now constrainted to be a vector type
368 /// whose element is VT.
369 bool EEVT::TypeSet::EnforceVectorEltTypeIs(MVT::SimpleValueType VT,
371 TypeSet InputSet(*this);
372 bool MadeChange = false;
374 // If we know nothing, then get the full set.
375 if (TypeVec.empty()) {
376 *this = TP.getDAGPatterns().getTargetInfo().getLegalValueTypes();
380 // Filter out all the non-vector types and types which don't have the right
382 for (unsigned i = 0; i != TypeVec.size(); ++i)
383 if (!isVector(TypeVec[i]) ||
384 EVT(TypeVec[i]).getVectorElementType().getSimpleVT().SimpleTy != VT) {
385 TypeVec.erase(TypeVec.begin()+i--);
389 if (TypeVec.empty()) // FIXME: Really want an SMLoc here!
390 TP.error("Type inference contradiction found, forcing '" +
391 InputSet.getName() + "' to have a vector element");
395 //===----------------------------------------------------------------------===//
396 // Helpers for working with extended types.
398 bool RecordPtrCmp::operator()(const Record *LHS, const Record *RHS) const {
399 return LHS->getID() < RHS->getID();
402 /// Dependent variable map for CodeGenDAGPattern variant generation
403 typedef std::map<std::string, int> DepVarMap;
405 /// Const iterator shorthand for DepVarMap
406 typedef DepVarMap::const_iterator DepVarMap_citer;
409 void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
411 if (dynamic_cast<DefInit*>(N->getLeafValue()) != NULL) {
412 DepMap[N->getName()]++;
415 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
416 FindDepVarsOf(N->getChild(i), DepMap);
420 //! Find dependent variables within child patterns
423 void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
425 FindDepVarsOf(N, depcounts);
426 for (DepVarMap_citer i = depcounts.begin(); i != depcounts.end(); ++i) {
427 if (i->second > 1) { // std::pair<std::string, int>
428 DepVars.insert(i->first);
433 //! Dump the dependent variable set:
434 void DumpDepVars(MultipleUseVarSet &DepVars) {
435 if (DepVars.empty()) {
436 DEBUG(errs() << "<empty set>");
438 DEBUG(errs() << "[ ");
439 for (MultipleUseVarSet::const_iterator i = DepVars.begin(), e = DepVars.end();
441 DEBUG(errs() << (*i) << " ");
443 DEBUG(errs() << "]");
448 //===----------------------------------------------------------------------===//
449 // PatternToMatch implementation
452 /// getPredicateCheck - Return a single string containing all of this
453 /// pattern's predicates concatenated with "&&" operators.
455 std::string PatternToMatch::getPredicateCheck() const {
456 std::string PredicateCheck;
457 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
458 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
459 Record *Def = Pred->getDef();
460 if (!Def->isSubClassOf("Predicate")) {
464 assert(0 && "Unknown predicate type!");
466 if (!PredicateCheck.empty())
467 PredicateCheck += " && ";
468 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
472 return PredicateCheck;
475 //===----------------------------------------------------------------------===//
476 // SDTypeConstraint implementation
479 SDTypeConstraint::SDTypeConstraint(Record *R) {
480 OperandNo = R->getValueAsInt("OperandNum");
482 if (R->isSubClassOf("SDTCisVT")) {
483 ConstraintType = SDTCisVT;
484 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
485 } else if (R->isSubClassOf("SDTCisPtrTy")) {
486 ConstraintType = SDTCisPtrTy;
487 } else if (R->isSubClassOf("SDTCisInt")) {
488 ConstraintType = SDTCisInt;
489 } else if (R->isSubClassOf("SDTCisFP")) {
490 ConstraintType = SDTCisFP;
491 } else if (R->isSubClassOf("SDTCisVec")) {
492 ConstraintType = SDTCisVec;
493 } else if (R->isSubClassOf("SDTCisSameAs")) {
494 ConstraintType = SDTCisSameAs;
495 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
496 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
497 ConstraintType = SDTCisVTSmallerThanOp;
498 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
499 R->getValueAsInt("OtherOperandNum");
500 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
501 ConstraintType = SDTCisOpSmallerThanOp;
502 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
503 R->getValueAsInt("BigOperandNum");
504 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
505 ConstraintType = SDTCisEltOfVec;
506 x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
508 errs() << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
513 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
514 /// N, which has NumResults results.
515 TreePatternNode *SDTypeConstraint::getOperandNum(unsigned OpNo,
517 unsigned NumResults) const {
518 assert(NumResults <= 1 &&
519 "We only work with nodes with zero or one result so far!");
521 if (OpNo >= (NumResults + N->getNumChildren())) {
522 errs() << "Invalid operand number " << OpNo << " ";
528 if (OpNo < NumResults)
529 return N; // FIXME: need value #
531 return N->getChild(OpNo-NumResults);
534 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
535 /// constraint to the nodes operands. This returns true if it makes a
536 /// change, false otherwise. If a type contradiction is found, throw an
538 bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
539 const SDNodeInfo &NodeInfo,
540 TreePattern &TP) const {
541 unsigned NumResults = NodeInfo.getNumResults();
542 assert(NumResults <= 1 &&
543 "We only work with nodes with zero or one result so far!");
545 // Check that the number of operands is sane. Negative operands -> varargs.
546 if (NodeInfo.getNumOperands() >= 0) {
547 if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands())
548 TP.error(N->getOperator()->getName() + " node requires exactly " +
549 itostr(NodeInfo.getNumOperands()) + " operands!");
552 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NumResults);
554 switch (ConstraintType) {
555 default: assert(0 && "Unknown constraint type!");
557 // Operand must be a particular type.
558 return NodeToApply->UpdateNodeType(x.SDTCisVT_Info.VT, TP);
560 // Operand must be same as target pointer type.
561 return NodeToApply->UpdateNodeType(MVT::iPTR, TP);
563 // Require it to be one of the legal integer VTs.
564 return NodeToApply->getExtType().EnforceInteger(TP);
566 // Require it to be one of the legal fp VTs.
567 return NodeToApply->getExtType().EnforceFloatingPoint(TP);
569 // Require it to be one of the legal vector VTs.
570 return NodeToApply->getExtType().EnforceVector(TP);
572 TreePatternNode *OtherNode =
573 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NumResults);
574 return NodeToApply->UpdateNodeType(OtherNode->getExtType(), TP) |
575 OtherNode->UpdateNodeType(NodeToApply->getExtType(), TP);
577 case SDTCisVTSmallerThanOp: {
578 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
579 // have an integer type that is smaller than the VT.
580 if (!NodeToApply->isLeaf() ||
581 !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
582 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
583 ->isSubClassOf("ValueType"))
584 TP.error(N->getOperator()->getName() + " expects a VT operand!");
585 MVT::SimpleValueType VT =
586 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
588 TP.error(N->getOperator()->getName() + " VT operand must be integer!");
590 TreePatternNode *OtherNode =
591 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N,NumResults);
593 // It must be integer.
594 bool MadeChange = OtherNode->getExtType().EnforceInteger(TP);
596 // This doesn't try to enforce any information on the OtherNode, it just
597 // validates it when information is determined.
598 if (OtherNode->hasTypeSet() && OtherNode->getType() <= VT)
599 OtherNode->UpdateNodeType(MVT::Other, TP); // Throw an error.
602 case SDTCisOpSmallerThanOp: {
603 TreePatternNode *BigOperand =
604 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NumResults);
605 return NodeToApply->getExtType().
606 EnforceSmallerThan(BigOperand->getExtType(), TP);
608 case SDTCisEltOfVec: {
609 TreePatternNode *VecOperand =
610 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NumResults);
611 if (VecOperand->hasTypeSet()) {
612 if (!isVector(VecOperand->getType()))
613 TP.error(N->getOperator()->getName() + " VT operand must be a vector!");
614 EVT IVT = VecOperand->getType();
615 IVT = IVT.getVectorElementType();
616 return NodeToApply->UpdateNodeType(IVT.getSimpleVT().SimpleTy, TP);
619 if (NodeToApply->hasTypeSet() && VecOperand->getExtType().hasVectorTypes()){
620 // Filter vector types out of VecOperand that don't have the right element
622 return VecOperand->getExtType().
623 EnforceVectorEltTypeIs(NodeToApply->getType(), TP);
631 //===----------------------------------------------------------------------===//
632 // SDNodeInfo implementation
634 SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
635 EnumName = R->getValueAsString("Opcode");
636 SDClassName = R->getValueAsString("SDClass");
637 Record *TypeProfile = R->getValueAsDef("TypeProfile");
638 NumResults = TypeProfile->getValueAsInt("NumResults");
639 NumOperands = TypeProfile->getValueAsInt("NumOperands");
641 // Parse the properties.
643 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
644 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
645 if (PropList[i]->getName() == "SDNPCommutative") {
646 Properties |= 1 << SDNPCommutative;
647 } else if (PropList[i]->getName() == "SDNPAssociative") {
648 Properties |= 1 << SDNPAssociative;
649 } else if (PropList[i]->getName() == "SDNPHasChain") {
650 Properties |= 1 << SDNPHasChain;
651 } else if (PropList[i]->getName() == "SDNPOutFlag") {
652 Properties |= 1 << SDNPOutFlag;
653 } else if (PropList[i]->getName() == "SDNPInFlag") {
654 Properties |= 1 << SDNPInFlag;
655 } else if (PropList[i]->getName() == "SDNPOptInFlag") {
656 Properties |= 1 << SDNPOptInFlag;
657 } else if (PropList[i]->getName() == "SDNPMayStore") {
658 Properties |= 1 << SDNPMayStore;
659 } else if (PropList[i]->getName() == "SDNPMayLoad") {
660 Properties |= 1 << SDNPMayLoad;
661 } else if (PropList[i]->getName() == "SDNPSideEffect") {
662 Properties |= 1 << SDNPSideEffect;
663 } else if (PropList[i]->getName() == "SDNPMemOperand") {
664 Properties |= 1 << SDNPMemOperand;
666 errs() << "Unknown SD Node property '" << PropList[i]->getName()
667 << "' on node '" << R->getName() << "'!\n";
673 // Parse the type constraints.
674 std::vector<Record*> ConstraintList =
675 TypeProfile->getValueAsListOfDefs("Constraints");
676 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
679 /// getKnownType - If the type constraints on this node imply a fixed type
680 /// (e.g. all stores return void, etc), then return it as an
681 /// MVT::SimpleValueType. Otherwise, return EEVT::isUnknown.
682 unsigned SDNodeInfo::getKnownType() const {
683 unsigned NumResults = getNumResults();
684 assert(NumResults <= 1 &&
685 "We only work with nodes with zero or one result so far!");
687 for (unsigned i = 0, e = TypeConstraints.size(); i != e; ++i) {
688 // Make sure that this applies to the correct node result.
689 if (TypeConstraints[i].OperandNo >= NumResults) // FIXME: need value #
692 switch (TypeConstraints[i].ConstraintType) {
694 case SDTypeConstraint::SDTCisVT:
695 return TypeConstraints[i].x.SDTCisVT_Info.VT;
696 case SDTypeConstraint::SDTCisPtrTy:
700 return EEVT::isUnknown;
703 //===----------------------------------------------------------------------===//
704 // TreePatternNode implementation
707 TreePatternNode::~TreePatternNode() {
708 #if 0 // FIXME: implement refcounted tree nodes!
709 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
716 void TreePatternNode::print(raw_ostream &OS) const {
718 OS << *getLeafValue();
720 OS << '(' << getOperator()->getName();
723 if (!isTypeCompletelyUnknown())
724 OS << ':' << getExtType().getName();
727 if (getNumChildren() != 0) {
729 getChild(0)->print(OS);
730 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
732 getChild(i)->print(OS);
738 for (unsigned i = 0, e = PredicateFns.size(); i != e; ++i)
739 OS << "<<P:" << PredicateFns[i] << ">>";
741 OS << "<<X:" << TransformFn->getName() << ">>";
742 if (!getName().empty())
743 OS << ":$" << getName();
746 void TreePatternNode::dump() const {
750 /// isIsomorphicTo - Return true if this node is recursively
751 /// isomorphic to the specified node. For this comparison, the node's
752 /// entire state is considered. The assigned name is ignored, since
753 /// nodes with differing names are considered isomorphic. However, if
754 /// the assigned name is present in the dependent variable set, then
755 /// the assigned name is considered significant and the node is
756 /// isomorphic if the names match.
757 bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
758 const MultipleUseVarSet &DepVars) const {
759 if (N == this) return true;
760 if (N->isLeaf() != isLeaf() || getExtType() != N->getExtType() ||
761 getPredicateFns() != N->getPredicateFns() ||
762 getTransformFn() != N->getTransformFn())
766 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
767 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue())) {
768 return ((DI->getDef() == NDI->getDef())
769 && (DepVars.find(getName()) == DepVars.end()
770 || getName() == N->getName()));
773 return getLeafValue() == N->getLeafValue();
776 if (N->getOperator() != getOperator() ||
777 N->getNumChildren() != getNumChildren()) return false;
778 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
779 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
784 /// clone - Make a copy of this tree and all of its children.
786 TreePatternNode *TreePatternNode::clone() const {
787 TreePatternNode *New;
789 New = new TreePatternNode(getLeafValue());
791 std::vector<TreePatternNode*> CChildren;
792 CChildren.reserve(Children.size());
793 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
794 CChildren.push_back(getChild(i)->clone());
795 New = new TreePatternNode(getOperator(), CChildren);
797 New->setName(getName());
798 New->setType(getExtType());
799 New->setPredicateFns(getPredicateFns());
800 New->setTransformFn(getTransformFn());
804 /// RemoveAllTypes - Recursively strip all the types of this tree.
805 void TreePatternNode::RemoveAllTypes() {
806 setType(EEVT::TypeSet()); // Reset to unknown type.
807 if (isLeaf()) return;
808 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
809 getChild(i)->RemoveAllTypes();
813 /// SubstituteFormalArguments - Replace the formal arguments in this tree
814 /// with actual values specified by ArgMap.
815 void TreePatternNode::
816 SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
817 if (isLeaf()) return;
819 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
820 TreePatternNode *Child = getChild(i);
821 if (Child->isLeaf()) {
822 Init *Val = Child->getLeafValue();
823 if (dynamic_cast<DefInit*>(Val) &&
824 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
825 // We found a use of a formal argument, replace it with its value.
826 TreePatternNode *NewChild = ArgMap[Child->getName()];
827 assert(NewChild && "Couldn't find formal argument!");
828 assert((Child->getPredicateFns().empty() ||
829 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
830 "Non-empty child predicate clobbered!");
831 setChild(i, NewChild);
834 getChild(i)->SubstituteFormalArguments(ArgMap);
840 /// InlinePatternFragments - If this pattern refers to any pattern
841 /// fragments, inline them into place, giving us a pattern without any
842 /// PatFrag references.
843 TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
844 if (isLeaf()) return this; // nothing to do.
845 Record *Op = getOperator();
847 if (!Op->isSubClassOf("PatFrag")) {
848 // Just recursively inline children nodes.
849 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
850 TreePatternNode *Child = getChild(i);
851 TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
853 assert((Child->getPredicateFns().empty() ||
854 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
855 "Non-empty child predicate clobbered!");
857 setChild(i, NewChild);
862 // Otherwise, we found a reference to a fragment. First, look up its
863 // TreePattern record.
864 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
866 // Verify that we are passing the right number of operands.
867 if (Frag->getNumArgs() != Children.size())
868 TP.error("'" + Op->getName() + "' fragment requires " +
869 utostr(Frag->getNumArgs()) + " operands!");
871 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
873 std::string Code = Op->getValueAsCode("Predicate");
875 FragTree->addPredicateFn("Predicate_"+Op->getName());
877 // Resolve formal arguments to their actual value.
878 if (Frag->getNumArgs()) {
879 // Compute the map of formal to actual arguments.
880 std::map<std::string, TreePatternNode*> ArgMap;
881 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
882 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
884 FragTree->SubstituteFormalArguments(ArgMap);
887 FragTree->setName(getName());
888 FragTree->UpdateNodeType(getExtType(), TP);
890 // Transfer in the old predicates.
891 for (unsigned i = 0, e = getPredicateFns().size(); i != e; ++i)
892 FragTree->addPredicateFn(getPredicateFns()[i]);
894 // Get a new copy of this fragment to stitch into here.
895 //delete this; // FIXME: implement refcounting!
897 // The fragment we inlined could have recursive inlining that is needed. See
898 // if there are any pattern fragments in it and inline them as needed.
899 return FragTree->InlinePatternFragments(TP);
902 /// getImplicitType - Check to see if the specified record has an implicit
903 /// type which should be applied to it. This will infer the type of register
904 /// references from the register file information, for example.
906 static EEVT::TypeSet getImplicitType(Record *R, bool NotRegisters,
908 // Check to see if this is a register or a register class.
909 if (R->isSubClassOf("RegisterClass")) {
911 return EEVT::TypeSet(); // Unknown.
912 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
913 return EEVT::TypeSet(T.getRegisterClass(R).getValueTypes());
914 } else if (R->isSubClassOf("PatFrag")) {
915 // Pattern fragment types will be resolved when they are inlined.
916 return EEVT::TypeSet(); // Unknown.
917 } else if (R->isSubClassOf("Register")) {
919 return EEVT::TypeSet(); // Unknown.
920 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
921 return EEVT::TypeSet(T.getRegisterVTs(R));
922 } else if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
923 // Using a VTSDNode or CondCodeSDNode.
924 return EEVT::TypeSet(MVT::Other, TP);
925 } else if (R->isSubClassOf("ComplexPattern")) {
927 return EEVT::TypeSet(); // Unknown.
928 return EEVT::TypeSet(TP.getDAGPatterns().getComplexPattern(R).getValueType(),
930 } else if (R->isSubClassOf("PointerLikeRegClass")) {
931 return EEVT::TypeSet(MVT::iPTR, TP);
932 } else if (R->getName() == "node" || R->getName() == "srcvalue" ||
933 R->getName() == "zero_reg") {
935 return EEVT::TypeSet(); // Unknown.
938 TP.error("Unknown node flavor used in pattern: " + R->getName());
939 return EEVT::TypeSet(MVT::Other, TP);
943 /// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
944 /// CodeGenIntrinsic information for it, otherwise return a null pointer.
945 const CodeGenIntrinsic *TreePatternNode::
946 getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
947 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
948 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
949 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
953 dynamic_cast<IntInit*>(getChild(0)->getLeafValue())->getValue();
954 return &CDP.getIntrinsicInfo(IID);
957 /// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
958 /// return the ComplexPattern information, otherwise return null.
959 const ComplexPattern *
960 TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
961 if (!isLeaf()) return 0;
963 DefInit *DI = dynamic_cast<DefInit*>(getLeafValue());
964 if (DI && DI->getDef()->isSubClassOf("ComplexPattern"))
965 return &CGP.getComplexPattern(DI->getDef());
969 /// NodeHasProperty - Return true if this node has the specified property.
970 bool TreePatternNode::NodeHasProperty(SDNP Property,
971 const CodeGenDAGPatterns &CGP) const {
973 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
974 return CP->hasProperty(Property);
978 Record *Operator = getOperator();
979 if (!Operator->isSubClassOf("SDNode")) return false;
981 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
987 /// TreeHasProperty - Return true if any node in this tree has the specified
989 bool TreePatternNode::TreeHasProperty(SDNP Property,
990 const CodeGenDAGPatterns &CGP) const {
991 if (NodeHasProperty(Property, CGP))
993 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
994 if (getChild(i)->TreeHasProperty(Property, CGP))
999 /// isCommutativeIntrinsic - Return true if the node corresponds to a
1000 /// commutative intrinsic.
1002 TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
1003 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
1004 return Int->isCommutative;
1009 /// ApplyTypeConstraints - Apply all of the type constraints relevant to
1010 /// this node and its children in the tree. This returns true if it makes a
1011 /// change, false otherwise. If a type contradiction is found, throw an
1013 bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
1014 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
1016 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
1017 // If it's a regclass or something else known, include the type.
1018 return UpdateNodeType(getImplicitType(DI->getDef(), NotRegisters, TP),TP);
1021 if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
1022 // Int inits are always integers. :)
1023 bool MadeChange = Type.EnforceInteger(TP);
1028 MVT::SimpleValueType VT = getType();
1029 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
1032 unsigned Size = EVT(VT).getSizeInBits();
1033 // Make sure that the value is representable for this type.
1034 if (Size >= 32) return MadeChange;
1036 int Val = (II->getValue() << (32-Size)) >> (32-Size);
1037 if (Val == II->getValue()) return MadeChange;
1039 // If sign-extended doesn't fit, does it fit as unsigned?
1041 unsigned UnsignedVal;
1042 ValueMask = unsigned(~uint32_t(0UL) >> (32-Size));
1043 UnsignedVal = unsigned(II->getValue());
1045 if ((ValueMask & UnsignedVal) == UnsignedVal)
1048 TP.error("Integer value '" + itostr(II->getValue())+
1049 "' is out of range for type '" + getEnumName(getType()) + "'!");
1055 // special handling for set, which isn't really an SDNode.
1056 if (getOperator()->getName() == "set") {
1057 assert (getNumChildren() >= 2 && "Missing RHS of a set?");
1058 unsigned NC = getNumChildren();
1059 bool MadeChange = false;
1060 for (unsigned i = 0; i < NC-1; ++i) {
1061 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1062 MadeChange |= getChild(NC-1)->ApplyTypeConstraints(TP, NotRegisters);
1064 // Types of operands must match.
1065 MadeChange |=getChild(i)->UpdateNodeType(getChild(NC-1)->getExtType(),TP);
1066 MadeChange |=getChild(NC-1)->UpdateNodeType(getChild(i)->getExtType(),TP);
1067 MadeChange |=UpdateNodeType(MVT::isVoid, TP);
1072 if (getOperator()->getName() == "implicit" ||
1073 getOperator()->getName() == "parallel") {
1074 bool MadeChange = false;
1075 for (unsigned i = 0; i < getNumChildren(); ++i)
1076 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1077 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
1081 if (getOperator()->getName() == "COPY_TO_REGCLASS") {
1082 bool MadeChange = false;
1083 MadeChange |= getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1084 MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
1086 // child #1 of COPY_TO_REGCLASS should be a register class. We don't care
1087 // what type it gets, so if it didn't get a concrete type just give it the
1088 // first viable type from the reg class.
1089 if (!getChild(1)->hasTypeSet() &&
1090 !getChild(1)->getExtType().isCompletelyUnknown()) {
1091 MVT::SimpleValueType RCVT = getChild(1)->getExtType().getTypeList()[0];
1092 MadeChange |= getChild(1)->UpdateNodeType(RCVT, TP);
1097 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
1098 bool MadeChange = false;
1100 // Apply the result type to the node.
1101 unsigned NumRetVTs = Int->IS.RetVTs.size();
1102 unsigned NumParamVTs = Int->IS.ParamVTs.size();
1104 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
1105 MadeChange |= UpdateNodeType(Int->IS.RetVTs[i], TP);
1107 if (getNumChildren() != NumParamVTs + NumRetVTs)
1108 TP.error("Intrinsic '" + Int->Name + "' expects " +
1109 utostr(NumParamVTs + NumRetVTs - 1) + " operands, not " +
1110 utostr(getNumChildren() - 1) + " operands!");
1112 // Apply type info to the intrinsic ID.
1113 MadeChange |= getChild(0)->UpdateNodeType(MVT::iPTR, TP);
1115 for (unsigned i = NumRetVTs, e = getNumChildren(); i != e; ++i) {
1116 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i - NumRetVTs];
1117 MadeChange |= getChild(i)->UpdateNodeType(OpVT, TP);
1118 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1123 if (getOperator()->isSubClassOf("SDNode")) {
1124 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
1126 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
1127 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1128 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1129 // Branch, etc. do not produce results and top-level forms in instr pattern
1130 // must have void types.
1131 if (NI.getNumResults() == 0)
1132 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
1137 if (getOperator()->isSubClassOf("Instruction")) {
1138 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
1139 unsigned NumResults = Inst.getNumResults();
1140 assert(NumResults <= 1 &&
1141 "Only supports zero or one result instrs!");
1143 CodeGenInstruction &InstInfo =
1144 CDP.getTargetInfo().getInstruction(getOperator()->getName());
1146 EEVT::TypeSet ResultType;
1148 // Apply the result type to the node
1149 if (InstInfo.NumDefs != 0) { // # of elements in (outs) list
1150 Record *ResultNode = Inst.getResult(0);
1152 if (ResultNode->isSubClassOf("PointerLikeRegClass")) {
1153 ResultType = EEVT::TypeSet(MVT::iPTR, TP);
1154 } else if (ResultNode->getName() == "unknown") {
1157 assert(ResultNode->isSubClassOf("RegisterClass") &&
1158 "Operands should be register classes!");
1159 const CodeGenRegisterClass &RC =
1160 CDP.getTargetInfo().getRegisterClass(ResultNode);
1161 ResultType = RC.getValueTypes();
1163 } else if (!InstInfo.ImplicitDefs.empty()) {
1164 // If the instruction has implicit defs, the first one defines the result
1166 assert(InstInfo.ImplicitDefs[0]->isSubClassOf("Register"));
1167 Record *FirstImplicitDef = InstInfo.ImplicitDefs[0];
1168 const std::vector<MVT::SimpleValueType> &RegVTs =
1169 CDP.getTargetInfo().getRegisterVTs(FirstImplicitDef);
1170 if (!RegVTs.empty())
1171 ResultType = EEVT::TypeSet(RegVTs);
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);
1188 unsigned ChildNo = 0;
1189 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
1190 Record *OperandNode = Inst.getOperand(i);
1192 // If the instruction expects a predicate or optional def operand, we
1193 // codegen this by setting the operand to it's default value if it has a
1194 // non-empty DefaultOps field.
1195 if ((OperandNode->isSubClassOf("PredicateOperand") ||
1196 OperandNode->isSubClassOf("OptionalDefOperand")) &&
1197 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1200 // Verify that we didn't run out of provided operands.
1201 if (ChildNo >= getNumChildren())
1202 TP.error("Instruction '" + getOperator()->getName() +
1203 "' expects more operands than were provided.");
1205 MVT::SimpleValueType VT;
1206 TreePatternNode *Child = getChild(ChildNo++);
1207 if (OperandNode->isSubClassOf("RegisterClass")) {
1208 const CodeGenRegisterClass &RC =
1209 CDP.getTargetInfo().getRegisterClass(OperandNode);
1210 MadeChange |= Child->UpdateNodeType(RC.getValueTypes(), TP);
1211 } else if (OperandNode->isSubClassOf("Operand")) {
1212 VT = getValueType(OperandNode->getValueAsDef("Type"));
1213 MadeChange |= Child->UpdateNodeType(VT, TP);
1214 } else if (OperandNode->isSubClassOf("PointerLikeRegClass")) {
1215 MadeChange |= Child->UpdateNodeType(MVT::iPTR, TP);
1216 } else if (OperandNode->getName() == "unknown") {
1219 assert(0 && "Unknown operand type!");
1222 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
1225 if (ChildNo != getNumChildren())
1226 TP.error("Instruction '" + getOperator()->getName() +
1227 "' was provided too many operands!");
1232 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
1234 // Node transforms always take one operand.
1235 if (getNumChildren() != 1)
1236 TP.error("Node transform '" + getOperator()->getName() +
1237 "' requires one operand!");
1239 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1242 // If either the output or input of the xform does not have exact
1243 // type info. We assume they must be the same. Otherwise, it is perfectly
1244 // legal to transform from one type to a completely different type.
1246 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
1247 bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
1248 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
1255 /// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
1256 /// RHS of a commutative operation, not the on LHS.
1257 static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
1258 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
1260 if (N->isLeaf() && dynamic_cast<IntInit*>(N->getLeafValue()))
1266 /// canPatternMatch - If it is impossible for this pattern to match on this
1267 /// target, fill in Reason and return false. Otherwise, return true. This is
1268 /// used as a sanity check for .td files (to prevent people from writing stuff
1269 /// that can never possibly work), and to prevent the pattern permuter from
1270 /// generating stuff that is useless.
1271 bool TreePatternNode::canPatternMatch(std::string &Reason,
1272 const CodeGenDAGPatterns &CDP) {
1273 if (isLeaf()) return true;
1275 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1276 if (!getChild(i)->canPatternMatch(Reason, CDP))
1279 // If this is an intrinsic, handle cases that would make it not match. For
1280 // example, if an operand is required to be an immediate.
1281 if (getOperator()->isSubClassOf("Intrinsic")) {
1286 // If this node is a commutative operator, check that the LHS isn't an
1288 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
1289 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
1290 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
1291 // Scan all of the operands of the node and make sure that only the last one
1292 // is a constant node, unless the RHS also is.
1293 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
1294 bool Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
1295 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
1296 if (OnlyOnRHSOfCommutative(getChild(i))) {
1297 Reason="Immediate value must be on the RHS of commutative operators!";
1306 //===----------------------------------------------------------------------===//
1307 // TreePattern implementation
1310 TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
1311 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
1312 isInputPattern = isInput;
1313 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
1314 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
1317 TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
1318 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
1319 isInputPattern = isInput;
1320 Trees.push_back(ParseTreePattern(Pat));
1323 TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
1324 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
1325 isInputPattern = isInput;
1326 Trees.push_back(Pat);
1329 void TreePattern::error(const std::string &Msg) const {
1331 throw TGError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
1334 void TreePattern::ComputeNamedNodes() {
1335 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1336 ComputeNamedNodes(Trees[i]);
1339 void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
1340 if (!N->getName().empty())
1341 NamedNodes[N->getName()].push_back(N);
1343 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1344 ComputeNamedNodes(N->getChild(i));
1347 TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
1348 DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
1349 if (!OpDef) error("Pattern has unexpected operator type!");
1350 Record *Operator = OpDef->getDef();
1352 if (Operator->isSubClassOf("ValueType")) {
1353 // If the operator is a ValueType, then this must be "type cast" of a leaf
1355 if (Dag->getNumArgs() != 1)
1356 error("Type cast only takes one operand!");
1358 Init *Arg = Dag->getArg(0);
1359 TreePatternNode *New;
1360 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
1361 Record *R = DI->getDef();
1362 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
1363 Dag->setArg(0, new DagInit(DI, "",
1364 std::vector<std::pair<Init*, std::string> >()));
1365 return ParseTreePattern(Dag);
1369 if (R->getName() == "node") {
1370 if (Dag->getArgName(0).empty())
1371 error("'node' argument requires a name to match with operand list");
1372 Args.push_back(Dag->getArgName(0));
1375 New = new TreePatternNode(DI);
1376 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
1377 New = ParseTreePattern(DI);
1378 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
1379 New = new TreePatternNode(II);
1380 if (!Dag->getArgName(0).empty())
1381 error("Constant int argument should not have a name!");
1382 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
1383 // Turn this into an IntInit.
1384 Init *II = BI->convertInitializerTo(new IntRecTy());
1385 if (II == 0 || !dynamic_cast<IntInit*>(II))
1386 error("Bits value must be constants!");
1388 New = new TreePatternNode(dynamic_cast<IntInit*>(II));
1389 if (!Dag->getArgName(0).empty())
1390 error("Constant int argument should not have a name!");
1393 error("Unknown leaf value for tree pattern!");
1397 // Apply the type cast.
1398 New->UpdateNodeType(getValueType(Operator), *this);
1399 if (New->getNumChildren() == 0)
1400 New->setName(Dag->getArgName(0));
1404 // Verify that this is something that makes sense for an operator.
1405 if (!Operator->isSubClassOf("PatFrag") &&
1406 !Operator->isSubClassOf("SDNode") &&
1407 !Operator->isSubClassOf("Instruction") &&
1408 !Operator->isSubClassOf("SDNodeXForm") &&
1409 !Operator->isSubClassOf("Intrinsic") &&
1410 Operator->getName() != "set" &&
1411 Operator->getName() != "implicit" &&
1412 Operator->getName() != "parallel")
1413 error("Unrecognized node '" + Operator->getName() + "'!");
1415 // Check to see if this is something that is illegal in an input pattern.
1416 if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
1417 Operator->isSubClassOf("SDNodeXForm")))
1418 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
1420 std::vector<TreePatternNode*> Children;
1422 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
1423 Init *Arg = Dag->getArg(i);
1424 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
1425 Children.push_back(ParseTreePattern(DI));
1426 if (Children.back()->getName().empty())
1427 Children.back()->setName(Dag->getArgName(i));
1428 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
1429 Record *R = DefI->getDef();
1430 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
1431 // TreePatternNode if its own.
1432 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
1433 Dag->setArg(i, new DagInit(DefI, "",
1434 std::vector<std::pair<Init*, std::string> >()));
1435 --i; // Revisit this node...
1437 TreePatternNode *Node = new TreePatternNode(DefI);
1438 Node->setName(Dag->getArgName(i));
1439 Children.push_back(Node);
1442 if (R->getName() == "node") {
1443 if (Dag->getArgName(i).empty())
1444 error("'node' argument requires a name to match with operand list");
1445 Args.push_back(Dag->getArgName(i));
1448 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
1449 TreePatternNode *Node = new TreePatternNode(II);
1450 if (!Dag->getArgName(i).empty())
1451 error("Constant int argument should not have a name!");
1452 Children.push_back(Node);
1453 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
1454 // Turn this into an IntInit.
1455 Init *II = BI->convertInitializerTo(new IntRecTy());
1456 if (II == 0 || !dynamic_cast<IntInit*>(II))
1457 error("Bits value must be constants!");
1459 TreePatternNode *Node = new TreePatternNode(dynamic_cast<IntInit*>(II));
1460 if (!Dag->getArgName(i).empty())
1461 error("Constant int argument should not have a name!");
1462 Children.push_back(Node);
1467 error("Unknown leaf value for tree pattern!");
1471 // If the operator is an intrinsic, then this is just syntactic sugar for for
1472 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
1473 // convert the intrinsic name to a number.
1474 if (Operator->isSubClassOf("Intrinsic")) {
1475 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
1476 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
1478 // If this intrinsic returns void, it must have side-effects and thus a
1480 if (Int.IS.RetVTs[0] == MVT::isVoid) {
1481 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
1482 } else if (Int.ModRef != CodeGenIntrinsic::NoMem) {
1483 // Has side-effects, requires chain.
1484 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
1486 // Otherwise, no chain.
1487 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
1490 TreePatternNode *IIDNode = new TreePatternNode(new IntInit(IID));
1491 Children.insert(Children.begin(), IIDNode);
1494 TreePatternNode *Result = new TreePatternNode(Operator, Children);
1495 Result->setName(Dag->getName());
1499 /// InferAllTypes - Infer/propagate as many types throughout the expression
1500 /// patterns as possible. Return true if all types are inferred, false
1501 /// otherwise. Throw an exception if a type contradiction is found.
1503 InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
1504 if (NamedNodes.empty())
1505 ComputeNamedNodes();
1507 bool MadeChange = true;
1508 while (MadeChange) {
1510 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1511 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
1513 // If there are constraints on our named nodes, apply them.
1514 for (StringMap<SmallVector<TreePatternNode*,1> >::iterator
1515 I = NamedNodes.begin(), E = NamedNodes.end(); I != E; ++I) {
1516 SmallVectorImpl<TreePatternNode*> &Nodes = I->second;
1518 // If we have input named node types, propagate their types to the named
1521 // FIXME: Should be error?
1522 assert(InNamedTypes->count(I->getKey()) &&
1523 "Named node in output pattern but not input pattern?");
1525 const SmallVectorImpl<TreePatternNode*> &InNodes =
1526 InNamedTypes->find(I->getKey())->second;
1528 // The input types should be fully resolved by now.
1529 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
1530 // If this node is a register class, and it is the root of the pattern
1531 // then we're mapping something onto an input register. We allow
1532 // changing the type of the input register in this case. This allows
1533 // us to match things like:
1534 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
1535 if (Nodes[i] == Trees[0] && Nodes[i]->isLeaf()) {
1536 DefInit *DI = dynamic_cast<DefInit*>(Nodes[i]->getLeafValue());
1537 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1541 MadeChange |=Nodes[i]->UpdateNodeType(InNodes[0]->getExtType(),*this);
1545 // If there are multiple nodes with the same name, they must all have the
1547 if (I->second.size() > 1) {
1548 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
1549 MadeChange |=Nodes[i]->UpdateNodeType(Nodes[i+1]->getExtType(),*this);
1550 MadeChange |=Nodes[i+1]->UpdateNodeType(Nodes[i]->getExtType(),*this);
1556 bool HasUnresolvedTypes = false;
1557 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1558 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
1559 return !HasUnresolvedTypes;
1562 void TreePattern::print(raw_ostream &OS) const {
1563 OS << getRecord()->getName();
1564 if (!Args.empty()) {
1565 OS << "(" << Args[0];
1566 for (unsigned i = 1, e = Args.size(); i != e; ++i)
1567 OS << ", " << Args[i];
1572 if (Trees.size() > 1)
1574 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
1576 Trees[i]->print(OS);
1580 if (Trees.size() > 1)
1584 void TreePattern::dump() const { print(errs()); }
1586 //===----------------------------------------------------------------------===//
1587 // CodeGenDAGPatterns implementation
1590 CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) : Records(R) {
1591 Intrinsics = LoadIntrinsics(Records, false);
1592 TgtIntrinsics = LoadIntrinsics(Records, true);
1594 ParseNodeTransforms();
1595 ParseComplexPatterns();
1596 ParsePatternFragments();
1597 ParseDefaultOperands();
1598 ParseInstructions();
1601 // Generate variants. For example, commutative patterns can match
1602 // multiple ways. Add them to PatternsToMatch as well.
1605 // Infer instruction flags. For example, we can detect loads,
1606 // stores, and side effects in many cases by examining an
1607 // instruction's pattern.
1608 InferInstructionFlags();
1611 CodeGenDAGPatterns::~CodeGenDAGPatterns() {
1612 for (pf_iterator I = PatternFragments.begin(),
1613 E = PatternFragments.end(); I != E; ++I)
1618 Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
1619 Record *N = Records.getDef(Name);
1620 if (!N || !N->isSubClassOf("SDNode")) {
1621 errs() << "Error getting SDNode '" << Name << "'!\n";
1627 // Parse all of the SDNode definitions for the target, populating SDNodes.
1628 void CodeGenDAGPatterns::ParseNodeInfo() {
1629 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
1630 while (!Nodes.empty()) {
1631 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
1635 // Get the builtin intrinsic nodes.
1636 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
1637 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
1638 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
1641 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
1642 /// map, and emit them to the file as functions.
1643 void CodeGenDAGPatterns::ParseNodeTransforms() {
1644 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
1645 while (!Xforms.empty()) {
1646 Record *XFormNode = Xforms.back();
1647 Record *SDNode = XFormNode->getValueAsDef("Opcode");
1648 std::string Code = XFormNode->getValueAsCode("XFormFunction");
1649 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
1655 void CodeGenDAGPatterns::ParseComplexPatterns() {
1656 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
1657 while (!AMs.empty()) {
1658 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
1664 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
1665 /// file, building up the PatternFragments map. After we've collected them all,
1666 /// inline fragments together as necessary, so that there are no references left
1667 /// inside a pattern fragment to a pattern fragment.
1669 void CodeGenDAGPatterns::ParsePatternFragments() {
1670 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
1672 // First step, parse all of the fragments.
1673 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1674 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
1675 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
1676 PatternFragments[Fragments[i]] = P;
1678 // Validate the argument list, converting it to set, to discard duplicates.
1679 std::vector<std::string> &Args = P->getArgList();
1680 std::set<std::string> OperandsSet(Args.begin(), Args.end());
1682 if (OperandsSet.count(""))
1683 P->error("Cannot have unnamed 'node' values in pattern fragment!");
1685 // Parse the operands list.
1686 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
1687 DefInit *OpsOp = dynamic_cast<DefInit*>(OpsList->getOperator());
1688 // Special cases: ops == outs == ins. Different names are used to
1689 // improve readability.
1691 (OpsOp->getDef()->getName() != "ops" &&
1692 OpsOp->getDef()->getName() != "outs" &&
1693 OpsOp->getDef()->getName() != "ins"))
1694 P->error("Operands list should start with '(ops ... '!");
1696 // Copy over the arguments.
1698 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
1699 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
1700 static_cast<DefInit*>(OpsList->getArg(j))->
1701 getDef()->getName() != "node")
1702 P->error("Operands list should all be 'node' values.");
1703 if (OpsList->getArgName(j).empty())
1704 P->error("Operands list should have names for each operand!");
1705 if (!OperandsSet.count(OpsList->getArgName(j)))
1706 P->error("'" + OpsList->getArgName(j) +
1707 "' does not occur in pattern or was multiply specified!");
1708 OperandsSet.erase(OpsList->getArgName(j));
1709 Args.push_back(OpsList->getArgName(j));
1712 if (!OperandsSet.empty())
1713 P->error("Operands list does not contain an entry for operand '" +
1714 *OperandsSet.begin() + "'!");
1716 // If there is a code init for this fragment, keep track of the fact that
1717 // this fragment uses it.
1718 std::string Code = Fragments[i]->getValueAsCode("Predicate");
1720 P->getOnlyTree()->addPredicateFn("Predicate_"+Fragments[i]->getName());
1722 // If there is a node transformation corresponding to this, keep track of
1724 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
1725 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
1726 P->getOnlyTree()->setTransformFn(Transform);
1729 // Now that we've parsed all of the tree fragments, do a closure on them so
1730 // that there are not references to PatFrags left inside of them.
1731 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1732 TreePattern *ThePat = PatternFragments[Fragments[i]];
1733 ThePat->InlinePatternFragments();
1735 // Infer as many types as possible. Don't worry about it if we don't infer
1736 // all of them, some may depend on the inputs of the pattern.
1738 ThePat->InferAllTypes();
1740 // If this pattern fragment is not supported by this target (no types can
1741 // satisfy its constraints), just ignore it. If the bogus pattern is
1742 // actually used by instructions, the type consistency error will be
1746 // If debugging, print out the pattern fragment result.
1747 DEBUG(ThePat->dump());
1751 void CodeGenDAGPatterns::ParseDefaultOperands() {
1752 std::vector<Record*> DefaultOps[2];
1753 DefaultOps[0] = Records.getAllDerivedDefinitions("PredicateOperand");
1754 DefaultOps[1] = Records.getAllDerivedDefinitions("OptionalDefOperand");
1756 // Find some SDNode.
1757 assert(!SDNodes.empty() && "No SDNodes parsed?");
1758 Init *SomeSDNode = new DefInit(SDNodes.begin()->first);
1760 for (unsigned iter = 0; iter != 2; ++iter) {
1761 for (unsigned i = 0, e = DefaultOps[iter].size(); i != e; ++i) {
1762 DagInit *DefaultInfo = DefaultOps[iter][i]->getValueAsDag("DefaultOps");
1764 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
1765 // SomeSDnode so that we can parse this.
1766 std::vector<std::pair<Init*, std::string> > Ops;
1767 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
1768 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
1769 DefaultInfo->getArgName(op)));
1770 DagInit *DI = new DagInit(SomeSDNode, "", Ops);
1772 // Create a TreePattern to parse this.
1773 TreePattern P(DefaultOps[iter][i], DI, false, *this);
1774 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
1776 // Copy the operands over into a DAGDefaultOperand.
1777 DAGDefaultOperand DefaultOpInfo;
1779 TreePatternNode *T = P.getTree(0);
1780 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
1781 TreePatternNode *TPN = T->getChild(op);
1782 while (TPN->ApplyTypeConstraints(P, false))
1783 /* Resolve all types */;
1785 if (TPN->ContainsUnresolvedType()) {
1787 throw "Value #" + utostr(i) + " of PredicateOperand '" +
1788 DefaultOps[iter][i]->getName() +"' doesn't have a concrete type!";
1790 throw "Value #" + utostr(i) + " of OptionalDefOperand '" +
1791 DefaultOps[iter][i]->getName() +"' doesn't have a concrete type!";
1793 DefaultOpInfo.DefaultOps.push_back(TPN);
1796 // Insert it into the DefaultOperands map so we can find it later.
1797 DefaultOperands[DefaultOps[iter][i]] = DefaultOpInfo;
1802 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
1803 /// instruction input. Return true if this is a real use.
1804 static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
1805 std::map<std::string, TreePatternNode*> &InstInputs,
1806 std::vector<Record*> &InstImpInputs) {
1807 // No name -> not interesting.
1808 if (Pat->getName().empty()) {
1809 if (Pat->isLeaf()) {
1810 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1811 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1812 I->error("Input " + DI->getDef()->getName() + " must be named!");
1813 else if (DI && DI->getDef()->isSubClassOf("Register"))
1814 InstImpInputs.push_back(DI->getDef());
1820 if (Pat->isLeaf()) {
1821 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1822 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
1825 Rec = Pat->getOperator();
1828 // SRCVALUE nodes are ignored.
1829 if (Rec->getName() == "srcvalue")
1832 TreePatternNode *&Slot = InstInputs[Pat->getName()];
1838 if (Slot->isLeaf()) {
1839 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
1841 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
1842 SlotRec = Slot->getOperator();
1845 // Ensure that the inputs agree if we've already seen this input.
1847 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1848 if (Slot->getExtType() != Pat->getExtType())
1849 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1853 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
1854 /// part of "I", the instruction), computing the set of inputs and outputs of
1855 /// the pattern. Report errors if we see anything naughty.
1856 void CodeGenDAGPatterns::
1857 FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
1858 std::map<std::string, TreePatternNode*> &InstInputs,
1859 std::map<std::string, TreePatternNode*>&InstResults,
1860 std::vector<Record*> &InstImpInputs,
1861 std::vector<Record*> &InstImpResults) {
1862 if (Pat->isLeaf()) {
1863 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1864 if (!isUse && Pat->getTransformFn())
1865 I->error("Cannot specify a transform function for a non-input value!");
1869 if (Pat->getOperator()->getName() == "implicit") {
1870 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1871 TreePatternNode *Dest = Pat->getChild(i);
1872 if (!Dest->isLeaf())
1873 I->error("implicitly defined value should be a register!");
1875 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1876 if (!Val || !Val->getDef()->isSubClassOf("Register"))
1877 I->error("implicitly defined value should be a register!");
1878 InstImpResults.push_back(Val->getDef());
1883 if (Pat->getOperator()->getName() != "set") {
1884 // If this is not a set, verify that the children nodes are not void typed,
1886 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1887 if (Pat->getChild(i)->getType() == MVT::isVoid)
1888 I->error("Cannot have void nodes inside of patterns!");
1889 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
1890 InstImpInputs, InstImpResults);
1893 // If this is a non-leaf node with no children, treat it basically as if
1894 // it were a leaf. This handles nodes like (imm).
1895 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1897 if (!isUse && Pat->getTransformFn())
1898 I->error("Cannot specify a transform function for a non-input value!");
1902 // Otherwise, this is a set, validate and collect instruction results.
1903 if (Pat->getNumChildren() == 0)
1904 I->error("set requires operands!");
1906 if (Pat->getTransformFn())
1907 I->error("Cannot specify a transform function on a set node!");
1909 // Check the set destinations.
1910 unsigned NumDests = Pat->getNumChildren()-1;
1911 for (unsigned i = 0; i != NumDests; ++i) {
1912 TreePatternNode *Dest = Pat->getChild(i);
1913 if (!Dest->isLeaf())
1914 I->error("set destination should be a register!");
1916 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1918 I->error("set destination should be a register!");
1920 if (Val->getDef()->isSubClassOf("RegisterClass") ||
1921 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
1922 if (Dest->getName().empty())
1923 I->error("set destination must have a name!");
1924 if (InstResults.count(Dest->getName()))
1925 I->error("cannot set '" + Dest->getName() +"' multiple times");
1926 InstResults[Dest->getName()] = Dest;
1927 } else if (Val->getDef()->isSubClassOf("Register")) {
1928 InstImpResults.push_back(Val->getDef());
1930 I->error("set destination should be a register!");
1934 // Verify and collect info from the computation.
1935 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
1936 InstInputs, InstResults,
1937 InstImpInputs, InstImpResults);
1940 //===----------------------------------------------------------------------===//
1941 // Instruction Analysis
1942 //===----------------------------------------------------------------------===//
1944 class InstAnalyzer {
1945 const CodeGenDAGPatterns &CDP;
1948 bool &HasSideEffects;
1950 InstAnalyzer(const CodeGenDAGPatterns &cdp,
1951 bool &maystore, bool &mayload, bool &hse)
1952 : CDP(cdp), mayStore(maystore), mayLoad(mayload), HasSideEffects(hse){
1955 /// Analyze - Analyze the specified instruction, returning true if the
1956 /// instruction had a pattern.
1957 bool Analyze(Record *InstRecord) {
1958 const TreePattern *Pattern = CDP.getInstruction(InstRecord).getPattern();
1961 return false; // No pattern.
1964 // FIXME: Assume only the first tree is the pattern. The others are clobber
1966 AnalyzeNode(Pattern->getTree(0));
1971 void AnalyzeNode(const TreePatternNode *N) {
1973 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
1974 Record *LeafRec = DI->getDef();
1975 // Handle ComplexPattern leaves.
1976 if (LeafRec->isSubClassOf("ComplexPattern")) {
1977 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
1978 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
1979 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
1980 if (CP.hasProperty(SDNPSideEffect)) HasSideEffects = true;
1986 // Analyze children.
1987 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1988 AnalyzeNode(N->getChild(i));
1990 // Ignore set nodes, which are not SDNodes.
1991 if (N->getOperator()->getName() == "set")
1994 // Get information about the SDNode for the operator.
1995 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N->getOperator());
1997 // Notice properties of the node.
1998 if (OpInfo.hasProperty(SDNPMayStore)) mayStore = true;
1999 if (OpInfo.hasProperty(SDNPMayLoad)) mayLoad = true;
2000 if (OpInfo.hasProperty(SDNPSideEffect)) HasSideEffects = true;
2002 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
2003 // If this is an intrinsic, analyze it.
2004 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
2005 mayLoad = true;// These may load memory.
2007 if (IntInfo->ModRef >= CodeGenIntrinsic::WriteArgMem)
2008 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
2010 if (IntInfo->ModRef >= CodeGenIntrinsic::WriteMem)
2011 // WriteMem intrinsics can have other strange effects.
2012 HasSideEffects = true;
2018 static void InferFromPattern(const CodeGenInstruction &Inst,
2019 bool &MayStore, bool &MayLoad,
2020 bool &HasSideEffects,
2021 const CodeGenDAGPatterns &CDP) {
2022 MayStore = MayLoad = HasSideEffects = false;
2025 InstAnalyzer(CDP, MayStore, MayLoad, HasSideEffects).Analyze(Inst.TheDef);
2027 // InstAnalyzer only correctly analyzes mayStore/mayLoad so far.
2028 if (Inst.mayStore) { // If the .td file explicitly sets mayStore, use it.
2029 // If we decided that this is a store from the pattern, then the .td file
2030 // entry is redundant.
2033 "Warning: mayStore flag explicitly set on instruction '%s'"
2034 " but flag already inferred from pattern.\n",
2035 Inst.TheDef->getName().c_str());
2039 if (Inst.mayLoad) { // If the .td file explicitly sets mayLoad, use it.
2040 // If we decided that this is a load from the pattern, then the .td file
2041 // entry is redundant.
2044 "Warning: mayLoad flag explicitly set on instruction '%s'"
2045 " but flag already inferred from pattern.\n",
2046 Inst.TheDef->getName().c_str());
2050 if (Inst.neverHasSideEffects) {
2052 fprintf(stderr, "Warning: neverHasSideEffects set on instruction '%s' "
2053 "which already has a pattern\n", Inst.TheDef->getName().c_str());
2054 HasSideEffects = false;
2057 if (Inst.hasSideEffects) {
2059 fprintf(stderr, "Warning: hasSideEffects set on instruction '%s' "
2060 "which already inferred this.\n", Inst.TheDef->getName().c_str());
2061 HasSideEffects = true;
2065 /// ParseInstructions - Parse all of the instructions, inlining and resolving
2066 /// any fragments involved. This populates the Instructions list with fully
2067 /// resolved instructions.
2068 void CodeGenDAGPatterns::ParseInstructions() {
2069 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
2071 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
2074 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
2075 LI = Instrs[i]->getValueAsListInit("Pattern");
2077 // If there is no pattern, only collect minimal information about the
2078 // instruction for its operand list. We have to assume that there is one
2079 // result, as we have no detailed info.
2080 if (!LI || LI->getSize() == 0) {
2081 std::vector<Record*> Results;
2082 std::vector<Record*> Operands;
2084 CodeGenInstruction &InstInfo =Target.getInstruction(Instrs[i]->getName());
2086 if (InstInfo.OperandList.size() != 0) {
2087 if (InstInfo.NumDefs == 0) {
2088 // These produce no results
2089 for (unsigned j = 0, e = InstInfo.OperandList.size(); j < e; ++j)
2090 Operands.push_back(InstInfo.OperandList[j].Rec);
2092 // Assume the first operand is the result.
2093 Results.push_back(InstInfo.OperandList[0].Rec);
2095 // The rest are inputs.
2096 for (unsigned j = 1, e = InstInfo.OperandList.size(); j < e; ++j)
2097 Operands.push_back(InstInfo.OperandList[j].Rec);
2101 // Create and insert the instruction.
2102 std::vector<Record*> ImpResults;
2103 std::vector<Record*> ImpOperands;
2104 Instructions.insert(std::make_pair(Instrs[i],
2105 DAGInstruction(0, Results, Operands, ImpResults,
2107 continue; // no pattern.
2110 // Parse the instruction.
2111 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
2112 // Inline pattern fragments into it.
2113 I->InlinePatternFragments();
2115 // Infer as many types as possible. If we cannot infer all of them, we can
2116 // never do anything with this instruction pattern: report it to the user.
2117 if (!I->InferAllTypes())
2118 I->error("Could not infer all types in pattern!");
2120 // InstInputs - Keep track of all of the inputs of the instruction, along
2121 // with the record they are declared as.
2122 std::map<std::string, TreePatternNode*> InstInputs;
2124 // InstResults - Keep track of all the virtual registers that are 'set'
2125 // in the instruction, including what reg class they are.
2126 std::map<std::string, TreePatternNode*> InstResults;
2128 std::vector<Record*> InstImpInputs;
2129 std::vector<Record*> InstImpResults;
2131 // Verify that the top-level forms in the instruction are of void type, and
2132 // fill in the InstResults map.
2133 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
2134 TreePatternNode *Pat = I->getTree(j);
2135 if (!Pat->hasTypeSet() || Pat->getType() != MVT::isVoid)
2136 I->error("Top-level forms in instruction pattern should have"
2139 // Find inputs and outputs, and verify the structure of the uses/defs.
2140 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
2141 InstImpInputs, InstImpResults);
2144 // Now that we have inputs and outputs of the pattern, inspect the operands
2145 // list for the instruction. This determines the order that operands are
2146 // added to the machine instruction the node corresponds to.
2147 unsigned NumResults = InstResults.size();
2149 // Parse the operands list from the (ops) list, validating it.
2150 assert(I->getArgList().empty() && "Args list should still be empty here!");
2151 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
2153 // Check that all of the results occur first in the list.
2154 std::vector<Record*> Results;
2155 TreePatternNode *Res0Node = NULL;
2156 for (unsigned i = 0; i != NumResults; ++i) {
2157 if (i == CGI.OperandList.size())
2158 I->error("'" + InstResults.begin()->first +
2159 "' set but does not appear in operand list!");
2160 const std::string &OpName = CGI.OperandList[i].Name;
2162 // Check that it exists in InstResults.
2163 TreePatternNode *RNode = InstResults[OpName];
2165 I->error("Operand $" + OpName + " does not exist in operand list!");
2169 Record *R = dynamic_cast<DefInit*>(RNode->getLeafValue())->getDef();
2171 I->error("Operand $" + OpName + " should be a set destination: all "
2172 "outputs must occur before inputs in operand list!");
2174 if (CGI.OperandList[i].Rec != R)
2175 I->error("Operand $" + OpName + " class mismatch!");
2177 // Remember the return type.
2178 Results.push_back(CGI.OperandList[i].Rec);
2180 // Okay, this one checks out.
2181 InstResults.erase(OpName);
2184 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
2185 // the copy while we're checking the inputs.
2186 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
2188 std::vector<TreePatternNode*> ResultNodeOperands;
2189 std::vector<Record*> Operands;
2190 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
2191 CodeGenInstruction::OperandInfo &Op = CGI.OperandList[i];
2192 const std::string &OpName = Op.Name;
2194 I->error("Operand #" + utostr(i) + " in operands list has no name!");
2196 if (!InstInputsCheck.count(OpName)) {
2197 // If this is an predicate operand or optional def operand with an
2198 // DefaultOps set filled in, we can ignore this. When we codegen it,
2199 // we will do so as always executed.
2200 if (Op.Rec->isSubClassOf("PredicateOperand") ||
2201 Op.Rec->isSubClassOf("OptionalDefOperand")) {
2202 // Does it have a non-empty DefaultOps field? If so, ignore this
2204 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
2207 I->error("Operand $" + OpName +
2208 " does not appear in the instruction pattern");
2210 TreePatternNode *InVal = InstInputsCheck[OpName];
2211 InstInputsCheck.erase(OpName); // It occurred, remove from map.
2213 if (InVal->isLeaf() &&
2214 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
2215 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
2216 if (Op.Rec != InRec && !InRec->isSubClassOf("ComplexPattern"))
2217 I->error("Operand $" + OpName + "'s register class disagrees"
2218 " between the operand and pattern");
2220 Operands.push_back(Op.Rec);
2222 // Construct the result for the dest-pattern operand list.
2223 TreePatternNode *OpNode = InVal->clone();
2225 // No predicate is useful on the result.
2226 OpNode->clearPredicateFns();
2228 // Promote the xform function to be an explicit node if set.
2229 if (Record *Xform = OpNode->getTransformFn()) {
2230 OpNode->setTransformFn(0);
2231 std::vector<TreePatternNode*> Children;
2232 Children.push_back(OpNode);
2233 OpNode = new TreePatternNode(Xform, Children);
2236 ResultNodeOperands.push_back(OpNode);
2239 if (!InstInputsCheck.empty())
2240 I->error("Input operand $" + InstInputsCheck.begin()->first +
2241 " occurs in pattern but not in operands list!");
2243 TreePatternNode *ResultPattern =
2244 new TreePatternNode(I->getRecord(), ResultNodeOperands);
2245 // Copy fully inferred output node type to instruction result pattern.
2247 ResultPattern->setType(Res0Node->getExtType());
2249 // Create and insert the instruction.
2250 // FIXME: InstImpResults and InstImpInputs should not be part of
2252 DAGInstruction TheInst(I, Results, Operands, InstImpResults, InstImpInputs);
2253 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
2255 // Use a temporary tree pattern to infer all types and make sure that the
2256 // constructed result is correct. This depends on the instruction already
2257 // being inserted into the Instructions map.
2258 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
2259 Temp.InferAllTypes(&I->getNamedNodesMap());
2261 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
2262 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
2267 // If we can, convert the instructions to be patterns that are matched!
2268 for (std::map<Record*, DAGInstruction, RecordPtrCmp>::iterator II =
2269 Instructions.begin(),
2270 E = Instructions.end(); II != E; ++II) {
2271 DAGInstruction &TheInst = II->second;
2272 const TreePattern *I = TheInst.getPattern();
2273 if (I == 0) continue; // No pattern.
2275 // FIXME: Assume only the first tree is the pattern. The others are clobber
2277 TreePatternNode *Pattern = I->getTree(0);
2278 TreePatternNode *SrcPattern;
2279 if (Pattern->getOperator()->getName() == "set") {
2280 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
2282 // Not a set (store or something?)
2283 SrcPattern = Pattern;
2286 Record *Instr = II->first;
2287 AddPatternToMatch(I,
2288 PatternToMatch(Instr->getValueAsListInit("Predicates"),
2290 TheInst.getResultPattern(),
2291 TheInst.getImpResults(),
2292 Instr->getValueAsInt("AddedComplexity"),
2298 typedef std::pair<const TreePatternNode*, unsigned> NameRecord;
2300 static void FindNames(const TreePatternNode *P,
2301 std::map<std::string, NameRecord> &Names,
2302 const TreePattern *PatternTop) {
2303 if (!P->getName().empty()) {
2304 NameRecord &Rec = Names[P->getName()];
2305 // If this is the first instance of the name, remember the node.
2306 if (Rec.second++ == 0)
2308 else if (Rec.first->getType() != P->getType())
2309 PatternTop->error("repetition of value: $" + P->getName() +
2310 " where different uses have different types!");
2314 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
2315 FindNames(P->getChild(i), Names, PatternTop);
2319 void CodeGenDAGPatterns::AddPatternToMatch(const TreePattern *Pattern,
2320 const PatternToMatch &PTM) {
2321 // Do some sanity checking on the pattern we're about to match.
2323 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this))
2324 Pattern->error("Pattern can never match: " + Reason);
2326 // If the source pattern's root is a complex pattern, that complex pattern
2327 // must specify the nodes it can potentially match.
2328 if (const ComplexPattern *CP =
2329 PTM.getSrcPattern()->getComplexPatternInfo(*this))
2330 if (CP->getRootNodes().empty())
2331 Pattern->error("ComplexPattern at root must specify list of opcodes it"
2335 // Find all of the named values in the input and output, ensure they have the
2337 std::map<std::string, NameRecord> SrcNames, DstNames;
2338 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
2339 FindNames(PTM.getDstPattern(), DstNames, Pattern);
2341 // Scan all of the named values in the destination pattern, rejecting them if
2342 // they don't exist in the input pattern.
2343 for (std::map<std::string, NameRecord>::iterator
2344 I = DstNames.begin(), E = DstNames.end(); I != E; ++I) {
2345 if (SrcNames[I->first].first == 0)
2346 Pattern->error("Pattern has input without matching name in output: $" +
2350 // Scan all of the named values in the source pattern, rejecting them if the
2351 // name isn't used in the dest, and isn't used to tie two values together.
2352 for (std::map<std::string, NameRecord>::iterator
2353 I = SrcNames.begin(), E = SrcNames.end(); I != E; ++I)
2354 if (DstNames[I->first].first == 0 && SrcNames[I->first].second == 1)
2355 Pattern->error("Pattern has dead named input: $" + I->first);
2357 PatternsToMatch.push_back(PTM);
2362 void CodeGenDAGPatterns::InferInstructionFlags() {
2363 std::map<std::string, CodeGenInstruction> &InstrDescs =
2364 Target.getInstructions();
2365 for (std::map<std::string, CodeGenInstruction>::iterator
2366 II = InstrDescs.begin(), E = InstrDescs.end(); II != E; ++II) {
2367 CodeGenInstruction &InstInfo = II->second;
2368 // Determine properties of the instruction from its pattern.
2369 bool MayStore, MayLoad, HasSideEffects;
2370 InferFromPattern(InstInfo, MayStore, MayLoad, HasSideEffects, *this);
2371 InstInfo.mayStore = MayStore;
2372 InstInfo.mayLoad = MayLoad;
2373 InstInfo.hasSideEffects = HasSideEffects;
2377 /// Given a pattern result with an unresolved type, see if we can find one
2378 /// instruction with an unresolved result type. Force this result type to an
2379 /// arbitrary element if it's possible types to converge results.
2380 static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
2384 // Analyze children.
2385 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2386 if (ForceArbitraryInstResultType(N->getChild(i), TP))
2389 if (!N->getOperator()->isSubClassOf("Instruction"))
2392 // If this type is already concrete or completely unknown we can't do
2394 if (N->getExtType().isCompletelyUnknown() || N->getExtType().isConcrete())
2397 // Otherwise, force its type to the first possibility (an arbitrary choice).
2398 return N->getExtType().MergeInTypeInfo(N->getExtType().getTypeList()[0], TP);
2401 void CodeGenDAGPatterns::ParsePatterns() {
2402 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
2404 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
2405 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
2406 DefInit *OpDef = dynamic_cast<DefInit*>(Tree->getOperator());
2407 Record *Operator = OpDef->getDef();
2408 TreePattern *Pattern;
2409 if (Operator->getName() != "parallel")
2410 Pattern = new TreePattern(Patterns[i], Tree, true, *this);
2412 std::vector<Init*> Values;
2414 for (unsigned j = 0, ee = Tree->getNumArgs(); j != ee; ++j) {
2415 Values.push_back(Tree->getArg(j));
2416 TypedInit *TArg = dynamic_cast<TypedInit*>(Tree->getArg(j));
2418 errs() << "In dag: " << Tree->getAsString();
2419 errs() << " -- Untyped argument in pattern\n";
2420 assert(0 && "Untyped argument in pattern");
2423 ListTy = resolveTypes(ListTy, TArg->getType());
2425 errs() << "In dag: " << Tree->getAsString();
2426 errs() << " -- Incompatible types in pattern arguments\n";
2427 assert(0 && "Incompatible types in pattern arguments");
2431 ListTy = TArg->getType();
2434 ListInit *LI = new ListInit(Values, new ListRecTy(ListTy));
2435 Pattern = new TreePattern(Patterns[i], LI, true, *this);
2438 // Inline pattern fragments into it.
2439 Pattern->InlinePatternFragments();
2441 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
2442 if (LI->getSize() == 0) continue; // no pattern.
2444 // Parse the instruction.
2445 TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
2447 // Inline pattern fragments into it.
2448 Result->InlinePatternFragments();
2450 if (Result->getNumTrees() != 1)
2451 Result->error("Cannot handle instructions producing instructions "
2452 "with temporaries yet!");
2454 bool IterateInference;
2455 bool InferredAllPatternTypes, InferredAllResultTypes;
2457 // Infer as many types as possible. If we cannot infer all of them, we
2458 // can never do anything with this pattern: report it to the user.
2459 InferredAllPatternTypes =
2460 Pattern->InferAllTypes(&Pattern->getNamedNodesMap());
2462 // Infer as many types as possible. If we cannot infer all of them, we
2463 // can never do anything with this pattern: report it to the user.
2464 InferredAllResultTypes =
2465 Result->InferAllTypes(&Pattern->getNamedNodesMap());
2467 IterateInference = false;
2469 // Apply the type of the result to the source pattern. This helps us
2470 // resolve cases where the input type is known to be a pointer type (which
2471 // is considered resolved), but the result knows it needs to be 32- or
2472 // 64-bits. Infer the other way for good measure.
2473 if (!Result->getTree(0)->getExtType().isVoid() &&
2474 !Pattern->getTree(0)->getExtType().isVoid()) {
2475 IterateInference = Pattern->getTree(0)->
2476 UpdateNodeType(Result->getTree(0)->getExtType(), *Result);
2477 IterateInference |= Result->getTree(0)->
2478 UpdateNodeType(Pattern->getTree(0)->getExtType(), *Result);
2481 // If our iteration has converged and the input pattern's types are fully
2482 // resolved but the result pattern is not fully resolved, we may have a
2483 // situation where we have two instructions in the result pattern and
2484 // the instructions require a common register class, but don't care about
2485 // what actual MVT is used. This is actually a bug in our modelling:
2486 // output patterns should have register classes, not MVTs.
2488 // In any case, to handle this, we just go through and disambiguate some
2489 // arbitrary types to the result pattern's nodes.
2490 if (!IterateInference && InferredAllPatternTypes &&
2491 !InferredAllResultTypes)
2492 IterateInference = ForceArbitraryInstResultType(Result->getTree(0),
2494 } while (IterateInference);
2496 // Verify that we inferred enough types that we can do something with the
2497 // pattern and result. If these fire the user has to add type casts.
2498 if (!InferredAllPatternTypes)
2499 Pattern->error("Could not infer all types in pattern!");
2500 if (!InferredAllResultTypes) {
2502 Result->error("Could not infer all types in pattern result!");
2505 // Validate that the input pattern is correct.
2506 std::map<std::string, TreePatternNode*> InstInputs;
2507 std::map<std::string, TreePatternNode*> InstResults;
2508 std::vector<Record*> InstImpInputs;
2509 std::vector<Record*> InstImpResults;
2510 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
2511 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
2512 InstInputs, InstResults,
2513 InstImpInputs, InstImpResults);
2515 // Promote the xform function to be an explicit node if set.
2516 TreePatternNode *DstPattern = Result->getOnlyTree();
2517 std::vector<TreePatternNode*> ResultNodeOperands;
2518 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
2519 TreePatternNode *OpNode = DstPattern->getChild(ii);
2520 if (Record *Xform = OpNode->getTransformFn()) {
2521 OpNode->setTransformFn(0);
2522 std::vector<TreePatternNode*> Children;
2523 Children.push_back(OpNode);
2524 OpNode = new TreePatternNode(Xform, Children);
2526 ResultNodeOperands.push_back(OpNode);
2528 DstPattern = Result->getOnlyTree();
2529 if (!DstPattern->isLeaf())
2530 DstPattern = new TreePatternNode(DstPattern->getOperator(),
2531 ResultNodeOperands);
2532 DstPattern->setType(Result->getOnlyTree()->getExtType());
2533 TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
2534 Temp.InferAllTypes();
2537 AddPatternToMatch(Pattern,
2538 PatternToMatch(Patterns[i]->getValueAsListInit("Predicates"),
2539 Pattern->getTree(0),
2540 Temp.getOnlyTree(), InstImpResults,
2541 Patterns[i]->getValueAsInt("AddedComplexity"),
2542 Patterns[i]->getID()));
2546 /// CombineChildVariants - Given a bunch of permutations of each child of the
2547 /// 'operator' node, put them together in all possible ways.
2548 static void CombineChildVariants(TreePatternNode *Orig,
2549 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
2550 std::vector<TreePatternNode*> &OutVariants,
2551 CodeGenDAGPatterns &CDP,
2552 const MultipleUseVarSet &DepVars) {
2553 // Make sure that each operand has at least one variant to choose from.
2554 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2555 if (ChildVariants[i].empty())
2558 // The end result is an all-pairs construction of the resultant pattern.
2559 std::vector<unsigned> Idxs;
2560 Idxs.resize(ChildVariants.size());
2564 DEBUG(if (!Idxs.empty()) {
2565 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
2566 for (unsigned i = 0; i < Idxs.size(); ++i) {
2567 errs() << Idxs[i] << " ";
2572 // Create the variant and add it to the output list.
2573 std::vector<TreePatternNode*> NewChildren;
2574 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2575 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
2576 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
2578 // Copy over properties.
2579 R->setName(Orig->getName());
2580 R->setPredicateFns(Orig->getPredicateFns());
2581 R->setTransformFn(Orig->getTransformFn());
2582 R->setType(Orig->getExtType());
2584 // If this pattern cannot match, do not include it as a variant.
2585 std::string ErrString;
2586 if (!R->canPatternMatch(ErrString, CDP)) {
2589 bool AlreadyExists = false;
2591 // Scan to see if this pattern has already been emitted. We can get
2592 // duplication due to things like commuting:
2593 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
2594 // which are the same pattern. Ignore the dups.
2595 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
2596 if (R->isIsomorphicTo(OutVariants[i], DepVars)) {
2597 AlreadyExists = true;
2604 OutVariants.push_back(R);
2607 // Increment indices to the next permutation by incrementing the
2608 // indicies from last index backward, e.g., generate the sequence
2609 // [0, 0], [0, 1], [1, 0], [1, 1].
2611 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
2612 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
2617 NotDone = (IdxsIdx >= 0);
2621 /// CombineChildVariants - A helper function for binary operators.
2623 static void CombineChildVariants(TreePatternNode *Orig,
2624 const std::vector<TreePatternNode*> &LHS,
2625 const std::vector<TreePatternNode*> &RHS,
2626 std::vector<TreePatternNode*> &OutVariants,
2627 CodeGenDAGPatterns &CDP,
2628 const MultipleUseVarSet &DepVars) {
2629 std::vector<std::vector<TreePatternNode*> > ChildVariants;
2630 ChildVariants.push_back(LHS);
2631 ChildVariants.push_back(RHS);
2632 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
2636 static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
2637 std::vector<TreePatternNode *> &Children) {
2638 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
2639 Record *Operator = N->getOperator();
2641 // Only permit raw nodes.
2642 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
2643 N->getTransformFn()) {
2644 Children.push_back(N);
2648 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
2649 Children.push_back(N->getChild(0));
2651 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
2653 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
2654 Children.push_back(N->getChild(1));
2656 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
2659 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
2660 /// the (potentially recursive) pattern by using algebraic laws.
2662 static void GenerateVariantsOf(TreePatternNode *N,
2663 std::vector<TreePatternNode*> &OutVariants,
2664 CodeGenDAGPatterns &CDP,
2665 const MultipleUseVarSet &DepVars) {
2666 // We cannot permute leaves.
2668 OutVariants.push_back(N);
2672 // Look up interesting info about the node.
2673 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
2675 // If this node is associative, re-associate.
2676 if (NodeInfo.hasProperty(SDNPAssociative)) {
2677 // Re-associate by pulling together all of the linked operators
2678 std::vector<TreePatternNode*> MaximalChildren;
2679 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
2681 // Only handle child sizes of 3. Otherwise we'll end up trying too many
2683 if (MaximalChildren.size() == 3) {
2684 // Find the variants of all of our maximal children.
2685 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
2686 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
2687 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
2688 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
2690 // There are only two ways we can permute the tree:
2691 // (A op B) op C and A op (B op C)
2692 // Within these forms, we can also permute A/B/C.
2694 // Generate legal pair permutations of A/B/C.
2695 std::vector<TreePatternNode*> ABVariants;
2696 std::vector<TreePatternNode*> BAVariants;
2697 std::vector<TreePatternNode*> ACVariants;
2698 std::vector<TreePatternNode*> CAVariants;
2699 std::vector<TreePatternNode*> BCVariants;
2700 std::vector<TreePatternNode*> CBVariants;
2701 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
2702 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
2703 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
2704 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
2705 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
2706 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
2708 // Combine those into the result: (x op x) op x
2709 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
2710 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
2711 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
2712 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
2713 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
2714 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
2716 // Combine those into the result: x op (x op x)
2717 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
2718 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
2719 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
2720 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
2721 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
2722 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
2727 // Compute permutations of all children.
2728 std::vector<std::vector<TreePatternNode*> > ChildVariants;
2729 ChildVariants.resize(N->getNumChildren());
2730 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2731 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
2733 // Build all permutations based on how the children were formed.
2734 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
2736 // If this node is commutative, consider the commuted order.
2737 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
2738 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
2739 assert((N->getNumChildren()==2 || isCommIntrinsic) &&
2740 "Commutative but doesn't have 2 children!");
2741 // Don't count children which are actually register references.
2743 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2744 TreePatternNode *Child = N->getChild(i);
2745 if (Child->isLeaf())
2746 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2747 Record *RR = DI->getDef();
2748 if (RR->isSubClassOf("Register"))
2753 // Consider the commuted order.
2754 if (isCommIntrinsic) {
2755 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
2756 // operands are the commutative operands, and there might be more operands
2759 "Commutative intrinsic should have at least 3 childrean!");
2760 std::vector<std::vector<TreePatternNode*> > Variants;
2761 Variants.push_back(ChildVariants[0]); // Intrinsic id.
2762 Variants.push_back(ChildVariants[2]);
2763 Variants.push_back(ChildVariants[1]);
2764 for (unsigned i = 3; i != NC; ++i)
2765 Variants.push_back(ChildVariants[i]);
2766 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
2768 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
2769 OutVariants, CDP, DepVars);
2774 // GenerateVariants - Generate variants. For example, commutative patterns can
2775 // match multiple ways. Add them to PatternsToMatch as well.
2776 void CodeGenDAGPatterns::GenerateVariants() {
2777 DEBUG(errs() << "Generating instruction variants.\n");
2779 // Loop over all of the patterns we've collected, checking to see if we can
2780 // generate variants of the instruction, through the exploitation of
2781 // identities. This permits the target to provide aggressive matching without
2782 // the .td file having to contain tons of variants of instructions.
2784 // Note that this loop adds new patterns to the PatternsToMatch list, but we
2785 // intentionally do not reconsider these. Any variants of added patterns have
2786 // already been added.
2788 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
2789 MultipleUseVarSet DepVars;
2790 std::vector<TreePatternNode*> Variants;
2791 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
2792 DEBUG(errs() << "Dependent/multiply used variables: ");
2793 DEBUG(DumpDepVars(DepVars));
2794 DEBUG(errs() << "\n");
2795 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this, DepVars);
2797 assert(!Variants.empty() && "Must create at least original variant!");
2798 Variants.erase(Variants.begin()); // Remove the original pattern.
2800 if (Variants.empty()) // No variants for this pattern.
2803 DEBUG(errs() << "FOUND VARIANTS OF: ";
2804 PatternsToMatch[i].getSrcPattern()->dump();
2807 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
2808 TreePatternNode *Variant = Variants[v];
2810 DEBUG(errs() << " VAR#" << v << ": ";
2814 // Scan to see if an instruction or explicit pattern already matches this.
2815 bool AlreadyExists = false;
2816 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
2817 // Skip if the top level predicates do not match.
2818 if (PatternsToMatch[i].getPredicates() !=
2819 PatternsToMatch[p].getPredicates())
2821 // Check to see if this variant already exists.
2822 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(), DepVars)) {
2823 DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
2824 AlreadyExists = true;
2828 // If we already have it, ignore the variant.
2829 if (AlreadyExists) continue;
2831 // Otherwise, add it to the list of patterns we have.
2833 push_back(PatternToMatch(PatternsToMatch[i].getPredicates(),
2834 Variant, PatternsToMatch[i].getDstPattern(),
2835 PatternsToMatch[i].getDstRegs(),
2836 PatternsToMatch[i].getAddedComplexity(),
2837 Record::getNewUID()));
2840 DEBUG(errs() << "\n");