add some missing quotes in debug output
[llvm/avr.git] / utils / TableGen / CodeGenDAGPatterns.cpp
blob6b8ceaefa25ee553f1b6634982866ecb853eea62
1 //===- CodeGenDAGPatterns.cpp - Read DAG patterns from .td file -----------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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"
16 #include "Record.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/Support/Debug.h"
19 #include <set>
20 #include <algorithm>
21 #include <iostream>
22 using namespace llvm;
24 //===----------------------------------------------------------------------===//
25 // Helpers for working with extended types.
27 /// FilterVTs - Filter a list of VT's according to a predicate.
28 ///
29 template<typename T>
30 static std::vector<MVT::SimpleValueType>
31 FilterVTs(const std::vector<MVT::SimpleValueType> &InVTs, T Filter) {
32 std::vector<MVT::SimpleValueType> Result;
33 for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
34 if (Filter(InVTs[i]))
35 Result.push_back(InVTs[i]);
36 return Result;
39 template<typename T>
40 static std::vector<unsigned char>
41 FilterEVTs(const std::vector<unsigned char> &InVTs, T Filter) {
42 std::vector<unsigned char> Result;
43 for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
44 if (Filter((MVT::SimpleValueType)InVTs[i]))
45 Result.push_back(InVTs[i]);
46 return Result;
49 static std::vector<unsigned char>
50 ConvertVTs(const std::vector<MVT::SimpleValueType> &InVTs) {
51 std::vector<unsigned char> Result;
52 for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
53 Result.push_back(InVTs[i]);
54 return Result;
57 static inline bool isInteger(MVT::SimpleValueType VT) {
58 return EVT(VT).isInteger();
61 static inline bool isFloatingPoint(MVT::SimpleValueType VT) {
62 return EVT(VT).isFloatingPoint();
65 static inline bool isVector(MVT::SimpleValueType VT) {
66 return EVT(VT).isVector();
69 static bool LHSIsSubsetOfRHS(const std::vector<unsigned char> &LHS,
70 const std::vector<unsigned char> &RHS) {
71 if (LHS.size() > RHS.size()) return false;
72 for (unsigned i = 0, e = LHS.size(); i != e; ++i)
73 if (std::find(RHS.begin(), RHS.end(), LHS[i]) == RHS.end())
74 return false;
75 return true;
78 namespace llvm {
79 namespace EEVT {
80 /// isExtIntegerInVTs - Return true if the specified extended value type vector
81 /// contains iAny or an integer value type.
82 bool isExtIntegerInVTs(const std::vector<unsigned char> &EVTs) {
83 assert(!EVTs.empty() && "Cannot check for integer in empty ExtVT list!");
84 return EVTs[0] == MVT::iAny || !(FilterEVTs(EVTs, isInteger).empty());
87 /// isExtFloatingPointInVTs - Return true if the specified extended value type
88 /// vector contains fAny or a FP value type.
89 bool isExtFloatingPointInVTs(const std::vector<unsigned char> &EVTs) {
90 assert(!EVTs.empty() && "Cannot check for FP in empty ExtVT list!");
91 return EVTs[0] == MVT::fAny || !(FilterEVTs(EVTs, isFloatingPoint).empty());
94 /// isExtVectorInVTs - Return true if the specified extended value type
95 /// vector contains vAny or a vector value type.
96 bool isExtVectorInVTs(const std::vector<unsigned char> &EVTs) {
97 assert(!EVTs.empty() && "Cannot check for vector in empty ExtVT list!");
98 return EVTs[0] == MVT::vAny || !(FilterEVTs(EVTs, isVector).empty());
100 } // end namespace EEVT.
101 } // end namespace llvm.
103 bool RecordPtrCmp::operator()(const Record *LHS, const Record *RHS) const {
104 return LHS->getID() < RHS->getID();
107 /// Dependent variable map for CodeGenDAGPattern variant generation
108 typedef std::map<std::string, int> DepVarMap;
110 /// Const iterator shorthand for DepVarMap
111 typedef DepVarMap::const_iterator DepVarMap_citer;
113 namespace {
114 void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
115 if (N->isLeaf()) {
116 if (dynamic_cast<DefInit*>(N->getLeafValue()) != NULL) {
117 DepMap[N->getName()]++;
119 } else {
120 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
121 FindDepVarsOf(N->getChild(i), DepMap);
125 //! Find dependent variables within child patterns
128 void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
129 DepVarMap depcounts;
130 FindDepVarsOf(N, depcounts);
131 for (DepVarMap_citer i = depcounts.begin(); i != depcounts.end(); ++i) {
132 if (i->second > 1) { // std::pair<std::string, int>
133 DepVars.insert(i->first);
138 //! Dump the dependent variable set:
139 void DumpDepVars(MultipleUseVarSet &DepVars) {
140 if (DepVars.empty()) {
141 DEBUG(errs() << "<empty set>");
142 } else {
143 DEBUG(errs() << "[ ");
144 for (MultipleUseVarSet::const_iterator i = DepVars.begin(), e = DepVars.end();
145 i != e; ++i) {
146 DEBUG(errs() << (*i) << " ");
148 DEBUG(errs() << "]");
153 //===----------------------------------------------------------------------===//
154 // PatternToMatch implementation
157 /// getPredicateCheck - Return a single string containing all of this
158 /// pattern's predicates concatenated with "&&" operators.
160 std::string PatternToMatch::getPredicateCheck() const {
161 std::string PredicateCheck;
162 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
163 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
164 Record *Def = Pred->getDef();
165 if (!Def->isSubClassOf("Predicate")) {
166 #ifndef NDEBUG
167 Def->dump();
168 #endif
169 assert(0 && "Unknown predicate type!");
171 if (!PredicateCheck.empty())
172 PredicateCheck += " && ";
173 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
177 return PredicateCheck;
180 //===----------------------------------------------------------------------===//
181 // SDTypeConstraint implementation
184 SDTypeConstraint::SDTypeConstraint(Record *R) {
185 OperandNo = R->getValueAsInt("OperandNum");
187 if (R->isSubClassOf("SDTCisVT")) {
188 ConstraintType = SDTCisVT;
189 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
190 } else if (R->isSubClassOf("SDTCisPtrTy")) {
191 ConstraintType = SDTCisPtrTy;
192 } else if (R->isSubClassOf("SDTCisInt")) {
193 ConstraintType = SDTCisInt;
194 } else if (R->isSubClassOf("SDTCisFP")) {
195 ConstraintType = SDTCisFP;
196 } else if (R->isSubClassOf("SDTCisVec")) {
197 ConstraintType = SDTCisVec;
198 } else if (R->isSubClassOf("SDTCisSameAs")) {
199 ConstraintType = SDTCisSameAs;
200 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
201 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
202 ConstraintType = SDTCisVTSmallerThanOp;
203 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
204 R->getValueAsInt("OtherOperandNum");
205 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
206 ConstraintType = SDTCisOpSmallerThanOp;
207 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
208 R->getValueAsInt("BigOperandNum");
209 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
210 ConstraintType = SDTCisEltOfVec;
211 x.SDTCisEltOfVec_Info.OtherOperandNum =
212 R->getValueAsInt("OtherOpNum");
213 } else {
214 errs() << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
215 exit(1);
219 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
220 /// N, which has NumResults results.
221 TreePatternNode *SDTypeConstraint::getOperandNum(unsigned OpNo,
222 TreePatternNode *N,
223 unsigned NumResults) const {
224 assert(NumResults <= 1 &&
225 "We only work with nodes with zero or one result so far!");
227 if (OpNo >= (NumResults + N->getNumChildren())) {
228 errs() << "Invalid operand number " << OpNo << " ";
229 N->dump();
230 errs() << '\n';
231 exit(1);
234 if (OpNo < NumResults)
235 return N; // FIXME: need value #
236 else
237 return N->getChild(OpNo-NumResults);
240 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
241 /// constraint to the nodes operands. This returns true if it makes a
242 /// change, false otherwise. If a type contradiction is found, throw an
243 /// exception.
244 bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
245 const SDNodeInfo &NodeInfo,
246 TreePattern &TP) const {
247 unsigned NumResults = NodeInfo.getNumResults();
248 assert(NumResults <= 1 &&
249 "We only work with nodes with zero or one result so far!");
251 // Check that the number of operands is sane. Negative operands -> varargs.
252 if (NodeInfo.getNumOperands() >= 0) {
253 if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands())
254 TP.error(N->getOperator()->getName() + " node requires exactly " +
255 itostr(NodeInfo.getNumOperands()) + " operands!");
258 const CodeGenTarget &CGT = TP.getDAGPatterns().getTargetInfo();
260 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NumResults);
262 switch (ConstraintType) {
263 default: assert(0 && "Unknown constraint type!");
264 case SDTCisVT:
265 // Operand must be a particular type.
266 return NodeToApply->UpdateNodeType(x.SDTCisVT_Info.VT, TP);
267 case SDTCisPtrTy: {
268 // Operand must be same as target pointer type.
269 return NodeToApply->UpdateNodeType(MVT::iPTR, TP);
271 case SDTCisInt: {
272 // If there is only one integer type supported, this must be it.
273 std::vector<MVT::SimpleValueType> IntVTs =
274 FilterVTs(CGT.getLegalValueTypes(), isInteger);
276 // If we found exactly one supported integer type, apply it.
277 if (IntVTs.size() == 1)
278 return NodeToApply->UpdateNodeType(IntVTs[0], TP);
279 return NodeToApply->UpdateNodeType(MVT::iAny, TP);
281 case SDTCisFP: {
282 // If there is only one FP type supported, this must be it.
283 std::vector<MVT::SimpleValueType> FPVTs =
284 FilterVTs(CGT.getLegalValueTypes(), isFloatingPoint);
286 // If we found exactly one supported FP type, apply it.
287 if (FPVTs.size() == 1)
288 return NodeToApply->UpdateNodeType(FPVTs[0], TP);
289 return NodeToApply->UpdateNodeType(MVT::fAny, TP);
291 case SDTCisVec: {
292 // If there is only one vector type supported, this must be it.
293 std::vector<MVT::SimpleValueType> VecVTs =
294 FilterVTs(CGT.getLegalValueTypes(), isVector);
296 // If we found exactly one supported vector type, apply it.
297 if (VecVTs.size() == 1)
298 return NodeToApply->UpdateNodeType(VecVTs[0], TP);
299 return NodeToApply->UpdateNodeType(MVT::vAny, TP);
301 case SDTCisSameAs: {
302 TreePatternNode *OtherNode =
303 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NumResults);
304 return NodeToApply->UpdateNodeType(OtherNode->getExtTypes(), TP) |
305 OtherNode->UpdateNodeType(NodeToApply->getExtTypes(), TP);
307 case SDTCisVTSmallerThanOp: {
308 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
309 // have an integer type that is smaller than the VT.
310 if (!NodeToApply->isLeaf() ||
311 !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
312 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
313 ->isSubClassOf("ValueType"))
314 TP.error(N->getOperator()->getName() + " expects a VT operand!");
315 MVT::SimpleValueType VT =
316 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
317 if (!isInteger(VT))
318 TP.error(N->getOperator()->getName() + " VT operand must be integer!");
320 TreePatternNode *OtherNode =
321 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N,NumResults);
323 // It must be integer.
324 bool MadeChange = false;
325 MadeChange |= OtherNode->UpdateNodeType(MVT::iAny, TP);
327 // This code only handles nodes that have one type set. Assert here so
328 // that we can change this if we ever need to deal with multiple value
329 // types at this point.
330 assert(OtherNode->getExtTypes().size() == 1 && "Node has too many types!");
331 if (OtherNode->hasTypeSet() && OtherNode->getTypeNum(0) <= VT)
332 OtherNode->UpdateNodeType(MVT::Other, TP); // Throw an error.
333 return false;
335 case SDTCisOpSmallerThanOp: {
336 TreePatternNode *BigOperand =
337 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NumResults);
339 // Both operands must be integer or FP, but we don't care which.
340 bool MadeChange = false;
342 // This code does not currently handle nodes which have multiple types,
343 // where some types are integer, and some are fp. Assert that this is not
344 // the case.
345 assert(!(EEVT::isExtIntegerInVTs(NodeToApply->getExtTypes()) &&
346 EEVT::isExtFloatingPointInVTs(NodeToApply->getExtTypes())) &&
347 !(EEVT::isExtIntegerInVTs(BigOperand->getExtTypes()) &&
348 EEVT::isExtFloatingPointInVTs(BigOperand->getExtTypes())) &&
349 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
350 if (EEVT::isExtIntegerInVTs(NodeToApply->getExtTypes()))
351 MadeChange |= BigOperand->UpdateNodeType(MVT::iAny, TP);
352 else if (EEVT::isExtFloatingPointInVTs(NodeToApply->getExtTypes()))
353 MadeChange |= BigOperand->UpdateNodeType(MVT::fAny, TP);
354 if (EEVT::isExtIntegerInVTs(BigOperand->getExtTypes()))
355 MadeChange |= NodeToApply->UpdateNodeType(MVT::iAny, TP);
356 else if (EEVT::isExtFloatingPointInVTs(BigOperand->getExtTypes()))
357 MadeChange |= NodeToApply->UpdateNodeType(MVT::fAny, TP);
359 std::vector<MVT::SimpleValueType> VTs = CGT.getLegalValueTypes();
361 if (EEVT::isExtIntegerInVTs(NodeToApply->getExtTypes())) {
362 VTs = FilterVTs(VTs, isInteger);
363 } else if (EEVT::isExtFloatingPointInVTs(NodeToApply->getExtTypes())) {
364 VTs = FilterVTs(VTs, isFloatingPoint);
365 } else {
366 VTs.clear();
369 switch (VTs.size()) {
370 default: // Too many VT's to pick from.
371 case 0: break; // No info yet.
372 case 1:
373 // Only one VT of this flavor. Cannot ever satisfy the constraints.
374 return NodeToApply->UpdateNodeType(MVT::Other, TP); // throw
375 case 2:
376 // If we have exactly two possible types, the little operand must be the
377 // small one, the big operand should be the big one. Common with
378 // float/double for example.
379 assert(VTs[0] < VTs[1] && "Should be sorted!");
380 MadeChange |= NodeToApply->UpdateNodeType(VTs[0], TP);
381 MadeChange |= BigOperand->UpdateNodeType(VTs[1], TP);
382 break;
384 return MadeChange;
386 case SDTCisEltOfVec: {
387 TreePatternNode *OtherOperand =
388 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum,
389 N, NumResults);
390 if (OtherOperand->hasTypeSet()) {
391 if (!isVector(OtherOperand->getTypeNum(0)))
392 TP.error(N->getOperator()->getName() + " VT operand must be a vector!");
393 EVT IVT = OtherOperand->getTypeNum(0);
394 IVT = IVT.getVectorElementType();
395 return NodeToApply->UpdateNodeType(IVT.getSimpleVT().SimpleTy, TP);
397 return false;
400 return false;
403 //===----------------------------------------------------------------------===//
404 // SDNodeInfo implementation
406 SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
407 EnumName = R->getValueAsString("Opcode");
408 SDClassName = R->getValueAsString("SDClass");
409 Record *TypeProfile = R->getValueAsDef("TypeProfile");
410 NumResults = TypeProfile->getValueAsInt("NumResults");
411 NumOperands = TypeProfile->getValueAsInt("NumOperands");
413 // Parse the properties.
414 Properties = 0;
415 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
416 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
417 if (PropList[i]->getName() == "SDNPCommutative") {
418 Properties |= 1 << SDNPCommutative;
419 } else if (PropList[i]->getName() == "SDNPAssociative") {
420 Properties |= 1 << SDNPAssociative;
421 } else if (PropList[i]->getName() == "SDNPHasChain") {
422 Properties |= 1 << SDNPHasChain;
423 } else if (PropList[i]->getName() == "SDNPOutFlag") {
424 Properties |= 1 << SDNPOutFlag;
425 } else if (PropList[i]->getName() == "SDNPInFlag") {
426 Properties |= 1 << SDNPInFlag;
427 } else if (PropList[i]->getName() == "SDNPOptInFlag") {
428 Properties |= 1 << SDNPOptInFlag;
429 } else if (PropList[i]->getName() == "SDNPMayStore") {
430 Properties |= 1 << SDNPMayStore;
431 } else if (PropList[i]->getName() == "SDNPMayLoad") {
432 Properties |= 1 << SDNPMayLoad;
433 } else if (PropList[i]->getName() == "SDNPSideEffect") {
434 Properties |= 1 << SDNPSideEffect;
435 } else if (PropList[i]->getName() == "SDNPMemOperand") {
436 Properties |= 1 << SDNPMemOperand;
437 } else {
438 errs() << "Unknown SD Node property '" << PropList[i]->getName()
439 << "' on node '" << R->getName() << "'!\n";
440 exit(1);
445 // Parse the type constraints.
446 std::vector<Record*> ConstraintList =
447 TypeProfile->getValueAsListOfDefs("Constraints");
448 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
451 //===----------------------------------------------------------------------===//
452 // TreePatternNode implementation
455 TreePatternNode::~TreePatternNode() {
456 #if 0 // FIXME: implement refcounted tree nodes!
457 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
458 delete getChild(i);
459 #endif
462 /// UpdateNodeType - Set the node type of N to VT if VT contains
463 /// information. If N already contains a conflicting type, then throw an
464 /// exception. This returns true if any information was updated.
466 bool TreePatternNode::UpdateNodeType(const std::vector<unsigned char> &ExtVTs,
467 TreePattern &TP) {
468 assert(!ExtVTs.empty() && "Cannot update node type with empty type vector!");
470 if (ExtVTs[0] == EEVT::isUnknown || LHSIsSubsetOfRHS(getExtTypes(), ExtVTs))
471 return false;
472 if (isTypeCompletelyUnknown() || LHSIsSubsetOfRHS(ExtVTs, getExtTypes())) {
473 setTypes(ExtVTs);
474 return true;
477 if (getExtTypeNum(0) == MVT::iPTR || getExtTypeNum(0) == MVT::iPTRAny) {
478 if (ExtVTs[0] == MVT::iPTR || ExtVTs[0] == MVT::iPTRAny ||
479 ExtVTs[0] == MVT::iAny)
480 return false;
481 if (EEVT::isExtIntegerInVTs(ExtVTs)) {
482 std::vector<unsigned char> FVTs = FilterEVTs(ExtVTs, isInteger);
483 if (FVTs.size()) {
484 setTypes(ExtVTs);
485 return true;
490 // Merge vAny with iAny/fAny. The latter include vector types so keep them
491 // as the more specific information.
492 if (ExtVTs[0] == MVT::vAny &&
493 (getExtTypeNum(0) == MVT::iAny || getExtTypeNum(0) == MVT::fAny))
494 return false;
495 if (getExtTypeNum(0) == MVT::vAny &&
496 (ExtVTs[0] == MVT::iAny || ExtVTs[0] == MVT::fAny)) {
497 setTypes(ExtVTs);
498 return true;
501 if (ExtVTs[0] == MVT::iAny &&
502 EEVT::isExtIntegerInVTs(getExtTypes())) {
503 assert(hasTypeSet() && "should be handled above!");
504 std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), isInteger);
505 if (getExtTypes() == FVTs)
506 return false;
507 setTypes(FVTs);
508 return true;
510 if ((ExtVTs[0] == MVT::iPTR || ExtVTs[0] == MVT::iPTRAny) &&
511 EEVT::isExtIntegerInVTs(getExtTypes())) {
512 //assert(hasTypeSet() && "should be handled above!");
513 std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), isInteger);
514 if (getExtTypes() == FVTs)
515 return false;
516 if (FVTs.size()) {
517 setTypes(FVTs);
518 return true;
521 if (ExtVTs[0] == MVT::fAny &&
522 EEVT::isExtFloatingPointInVTs(getExtTypes())) {
523 assert(hasTypeSet() && "should be handled above!");
524 std::vector<unsigned char> FVTs =
525 FilterEVTs(getExtTypes(), isFloatingPoint);
526 if (getExtTypes() == FVTs)
527 return false;
528 setTypes(FVTs);
529 return true;
531 if (ExtVTs[0] == MVT::vAny &&
532 EEVT::isExtVectorInVTs(getExtTypes())) {
533 assert(hasTypeSet() && "should be handled above!");
534 std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), isVector);
535 if (getExtTypes() == FVTs)
536 return false;
537 setTypes(FVTs);
538 return true;
541 // If we know this is an int, FP, or vector type, and we are told it is a
542 // specific one, take the advice.
544 // Similarly, we should probably set the type here to the intersection of
545 // {iAny|fAny|vAny} and ExtVTs
546 if ((getExtTypeNum(0) == MVT::iAny &&
547 EEVT::isExtIntegerInVTs(ExtVTs)) ||
548 (getExtTypeNum(0) == MVT::fAny &&
549 EEVT::isExtFloatingPointInVTs(ExtVTs)) ||
550 (getExtTypeNum(0) == MVT::vAny &&
551 EEVT::isExtVectorInVTs(ExtVTs))) {
552 setTypes(ExtVTs);
553 return true;
555 if (getExtTypeNum(0) == MVT::iAny &&
556 (ExtVTs[0] == MVT::iPTR || ExtVTs[0] == MVT::iPTRAny)) {
557 setTypes(ExtVTs);
558 return true;
561 if (isLeaf()) {
562 dump();
563 errs() << " ";
564 TP.error("Type inference contradiction found in node!");
565 } else {
566 TP.error("Type inference contradiction found in node " +
567 getOperator()->getName() + "!");
569 return true; // unreachable
573 void TreePatternNode::print(raw_ostream &OS) const {
574 if (isLeaf()) {
575 OS << *getLeafValue();
576 } else {
577 OS << "(" << getOperator()->getName();
580 // FIXME: At some point we should handle printing all the value types for
581 // nodes that are multiply typed.
582 switch (getExtTypeNum(0)) {
583 case MVT::Other: OS << ":Other"; break;
584 case MVT::iAny: OS << ":iAny"; break;
585 case MVT::fAny : OS << ":fAny"; break;
586 case MVT::vAny: OS << ":vAny"; break;
587 case EEVT::isUnknown: ; /*OS << ":?";*/ break;
588 case MVT::iPTR: OS << ":iPTR"; break;
589 case MVT::iPTRAny: OS << ":iPTRAny"; break;
590 default: {
591 std::string VTName = llvm::getName(getTypeNum(0));
592 // Strip off EVT:: prefix if present.
593 if (VTName.substr(0,5) == "MVT::")
594 VTName = VTName.substr(5);
595 OS << ":" << VTName;
596 break;
600 if (!isLeaf()) {
601 if (getNumChildren() != 0) {
602 OS << " ";
603 getChild(0)->print(OS);
604 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
605 OS << ", ";
606 getChild(i)->print(OS);
609 OS << ")";
612 for (unsigned i = 0, e = PredicateFns.size(); i != e; ++i)
613 OS << "<<P:" << PredicateFns[i] << ">>";
614 if (TransformFn)
615 OS << "<<X:" << TransformFn->getName() << ">>";
616 if (!getName().empty())
617 OS << ":$" << getName();
620 void TreePatternNode::dump() const {
621 print(errs());
624 /// isIsomorphicTo - Return true if this node is recursively
625 /// isomorphic to the specified node. For this comparison, the node's
626 /// entire state is considered. The assigned name is ignored, since
627 /// nodes with differing names are considered isomorphic. However, if
628 /// the assigned name is present in the dependent variable set, then
629 /// the assigned name is considered significant and the node is
630 /// isomorphic if the names match.
631 bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
632 const MultipleUseVarSet &DepVars) const {
633 if (N == this) return true;
634 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
635 getPredicateFns() != N->getPredicateFns() ||
636 getTransformFn() != N->getTransformFn())
637 return false;
639 if (isLeaf()) {
640 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
641 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue())) {
642 return ((DI->getDef() == NDI->getDef())
643 && (DepVars.find(getName()) == DepVars.end()
644 || getName() == N->getName()));
647 return getLeafValue() == N->getLeafValue();
650 if (N->getOperator() != getOperator() ||
651 N->getNumChildren() != getNumChildren()) return false;
652 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
653 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
654 return false;
655 return true;
658 /// clone - Make a copy of this tree and all of its children.
660 TreePatternNode *TreePatternNode::clone() const {
661 TreePatternNode *New;
662 if (isLeaf()) {
663 New = new TreePatternNode(getLeafValue());
664 } else {
665 std::vector<TreePatternNode*> CChildren;
666 CChildren.reserve(Children.size());
667 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
668 CChildren.push_back(getChild(i)->clone());
669 New = new TreePatternNode(getOperator(), CChildren);
671 New->setName(getName());
672 New->setTypes(getExtTypes());
673 New->setPredicateFns(getPredicateFns());
674 New->setTransformFn(getTransformFn());
675 return New;
678 /// SubstituteFormalArguments - Replace the formal arguments in this tree
679 /// with actual values specified by ArgMap.
680 void TreePatternNode::
681 SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
682 if (isLeaf()) return;
684 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
685 TreePatternNode *Child = getChild(i);
686 if (Child->isLeaf()) {
687 Init *Val = Child->getLeafValue();
688 if (dynamic_cast<DefInit*>(Val) &&
689 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
690 // We found a use of a formal argument, replace it with its value.
691 TreePatternNode *NewChild = ArgMap[Child->getName()];
692 assert(NewChild && "Couldn't find formal argument!");
693 assert((Child->getPredicateFns().empty() ||
694 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
695 "Non-empty child predicate clobbered!");
696 setChild(i, NewChild);
698 } else {
699 getChild(i)->SubstituteFormalArguments(ArgMap);
705 /// InlinePatternFragments - If this pattern refers to any pattern
706 /// fragments, inline them into place, giving us a pattern without any
707 /// PatFrag references.
708 TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
709 if (isLeaf()) return this; // nothing to do.
710 Record *Op = getOperator();
712 if (!Op->isSubClassOf("PatFrag")) {
713 // Just recursively inline children nodes.
714 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
715 TreePatternNode *Child = getChild(i);
716 TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
718 assert((Child->getPredicateFns().empty() ||
719 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
720 "Non-empty child predicate clobbered!");
722 setChild(i, NewChild);
724 return this;
727 // Otherwise, we found a reference to a fragment. First, look up its
728 // TreePattern record.
729 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
731 // Verify that we are passing the right number of operands.
732 if (Frag->getNumArgs() != Children.size())
733 TP.error("'" + Op->getName() + "' fragment requires " +
734 utostr(Frag->getNumArgs()) + " operands!");
736 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
738 std::string Code = Op->getValueAsCode("Predicate");
739 if (!Code.empty())
740 FragTree->addPredicateFn("Predicate_"+Op->getName());
742 // Resolve formal arguments to their actual value.
743 if (Frag->getNumArgs()) {
744 // Compute the map of formal to actual arguments.
745 std::map<std::string, TreePatternNode*> ArgMap;
746 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
747 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
749 FragTree->SubstituteFormalArguments(ArgMap);
752 FragTree->setName(getName());
753 FragTree->UpdateNodeType(getExtTypes(), TP);
755 // Transfer in the old predicates.
756 for (unsigned i = 0, e = getPredicateFns().size(); i != e; ++i)
757 FragTree->addPredicateFn(getPredicateFns()[i]);
759 // Get a new copy of this fragment to stitch into here.
760 //delete this; // FIXME: implement refcounting!
762 // The fragment we inlined could have recursive inlining that is needed. See
763 // if there are any pattern fragments in it and inline them as needed.
764 return FragTree->InlinePatternFragments(TP);
767 /// getImplicitType - Check to see if the specified record has an implicit
768 /// type which should be applied to it. This will infer the type of register
769 /// references from the register file information, for example.
771 static std::vector<unsigned char> getImplicitType(Record *R, bool NotRegisters,
772 TreePattern &TP) {
773 // Some common return values
774 std::vector<unsigned char> Unknown(1, EEVT::isUnknown);
775 std::vector<unsigned char> Other(1, MVT::Other);
777 // Check to see if this is a register or a register class...
778 if (R->isSubClassOf("RegisterClass")) {
779 if (NotRegisters)
780 return Unknown;
781 const CodeGenRegisterClass &RC =
782 TP.getDAGPatterns().getTargetInfo().getRegisterClass(R);
783 return ConvertVTs(RC.getValueTypes());
784 } else if (R->isSubClassOf("PatFrag")) {
785 // Pattern fragment types will be resolved when they are inlined.
786 return Unknown;
787 } else if (R->isSubClassOf("Register")) {
788 if (NotRegisters)
789 return Unknown;
790 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
791 return T.getRegisterVTs(R);
792 } else if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
793 // Using a VTSDNode or CondCodeSDNode.
794 return Other;
795 } else if (R->isSubClassOf("ComplexPattern")) {
796 if (NotRegisters)
797 return Unknown;
798 std::vector<unsigned char>
799 ComplexPat(1, TP.getDAGPatterns().getComplexPattern(R).getValueType());
800 return ComplexPat;
801 } else if (R->isSubClassOf("PointerLikeRegClass")) {
802 Other[0] = MVT::iPTR;
803 return Other;
804 } else if (R->getName() == "node" || R->getName() == "srcvalue" ||
805 R->getName() == "zero_reg") {
806 // Placeholder.
807 return Unknown;
810 TP.error("Unknown node flavor used in pattern: " + R->getName());
811 return Other;
815 /// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
816 /// CodeGenIntrinsic information for it, otherwise return a null pointer.
817 const CodeGenIntrinsic *TreePatternNode::
818 getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
819 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
820 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
821 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
822 return 0;
824 unsigned IID =
825 dynamic_cast<IntInit*>(getChild(0)->getLeafValue())->getValue();
826 return &CDP.getIntrinsicInfo(IID);
829 /// isCommutativeIntrinsic - Return true if the node corresponds to a
830 /// commutative intrinsic.
831 bool
832 TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
833 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
834 return Int->isCommutative;
835 return false;
839 /// ApplyTypeConstraints - Apply all of the type constraints relevant to
840 /// this node and its children in the tree. This returns true if it makes a
841 /// change, false otherwise. If a type contradiction is found, throw an
842 /// exception.
843 bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
844 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
845 if (isLeaf()) {
846 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
847 // If it's a regclass or something else known, include the type.
848 return UpdateNodeType(getImplicitType(DI->getDef(), NotRegisters, TP),TP);
849 } else if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
850 // Int inits are always integers. :)
851 bool MadeChange = UpdateNodeType(MVT::iAny, TP);
853 if (hasTypeSet()) {
854 // At some point, it may make sense for this tree pattern to have
855 // multiple types. Assert here that it does not, so we revisit this
856 // code when appropriate.
857 assert(getExtTypes().size() >= 1 && "TreePattern doesn't have a type!");
858 MVT::SimpleValueType VT = getTypeNum(0);
859 for (unsigned i = 1, e = getExtTypes().size(); i != e; ++i)
860 assert(getTypeNum(i) == VT && "TreePattern has too many types!");
862 VT = getTypeNum(0);
863 if (VT != MVT::iPTR && VT != MVT::iPTRAny) {
864 unsigned Size = EVT(VT).getSizeInBits();
865 // Make sure that the value is representable for this type.
866 if (Size < 32) {
867 int Val = (II->getValue() << (32-Size)) >> (32-Size);
868 if (Val != II->getValue()) {
869 // If sign-extended doesn't fit, does it fit as unsigned?
870 unsigned ValueMask;
871 unsigned UnsignedVal;
872 ValueMask = unsigned(~uint32_t(0UL) >> (32-Size));
873 UnsignedVal = unsigned(II->getValue());
875 if ((ValueMask & UnsignedVal) != UnsignedVal) {
876 TP.error("Integer value '" + itostr(II->getValue())+
877 "' is out of range for type '" +
878 getEnumName(getTypeNum(0)) + "'!");
885 return MadeChange;
887 return false;
890 // special handling for set, which isn't really an SDNode.
891 if (getOperator()->getName() == "set") {
892 assert (getNumChildren() >= 2 && "Missing RHS of a set?");
893 unsigned NC = getNumChildren();
894 bool MadeChange = false;
895 for (unsigned i = 0; i < NC-1; ++i) {
896 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
897 MadeChange |= getChild(NC-1)->ApplyTypeConstraints(TP, NotRegisters);
899 // Types of operands must match.
900 MadeChange |= getChild(i)->UpdateNodeType(getChild(NC-1)->getExtTypes(),
901 TP);
902 MadeChange |= getChild(NC-1)->UpdateNodeType(getChild(i)->getExtTypes(),
903 TP);
904 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
906 return MadeChange;
907 } else if (getOperator()->getName() == "implicit" ||
908 getOperator()->getName() == "parallel") {
909 bool MadeChange = false;
910 for (unsigned i = 0; i < getNumChildren(); ++i)
911 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
912 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
913 return MadeChange;
914 } else if (getOperator()->getName() == "COPY_TO_REGCLASS") {
915 bool MadeChange = false;
916 MadeChange |= getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
917 MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
918 MadeChange |= UpdateNodeType(getChild(1)->getTypeNum(0), TP);
919 return MadeChange;
920 } else if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
921 bool MadeChange = false;
923 // Apply the result type to the node.
924 unsigned NumRetVTs = Int->IS.RetVTs.size();
925 unsigned NumParamVTs = Int->IS.ParamVTs.size();
927 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
928 MadeChange |= UpdateNodeType(Int->IS.RetVTs[i], TP);
930 if (getNumChildren() != NumParamVTs + NumRetVTs)
931 TP.error("Intrinsic '" + Int->Name + "' expects " +
932 utostr(NumParamVTs + NumRetVTs - 1) + " operands, not " +
933 utostr(getNumChildren() - 1) + " operands!");
935 // Apply type info to the intrinsic ID.
936 MadeChange |= getChild(0)->UpdateNodeType(MVT::iPTR, TP);
938 for (unsigned i = NumRetVTs, e = getNumChildren(); i != e; ++i) {
939 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i - NumRetVTs];
940 MadeChange |= getChild(i)->UpdateNodeType(OpVT, TP);
941 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
943 return MadeChange;
944 } else if (getOperator()->isSubClassOf("SDNode")) {
945 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
947 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
948 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
949 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
950 // Branch, etc. do not produce results and top-level forms in instr pattern
951 // must have void types.
952 if (NI.getNumResults() == 0)
953 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
955 return MadeChange;
956 } else if (getOperator()->isSubClassOf("Instruction")) {
957 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
958 bool MadeChange = false;
959 unsigned NumResults = Inst.getNumResults();
961 assert(NumResults <= 1 &&
962 "Only supports zero or one result instrs!");
964 CodeGenInstruction &InstInfo =
965 CDP.getTargetInfo().getInstruction(getOperator()->getName());
966 // Apply the result type to the node
967 if (NumResults == 0 || InstInfo.NumDefs == 0) {
968 MadeChange = UpdateNodeType(MVT::isVoid, TP);
969 } else {
970 Record *ResultNode = Inst.getResult(0);
972 if (ResultNode->isSubClassOf("PointerLikeRegClass")) {
973 std::vector<unsigned char> VT;
974 VT.push_back(MVT::iPTR);
975 MadeChange = UpdateNodeType(VT, TP);
976 } else if (ResultNode->getName() == "unknown") {
977 std::vector<unsigned char> VT;
978 VT.push_back(EEVT::isUnknown);
979 MadeChange = UpdateNodeType(VT, TP);
980 } else {
981 assert(ResultNode->isSubClassOf("RegisterClass") &&
982 "Operands should be register classes!");
984 const CodeGenRegisterClass &RC =
985 CDP.getTargetInfo().getRegisterClass(ResultNode);
986 MadeChange = UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
990 unsigned ChildNo = 0;
991 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
992 Record *OperandNode = Inst.getOperand(i);
994 // If the instruction expects a predicate or optional def operand, we
995 // codegen this by setting the operand to it's default value if it has a
996 // non-empty DefaultOps field.
997 if ((OperandNode->isSubClassOf("PredicateOperand") ||
998 OperandNode->isSubClassOf("OptionalDefOperand")) &&
999 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1000 continue;
1002 // Verify that we didn't run out of provided operands.
1003 if (ChildNo >= getNumChildren())
1004 TP.error("Instruction '" + getOperator()->getName() +
1005 "' expects more operands than were provided.");
1007 MVT::SimpleValueType VT;
1008 TreePatternNode *Child = getChild(ChildNo++);
1009 if (OperandNode->isSubClassOf("RegisterClass")) {
1010 const CodeGenRegisterClass &RC =
1011 CDP.getTargetInfo().getRegisterClass(OperandNode);
1012 MadeChange |= Child->UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
1013 } else if (OperandNode->isSubClassOf("Operand")) {
1014 VT = getValueType(OperandNode->getValueAsDef("Type"));
1015 MadeChange |= Child->UpdateNodeType(VT, TP);
1016 } else if (OperandNode->isSubClassOf("PointerLikeRegClass")) {
1017 MadeChange |= Child->UpdateNodeType(MVT::iPTR, TP);
1018 } else if (OperandNode->getName() == "unknown") {
1019 MadeChange |= Child->UpdateNodeType(EEVT::isUnknown, TP);
1020 } else {
1021 assert(0 && "Unknown operand type!");
1022 abort();
1024 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
1027 if (ChildNo != getNumChildren())
1028 TP.error("Instruction '" + getOperator()->getName() +
1029 "' was provided too many operands!");
1031 return MadeChange;
1032 } else {
1033 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
1035 // Node transforms always take one operand.
1036 if (getNumChildren() != 1)
1037 TP.error("Node transform '" + getOperator()->getName() +
1038 "' requires one operand!");
1040 // If either the output or input of the xform does not have exact
1041 // type info. We assume they must be the same. Otherwise, it is perfectly
1042 // legal to transform from one type to a completely different type.
1043 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
1044 bool MadeChange = UpdateNodeType(getChild(0)->getExtTypes(), TP);
1045 MadeChange |= getChild(0)->UpdateNodeType(getExtTypes(), TP);
1046 return MadeChange;
1048 return false;
1052 /// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
1053 /// RHS of a commutative operation, not the on LHS.
1054 static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
1055 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
1056 return true;
1057 if (N->isLeaf() && dynamic_cast<IntInit*>(N->getLeafValue()))
1058 return true;
1059 return false;
1063 /// canPatternMatch - If it is impossible for this pattern to match on this
1064 /// target, fill in Reason and return false. Otherwise, return true. This is
1065 /// used as a sanity check for .td files (to prevent people from writing stuff
1066 /// that can never possibly work), and to prevent the pattern permuter from
1067 /// generating stuff that is useless.
1068 bool TreePatternNode::canPatternMatch(std::string &Reason,
1069 const CodeGenDAGPatterns &CDP) {
1070 if (isLeaf()) return true;
1072 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1073 if (!getChild(i)->canPatternMatch(Reason, CDP))
1074 return false;
1076 // If this is an intrinsic, handle cases that would make it not match. For
1077 // example, if an operand is required to be an immediate.
1078 if (getOperator()->isSubClassOf("Intrinsic")) {
1079 // TODO:
1080 return true;
1083 // If this node is a commutative operator, check that the LHS isn't an
1084 // immediate.
1085 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
1086 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
1087 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
1088 // Scan all of the operands of the node and make sure that only the last one
1089 // is a constant node, unless the RHS also is.
1090 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
1091 bool Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
1092 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
1093 if (OnlyOnRHSOfCommutative(getChild(i))) {
1094 Reason="Immediate value must be on the RHS of commutative operators!";
1095 return false;
1100 return true;
1103 //===----------------------------------------------------------------------===//
1104 // TreePattern implementation
1107 TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
1108 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
1109 isInputPattern = isInput;
1110 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
1111 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
1114 TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
1115 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
1116 isInputPattern = isInput;
1117 Trees.push_back(ParseTreePattern(Pat));
1120 TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
1121 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
1122 isInputPattern = isInput;
1123 Trees.push_back(Pat);
1128 void TreePattern::error(const std::string &Msg) const {
1129 dump();
1130 throw TGError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
1133 TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
1134 DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
1135 if (!OpDef) error("Pattern has unexpected operator type!");
1136 Record *Operator = OpDef->getDef();
1138 if (Operator->isSubClassOf("ValueType")) {
1139 // If the operator is a ValueType, then this must be "type cast" of a leaf
1140 // node.
1141 if (Dag->getNumArgs() != 1)
1142 error("Type cast only takes one operand!");
1144 Init *Arg = Dag->getArg(0);
1145 TreePatternNode *New;
1146 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
1147 Record *R = DI->getDef();
1148 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
1149 Dag->setArg(0, new DagInit(DI, "",
1150 std::vector<std::pair<Init*, std::string> >()));
1151 return ParseTreePattern(Dag);
1153 New = new TreePatternNode(DI);
1154 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
1155 New = ParseTreePattern(DI);
1156 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
1157 New = new TreePatternNode(II);
1158 if (!Dag->getArgName(0).empty())
1159 error("Constant int argument should not have a name!");
1160 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
1161 // Turn this into an IntInit.
1162 Init *II = BI->convertInitializerTo(new IntRecTy());
1163 if (II == 0 || !dynamic_cast<IntInit*>(II))
1164 error("Bits value must be constants!");
1166 New = new TreePatternNode(dynamic_cast<IntInit*>(II));
1167 if (!Dag->getArgName(0).empty())
1168 error("Constant int argument should not have a name!");
1169 } else {
1170 Arg->dump();
1171 error("Unknown leaf value for tree pattern!");
1172 return 0;
1175 // Apply the type cast.
1176 New->UpdateNodeType(getValueType(Operator), *this);
1177 if (New->getNumChildren() == 0)
1178 New->setName(Dag->getArgName(0));
1179 return New;
1182 // Verify that this is something that makes sense for an operator.
1183 if (!Operator->isSubClassOf("PatFrag") &&
1184 !Operator->isSubClassOf("SDNode") &&
1185 !Operator->isSubClassOf("Instruction") &&
1186 !Operator->isSubClassOf("SDNodeXForm") &&
1187 !Operator->isSubClassOf("Intrinsic") &&
1188 Operator->getName() != "set" &&
1189 Operator->getName() != "implicit" &&
1190 Operator->getName() != "parallel")
1191 error("Unrecognized node '" + Operator->getName() + "'!");
1193 // Check to see if this is something that is illegal in an input pattern.
1194 if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
1195 Operator->isSubClassOf("SDNodeXForm")))
1196 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
1198 std::vector<TreePatternNode*> Children;
1200 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
1201 Init *Arg = Dag->getArg(i);
1202 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
1203 Children.push_back(ParseTreePattern(DI));
1204 if (Children.back()->getName().empty())
1205 Children.back()->setName(Dag->getArgName(i));
1206 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
1207 Record *R = DefI->getDef();
1208 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
1209 // TreePatternNode if its own.
1210 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
1211 Dag->setArg(i, new DagInit(DefI, "",
1212 std::vector<std::pair<Init*, std::string> >()));
1213 --i; // Revisit this node...
1214 } else {
1215 TreePatternNode *Node = new TreePatternNode(DefI);
1216 Node->setName(Dag->getArgName(i));
1217 Children.push_back(Node);
1219 // Input argument?
1220 if (R->getName() == "node") {
1221 if (Dag->getArgName(i).empty())
1222 error("'node' argument requires a name to match with operand list");
1223 Args.push_back(Dag->getArgName(i));
1226 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
1227 TreePatternNode *Node = new TreePatternNode(II);
1228 if (!Dag->getArgName(i).empty())
1229 error("Constant int argument should not have a name!");
1230 Children.push_back(Node);
1231 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
1232 // Turn this into an IntInit.
1233 Init *II = BI->convertInitializerTo(new IntRecTy());
1234 if (II == 0 || !dynamic_cast<IntInit*>(II))
1235 error("Bits value must be constants!");
1237 TreePatternNode *Node = new TreePatternNode(dynamic_cast<IntInit*>(II));
1238 if (!Dag->getArgName(i).empty())
1239 error("Constant int argument should not have a name!");
1240 Children.push_back(Node);
1241 } else {
1242 errs() << '"';
1243 Arg->dump();
1244 errs() << "\": ";
1245 error("Unknown leaf value for tree pattern!");
1249 // If the operator is an intrinsic, then this is just syntactic sugar for for
1250 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
1251 // convert the intrinsic name to a number.
1252 if (Operator->isSubClassOf("Intrinsic")) {
1253 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
1254 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
1256 // If this intrinsic returns void, it must have side-effects and thus a
1257 // chain.
1258 if (Int.IS.RetVTs[0] == MVT::isVoid) {
1259 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
1260 } else if (Int.ModRef != CodeGenIntrinsic::NoMem) {
1261 // Has side-effects, requires chain.
1262 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
1263 } else {
1264 // Otherwise, no chain.
1265 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
1268 TreePatternNode *IIDNode = new TreePatternNode(new IntInit(IID));
1269 Children.insert(Children.begin(), IIDNode);
1272 TreePatternNode *Result = new TreePatternNode(Operator, Children);
1273 Result->setName(Dag->getName());
1274 return Result;
1277 /// InferAllTypes - Infer/propagate as many types throughout the expression
1278 /// patterns as possible. Return true if all types are inferred, false
1279 /// otherwise. Throw an exception if a type contradiction is found.
1280 bool TreePattern::InferAllTypes() {
1281 bool MadeChange = true;
1282 while (MadeChange) {
1283 MadeChange = false;
1284 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1285 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
1288 bool HasUnresolvedTypes = false;
1289 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1290 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
1291 return !HasUnresolvedTypes;
1294 void TreePattern::print(raw_ostream &OS) const {
1295 OS << getRecord()->getName();
1296 if (!Args.empty()) {
1297 OS << "(" << Args[0];
1298 for (unsigned i = 1, e = Args.size(); i != e; ++i)
1299 OS << ", " << Args[i];
1300 OS << ")";
1302 OS << ": ";
1304 if (Trees.size() > 1)
1305 OS << "[\n";
1306 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
1307 OS << "\t";
1308 Trees[i]->print(OS);
1309 OS << "\n";
1312 if (Trees.size() > 1)
1313 OS << "]\n";
1316 void TreePattern::dump() const { print(errs()); }
1318 //===----------------------------------------------------------------------===//
1319 // CodeGenDAGPatterns implementation
1322 // FIXME: REMOVE OSTREAM ARGUMENT
1323 CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) : Records(R) {
1324 Intrinsics = LoadIntrinsics(Records, false);
1325 TgtIntrinsics = LoadIntrinsics(Records, true);
1326 ParseNodeInfo();
1327 ParseNodeTransforms();
1328 ParseComplexPatterns();
1329 ParsePatternFragments();
1330 ParseDefaultOperands();
1331 ParseInstructions();
1332 ParsePatterns();
1334 // Generate variants. For example, commutative patterns can match
1335 // multiple ways. Add them to PatternsToMatch as well.
1336 GenerateVariants();
1338 // Infer instruction flags. For example, we can detect loads,
1339 // stores, and side effects in many cases by examining an
1340 // instruction's pattern.
1341 InferInstructionFlags();
1344 CodeGenDAGPatterns::~CodeGenDAGPatterns() {
1345 for (pf_iterator I = PatternFragments.begin(),
1346 E = PatternFragments.end(); I != E; ++I)
1347 delete I->second;
1351 Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
1352 Record *N = Records.getDef(Name);
1353 if (!N || !N->isSubClassOf("SDNode")) {
1354 errs() << "Error getting SDNode '" << Name << "'!\n";
1355 exit(1);
1357 return N;
1360 // Parse all of the SDNode definitions for the target, populating SDNodes.
1361 void CodeGenDAGPatterns::ParseNodeInfo() {
1362 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
1363 while (!Nodes.empty()) {
1364 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
1365 Nodes.pop_back();
1368 // Get the builtin intrinsic nodes.
1369 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
1370 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
1371 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
1374 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
1375 /// map, and emit them to the file as functions.
1376 void CodeGenDAGPatterns::ParseNodeTransforms() {
1377 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
1378 while (!Xforms.empty()) {
1379 Record *XFormNode = Xforms.back();
1380 Record *SDNode = XFormNode->getValueAsDef("Opcode");
1381 std::string Code = XFormNode->getValueAsCode("XFormFunction");
1382 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
1384 Xforms.pop_back();
1388 void CodeGenDAGPatterns::ParseComplexPatterns() {
1389 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
1390 while (!AMs.empty()) {
1391 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
1392 AMs.pop_back();
1397 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
1398 /// file, building up the PatternFragments map. After we've collected them all,
1399 /// inline fragments together as necessary, so that there are no references left
1400 /// inside a pattern fragment to a pattern fragment.
1402 void CodeGenDAGPatterns::ParsePatternFragments() {
1403 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
1405 // First step, parse all of the fragments.
1406 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1407 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
1408 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
1409 PatternFragments[Fragments[i]] = P;
1411 // Validate the argument list, converting it to set, to discard duplicates.
1412 std::vector<std::string> &Args = P->getArgList();
1413 std::set<std::string> OperandsSet(Args.begin(), Args.end());
1415 if (OperandsSet.count(""))
1416 P->error("Cannot have unnamed 'node' values in pattern fragment!");
1418 // Parse the operands list.
1419 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
1420 DefInit *OpsOp = dynamic_cast<DefInit*>(OpsList->getOperator());
1421 // Special cases: ops == outs == ins. Different names are used to
1422 // improve readability.
1423 if (!OpsOp ||
1424 (OpsOp->getDef()->getName() != "ops" &&
1425 OpsOp->getDef()->getName() != "outs" &&
1426 OpsOp->getDef()->getName() != "ins"))
1427 P->error("Operands list should start with '(ops ... '!");
1429 // Copy over the arguments.
1430 Args.clear();
1431 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
1432 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
1433 static_cast<DefInit*>(OpsList->getArg(j))->
1434 getDef()->getName() != "node")
1435 P->error("Operands list should all be 'node' values.");
1436 if (OpsList->getArgName(j).empty())
1437 P->error("Operands list should have names for each operand!");
1438 if (!OperandsSet.count(OpsList->getArgName(j)))
1439 P->error("'" + OpsList->getArgName(j) +
1440 "' does not occur in pattern or was multiply specified!");
1441 OperandsSet.erase(OpsList->getArgName(j));
1442 Args.push_back(OpsList->getArgName(j));
1445 if (!OperandsSet.empty())
1446 P->error("Operands list does not contain an entry for operand '" +
1447 *OperandsSet.begin() + "'!");
1449 // If there is a code init for this fragment, keep track of the fact that
1450 // this fragment uses it.
1451 std::string Code = Fragments[i]->getValueAsCode("Predicate");
1452 if (!Code.empty())
1453 P->getOnlyTree()->addPredicateFn("Predicate_"+Fragments[i]->getName());
1455 // If there is a node transformation corresponding to this, keep track of
1456 // it.
1457 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
1458 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
1459 P->getOnlyTree()->setTransformFn(Transform);
1462 // Now that we've parsed all of the tree fragments, do a closure on them so
1463 // that there are not references to PatFrags left inside of them.
1464 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1465 TreePattern *ThePat = PatternFragments[Fragments[i]];
1466 ThePat->InlinePatternFragments();
1468 // Infer as many types as possible. Don't worry about it if we don't infer
1469 // all of them, some may depend on the inputs of the pattern.
1470 try {
1471 ThePat->InferAllTypes();
1472 } catch (...) {
1473 // If this pattern fragment is not supported by this target (no types can
1474 // satisfy its constraints), just ignore it. If the bogus pattern is
1475 // actually used by instructions, the type consistency error will be
1476 // reported there.
1479 // If debugging, print out the pattern fragment result.
1480 DEBUG(ThePat->dump());
1484 void CodeGenDAGPatterns::ParseDefaultOperands() {
1485 std::vector<Record*> DefaultOps[2];
1486 DefaultOps[0] = Records.getAllDerivedDefinitions("PredicateOperand");
1487 DefaultOps[1] = Records.getAllDerivedDefinitions("OptionalDefOperand");
1489 // Find some SDNode.
1490 assert(!SDNodes.empty() && "No SDNodes parsed?");
1491 Init *SomeSDNode = new DefInit(SDNodes.begin()->first);
1493 for (unsigned iter = 0; iter != 2; ++iter) {
1494 for (unsigned i = 0, e = DefaultOps[iter].size(); i != e; ++i) {
1495 DagInit *DefaultInfo = DefaultOps[iter][i]->getValueAsDag("DefaultOps");
1497 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
1498 // SomeSDnode so that we can parse this.
1499 std::vector<std::pair<Init*, std::string> > Ops;
1500 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
1501 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
1502 DefaultInfo->getArgName(op)));
1503 DagInit *DI = new DagInit(SomeSDNode, "", Ops);
1505 // Create a TreePattern to parse this.
1506 TreePattern P(DefaultOps[iter][i], DI, false, *this);
1507 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
1509 // Copy the operands over into a DAGDefaultOperand.
1510 DAGDefaultOperand DefaultOpInfo;
1512 TreePatternNode *T = P.getTree(0);
1513 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
1514 TreePatternNode *TPN = T->getChild(op);
1515 while (TPN->ApplyTypeConstraints(P, false))
1516 /* Resolve all types */;
1518 if (TPN->ContainsUnresolvedType()) {
1519 if (iter == 0)
1520 throw "Value #" + utostr(i) + " of PredicateOperand '" +
1521 DefaultOps[iter][i]->getName() + "' doesn't have a concrete type!";
1522 else
1523 throw "Value #" + utostr(i) + " of OptionalDefOperand '" +
1524 DefaultOps[iter][i]->getName() + "' doesn't have a concrete type!";
1526 DefaultOpInfo.DefaultOps.push_back(TPN);
1529 // Insert it into the DefaultOperands map so we can find it later.
1530 DefaultOperands[DefaultOps[iter][i]] = DefaultOpInfo;
1535 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
1536 /// instruction input. Return true if this is a real use.
1537 static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
1538 std::map<std::string, TreePatternNode*> &InstInputs,
1539 std::vector<Record*> &InstImpInputs) {
1540 // No name -> not interesting.
1541 if (Pat->getName().empty()) {
1542 if (Pat->isLeaf()) {
1543 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1544 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1545 I->error("Input " + DI->getDef()->getName() + " must be named!");
1546 else if (DI && DI->getDef()->isSubClassOf("Register"))
1547 InstImpInputs.push_back(DI->getDef());
1549 return false;
1552 Record *Rec;
1553 if (Pat->isLeaf()) {
1554 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1555 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
1556 Rec = DI->getDef();
1557 } else {
1558 Rec = Pat->getOperator();
1561 // SRCVALUE nodes are ignored.
1562 if (Rec->getName() == "srcvalue")
1563 return false;
1565 TreePatternNode *&Slot = InstInputs[Pat->getName()];
1566 if (!Slot) {
1567 Slot = Pat;
1568 } else {
1569 Record *SlotRec;
1570 if (Slot->isLeaf()) {
1571 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
1572 } else {
1573 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
1574 SlotRec = Slot->getOperator();
1577 // Ensure that the inputs agree if we've already seen this input.
1578 if (Rec != SlotRec)
1579 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1580 if (Slot->getExtTypes() != Pat->getExtTypes())
1581 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1583 return true;
1586 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
1587 /// part of "I", the instruction), computing the set of inputs and outputs of
1588 /// the pattern. Report errors if we see anything naughty.
1589 void CodeGenDAGPatterns::
1590 FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
1591 std::map<std::string, TreePatternNode*> &InstInputs,
1592 std::map<std::string, TreePatternNode*>&InstResults,
1593 std::vector<Record*> &InstImpInputs,
1594 std::vector<Record*> &InstImpResults) {
1595 if (Pat->isLeaf()) {
1596 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1597 if (!isUse && Pat->getTransformFn())
1598 I->error("Cannot specify a transform function for a non-input value!");
1599 return;
1600 } else if (Pat->getOperator()->getName() == "implicit") {
1601 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1602 TreePatternNode *Dest = Pat->getChild(i);
1603 if (!Dest->isLeaf())
1604 I->error("implicitly defined value should be a register!");
1606 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1607 if (!Val || !Val->getDef()->isSubClassOf("Register"))
1608 I->error("implicitly defined value should be a register!");
1609 InstImpResults.push_back(Val->getDef());
1611 return;
1612 } else if (Pat->getOperator()->getName() != "set") {
1613 // If this is not a set, verify that the children nodes are not void typed,
1614 // and recurse.
1615 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1616 if (Pat->getChild(i)->getExtTypeNum(0) == MVT::isVoid)
1617 I->error("Cannot have void nodes inside of patterns!");
1618 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
1619 InstImpInputs, InstImpResults);
1622 // If this is a non-leaf node with no children, treat it basically as if
1623 // it were a leaf. This handles nodes like (imm).
1624 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1626 if (!isUse && Pat->getTransformFn())
1627 I->error("Cannot specify a transform function for a non-input value!");
1628 return;
1631 // Otherwise, this is a set, validate and collect instruction results.
1632 if (Pat->getNumChildren() == 0)
1633 I->error("set requires operands!");
1635 if (Pat->getTransformFn())
1636 I->error("Cannot specify a transform function on a set node!");
1638 // Check the set destinations.
1639 unsigned NumDests = Pat->getNumChildren()-1;
1640 for (unsigned i = 0; i != NumDests; ++i) {
1641 TreePatternNode *Dest = Pat->getChild(i);
1642 if (!Dest->isLeaf())
1643 I->error("set destination should be a register!");
1645 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1646 if (!Val)
1647 I->error("set destination should be a register!");
1649 if (Val->getDef()->isSubClassOf("RegisterClass") ||
1650 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
1651 if (Dest->getName().empty())
1652 I->error("set destination must have a name!");
1653 if (InstResults.count(Dest->getName()))
1654 I->error("cannot set '" + Dest->getName() +"' multiple times");
1655 InstResults[Dest->getName()] = Dest;
1656 } else if (Val->getDef()->isSubClassOf("Register")) {
1657 InstImpResults.push_back(Val->getDef());
1658 } else {
1659 I->error("set destination should be a register!");
1663 // Verify and collect info from the computation.
1664 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
1665 InstInputs, InstResults,
1666 InstImpInputs, InstImpResults);
1669 //===----------------------------------------------------------------------===//
1670 // Instruction Analysis
1671 //===----------------------------------------------------------------------===//
1673 class InstAnalyzer {
1674 const CodeGenDAGPatterns &CDP;
1675 bool &mayStore;
1676 bool &mayLoad;
1677 bool &HasSideEffects;
1678 public:
1679 InstAnalyzer(const CodeGenDAGPatterns &cdp,
1680 bool &maystore, bool &mayload, bool &hse)
1681 : CDP(cdp), mayStore(maystore), mayLoad(mayload), HasSideEffects(hse){
1684 /// Analyze - Analyze the specified instruction, returning true if the
1685 /// instruction had a pattern.
1686 bool Analyze(Record *InstRecord) {
1687 const TreePattern *Pattern = CDP.getInstruction(InstRecord).getPattern();
1688 if (Pattern == 0) {
1689 HasSideEffects = 1;
1690 return false; // No pattern.
1693 // FIXME: Assume only the first tree is the pattern. The others are clobber
1694 // nodes.
1695 AnalyzeNode(Pattern->getTree(0));
1696 return true;
1699 private:
1700 void AnalyzeNode(const TreePatternNode *N) {
1701 if (N->isLeaf()) {
1702 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
1703 Record *LeafRec = DI->getDef();
1704 // Handle ComplexPattern leaves.
1705 if (LeafRec->isSubClassOf("ComplexPattern")) {
1706 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
1707 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
1708 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
1709 if (CP.hasProperty(SDNPSideEffect)) HasSideEffects = true;
1712 return;
1715 // Analyze children.
1716 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1717 AnalyzeNode(N->getChild(i));
1719 // Ignore set nodes, which are not SDNodes.
1720 if (N->getOperator()->getName() == "set")
1721 return;
1723 // Get information about the SDNode for the operator.
1724 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N->getOperator());
1726 // Notice properties of the node.
1727 if (OpInfo.hasProperty(SDNPMayStore)) mayStore = true;
1728 if (OpInfo.hasProperty(SDNPMayLoad)) mayLoad = true;
1729 if (OpInfo.hasProperty(SDNPSideEffect)) HasSideEffects = true;
1731 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
1732 // If this is an intrinsic, analyze it.
1733 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
1734 mayLoad = true;// These may load memory.
1736 if (IntInfo->ModRef >= CodeGenIntrinsic::WriteArgMem)
1737 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
1739 if (IntInfo->ModRef >= CodeGenIntrinsic::WriteMem)
1740 // WriteMem intrinsics can have other strange effects.
1741 HasSideEffects = true;
1747 static void InferFromPattern(const CodeGenInstruction &Inst,
1748 bool &MayStore, bool &MayLoad,
1749 bool &HasSideEffects,
1750 const CodeGenDAGPatterns &CDP) {
1751 MayStore = MayLoad = HasSideEffects = false;
1753 bool HadPattern =
1754 InstAnalyzer(CDP, MayStore, MayLoad, HasSideEffects).Analyze(Inst.TheDef);
1756 // InstAnalyzer only correctly analyzes mayStore/mayLoad so far.
1757 if (Inst.mayStore) { // If the .td file explicitly sets mayStore, use it.
1758 // If we decided that this is a store from the pattern, then the .td file
1759 // entry is redundant.
1760 if (MayStore)
1761 fprintf(stderr,
1762 "Warning: mayStore flag explicitly set on instruction '%s'"
1763 " but flag already inferred from pattern.\n",
1764 Inst.TheDef->getName().c_str());
1765 MayStore = true;
1768 if (Inst.mayLoad) { // If the .td file explicitly sets mayLoad, use it.
1769 // If we decided that this is a load from the pattern, then the .td file
1770 // entry is redundant.
1771 if (MayLoad)
1772 fprintf(stderr,
1773 "Warning: mayLoad flag explicitly set on instruction '%s'"
1774 " but flag already inferred from pattern.\n",
1775 Inst.TheDef->getName().c_str());
1776 MayLoad = true;
1779 if (Inst.neverHasSideEffects) {
1780 if (HadPattern)
1781 fprintf(stderr, "Warning: neverHasSideEffects set on instruction '%s' "
1782 "which already has a pattern\n", Inst.TheDef->getName().c_str());
1783 HasSideEffects = false;
1786 if (Inst.hasSideEffects) {
1787 if (HasSideEffects)
1788 fprintf(stderr, "Warning: hasSideEffects set on instruction '%s' "
1789 "which already inferred this.\n", Inst.TheDef->getName().c_str());
1790 HasSideEffects = true;
1794 /// ParseInstructions - Parse all of the instructions, inlining and resolving
1795 /// any fragments involved. This populates the Instructions list with fully
1796 /// resolved instructions.
1797 void CodeGenDAGPatterns::ParseInstructions() {
1798 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
1800 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
1801 ListInit *LI = 0;
1803 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
1804 LI = Instrs[i]->getValueAsListInit("Pattern");
1806 // If there is no pattern, only collect minimal information about the
1807 // instruction for its operand list. We have to assume that there is one
1808 // result, as we have no detailed info.
1809 if (!LI || LI->getSize() == 0) {
1810 std::vector<Record*> Results;
1811 std::vector<Record*> Operands;
1813 CodeGenInstruction &InstInfo =Target.getInstruction(Instrs[i]->getName());
1815 if (InstInfo.OperandList.size() != 0) {
1816 if (InstInfo.NumDefs == 0) {
1817 // These produce no results
1818 for (unsigned j = 0, e = InstInfo.OperandList.size(); j < e; ++j)
1819 Operands.push_back(InstInfo.OperandList[j].Rec);
1820 } else {
1821 // Assume the first operand is the result.
1822 Results.push_back(InstInfo.OperandList[0].Rec);
1824 // The rest are inputs.
1825 for (unsigned j = 1, e = InstInfo.OperandList.size(); j < e; ++j)
1826 Operands.push_back(InstInfo.OperandList[j].Rec);
1830 // Create and insert the instruction.
1831 std::vector<Record*> ImpResults;
1832 std::vector<Record*> ImpOperands;
1833 Instructions.insert(std::make_pair(Instrs[i],
1834 DAGInstruction(0, Results, Operands, ImpResults,
1835 ImpOperands)));
1836 continue; // no pattern.
1839 // Parse the instruction.
1840 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
1841 // Inline pattern fragments into it.
1842 I->InlinePatternFragments();
1844 // Infer as many types as possible. If we cannot infer all of them, we can
1845 // never do anything with this instruction pattern: report it to the user.
1846 if (!I->InferAllTypes())
1847 I->error("Could not infer all types in pattern!");
1849 // InstInputs - Keep track of all of the inputs of the instruction, along
1850 // with the record they are declared as.
1851 std::map<std::string, TreePatternNode*> InstInputs;
1853 // InstResults - Keep track of all the virtual registers that are 'set'
1854 // in the instruction, including what reg class they are.
1855 std::map<std::string, TreePatternNode*> InstResults;
1857 std::vector<Record*> InstImpInputs;
1858 std::vector<Record*> InstImpResults;
1860 // Verify that the top-level forms in the instruction are of void type, and
1861 // fill in the InstResults map.
1862 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
1863 TreePatternNode *Pat = I->getTree(j);
1864 if (Pat->getExtTypeNum(0) != MVT::isVoid)
1865 I->error("Top-level forms in instruction pattern should have"
1866 " void types");
1868 // Find inputs and outputs, and verify the structure of the uses/defs.
1869 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
1870 InstImpInputs, InstImpResults);
1873 // Now that we have inputs and outputs of the pattern, inspect the operands
1874 // list for the instruction. This determines the order that operands are
1875 // added to the machine instruction the node corresponds to.
1876 unsigned NumResults = InstResults.size();
1878 // Parse the operands list from the (ops) list, validating it.
1879 assert(I->getArgList().empty() && "Args list should still be empty here!");
1880 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
1882 // Check that all of the results occur first in the list.
1883 std::vector<Record*> Results;
1884 TreePatternNode *Res0Node = NULL;
1885 for (unsigned i = 0; i != NumResults; ++i) {
1886 if (i == CGI.OperandList.size())
1887 I->error("'" + InstResults.begin()->first +
1888 "' set but does not appear in operand list!");
1889 const std::string &OpName = CGI.OperandList[i].Name;
1891 // Check that it exists in InstResults.
1892 TreePatternNode *RNode = InstResults[OpName];
1893 if (RNode == 0)
1894 I->error("Operand $" + OpName + " does not exist in operand list!");
1896 if (i == 0)
1897 Res0Node = RNode;
1898 Record *R = dynamic_cast<DefInit*>(RNode->getLeafValue())->getDef();
1899 if (R == 0)
1900 I->error("Operand $" + OpName + " should be a set destination: all "
1901 "outputs must occur before inputs in operand list!");
1903 if (CGI.OperandList[i].Rec != R)
1904 I->error("Operand $" + OpName + " class mismatch!");
1906 // Remember the return type.
1907 Results.push_back(CGI.OperandList[i].Rec);
1909 // Okay, this one checks out.
1910 InstResults.erase(OpName);
1913 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
1914 // the copy while we're checking the inputs.
1915 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
1917 std::vector<TreePatternNode*> ResultNodeOperands;
1918 std::vector<Record*> Operands;
1919 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
1920 CodeGenInstruction::OperandInfo &Op = CGI.OperandList[i];
1921 const std::string &OpName = Op.Name;
1922 if (OpName.empty())
1923 I->error("Operand #" + utostr(i) + " in operands list has no name!");
1925 if (!InstInputsCheck.count(OpName)) {
1926 // If this is an predicate operand or optional def operand with an
1927 // DefaultOps set filled in, we can ignore this. When we codegen it,
1928 // we will do so as always executed.
1929 if (Op.Rec->isSubClassOf("PredicateOperand") ||
1930 Op.Rec->isSubClassOf("OptionalDefOperand")) {
1931 // Does it have a non-empty DefaultOps field? If so, ignore this
1932 // operand.
1933 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
1934 continue;
1936 I->error("Operand $" + OpName +
1937 " does not appear in the instruction pattern");
1939 TreePatternNode *InVal = InstInputsCheck[OpName];
1940 InstInputsCheck.erase(OpName); // It occurred, remove from map.
1942 if (InVal->isLeaf() &&
1943 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
1944 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
1945 if (Op.Rec != InRec && !InRec->isSubClassOf("ComplexPattern"))
1946 I->error("Operand $" + OpName + "'s register class disagrees"
1947 " between the operand and pattern");
1949 Operands.push_back(Op.Rec);
1951 // Construct the result for the dest-pattern operand list.
1952 TreePatternNode *OpNode = InVal->clone();
1954 // No predicate is useful on the result.
1955 OpNode->clearPredicateFns();
1957 // Promote the xform function to be an explicit node if set.
1958 if (Record *Xform = OpNode->getTransformFn()) {
1959 OpNode->setTransformFn(0);
1960 std::vector<TreePatternNode*> Children;
1961 Children.push_back(OpNode);
1962 OpNode = new TreePatternNode(Xform, Children);
1965 ResultNodeOperands.push_back(OpNode);
1968 if (!InstInputsCheck.empty())
1969 I->error("Input operand $" + InstInputsCheck.begin()->first +
1970 " occurs in pattern but not in operands list!");
1972 TreePatternNode *ResultPattern =
1973 new TreePatternNode(I->getRecord(), ResultNodeOperands);
1974 // Copy fully inferred output node type to instruction result pattern.
1975 if (NumResults > 0)
1976 ResultPattern->setTypes(Res0Node->getExtTypes());
1978 // Create and insert the instruction.
1979 // FIXME: InstImpResults and InstImpInputs should not be part of
1980 // DAGInstruction.
1981 DAGInstruction TheInst(I, Results, Operands, InstImpResults, InstImpInputs);
1982 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
1984 // Use a temporary tree pattern to infer all types and make sure that the
1985 // constructed result is correct. This depends on the instruction already
1986 // being inserted into the Instructions map.
1987 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
1988 Temp.InferAllTypes();
1990 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
1991 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
1993 DEBUG(I->dump());
1996 // If we can, convert the instructions to be patterns that are matched!
1997 for (std::map<Record*, DAGInstruction, RecordPtrCmp>::iterator II =
1998 Instructions.begin(),
1999 E = Instructions.end(); II != E; ++II) {
2000 DAGInstruction &TheInst = II->second;
2001 const TreePattern *I = TheInst.getPattern();
2002 if (I == 0) continue; // No pattern.
2004 // FIXME: Assume only the first tree is the pattern. The others are clobber
2005 // nodes.
2006 TreePatternNode *Pattern = I->getTree(0);
2007 TreePatternNode *SrcPattern;
2008 if (Pattern->getOperator()->getName() == "set") {
2009 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
2010 } else{
2011 // Not a set (store or something?)
2012 SrcPattern = Pattern;
2015 std::string Reason;
2016 if (!SrcPattern->canPatternMatch(Reason, *this))
2017 I->error("Instruction can never match: " + Reason);
2019 Record *Instr = II->first;
2020 TreePatternNode *DstPattern = TheInst.getResultPattern();
2021 PatternsToMatch.
2022 push_back(PatternToMatch(Instr->getValueAsListInit("Predicates"),
2023 SrcPattern, DstPattern, TheInst.getImpResults(),
2024 Instr->getValueAsInt("AddedComplexity")));
2029 void CodeGenDAGPatterns::InferInstructionFlags() {
2030 std::map<std::string, CodeGenInstruction> &InstrDescs =
2031 Target.getInstructions();
2032 for (std::map<std::string, CodeGenInstruction>::iterator
2033 II = InstrDescs.begin(), E = InstrDescs.end(); II != E; ++II) {
2034 CodeGenInstruction &InstInfo = II->second;
2035 // Determine properties of the instruction from its pattern.
2036 bool MayStore, MayLoad, HasSideEffects;
2037 InferFromPattern(InstInfo, MayStore, MayLoad, HasSideEffects, *this);
2038 InstInfo.mayStore = MayStore;
2039 InstInfo.mayLoad = MayLoad;
2040 InstInfo.hasSideEffects = HasSideEffects;
2044 void CodeGenDAGPatterns::ParsePatterns() {
2045 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
2047 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
2048 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
2049 DefInit *OpDef = dynamic_cast<DefInit*>(Tree->getOperator());
2050 Record *Operator = OpDef->getDef();
2051 TreePattern *Pattern;
2052 if (Operator->getName() != "parallel")
2053 Pattern = new TreePattern(Patterns[i], Tree, true, *this);
2054 else {
2055 std::vector<Init*> Values;
2056 RecTy *ListTy = 0;
2057 for (unsigned j = 0, ee = Tree->getNumArgs(); j != ee; ++j) {
2058 Values.push_back(Tree->getArg(j));
2059 TypedInit *TArg = dynamic_cast<TypedInit*>(Tree->getArg(j));
2060 if (TArg == 0) {
2061 errs() << "In dag: " << Tree->getAsString();
2062 errs() << " -- Untyped argument in pattern\n";
2063 assert(0 && "Untyped argument in pattern");
2065 if (ListTy != 0) {
2066 ListTy = resolveTypes(ListTy, TArg->getType());
2067 if (ListTy == 0) {
2068 errs() << "In dag: " << Tree->getAsString();
2069 errs() << " -- Incompatible types in pattern arguments\n";
2070 assert(0 && "Incompatible types in pattern arguments");
2073 else {
2074 ListTy = TArg->getType();
2077 ListInit *LI = new ListInit(Values, new ListRecTy(ListTy));
2078 Pattern = new TreePattern(Patterns[i], LI, true, *this);
2081 // Inline pattern fragments into it.
2082 Pattern->InlinePatternFragments();
2084 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
2085 if (LI->getSize() == 0) continue; // no pattern.
2087 // Parse the instruction.
2088 TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
2090 // Inline pattern fragments into it.
2091 Result->InlinePatternFragments();
2093 if (Result->getNumTrees() != 1)
2094 Result->error("Cannot handle instructions producing instructions "
2095 "with temporaries yet!");
2097 bool IterateInference;
2098 bool InferredAllPatternTypes, InferredAllResultTypes;
2099 do {
2100 // Infer as many types as possible. If we cannot infer all of them, we
2101 // can never do anything with this pattern: report it to the user.
2102 InferredAllPatternTypes = Pattern->InferAllTypes();
2104 // Infer as many types as possible. If we cannot infer all of them, we
2105 // can never do anything with this pattern: report it to the user.
2106 InferredAllResultTypes = Result->InferAllTypes();
2108 // Apply the type of the result to the source pattern. This helps us
2109 // resolve cases where the input type is known to be a pointer type (which
2110 // is considered resolved), but the result knows it needs to be 32- or
2111 // 64-bits. Infer the other way for good measure.
2112 IterateInference = Pattern->getTree(0)->
2113 UpdateNodeType(Result->getTree(0)->getExtTypes(), *Result);
2114 IterateInference |= Result->getTree(0)->
2115 UpdateNodeType(Pattern->getTree(0)->getExtTypes(), *Result);
2116 } while (IterateInference);
2118 // Verify that we inferred enough types that we can do something with the
2119 // pattern and result. If these fire the user has to add type casts.
2120 if (!InferredAllPatternTypes)
2121 Pattern->error("Could not infer all types in pattern!");
2122 if (!InferredAllResultTypes)
2123 Result->error("Could not infer all types in pattern result!");
2125 // Validate that the input pattern is correct.
2126 std::map<std::string, TreePatternNode*> InstInputs;
2127 std::map<std::string, TreePatternNode*> InstResults;
2128 std::vector<Record*> InstImpInputs;
2129 std::vector<Record*> InstImpResults;
2130 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
2131 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
2132 InstInputs, InstResults,
2133 InstImpInputs, InstImpResults);
2135 // Promote the xform function to be an explicit node if set.
2136 TreePatternNode *DstPattern = Result->getOnlyTree();
2137 std::vector<TreePatternNode*> ResultNodeOperands;
2138 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
2139 TreePatternNode *OpNode = DstPattern->getChild(ii);
2140 if (Record *Xform = OpNode->getTransformFn()) {
2141 OpNode->setTransformFn(0);
2142 std::vector<TreePatternNode*> Children;
2143 Children.push_back(OpNode);
2144 OpNode = new TreePatternNode(Xform, Children);
2146 ResultNodeOperands.push_back(OpNode);
2148 DstPattern = Result->getOnlyTree();
2149 if (!DstPattern->isLeaf())
2150 DstPattern = new TreePatternNode(DstPattern->getOperator(),
2151 ResultNodeOperands);
2152 DstPattern->setTypes(Result->getOnlyTree()->getExtTypes());
2153 TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
2154 Temp.InferAllTypes();
2156 std::string Reason;
2157 if (!Pattern->getTree(0)->canPatternMatch(Reason, *this))
2158 Pattern->error("Pattern can never match: " + Reason);
2160 PatternsToMatch.
2161 push_back(PatternToMatch(Patterns[i]->getValueAsListInit("Predicates"),
2162 Pattern->getTree(0),
2163 Temp.getOnlyTree(), InstImpResults,
2164 Patterns[i]->getValueAsInt("AddedComplexity")));
2168 /// CombineChildVariants - Given a bunch of permutations of each child of the
2169 /// 'operator' node, put them together in all possible ways.
2170 static void CombineChildVariants(TreePatternNode *Orig,
2171 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
2172 std::vector<TreePatternNode*> &OutVariants,
2173 CodeGenDAGPatterns &CDP,
2174 const MultipleUseVarSet &DepVars) {
2175 // Make sure that each operand has at least one variant to choose from.
2176 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2177 if (ChildVariants[i].empty())
2178 return;
2180 // The end result is an all-pairs construction of the resultant pattern.
2181 std::vector<unsigned> Idxs;
2182 Idxs.resize(ChildVariants.size());
2183 bool NotDone;
2184 do {
2185 #ifndef NDEBUG
2186 if (DebugFlag && !Idxs.empty()) {
2187 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
2188 for (unsigned i = 0; i < Idxs.size(); ++i) {
2189 errs() << Idxs[i] << " ";
2191 errs() << "]\n";
2193 #endif
2194 // Create the variant and add it to the output list.
2195 std::vector<TreePatternNode*> NewChildren;
2196 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2197 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
2198 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
2200 // Copy over properties.
2201 R->setName(Orig->getName());
2202 R->setPredicateFns(Orig->getPredicateFns());
2203 R->setTransformFn(Orig->getTransformFn());
2204 R->setTypes(Orig->getExtTypes());
2206 // If this pattern cannot match, do not include it as a variant.
2207 std::string ErrString;
2208 if (!R->canPatternMatch(ErrString, CDP)) {
2209 delete R;
2210 } else {
2211 bool AlreadyExists = false;
2213 // Scan to see if this pattern has already been emitted. We can get
2214 // duplication due to things like commuting:
2215 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
2216 // which are the same pattern. Ignore the dups.
2217 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
2218 if (R->isIsomorphicTo(OutVariants[i], DepVars)) {
2219 AlreadyExists = true;
2220 break;
2223 if (AlreadyExists)
2224 delete R;
2225 else
2226 OutVariants.push_back(R);
2229 // Increment indices to the next permutation by incrementing the
2230 // indicies from last index backward, e.g., generate the sequence
2231 // [0, 0], [0, 1], [1, 0], [1, 1].
2232 int IdxsIdx;
2233 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
2234 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
2235 Idxs[IdxsIdx] = 0;
2236 else
2237 break;
2239 NotDone = (IdxsIdx >= 0);
2240 } while (NotDone);
2243 /// CombineChildVariants - A helper function for binary operators.
2245 static void CombineChildVariants(TreePatternNode *Orig,
2246 const std::vector<TreePatternNode*> &LHS,
2247 const std::vector<TreePatternNode*> &RHS,
2248 std::vector<TreePatternNode*> &OutVariants,
2249 CodeGenDAGPatterns &CDP,
2250 const MultipleUseVarSet &DepVars) {
2251 std::vector<std::vector<TreePatternNode*> > ChildVariants;
2252 ChildVariants.push_back(LHS);
2253 ChildVariants.push_back(RHS);
2254 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
2258 static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
2259 std::vector<TreePatternNode *> &Children) {
2260 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
2261 Record *Operator = N->getOperator();
2263 // Only permit raw nodes.
2264 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
2265 N->getTransformFn()) {
2266 Children.push_back(N);
2267 return;
2270 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
2271 Children.push_back(N->getChild(0));
2272 else
2273 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
2275 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
2276 Children.push_back(N->getChild(1));
2277 else
2278 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
2281 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
2282 /// the (potentially recursive) pattern by using algebraic laws.
2284 static void GenerateVariantsOf(TreePatternNode *N,
2285 std::vector<TreePatternNode*> &OutVariants,
2286 CodeGenDAGPatterns &CDP,
2287 const MultipleUseVarSet &DepVars) {
2288 // We cannot permute leaves.
2289 if (N->isLeaf()) {
2290 OutVariants.push_back(N);
2291 return;
2294 // Look up interesting info about the node.
2295 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
2297 // If this node is associative, re-associate.
2298 if (NodeInfo.hasProperty(SDNPAssociative)) {
2299 // Re-associate by pulling together all of the linked operators
2300 std::vector<TreePatternNode*> MaximalChildren;
2301 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
2303 // Only handle child sizes of 3. Otherwise we'll end up trying too many
2304 // permutations.
2305 if (MaximalChildren.size() == 3) {
2306 // Find the variants of all of our maximal children.
2307 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
2308 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
2309 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
2310 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
2312 // There are only two ways we can permute the tree:
2313 // (A op B) op C and A op (B op C)
2314 // Within these forms, we can also permute A/B/C.
2316 // Generate legal pair permutations of A/B/C.
2317 std::vector<TreePatternNode*> ABVariants;
2318 std::vector<TreePatternNode*> BAVariants;
2319 std::vector<TreePatternNode*> ACVariants;
2320 std::vector<TreePatternNode*> CAVariants;
2321 std::vector<TreePatternNode*> BCVariants;
2322 std::vector<TreePatternNode*> CBVariants;
2323 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
2324 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
2325 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
2326 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
2327 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
2328 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
2330 // Combine those into the result: (x op x) op x
2331 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
2332 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
2333 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
2334 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
2335 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
2336 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
2338 // Combine those into the result: x op (x op x)
2339 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
2340 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
2341 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
2342 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
2343 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
2344 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
2345 return;
2349 // Compute permutations of all children.
2350 std::vector<std::vector<TreePatternNode*> > ChildVariants;
2351 ChildVariants.resize(N->getNumChildren());
2352 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2353 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
2355 // Build all permutations based on how the children were formed.
2356 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
2358 // If this node is commutative, consider the commuted order.
2359 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
2360 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
2361 assert((N->getNumChildren()==2 || isCommIntrinsic) &&
2362 "Commutative but doesn't have 2 children!");
2363 // Don't count children which are actually register references.
2364 unsigned NC = 0;
2365 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2366 TreePatternNode *Child = N->getChild(i);
2367 if (Child->isLeaf())
2368 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2369 Record *RR = DI->getDef();
2370 if (RR->isSubClassOf("Register"))
2371 continue;
2373 NC++;
2375 // Consider the commuted order.
2376 if (isCommIntrinsic) {
2377 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
2378 // operands are the commutative operands, and there might be more operands
2379 // after those.
2380 assert(NC >= 3 &&
2381 "Commutative intrinsic should have at least 3 childrean!");
2382 std::vector<std::vector<TreePatternNode*> > Variants;
2383 Variants.push_back(ChildVariants[0]); // Intrinsic id.
2384 Variants.push_back(ChildVariants[2]);
2385 Variants.push_back(ChildVariants[1]);
2386 for (unsigned i = 3; i != NC; ++i)
2387 Variants.push_back(ChildVariants[i]);
2388 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
2389 } else if (NC == 2)
2390 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
2391 OutVariants, CDP, DepVars);
2396 // GenerateVariants - Generate variants. For example, commutative patterns can
2397 // match multiple ways. Add them to PatternsToMatch as well.
2398 void CodeGenDAGPatterns::GenerateVariants() {
2399 DEBUG(errs() << "Generating instruction variants.\n");
2401 // Loop over all of the patterns we've collected, checking to see if we can
2402 // generate variants of the instruction, through the exploitation of
2403 // identities. This permits the target to provide aggressive matching without
2404 // the .td file having to contain tons of variants of instructions.
2406 // Note that this loop adds new patterns to the PatternsToMatch list, but we
2407 // intentionally do not reconsider these. Any variants of added patterns have
2408 // already been added.
2410 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
2411 MultipleUseVarSet DepVars;
2412 std::vector<TreePatternNode*> Variants;
2413 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
2414 DEBUG(errs() << "Dependent/multiply used variables: ");
2415 DEBUG(DumpDepVars(DepVars));
2416 DEBUG(errs() << "\n");
2417 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this, DepVars);
2419 assert(!Variants.empty() && "Must create at least original variant!");
2420 Variants.erase(Variants.begin()); // Remove the original pattern.
2422 if (Variants.empty()) // No variants for this pattern.
2423 continue;
2425 DEBUG(errs() << "FOUND VARIANTS OF: ";
2426 PatternsToMatch[i].getSrcPattern()->dump();
2427 errs() << "\n");
2429 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
2430 TreePatternNode *Variant = Variants[v];
2432 DEBUG(errs() << " VAR#" << v << ": ";
2433 Variant->dump();
2434 errs() << "\n");
2436 // Scan to see if an instruction or explicit pattern already matches this.
2437 bool AlreadyExists = false;
2438 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
2439 // Skip if the top level predicates do not match.
2440 if (PatternsToMatch[i].getPredicates() !=
2441 PatternsToMatch[p].getPredicates())
2442 continue;
2443 // Check to see if this variant already exists.
2444 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(), DepVars)) {
2445 DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
2446 AlreadyExists = true;
2447 break;
2450 // If we already have it, ignore the variant.
2451 if (AlreadyExists) continue;
2453 // Otherwise, add it to the list of patterns we have.
2454 PatternsToMatch.
2455 push_back(PatternToMatch(PatternsToMatch[i].getPredicates(),
2456 Variant, PatternsToMatch[i].getDstPattern(),
2457 PatternsToMatch[i].getDstRegs(),
2458 PatternsToMatch[i].getAddedComplexity()));
2461 DEBUG(errs() << "\n");