Fix typo pointed out in pr9339.
[llvm/stm8.git] / utils / TableGen / CodeGenDAGPatterns.cpp
blobaa60f871bff50f5fcdc2ca8173ebedd3dd529941
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/ADT/STLExtras.h"
19 #include "llvm/Support/Debug.h"
20 #include <set>
21 #include <algorithm>
22 using namespace llvm;
24 //===----------------------------------------------------------------------===//
25 // EEVT::TypeSet Implementation
26 //===----------------------------------------------------------------------===//
28 static inline bool isInteger(MVT::SimpleValueType VT) {
29 return EVT(VT).isInteger();
31 static inline bool isFloatingPoint(MVT::SimpleValueType VT) {
32 return EVT(VT).isFloatingPoint();
34 static inline bool isVector(MVT::SimpleValueType VT) {
35 return EVT(VT).isVector();
37 static inline bool isScalar(MVT::SimpleValueType VT) {
38 return !EVT(VT).isVector();
41 EEVT::TypeSet::TypeSet(MVT::SimpleValueType VT, TreePattern &TP) {
42 if (VT == MVT::iAny)
43 EnforceInteger(TP);
44 else if (VT == MVT::fAny)
45 EnforceFloatingPoint(TP);
46 else if (VT == MVT::vAny)
47 EnforceVector(TP);
48 else {
49 assert((VT < MVT::LAST_VALUETYPE || VT == MVT::iPTR ||
50 VT == MVT::iPTRAny) && "Not a concrete type!");
51 TypeVec.push_back(VT);
56 EEVT::TypeSet::TypeSet(const std::vector<MVT::SimpleValueType> &VTList) {
57 assert(!VTList.empty() && "empty list?");
58 TypeVec.append(VTList.begin(), VTList.end());
60 if (!VTList.empty())
61 assert(VTList[0] != MVT::iAny && VTList[0] != MVT::vAny &&
62 VTList[0] != MVT::fAny);
64 // Verify no duplicates.
65 array_pod_sort(TypeVec.begin(), TypeVec.end());
66 assert(std::unique(TypeVec.begin(), TypeVec.end()) == TypeVec.end());
69 /// FillWithPossibleTypes - Set to all legal types and return true, only valid
70 /// on completely unknown type sets.
71 bool EEVT::TypeSet::FillWithPossibleTypes(TreePattern &TP,
72 bool (*Pred)(MVT::SimpleValueType),
73 const char *PredicateName) {
74 assert(isCompletelyUnknown());
75 const std::vector<MVT::SimpleValueType> &LegalTypes =
76 TP.getDAGPatterns().getTargetInfo().getLegalValueTypes();
78 for (unsigned i = 0, e = LegalTypes.size(); i != e; ++i)
79 if (Pred == 0 || Pred(LegalTypes[i]))
80 TypeVec.push_back(LegalTypes[i]);
82 // If we have nothing that matches the predicate, bail out.
83 if (TypeVec.empty())
84 TP.error("Type inference contradiction found, no " +
85 std::string(PredicateName) + " types found");
86 // No need to sort with one element.
87 if (TypeVec.size() == 1) return true;
89 // Remove duplicates.
90 array_pod_sort(TypeVec.begin(), TypeVec.end());
91 TypeVec.erase(std::unique(TypeVec.begin(), TypeVec.end()), TypeVec.end());
93 return true;
96 /// hasIntegerTypes - Return true if this TypeSet contains iAny or an
97 /// integer value type.
98 bool EEVT::TypeSet::hasIntegerTypes() const {
99 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
100 if (isInteger(TypeVec[i]))
101 return true;
102 return false;
105 /// hasFloatingPointTypes - Return true if this TypeSet contains an fAny or
106 /// a floating point value type.
107 bool EEVT::TypeSet::hasFloatingPointTypes() const {
108 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
109 if (isFloatingPoint(TypeVec[i]))
110 return true;
111 return false;
114 /// hasVectorTypes - Return true if this TypeSet contains a vAny or a vector
115 /// value type.
116 bool EEVT::TypeSet::hasVectorTypes() const {
117 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
118 if (isVector(TypeVec[i]))
119 return true;
120 return false;
124 std::string EEVT::TypeSet::getName() const {
125 if (TypeVec.empty()) return "<empty>";
127 std::string Result;
129 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i) {
130 std::string VTName = llvm::getEnumName(TypeVec[i]);
131 // Strip off MVT:: prefix if present.
132 if (VTName.substr(0,5) == "MVT::")
133 VTName = VTName.substr(5);
134 if (i) Result += ':';
135 Result += VTName;
138 if (TypeVec.size() == 1)
139 return Result;
140 return "{" + Result + "}";
143 /// MergeInTypeInfo - This merges in type information from the specified
144 /// argument. If 'this' changes, it returns true. If the two types are
145 /// contradictory (e.g. merge f32 into i32) then this throws an exception.
146 bool EEVT::TypeSet::MergeInTypeInfo(const EEVT::TypeSet &InVT, TreePattern &TP){
147 if (InVT.isCompletelyUnknown() || *this == InVT)
148 return false;
150 if (isCompletelyUnknown()) {
151 *this = InVT;
152 return true;
155 assert(TypeVec.size() >= 1 && InVT.TypeVec.size() >= 1 && "No unknowns");
157 // Handle the abstract cases, seeing if we can resolve them better.
158 switch (TypeVec[0]) {
159 default: break;
160 case MVT::iPTR:
161 case MVT::iPTRAny:
162 if (InVT.hasIntegerTypes()) {
163 EEVT::TypeSet InCopy(InVT);
164 InCopy.EnforceInteger(TP);
165 InCopy.EnforceScalar(TP);
167 if (InCopy.isConcrete()) {
168 // If the RHS has one integer type, upgrade iPTR to i32.
169 TypeVec[0] = InVT.TypeVec[0];
170 return true;
173 // If the input has multiple scalar integers, this doesn't add any info.
174 if (!InCopy.isCompletelyUnknown())
175 return false;
177 break;
180 // If the input constraint is iAny/iPTR and this is an integer type list,
181 // remove non-integer types from the list.
182 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
183 hasIntegerTypes()) {
184 bool MadeChange = EnforceInteger(TP);
186 // If we're merging in iPTR/iPTRAny and the node currently has a list of
187 // multiple different integer types, replace them with a single iPTR.
188 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
189 TypeVec.size() != 1) {
190 TypeVec.resize(1);
191 TypeVec[0] = InVT.TypeVec[0];
192 MadeChange = true;
195 return MadeChange;
198 // If this is a type list and the RHS is a typelist as well, eliminate entries
199 // from this list that aren't in the other one.
200 bool MadeChange = false;
201 TypeSet InputSet(*this);
203 for (unsigned i = 0; i != TypeVec.size(); ++i) {
204 bool InInVT = false;
205 for (unsigned j = 0, e = InVT.TypeVec.size(); j != e; ++j)
206 if (TypeVec[i] == InVT.TypeVec[j]) {
207 InInVT = true;
208 break;
211 if (InInVT) continue;
212 TypeVec.erase(TypeVec.begin()+i--);
213 MadeChange = true;
216 // If we removed all of our types, we have a type contradiction.
217 if (!TypeVec.empty())
218 return MadeChange;
220 // FIXME: Really want an SMLoc here!
221 TP.error("Type inference contradiction found, merging '" +
222 InVT.getName() + "' into '" + InputSet.getName() + "'");
223 return true; // unreachable
226 /// EnforceInteger - Remove all non-integer types from this set.
227 bool EEVT::TypeSet::EnforceInteger(TreePattern &TP) {
228 // If we know nothing, then get the full set.
229 if (TypeVec.empty())
230 return FillWithPossibleTypes(TP, isInteger, "integer");
231 if (!hasFloatingPointTypes())
232 return false;
234 TypeSet InputSet(*this);
236 // Filter out all the fp types.
237 for (unsigned i = 0; i != TypeVec.size(); ++i)
238 if (!isInteger(TypeVec[i]))
239 TypeVec.erase(TypeVec.begin()+i--);
241 if (TypeVec.empty())
242 TP.error("Type inference contradiction found, '" +
243 InputSet.getName() + "' needs to be integer");
244 return true;
247 /// EnforceFloatingPoint - Remove all integer types from this set.
248 bool EEVT::TypeSet::EnforceFloatingPoint(TreePattern &TP) {
249 // If we know nothing, then get the full set.
250 if (TypeVec.empty())
251 return FillWithPossibleTypes(TP, isFloatingPoint, "floating point");
253 if (!hasIntegerTypes())
254 return false;
256 TypeSet InputSet(*this);
258 // Filter out all the fp types.
259 for (unsigned i = 0; i != TypeVec.size(); ++i)
260 if (!isFloatingPoint(TypeVec[i]))
261 TypeVec.erase(TypeVec.begin()+i--);
263 if (TypeVec.empty())
264 TP.error("Type inference contradiction found, '" +
265 InputSet.getName() + "' needs to be floating point");
266 return true;
269 /// EnforceScalar - Remove all vector types from this.
270 bool EEVT::TypeSet::EnforceScalar(TreePattern &TP) {
271 // If we know nothing, then get the full set.
272 if (TypeVec.empty())
273 return FillWithPossibleTypes(TP, isScalar, "scalar");
275 if (!hasVectorTypes())
276 return false;
278 TypeSet InputSet(*this);
280 // Filter out all the vector types.
281 for (unsigned i = 0; i != TypeVec.size(); ++i)
282 if (!isScalar(TypeVec[i]))
283 TypeVec.erase(TypeVec.begin()+i--);
285 if (TypeVec.empty())
286 TP.error("Type inference contradiction found, '" +
287 InputSet.getName() + "' needs to be scalar");
288 return true;
291 /// EnforceVector - Remove all vector types from this.
292 bool EEVT::TypeSet::EnforceVector(TreePattern &TP) {
293 // If we know nothing, then get the full set.
294 if (TypeVec.empty())
295 return FillWithPossibleTypes(TP, isVector, "vector");
297 TypeSet InputSet(*this);
298 bool MadeChange = false;
300 // Filter out all the scalar types.
301 for (unsigned i = 0; i != TypeVec.size(); ++i)
302 if (!isVector(TypeVec[i])) {
303 TypeVec.erase(TypeVec.begin()+i--);
304 MadeChange = true;
307 if (TypeVec.empty())
308 TP.error("Type inference contradiction found, '" +
309 InputSet.getName() + "' needs to be a vector");
310 return MadeChange;
315 /// EnforceSmallerThan - 'this' must be a smaller VT than Other. Update
316 /// this an other based on this information.
317 bool EEVT::TypeSet::EnforceSmallerThan(EEVT::TypeSet &Other, TreePattern &TP) {
318 // Both operands must be integer or FP, but we don't care which.
319 bool MadeChange = false;
321 if (isCompletelyUnknown())
322 MadeChange = FillWithPossibleTypes(TP);
324 if (Other.isCompletelyUnknown())
325 MadeChange = Other.FillWithPossibleTypes(TP);
327 // If one side is known to be integer or known to be FP but the other side has
328 // no information, get at least the type integrality info in there.
329 if (!hasFloatingPointTypes())
330 MadeChange |= Other.EnforceInteger(TP);
331 else if (!hasIntegerTypes())
332 MadeChange |= Other.EnforceFloatingPoint(TP);
333 if (!Other.hasFloatingPointTypes())
334 MadeChange |= EnforceInteger(TP);
335 else if (!Other.hasIntegerTypes())
336 MadeChange |= EnforceFloatingPoint(TP);
338 assert(!isCompletelyUnknown() && !Other.isCompletelyUnknown() &&
339 "Should have a type list now");
341 // If one contains vectors but the other doesn't pull vectors out.
342 if (!hasVectorTypes())
343 MadeChange |= Other.EnforceScalar(TP);
344 if (!hasVectorTypes())
345 MadeChange |= EnforceScalar(TP);
347 if (TypeVec.size() == 1 && Other.TypeVec.size() == 1) {
348 // If we are down to concrete types, this code does not currently
349 // handle nodes which have multiple types, where some types are
350 // integer, and some are fp. Assert that this is not the case.
351 assert(!(hasIntegerTypes() && hasFloatingPointTypes()) &&
352 !(Other.hasIntegerTypes() && Other.hasFloatingPointTypes()) &&
353 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
355 // Otherwise, if these are both vector types, either this vector
356 // must have a larger bitsize than the other, or this element type
357 // must be larger than the other.
358 EVT Type(TypeVec[0]);
359 EVT OtherType(Other.TypeVec[0]);
361 if (hasVectorTypes() && Other.hasVectorTypes()) {
362 if (Type.getSizeInBits() >= OtherType.getSizeInBits())
363 if (Type.getVectorElementType().getSizeInBits()
364 >= OtherType.getVectorElementType().getSizeInBits())
365 TP.error("Type inference contradiction found, '" +
366 getName() + "' element type not smaller than '" +
367 Other.getName() +"'!");
369 else
370 // For scalar types, the bitsize of this type must be larger
371 // than that of the other.
372 if (Type.getSizeInBits() >= OtherType.getSizeInBits())
373 TP.error("Type inference contradiction found, '" +
374 getName() + "' is not smaller than '" +
375 Other.getName() +"'!");
380 // Handle int and fp as disjoint sets. This won't work for patterns
381 // that have mixed fp/int types but those are likely rare and would
382 // not have been accepted by this code previously.
384 // Okay, find the smallest type from the current set and remove it from the
385 // largest set.
386 MVT::SimpleValueType SmallestInt = MVT::LAST_VALUETYPE;
387 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
388 if (isInteger(TypeVec[i])) {
389 SmallestInt = TypeVec[i];
390 break;
392 for (unsigned i = 1, e = TypeVec.size(); i != e; ++i)
393 if (isInteger(TypeVec[i]) && TypeVec[i] < SmallestInt)
394 SmallestInt = TypeVec[i];
396 MVT::SimpleValueType SmallestFP = MVT::LAST_VALUETYPE;
397 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
398 if (isFloatingPoint(TypeVec[i])) {
399 SmallestFP = TypeVec[i];
400 break;
402 for (unsigned i = 1, e = TypeVec.size(); i != e; ++i)
403 if (isFloatingPoint(TypeVec[i]) && TypeVec[i] < SmallestFP)
404 SmallestFP = TypeVec[i];
406 int OtherIntSize = 0;
407 int OtherFPSize = 0;
408 for (SmallVector<MVT::SimpleValueType, 2>::iterator TVI =
409 Other.TypeVec.begin();
410 TVI != Other.TypeVec.end();
411 /* NULL */) {
412 if (isInteger(*TVI)) {
413 ++OtherIntSize;
414 if (*TVI == SmallestInt) {
415 TVI = Other.TypeVec.erase(TVI);
416 --OtherIntSize;
417 MadeChange = true;
418 continue;
421 else if (isFloatingPoint(*TVI)) {
422 ++OtherFPSize;
423 if (*TVI == SmallestFP) {
424 TVI = Other.TypeVec.erase(TVI);
425 --OtherFPSize;
426 MadeChange = true;
427 continue;
430 ++TVI;
433 // If this is the only type in the large set, the constraint can never be
434 // satisfied.
435 if ((Other.hasIntegerTypes() && OtherIntSize == 0)
436 || (Other.hasFloatingPointTypes() && OtherFPSize == 0))
437 TP.error("Type inference contradiction found, '" +
438 Other.getName() + "' has nothing larger than '" + getName() +"'!");
440 // Okay, find the largest type in the Other set and remove it from the
441 // current set.
442 MVT::SimpleValueType LargestInt = MVT::Other;
443 for (unsigned i = 0, e = Other.TypeVec.size(); i != e; ++i)
444 if (isInteger(Other.TypeVec[i])) {
445 LargestInt = Other.TypeVec[i];
446 break;
448 for (unsigned i = 1, e = Other.TypeVec.size(); i != e; ++i)
449 if (isInteger(Other.TypeVec[i]) && Other.TypeVec[i] > LargestInt)
450 LargestInt = Other.TypeVec[i];
452 MVT::SimpleValueType LargestFP = MVT::Other;
453 for (unsigned i = 0, e = Other.TypeVec.size(); i != e; ++i)
454 if (isFloatingPoint(Other.TypeVec[i])) {
455 LargestFP = Other.TypeVec[i];
456 break;
458 for (unsigned i = 1, e = Other.TypeVec.size(); i != e; ++i)
459 if (isFloatingPoint(Other.TypeVec[i]) && Other.TypeVec[i] > LargestFP)
460 LargestFP = Other.TypeVec[i];
462 int IntSize = 0;
463 int FPSize = 0;
464 for (SmallVector<MVT::SimpleValueType, 2>::iterator TVI =
465 TypeVec.begin();
466 TVI != TypeVec.end();
467 /* NULL */) {
468 if (isInteger(*TVI)) {
469 ++IntSize;
470 if (*TVI == LargestInt) {
471 TVI = TypeVec.erase(TVI);
472 --IntSize;
473 MadeChange = true;
474 continue;
477 else if (isFloatingPoint(*TVI)) {
478 ++FPSize;
479 if (*TVI == LargestFP) {
480 TVI = TypeVec.erase(TVI);
481 --FPSize;
482 MadeChange = true;
483 continue;
486 ++TVI;
489 // If this is the only type in the small set, the constraint can never be
490 // satisfied.
491 if ((hasIntegerTypes() && IntSize == 0)
492 || (hasFloatingPointTypes() && FPSize == 0))
493 TP.error("Type inference contradiction found, '" +
494 getName() + "' has nothing smaller than '" + Other.getName()+"'!");
496 return MadeChange;
499 /// EnforceVectorEltTypeIs - 'this' is now constrainted to be a vector type
500 /// whose element is specified by VTOperand.
501 bool EEVT::TypeSet::EnforceVectorEltTypeIs(EEVT::TypeSet &VTOperand,
502 TreePattern &TP) {
503 // "This" must be a vector and "VTOperand" must be a scalar.
504 bool MadeChange = false;
505 MadeChange |= EnforceVector(TP);
506 MadeChange |= VTOperand.EnforceScalar(TP);
508 // If we know the vector type, it forces the scalar to agree.
509 if (isConcrete()) {
510 EVT IVT = getConcrete();
511 IVT = IVT.getVectorElementType();
512 return MadeChange |
513 VTOperand.MergeInTypeInfo(IVT.getSimpleVT().SimpleTy, TP);
516 // If the scalar type is known, filter out vector types whose element types
517 // disagree.
518 if (!VTOperand.isConcrete())
519 return MadeChange;
521 MVT::SimpleValueType VT = VTOperand.getConcrete();
523 TypeSet InputSet(*this);
525 // Filter out all the types which don't have the right element type.
526 for (unsigned i = 0; i != TypeVec.size(); ++i) {
527 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
528 if (EVT(TypeVec[i]).getVectorElementType().getSimpleVT().SimpleTy != VT) {
529 TypeVec.erase(TypeVec.begin()+i--);
530 MadeChange = true;
534 if (TypeVec.empty()) // FIXME: Really want an SMLoc here!
535 TP.error("Type inference contradiction found, forcing '" +
536 InputSet.getName() + "' to have a vector element");
537 return MadeChange;
540 /// EnforceVectorSubVectorTypeIs - 'this' is now constrainted to be a
541 /// vector type specified by VTOperand.
542 bool EEVT::TypeSet::EnforceVectorSubVectorTypeIs(EEVT::TypeSet &VTOperand,
543 TreePattern &TP) {
544 // "This" must be a vector and "VTOperand" must be a vector.
545 bool MadeChange = false;
546 MadeChange |= EnforceVector(TP);
547 MadeChange |= VTOperand.EnforceVector(TP);
549 // "This" must be larger than "VTOperand."
550 MadeChange |= VTOperand.EnforceSmallerThan(*this, TP);
552 // If we know the vector type, it forces the scalar types to agree.
553 if (isConcrete()) {
554 EVT IVT = getConcrete();
555 IVT = IVT.getVectorElementType();
557 EEVT::TypeSet EltTypeSet(IVT.getSimpleVT().SimpleTy, TP);
558 MadeChange |= VTOperand.EnforceVectorEltTypeIs(EltTypeSet, TP);
559 } else if (VTOperand.isConcrete()) {
560 EVT IVT = VTOperand.getConcrete();
561 IVT = IVT.getVectorElementType();
563 EEVT::TypeSet EltTypeSet(IVT.getSimpleVT().SimpleTy, TP);
564 MadeChange |= EnforceVectorEltTypeIs(EltTypeSet, TP);
567 return MadeChange;
570 //===----------------------------------------------------------------------===//
571 // Helpers for working with extended types.
573 bool RecordPtrCmp::operator()(const Record *LHS, const Record *RHS) const {
574 return LHS->getID() < RHS->getID();
577 /// Dependent variable map for CodeGenDAGPattern variant generation
578 typedef std::map<std::string, int> DepVarMap;
580 /// Const iterator shorthand for DepVarMap
581 typedef DepVarMap::const_iterator DepVarMap_citer;
583 namespace {
584 void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
585 if (N->isLeaf()) {
586 if (dynamic_cast<DefInit*>(N->getLeafValue()) != NULL) {
587 DepMap[N->getName()]++;
589 } else {
590 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
591 FindDepVarsOf(N->getChild(i), DepMap);
595 //! Find dependent variables within child patterns
598 void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
599 DepVarMap depcounts;
600 FindDepVarsOf(N, depcounts);
601 for (DepVarMap_citer i = depcounts.begin(); i != depcounts.end(); ++i) {
602 if (i->second > 1) { // std::pair<std::string, int>
603 DepVars.insert(i->first);
608 //! Dump the dependent variable set:
609 #ifndef NDEBUG
610 void DumpDepVars(MultipleUseVarSet &DepVars) {
611 if (DepVars.empty()) {
612 DEBUG(errs() << "<empty set>");
613 } else {
614 DEBUG(errs() << "[ ");
615 for (MultipleUseVarSet::const_iterator i = DepVars.begin(),
616 e = DepVars.end(); i != e; ++i) {
617 DEBUG(errs() << (*i) << " ");
619 DEBUG(errs() << "]");
622 #endif
626 //===----------------------------------------------------------------------===//
627 // PatternToMatch implementation
631 /// getPatternSize - Return the 'size' of this pattern. We want to match large
632 /// patterns before small ones. This is used to determine the size of a
633 /// pattern.
634 static unsigned getPatternSize(const TreePatternNode *P,
635 const CodeGenDAGPatterns &CGP) {
636 unsigned Size = 3; // The node itself.
637 // If the root node is a ConstantSDNode, increases its size.
638 // e.g. (set R32:$dst, 0).
639 if (P->isLeaf() && dynamic_cast<IntInit*>(P->getLeafValue()))
640 Size += 2;
642 // FIXME: This is a hack to statically increase the priority of patterns
643 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
644 // Later we can allow complexity / cost for each pattern to be (optionally)
645 // specified. To get best possible pattern match we'll need to dynamically
646 // calculate the complexity of all patterns a dag can potentially map to.
647 const ComplexPattern *AM = P->getComplexPatternInfo(CGP);
648 if (AM)
649 Size += AM->getNumOperands() * 3;
651 // If this node has some predicate function that must match, it adds to the
652 // complexity of this node.
653 if (!P->getPredicateFns().empty())
654 ++Size;
656 // Count children in the count if they are also nodes.
657 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
658 TreePatternNode *Child = P->getChild(i);
659 if (!Child->isLeaf() && Child->getNumTypes() &&
660 Child->getType(0) != MVT::Other)
661 Size += getPatternSize(Child, CGP);
662 else if (Child->isLeaf()) {
663 if (dynamic_cast<IntInit*>(Child->getLeafValue()))
664 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
665 else if (Child->getComplexPatternInfo(CGP))
666 Size += getPatternSize(Child, CGP);
667 else if (!Child->getPredicateFns().empty())
668 ++Size;
672 return Size;
675 /// Compute the complexity metric for the input pattern. This roughly
676 /// corresponds to the number of nodes that are covered.
677 unsigned PatternToMatch::
678 getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
679 return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();
683 /// getPredicateCheck - Return a single string containing all of this
684 /// pattern's predicates concatenated with "&&" operators.
686 std::string PatternToMatch::getPredicateCheck() const {
687 std::string PredicateCheck;
688 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
689 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
690 Record *Def = Pred->getDef();
691 if (!Def->isSubClassOf("Predicate")) {
692 #ifndef NDEBUG
693 Def->dump();
694 #endif
695 assert(0 && "Unknown predicate type!");
697 if (!PredicateCheck.empty())
698 PredicateCheck += " && ";
699 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
703 return PredicateCheck;
706 //===----------------------------------------------------------------------===//
707 // SDTypeConstraint implementation
710 SDTypeConstraint::SDTypeConstraint(Record *R) {
711 OperandNo = R->getValueAsInt("OperandNum");
713 if (R->isSubClassOf("SDTCisVT")) {
714 ConstraintType = SDTCisVT;
715 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
716 if (x.SDTCisVT_Info.VT == MVT::isVoid)
717 throw TGError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
719 } else if (R->isSubClassOf("SDTCisPtrTy")) {
720 ConstraintType = SDTCisPtrTy;
721 } else if (R->isSubClassOf("SDTCisInt")) {
722 ConstraintType = SDTCisInt;
723 } else if (R->isSubClassOf("SDTCisFP")) {
724 ConstraintType = SDTCisFP;
725 } else if (R->isSubClassOf("SDTCisVec")) {
726 ConstraintType = SDTCisVec;
727 } else if (R->isSubClassOf("SDTCisSameAs")) {
728 ConstraintType = SDTCisSameAs;
729 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
730 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
731 ConstraintType = SDTCisVTSmallerThanOp;
732 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
733 R->getValueAsInt("OtherOperandNum");
734 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
735 ConstraintType = SDTCisOpSmallerThanOp;
736 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
737 R->getValueAsInt("BigOperandNum");
738 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
739 ConstraintType = SDTCisEltOfVec;
740 x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
741 } else if (R->isSubClassOf("SDTCisSubVecOfVec")) {
742 ConstraintType = SDTCisSubVecOfVec;
743 x.SDTCisSubVecOfVec_Info.OtherOperandNum =
744 R->getValueAsInt("OtherOpNum");
745 } else {
746 errs() << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
747 exit(1);
751 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
752 /// N, and the result number in ResNo.
753 static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
754 const SDNodeInfo &NodeInfo,
755 unsigned &ResNo) {
756 unsigned NumResults = NodeInfo.getNumResults();
757 if (OpNo < NumResults) {
758 ResNo = OpNo;
759 return N;
762 OpNo -= NumResults;
764 if (OpNo >= N->getNumChildren()) {
765 errs() << "Invalid operand number in type constraint "
766 << (OpNo+NumResults) << " ";
767 N->dump();
768 errs() << '\n';
769 exit(1);
772 return N->getChild(OpNo);
775 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
776 /// constraint to the nodes operands. This returns true if it makes a
777 /// change, false otherwise. If a type contradiction is found, throw an
778 /// exception.
779 bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
780 const SDNodeInfo &NodeInfo,
781 TreePattern &TP) const {
782 unsigned ResNo = 0; // The result number being referenced.
783 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
785 switch (ConstraintType) {
786 default: assert(0 && "Unknown constraint type!");
787 case SDTCisVT:
788 // Operand must be a particular type.
789 return NodeToApply->UpdateNodeType(ResNo, x.SDTCisVT_Info.VT, TP);
790 case SDTCisPtrTy:
791 // Operand must be same as target pointer type.
792 return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
793 case SDTCisInt:
794 // Require it to be one of the legal integer VTs.
795 return NodeToApply->getExtType(ResNo).EnforceInteger(TP);
796 case SDTCisFP:
797 // Require it to be one of the legal fp VTs.
798 return NodeToApply->getExtType(ResNo).EnforceFloatingPoint(TP);
799 case SDTCisVec:
800 // Require it to be one of the legal vector VTs.
801 return NodeToApply->getExtType(ResNo).EnforceVector(TP);
802 case SDTCisSameAs: {
803 unsigned OResNo = 0;
804 TreePatternNode *OtherNode =
805 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
806 return NodeToApply->UpdateNodeType(OResNo, OtherNode->getExtType(ResNo),TP)|
807 OtherNode->UpdateNodeType(ResNo,NodeToApply->getExtType(OResNo),TP);
809 case SDTCisVTSmallerThanOp: {
810 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
811 // have an integer type that is smaller than the VT.
812 if (!NodeToApply->isLeaf() ||
813 !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
814 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
815 ->isSubClassOf("ValueType"))
816 TP.error(N->getOperator()->getName() + " expects a VT operand!");
817 MVT::SimpleValueType VT =
818 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
820 EEVT::TypeSet TypeListTmp(VT, TP);
822 unsigned OResNo = 0;
823 TreePatternNode *OtherNode =
824 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
825 OResNo);
827 return TypeListTmp.EnforceSmallerThan(OtherNode->getExtType(OResNo), TP);
829 case SDTCisOpSmallerThanOp: {
830 unsigned BResNo = 0;
831 TreePatternNode *BigOperand =
832 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
833 BResNo);
834 return NodeToApply->getExtType(ResNo).
835 EnforceSmallerThan(BigOperand->getExtType(BResNo), TP);
837 case SDTCisEltOfVec: {
838 unsigned VResNo = 0;
839 TreePatternNode *VecOperand =
840 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
841 VResNo);
843 // Filter vector types out of VecOperand that don't have the right element
844 // type.
845 return VecOperand->getExtType(VResNo).
846 EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), TP);
848 case SDTCisSubVecOfVec: {
849 unsigned VResNo = 0;
850 TreePatternNode *BigVecOperand =
851 getOperandNum(x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo,
852 VResNo);
854 // Filter vector types out of BigVecOperand that don't have the
855 // right subvector type.
856 return BigVecOperand->getExtType(VResNo).
857 EnforceVectorSubVectorTypeIs(NodeToApply->getExtType(ResNo), TP);
860 return false;
863 //===----------------------------------------------------------------------===//
864 // SDNodeInfo implementation
866 SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
867 EnumName = R->getValueAsString("Opcode");
868 SDClassName = R->getValueAsString("SDClass");
869 Record *TypeProfile = R->getValueAsDef("TypeProfile");
870 NumResults = TypeProfile->getValueAsInt("NumResults");
871 NumOperands = TypeProfile->getValueAsInt("NumOperands");
873 // Parse the properties.
874 Properties = 0;
875 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
876 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
877 if (PropList[i]->getName() == "SDNPCommutative") {
878 Properties |= 1 << SDNPCommutative;
879 } else if (PropList[i]->getName() == "SDNPAssociative") {
880 Properties |= 1 << SDNPAssociative;
881 } else if (PropList[i]->getName() == "SDNPHasChain") {
882 Properties |= 1 << SDNPHasChain;
883 } else if (PropList[i]->getName() == "SDNPOutGlue") {
884 Properties |= 1 << SDNPOutGlue;
885 } else if (PropList[i]->getName() == "SDNPInGlue") {
886 Properties |= 1 << SDNPInGlue;
887 } else if (PropList[i]->getName() == "SDNPOptInGlue") {
888 Properties |= 1 << SDNPOptInGlue;
889 } else if (PropList[i]->getName() == "SDNPMayStore") {
890 Properties |= 1 << SDNPMayStore;
891 } else if (PropList[i]->getName() == "SDNPMayLoad") {
892 Properties |= 1 << SDNPMayLoad;
893 } else if (PropList[i]->getName() == "SDNPSideEffect") {
894 Properties |= 1 << SDNPSideEffect;
895 } else if (PropList[i]->getName() == "SDNPMemOperand") {
896 Properties |= 1 << SDNPMemOperand;
897 } else if (PropList[i]->getName() == "SDNPVariadic") {
898 Properties |= 1 << SDNPVariadic;
899 } else {
900 errs() << "Unknown SD Node property '" << PropList[i]->getName()
901 << "' on node '" << R->getName() << "'!\n";
902 exit(1);
907 // Parse the type constraints.
908 std::vector<Record*> ConstraintList =
909 TypeProfile->getValueAsListOfDefs("Constraints");
910 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
913 /// getKnownType - If the type constraints on this node imply a fixed type
914 /// (e.g. all stores return void, etc), then return it as an
915 /// MVT::SimpleValueType. Otherwise, return EEVT::Other.
916 MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
917 unsigned NumResults = getNumResults();
918 assert(NumResults <= 1 &&
919 "We only work with nodes with zero or one result so far!");
920 assert(ResNo == 0 && "Only handles single result nodes so far");
922 for (unsigned i = 0, e = TypeConstraints.size(); i != e; ++i) {
923 // Make sure that this applies to the correct node result.
924 if (TypeConstraints[i].OperandNo >= NumResults) // FIXME: need value #
925 continue;
927 switch (TypeConstraints[i].ConstraintType) {
928 default: break;
929 case SDTypeConstraint::SDTCisVT:
930 return TypeConstraints[i].x.SDTCisVT_Info.VT;
931 case SDTypeConstraint::SDTCisPtrTy:
932 return MVT::iPTR;
935 return MVT::Other;
938 //===----------------------------------------------------------------------===//
939 // TreePatternNode implementation
942 TreePatternNode::~TreePatternNode() {
943 #if 0 // FIXME: implement refcounted tree nodes!
944 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
945 delete getChild(i);
946 #endif
949 static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
950 if (Operator->getName() == "set" ||
951 Operator->getName() == "implicit")
952 return 0; // All return nothing.
954 if (Operator->isSubClassOf("Intrinsic"))
955 return CDP.getIntrinsic(Operator).IS.RetVTs.size();
957 if (Operator->isSubClassOf("SDNode"))
958 return CDP.getSDNodeInfo(Operator).getNumResults();
960 if (Operator->isSubClassOf("PatFrag")) {
961 // If we've already parsed this pattern fragment, get it. Otherwise, handle
962 // the forward reference case where one pattern fragment references another
963 // before it is processed.
964 if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator))
965 return PFRec->getOnlyTree()->getNumTypes();
967 // Get the result tree.
968 DagInit *Tree = Operator->getValueAsDag("Fragment");
969 Record *Op = 0;
970 if (Tree && dynamic_cast<DefInit*>(Tree->getOperator()))
971 Op = dynamic_cast<DefInit*>(Tree->getOperator())->getDef();
972 assert(Op && "Invalid Fragment");
973 return GetNumNodeResults(Op, CDP);
976 if (Operator->isSubClassOf("Instruction")) {
977 CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
979 // FIXME: Should allow access to all the results here.
980 unsigned NumDefsToAdd = InstInfo.Operands.NumDefs ? 1 : 0;
982 // Add on one implicit def if it has a resolvable type.
983 if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
984 ++NumDefsToAdd;
985 return NumDefsToAdd;
988 if (Operator->isSubClassOf("SDNodeXForm"))
989 return 1; // FIXME: Generalize SDNodeXForm
991 Operator->dump();
992 errs() << "Unhandled node in GetNumNodeResults\n";
993 exit(1);
996 void TreePatternNode::print(raw_ostream &OS) const {
997 if (isLeaf())
998 OS << *getLeafValue();
999 else
1000 OS << '(' << getOperator()->getName();
1002 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1003 OS << ':' << getExtType(i).getName();
1005 if (!isLeaf()) {
1006 if (getNumChildren() != 0) {
1007 OS << " ";
1008 getChild(0)->print(OS);
1009 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
1010 OS << ", ";
1011 getChild(i)->print(OS);
1014 OS << ")";
1017 for (unsigned i = 0, e = PredicateFns.size(); i != e; ++i)
1018 OS << "<<P:" << PredicateFns[i] << ">>";
1019 if (TransformFn)
1020 OS << "<<X:" << TransformFn->getName() << ">>";
1021 if (!getName().empty())
1022 OS << ":$" << getName();
1025 void TreePatternNode::dump() const {
1026 print(errs());
1029 /// isIsomorphicTo - Return true if this node is recursively
1030 /// isomorphic to the specified node. For this comparison, the node's
1031 /// entire state is considered. The assigned name is ignored, since
1032 /// nodes with differing names are considered isomorphic. However, if
1033 /// the assigned name is present in the dependent variable set, then
1034 /// the assigned name is considered significant and the node is
1035 /// isomorphic if the names match.
1036 bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
1037 const MultipleUseVarSet &DepVars) const {
1038 if (N == this) return true;
1039 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
1040 getPredicateFns() != N->getPredicateFns() ||
1041 getTransformFn() != N->getTransformFn())
1042 return false;
1044 if (isLeaf()) {
1045 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
1046 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue())) {
1047 return ((DI->getDef() == NDI->getDef())
1048 && (DepVars.find(getName()) == DepVars.end()
1049 || getName() == N->getName()));
1052 return getLeafValue() == N->getLeafValue();
1055 if (N->getOperator() != getOperator() ||
1056 N->getNumChildren() != getNumChildren()) return false;
1057 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1058 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
1059 return false;
1060 return true;
1063 /// clone - Make a copy of this tree and all of its children.
1065 TreePatternNode *TreePatternNode::clone() const {
1066 TreePatternNode *New;
1067 if (isLeaf()) {
1068 New = new TreePatternNode(getLeafValue(), getNumTypes());
1069 } else {
1070 std::vector<TreePatternNode*> CChildren;
1071 CChildren.reserve(Children.size());
1072 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1073 CChildren.push_back(getChild(i)->clone());
1074 New = new TreePatternNode(getOperator(), CChildren, getNumTypes());
1076 New->setName(getName());
1077 New->Types = Types;
1078 New->setPredicateFns(getPredicateFns());
1079 New->setTransformFn(getTransformFn());
1080 return New;
1083 /// RemoveAllTypes - Recursively strip all the types of this tree.
1084 void TreePatternNode::RemoveAllTypes() {
1085 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1086 Types[i] = EEVT::TypeSet(); // Reset to unknown type.
1087 if (isLeaf()) return;
1088 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1089 getChild(i)->RemoveAllTypes();
1093 /// SubstituteFormalArguments - Replace the formal arguments in this tree
1094 /// with actual values specified by ArgMap.
1095 void TreePatternNode::
1096 SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
1097 if (isLeaf()) return;
1099 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1100 TreePatternNode *Child = getChild(i);
1101 if (Child->isLeaf()) {
1102 Init *Val = Child->getLeafValue();
1103 if (dynamic_cast<DefInit*>(Val) &&
1104 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
1105 // We found a use of a formal argument, replace it with its value.
1106 TreePatternNode *NewChild = ArgMap[Child->getName()];
1107 assert(NewChild && "Couldn't find formal argument!");
1108 assert((Child->getPredicateFns().empty() ||
1109 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1110 "Non-empty child predicate clobbered!");
1111 setChild(i, NewChild);
1113 } else {
1114 getChild(i)->SubstituteFormalArguments(ArgMap);
1120 /// InlinePatternFragments - If this pattern refers to any pattern
1121 /// fragments, inline them into place, giving us a pattern without any
1122 /// PatFrag references.
1123 TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
1124 if (isLeaf()) return this; // nothing to do.
1125 Record *Op = getOperator();
1127 if (!Op->isSubClassOf("PatFrag")) {
1128 // Just recursively inline children nodes.
1129 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1130 TreePatternNode *Child = getChild(i);
1131 TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
1133 assert((Child->getPredicateFns().empty() ||
1134 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1135 "Non-empty child predicate clobbered!");
1137 setChild(i, NewChild);
1139 return this;
1142 // Otherwise, we found a reference to a fragment. First, look up its
1143 // TreePattern record.
1144 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
1146 // Verify that we are passing the right number of operands.
1147 if (Frag->getNumArgs() != Children.size())
1148 TP.error("'" + Op->getName() + "' fragment requires " +
1149 utostr(Frag->getNumArgs()) + " operands!");
1151 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
1153 std::string Code = Op->getValueAsCode("Predicate");
1154 if (!Code.empty())
1155 FragTree->addPredicateFn("Predicate_"+Op->getName());
1157 // Resolve formal arguments to their actual value.
1158 if (Frag->getNumArgs()) {
1159 // Compute the map of formal to actual arguments.
1160 std::map<std::string, TreePatternNode*> ArgMap;
1161 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
1162 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
1164 FragTree->SubstituteFormalArguments(ArgMap);
1167 FragTree->setName(getName());
1168 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1169 FragTree->UpdateNodeType(i, getExtType(i), TP);
1171 // Transfer in the old predicates.
1172 for (unsigned i = 0, e = getPredicateFns().size(); i != e; ++i)
1173 FragTree->addPredicateFn(getPredicateFns()[i]);
1175 // Get a new copy of this fragment to stitch into here.
1176 //delete this; // FIXME: implement refcounting!
1178 // The fragment we inlined could have recursive inlining that is needed. See
1179 // if there are any pattern fragments in it and inline them as needed.
1180 return FragTree->InlinePatternFragments(TP);
1183 /// getImplicitType - Check to see if the specified record has an implicit
1184 /// type which should be applied to it. This will infer the type of register
1185 /// references from the register file information, for example.
1187 static EEVT::TypeSet getImplicitType(Record *R, unsigned ResNo,
1188 bool NotRegisters, TreePattern &TP) {
1189 // Check to see if this is a register or a register class.
1190 if (R->isSubClassOf("RegisterClass")) {
1191 assert(ResNo == 0 && "Regclass ref only has one result!");
1192 if (NotRegisters)
1193 return EEVT::TypeSet(); // Unknown.
1194 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1195 return EEVT::TypeSet(T.getRegisterClass(R).getValueTypes());
1198 if (R->isSubClassOf("PatFrag")) {
1199 assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
1200 // Pattern fragment types will be resolved when they are inlined.
1201 return EEVT::TypeSet(); // Unknown.
1204 if (R->isSubClassOf("Register")) {
1205 assert(ResNo == 0 && "Registers only produce one result!");
1206 if (NotRegisters)
1207 return EEVT::TypeSet(); // Unknown.
1208 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1209 return EEVT::TypeSet(T.getRegisterVTs(R));
1212 if (R->isSubClassOf("SubRegIndex")) {
1213 assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
1214 return EEVT::TypeSet();
1217 if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
1218 assert(ResNo == 0 && "This node only has one result!");
1219 // Using a VTSDNode or CondCodeSDNode.
1220 return EEVT::TypeSet(MVT::Other, TP);
1223 if (R->isSubClassOf("ComplexPattern")) {
1224 assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
1225 if (NotRegisters)
1226 return EEVT::TypeSet(); // Unknown.
1227 return EEVT::TypeSet(TP.getDAGPatterns().getComplexPattern(R).getValueType(),
1228 TP);
1230 if (R->isSubClassOf("PointerLikeRegClass")) {
1231 assert(ResNo == 0 && "Regclass can only have one result!");
1232 return EEVT::TypeSet(MVT::iPTR, TP);
1235 if (R->getName() == "node" || R->getName() == "srcvalue" ||
1236 R->getName() == "zero_reg") {
1237 // Placeholder.
1238 return EEVT::TypeSet(); // Unknown.
1241 TP.error("Unknown node flavor used in pattern: " + R->getName());
1242 return EEVT::TypeSet(MVT::Other, TP);
1246 /// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
1247 /// CodeGenIntrinsic information for it, otherwise return a null pointer.
1248 const CodeGenIntrinsic *TreePatternNode::
1249 getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
1250 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
1251 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
1252 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
1253 return 0;
1255 unsigned IID =
1256 dynamic_cast<IntInit*>(getChild(0)->getLeafValue())->getValue();
1257 return &CDP.getIntrinsicInfo(IID);
1260 /// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
1261 /// return the ComplexPattern information, otherwise return null.
1262 const ComplexPattern *
1263 TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
1264 if (!isLeaf()) return 0;
1266 DefInit *DI = dynamic_cast<DefInit*>(getLeafValue());
1267 if (DI && DI->getDef()->isSubClassOf("ComplexPattern"))
1268 return &CGP.getComplexPattern(DI->getDef());
1269 return 0;
1272 /// NodeHasProperty - Return true if this node has the specified property.
1273 bool TreePatternNode::NodeHasProperty(SDNP Property,
1274 const CodeGenDAGPatterns &CGP) const {
1275 if (isLeaf()) {
1276 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1277 return CP->hasProperty(Property);
1278 return false;
1281 Record *Operator = getOperator();
1282 if (!Operator->isSubClassOf("SDNode")) return false;
1284 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
1290 /// TreeHasProperty - Return true if any node in this tree has the specified
1291 /// property.
1292 bool TreePatternNode::TreeHasProperty(SDNP Property,
1293 const CodeGenDAGPatterns &CGP) const {
1294 if (NodeHasProperty(Property, CGP))
1295 return true;
1296 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1297 if (getChild(i)->TreeHasProperty(Property, CGP))
1298 return true;
1299 return false;
1302 /// isCommutativeIntrinsic - Return true if the node corresponds to a
1303 /// commutative intrinsic.
1304 bool
1305 TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
1306 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
1307 return Int->isCommutative;
1308 return false;
1312 /// ApplyTypeConstraints - Apply all of the type constraints relevant to
1313 /// this node and its children in the tree. This returns true if it makes a
1314 /// change, false otherwise. If a type contradiction is found, throw an
1315 /// exception.
1316 bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
1317 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
1318 if (isLeaf()) {
1319 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
1320 // If it's a regclass or something else known, include the type.
1321 bool MadeChange = false;
1322 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1323 MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
1324 NotRegisters, TP), TP);
1325 return MadeChange;
1328 if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
1329 assert(Types.size() == 1 && "Invalid IntInit");
1331 // Int inits are always integers. :)
1332 bool MadeChange = Types[0].EnforceInteger(TP);
1334 if (!Types[0].isConcrete())
1335 return MadeChange;
1337 MVT::SimpleValueType VT = getType(0);
1338 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
1339 return MadeChange;
1341 unsigned Size = EVT(VT).getSizeInBits();
1342 // Make sure that the value is representable for this type.
1343 if (Size >= 32) return MadeChange;
1345 int Val = (II->getValue() << (32-Size)) >> (32-Size);
1346 if (Val == II->getValue()) return MadeChange;
1348 // If sign-extended doesn't fit, does it fit as unsigned?
1349 unsigned ValueMask;
1350 unsigned UnsignedVal;
1351 ValueMask = unsigned(~uint32_t(0UL) >> (32-Size));
1352 UnsignedVal = unsigned(II->getValue());
1354 if ((ValueMask & UnsignedVal) == UnsignedVal)
1355 return MadeChange;
1357 TP.error("Integer value '" + itostr(II->getValue())+
1358 "' is out of range for type '" + getEnumName(getType(0)) + "'!");
1359 return MadeChange;
1361 return false;
1364 // special handling for set, which isn't really an SDNode.
1365 if (getOperator()->getName() == "set") {
1366 assert(getNumTypes() == 0 && "Set doesn't produce a value");
1367 assert(getNumChildren() >= 2 && "Missing RHS of a set?");
1368 unsigned NC = getNumChildren();
1370 TreePatternNode *SetVal = getChild(NC-1);
1371 bool MadeChange = SetVal->ApplyTypeConstraints(TP, NotRegisters);
1373 for (unsigned i = 0; i < NC-1; ++i) {
1374 TreePatternNode *Child = getChild(i);
1375 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
1377 // Types of operands must match.
1378 MadeChange |= Child->UpdateNodeType(0, SetVal->getExtType(i), TP);
1379 MadeChange |= SetVal->UpdateNodeType(i, Child->getExtType(0), TP);
1381 return MadeChange;
1384 if (getOperator()->getName() == "implicit") {
1385 assert(getNumTypes() == 0 && "Node doesn't produce a value");
1387 bool MadeChange = false;
1388 for (unsigned i = 0; i < getNumChildren(); ++i)
1389 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1390 return MadeChange;
1393 if (getOperator()->getName() == "COPY_TO_REGCLASS") {
1394 bool MadeChange = false;
1395 MadeChange |= getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1396 MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
1398 assert(getChild(0)->getNumTypes() == 1 &&
1399 getChild(1)->getNumTypes() == 1 && "Unhandled case");
1401 // child #1 of COPY_TO_REGCLASS should be a register class. We don't care
1402 // what type it gets, so if it didn't get a concrete type just give it the
1403 // first viable type from the reg class.
1404 if (!getChild(1)->hasTypeSet(0) &&
1405 !getChild(1)->getExtType(0).isCompletelyUnknown()) {
1406 MVT::SimpleValueType RCVT = getChild(1)->getExtType(0).getTypeList()[0];
1407 MadeChange |= getChild(1)->UpdateNodeType(0, RCVT, TP);
1409 return MadeChange;
1412 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
1413 bool MadeChange = false;
1415 // Apply the result type to the node.
1416 unsigned NumRetVTs = Int->IS.RetVTs.size();
1417 unsigned NumParamVTs = Int->IS.ParamVTs.size();
1419 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
1420 MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
1422 if (getNumChildren() != NumParamVTs + 1)
1423 TP.error("Intrinsic '" + Int->Name + "' expects " +
1424 utostr(NumParamVTs) + " operands, not " +
1425 utostr(getNumChildren() - 1) + " operands!");
1427 // Apply type info to the intrinsic ID.
1428 MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
1430 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
1431 MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
1433 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
1434 assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
1435 MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
1437 return MadeChange;
1440 if (getOperator()->isSubClassOf("SDNode")) {
1441 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
1443 // Check that the number of operands is sane. Negative operands -> varargs.
1444 if (NI.getNumOperands() >= 0 &&
1445 getNumChildren() != (unsigned)NI.getNumOperands())
1446 TP.error(getOperator()->getName() + " node requires exactly " +
1447 itostr(NI.getNumOperands()) + " operands!");
1449 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
1450 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1451 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1452 return MadeChange;
1455 if (getOperator()->isSubClassOf("Instruction")) {
1456 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
1457 CodeGenInstruction &InstInfo =
1458 CDP.getTargetInfo().getInstruction(getOperator());
1460 bool MadeChange = false;
1462 // Apply the result types to the node, these come from the things in the
1463 // (outs) list of the instruction.
1464 // FIXME: Cap at one result so far.
1465 unsigned NumResultsToAdd = InstInfo.Operands.NumDefs ? 1 : 0;
1466 for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo) {
1467 Record *ResultNode = Inst.getResult(ResNo);
1469 if (ResultNode->isSubClassOf("PointerLikeRegClass")) {
1470 MadeChange |= UpdateNodeType(ResNo, MVT::iPTR, TP);
1471 } else if (ResultNode->getName() == "unknown") {
1472 // Nothing to do.
1473 } else {
1474 assert(ResultNode->isSubClassOf("RegisterClass") &&
1475 "Operands should be register classes!");
1476 const CodeGenRegisterClass &RC =
1477 CDP.getTargetInfo().getRegisterClass(ResultNode);
1478 MadeChange |= UpdateNodeType(ResNo, RC.getValueTypes(), TP);
1482 // If the instruction has implicit defs, we apply the first one as a result.
1483 // FIXME: This sucks, it should apply all implicit defs.
1484 if (!InstInfo.ImplicitDefs.empty()) {
1485 unsigned ResNo = NumResultsToAdd;
1487 // FIXME: Generalize to multiple possible types and multiple possible
1488 // ImplicitDefs.
1489 MVT::SimpleValueType VT =
1490 InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
1492 if (VT != MVT::Other)
1493 MadeChange |= UpdateNodeType(ResNo, VT, TP);
1496 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
1497 // be the same.
1498 if (getOperator()->getName() == "INSERT_SUBREG") {
1499 assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
1500 MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
1501 MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
1504 unsigned ChildNo = 0;
1505 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
1506 Record *OperandNode = Inst.getOperand(i);
1508 // If the instruction expects a predicate or optional def operand, we
1509 // codegen this by setting the operand to it's default value if it has a
1510 // non-empty DefaultOps field.
1511 if ((OperandNode->isSubClassOf("PredicateOperand") ||
1512 OperandNode->isSubClassOf("OptionalDefOperand")) &&
1513 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1514 continue;
1516 // Verify that we didn't run out of provided operands.
1517 if (ChildNo >= getNumChildren())
1518 TP.error("Instruction '" + getOperator()->getName() +
1519 "' expects more operands than were provided.");
1521 MVT::SimpleValueType VT;
1522 TreePatternNode *Child = getChild(ChildNo++);
1523 unsigned ChildResNo = 0; // Instructions always use res #0 of their op.
1525 if (OperandNode->isSubClassOf("RegisterClass")) {
1526 const CodeGenRegisterClass &RC =
1527 CDP.getTargetInfo().getRegisterClass(OperandNode);
1528 MadeChange |= Child->UpdateNodeType(ChildResNo, RC.getValueTypes(), TP);
1529 } else if (OperandNode->isSubClassOf("Operand")) {
1530 VT = getValueType(OperandNode->getValueAsDef("Type"));
1531 MadeChange |= Child->UpdateNodeType(ChildResNo, VT, TP);
1532 } else if (OperandNode->isSubClassOf("PointerLikeRegClass")) {
1533 MadeChange |= Child->UpdateNodeType(ChildResNo, MVT::iPTR, TP);
1534 } else if (OperandNode->getName() == "unknown") {
1535 // Nothing to do.
1536 } else {
1537 assert(0 && "Unknown operand type!");
1538 abort();
1540 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
1543 if (ChildNo != getNumChildren())
1544 TP.error("Instruction '" + getOperator()->getName() +
1545 "' was provided too many operands!");
1547 return MadeChange;
1550 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
1552 // Node transforms always take one operand.
1553 if (getNumChildren() != 1)
1554 TP.error("Node transform '" + getOperator()->getName() +
1555 "' requires one operand!");
1557 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1560 // If either the output or input of the xform does not have exact
1561 // type info. We assume they must be the same. Otherwise, it is perfectly
1562 // legal to transform from one type to a completely different type.
1563 #if 0
1564 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
1565 bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
1566 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
1567 return MadeChange;
1569 #endif
1570 return MadeChange;
1573 /// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
1574 /// RHS of a commutative operation, not the on LHS.
1575 static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
1576 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
1577 return true;
1578 if (N->isLeaf() && dynamic_cast<IntInit*>(N->getLeafValue()))
1579 return true;
1580 return false;
1584 /// canPatternMatch - If it is impossible for this pattern to match on this
1585 /// target, fill in Reason and return false. Otherwise, return true. This is
1586 /// used as a sanity check for .td files (to prevent people from writing stuff
1587 /// that can never possibly work), and to prevent the pattern permuter from
1588 /// generating stuff that is useless.
1589 bool TreePatternNode::canPatternMatch(std::string &Reason,
1590 const CodeGenDAGPatterns &CDP) {
1591 if (isLeaf()) return true;
1593 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1594 if (!getChild(i)->canPatternMatch(Reason, CDP))
1595 return false;
1597 // If this is an intrinsic, handle cases that would make it not match. For
1598 // example, if an operand is required to be an immediate.
1599 if (getOperator()->isSubClassOf("Intrinsic")) {
1600 // TODO:
1601 return true;
1604 // If this node is a commutative operator, check that the LHS isn't an
1605 // immediate.
1606 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
1607 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
1608 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
1609 // Scan all of the operands of the node and make sure that only the last one
1610 // is a constant node, unless the RHS also is.
1611 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
1612 bool Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
1613 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
1614 if (OnlyOnRHSOfCommutative(getChild(i))) {
1615 Reason="Immediate value must be on the RHS of commutative operators!";
1616 return false;
1621 return true;
1624 //===----------------------------------------------------------------------===//
1625 // TreePattern implementation
1628 TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
1629 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
1630 isInputPattern = isInput;
1631 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
1632 Trees.push_back(ParseTreePattern(RawPat->getElement(i), ""));
1635 TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
1636 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
1637 isInputPattern = isInput;
1638 Trees.push_back(ParseTreePattern(Pat, ""));
1641 TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
1642 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
1643 isInputPattern = isInput;
1644 Trees.push_back(Pat);
1647 void TreePattern::error(const std::string &Msg) const {
1648 dump();
1649 throw TGError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
1652 void TreePattern::ComputeNamedNodes() {
1653 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1654 ComputeNamedNodes(Trees[i]);
1657 void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
1658 if (!N->getName().empty())
1659 NamedNodes[N->getName()].push_back(N);
1661 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1662 ComputeNamedNodes(N->getChild(i));
1666 TreePatternNode *TreePattern::ParseTreePattern(Init *TheInit, StringRef OpName){
1667 if (DefInit *DI = dynamic_cast<DefInit*>(TheInit)) {
1668 Record *R = DI->getDef();
1670 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
1671 // TreePatternNode if its own. For example:
1672 /// (foo GPR, imm) -> (foo GPR, (imm))
1673 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag"))
1674 return ParseTreePattern(new DagInit(DI, "",
1675 std::vector<std::pair<Init*, std::string> >()),
1676 OpName);
1678 // Input argument?
1679 TreePatternNode *Res = new TreePatternNode(DI, 1);
1680 if (R->getName() == "node" && !OpName.empty()) {
1681 if (OpName.empty())
1682 error("'node' argument requires a name to match with operand list");
1683 Args.push_back(OpName);
1686 Res->setName(OpName);
1687 return Res;
1690 if (IntInit *II = dynamic_cast<IntInit*>(TheInit)) {
1691 if (!OpName.empty())
1692 error("Constant int argument should not have a name!");
1693 return new TreePatternNode(II, 1);
1696 if (BitsInit *BI = dynamic_cast<BitsInit*>(TheInit)) {
1697 // Turn this into an IntInit.
1698 Init *II = BI->convertInitializerTo(new IntRecTy());
1699 if (II == 0 || !dynamic_cast<IntInit*>(II))
1700 error("Bits value must be constants!");
1701 return ParseTreePattern(II, OpName);
1704 DagInit *Dag = dynamic_cast<DagInit*>(TheInit);
1705 if (!Dag) {
1706 TheInit->dump();
1707 error("Pattern has unexpected init kind!");
1709 DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
1710 if (!OpDef) error("Pattern has unexpected operator type!");
1711 Record *Operator = OpDef->getDef();
1713 if (Operator->isSubClassOf("ValueType")) {
1714 // If the operator is a ValueType, then this must be "type cast" of a leaf
1715 // node.
1716 if (Dag->getNumArgs() != 1)
1717 error("Type cast only takes one operand!");
1719 TreePatternNode *New = ParseTreePattern(Dag->getArg(0), Dag->getArgName(0));
1721 // Apply the type cast.
1722 assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
1723 New->UpdateNodeType(0, getValueType(Operator), *this);
1725 if (!OpName.empty())
1726 error("ValueType cast should not have a name!");
1727 return New;
1730 // Verify that this is something that makes sense for an operator.
1731 if (!Operator->isSubClassOf("PatFrag") &&
1732 !Operator->isSubClassOf("SDNode") &&
1733 !Operator->isSubClassOf("Instruction") &&
1734 !Operator->isSubClassOf("SDNodeXForm") &&
1735 !Operator->isSubClassOf("Intrinsic") &&
1736 Operator->getName() != "set" &&
1737 Operator->getName() != "implicit")
1738 error("Unrecognized node '" + Operator->getName() + "'!");
1740 // Check to see if this is something that is illegal in an input pattern.
1741 if (isInputPattern) {
1742 if (Operator->isSubClassOf("Instruction") ||
1743 Operator->isSubClassOf("SDNodeXForm"))
1744 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
1745 } else {
1746 if (Operator->isSubClassOf("Intrinsic"))
1747 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
1749 if (Operator->isSubClassOf("SDNode") &&
1750 Operator->getName() != "imm" &&
1751 Operator->getName() != "fpimm" &&
1752 Operator->getName() != "tglobaltlsaddr" &&
1753 Operator->getName() != "tconstpool" &&
1754 Operator->getName() != "tjumptable" &&
1755 Operator->getName() != "tframeindex" &&
1756 Operator->getName() != "texternalsym" &&
1757 Operator->getName() != "tblockaddress" &&
1758 Operator->getName() != "tglobaladdr" &&
1759 Operator->getName() != "bb" &&
1760 Operator->getName() != "vt")
1761 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
1764 std::vector<TreePatternNode*> Children;
1766 // Parse all the operands.
1767 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
1768 Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgName(i)));
1770 // If the operator is an intrinsic, then this is just syntactic sugar for for
1771 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
1772 // convert the intrinsic name to a number.
1773 if (Operator->isSubClassOf("Intrinsic")) {
1774 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
1775 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
1777 // If this intrinsic returns void, it must have side-effects and thus a
1778 // chain.
1779 if (Int.IS.RetVTs.empty())
1780 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
1781 else if (Int.ModRef != CodeGenIntrinsic::NoMem)
1782 // Has side-effects, requires chain.
1783 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
1784 else // Otherwise, no chain.
1785 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
1787 TreePatternNode *IIDNode = new TreePatternNode(new IntInit(IID), 1);
1788 Children.insert(Children.begin(), IIDNode);
1791 unsigned NumResults = GetNumNodeResults(Operator, CDP);
1792 TreePatternNode *Result = new TreePatternNode(Operator, Children, NumResults);
1793 Result->setName(OpName);
1795 if (!Dag->getName().empty()) {
1796 assert(Result->getName().empty());
1797 Result->setName(Dag->getName());
1799 return Result;
1802 /// SimplifyTree - See if we can simplify this tree to eliminate something that
1803 /// will never match in favor of something obvious that will. This is here
1804 /// strictly as a convenience to target authors because it allows them to write
1805 /// more type generic things and have useless type casts fold away.
1807 /// This returns true if any change is made.
1808 static bool SimplifyTree(TreePatternNode *&N) {
1809 if (N->isLeaf())
1810 return false;
1812 // If we have a bitconvert with a resolved type and if the source and
1813 // destination types are the same, then the bitconvert is useless, remove it.
1814 if (N->getOperator()->getName() == "bitconvert" &&
1815 N->getExtType(0).isConcrete() &&
1816 N->getExtType(0) == N->getChild(0)->getExtType(0) &&
1817 N->getName().empty()) {
1818 N = N->getChild(0);
1819 SimplifyTree(N);
1820 return true;
1823 // Walk all children.
1824 bool MadeChange = false;
1825 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
1826 TreePatternNode *Child = N->getChild(i);
1827 MadeChange |= SimplifyTree(Child);
1828 N->setChild(i, Child);
1830 return MadeChange;
1835 /// InferAllTypes - Infer/propagate as many types throughout the expression
1836 /// patterns as possible. Return true if all types are inferred, false
1837 /// otherwise. Throw an exception if a type contradiction is found.
1838 bool TreePattern::
1839 InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
1840 if (NamedNodes.empty())
1841 ComputeNamedNodes();
1843 bool MadeChange = true;
1844 while (MadeChange) {
1845 MadeChange = false;
1846 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
1847 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
1848 MadeChange |= SimplifyTree(Trees[i]);
1851 // If there are constraints on our named nodes, apply them.
1852 for (StringMap<SmallVector<TreePatternNode*,1> >::iterator
1853 I = NamedNodes.begin(), E = NamedNodes.end(); I != E; ++I) {
1854 SmallVectorImpl<TreePatternNode*> &Nodes = I->second;
1856 // If we have input named node types, propagate their types to the named
1857 // values here.
1858 if (InNamedTypes) {
1859 // FIXME: Should be error?
1860 assert(InNamedTypes->count(I->getKey()) &&
1861 "Named node in output pattern but not input pattern?");
1863 const SmallVectorImpl<TreePatternNode*> &InNodes =
1864 InNamedTypes->find(I->getKey())->second;
1866 // The input types should be fully resolved by now.
1867 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
1868 // If this node is a register class, and it is the root of the pattern
1869 // then we're mapping something onto an input register. We allow
1870 // changing the type of the input register in this case. This allows
1871 // us to match things like:
1872 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
1873 if (Nodes[i] == Trees[0] && Nodes[i]->isLeaf()) {
1874 DefInit *DI = dynamic_cast<DefInit*>(Nodes[i]->getLeafValue());
1875 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1876 continue;
1879 assert(Nodes[i]->getNumTypes() == 1 &&
1880 InNodes[0]->getNumTypes() == 1 &&
1881 "FIXME: cannot name multiple result nodes yet");
1882 MadeChange |= Nodes[i]->UpdateNodeType(0, InNodes[0]->getExtType(0),
1883 *this);
1887 // If there are multiple nodes with the same name, they must all have the
1888 // same type.
1889 if (I->second.size() > 1) {
1890 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
1891 TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
1892 assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
1893 "FIXME: cannot name multiple result nodes yet");
1895 MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
1896 MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
1902 bool HasUnresolvedTypes = false;
1903 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1904 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
1905 return !HasUnresolvedTypes;
1908 void TreePattern::print(raw_ostream &OS) const {
1909 OS << getRecord()->getName();
1910 if (!Args.empty()) {
1911 OS << "(" << Args[0];
1912 for (unsigned i = 1, e = Args.size(); i != e; ++i)
1913 OS << ", " << Args[i];
1914 OS << ")";
1916 OS << ": ";
1918 if (Trees.size() > 1)
1919 OS << "[\n";
1920 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
1921 OS << "\t";
1922 Trees[i]->print(OS);
1923 OS << "\n";
1926 if (Trees.size() > 1)
1927 OS << "]\n";
1930 void TreePattern::dump() const { print(errs()); }
1932 //===----------------------------------------------------------------------===//
1933 // CodeGenDAGPatterns implementation
1936 CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) :
1937 Records(R), Target(R) {
1939 Intrinsics = LoadIntrinsics(Records, false);
1940 TgtIntrinsics = LoadIntrinsics(Records, true);
1941 ParseNodeInfo();
1942 ParseNodeTransforms();
1943 ParseComplexPatterns();
1944 ParsePatternFragments();
1945 ParseDefaultOperands();
1946 ParseInstructions();
1947 ParsePatterns();
1949 // Generate variants. For example, commutative patterns can match
1950 // multiple ways. Add them to PatternsToMatch as well.
1951 GenerateVariants();
1953 // Infer instruction flags. For example, we can detect loads,
1954 // stores, and side effects in many cases by examining an
1955 // instruction's pattern.
1956 InferInstructionFlags();
1959 CodeGenDAGPatterns::~CodeGenDAGPatterns() {
1960 for (pf_iterator I = PatternFragments.begin(),
1961 E = PatternFragments.end(); I != E; ++I)
1962 delete I->second;
1966 Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
1967 Record *N = Records.getDef(Name);
1968 if (!N || !N->isSubClassOf("SDNode")) {
1969 errs() << "Error getting SDNode '" << Name << "'!\n";
1970 exit(1);
1972 return N;
1975 // Parse all of the SDNode definitions for the target, populating SDNodes.
1976 void CodeGenDAGPatterns::ParseNodeInfo() {
1977 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
1978 while (!Nodes.empty()) {
1979 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
1980 Nodes.pop_back();
1983 // Get the builtin intrinsic nodes.
1984 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
1985 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
1986 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
1989 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
1990 /// map, and emit them to the file as functions.
1991 void CodeGenDAGPatterns::ParseNodeTransforms() {
1992 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
1993 while (!Xforms.empty()) {
1994 Record *XFormNode = Xforms.back();
1995 Record *SDNode = XFormNode->getValueAsDef("Opcode");
1996 std::string Code = XFormNode->getValueAsCode("XFormFunction");
1997 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
1999 Xforms.pop_back();
2003 void CodeGenDAGPatterns::ParseComplexPatterns() {
2004 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
2005 while (!AMs.empty()) {
2006 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
2007 AMs.pop_back();
2012 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
2013 /// file, building up the PatternFragments map. After we've collected them all,
2014 /// inline fragments together as necessary, so that there are no references left
2015 /// inside a pattern fragment to a pattern fragment.
2017 void CodeGenDAGPatterns::ParsePatternFragments() {
2018 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
2020 // First step, parse all of the fragments.
2021 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
2022 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
2023 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
2024 PatternFragments[Fragments[i]] = P;
2026 // Validate the argument list, converting it to set, to discard duplicates.
2027 std::vector<std::string> &Args = P->getArgList();
2028 std::set<std::string> OperandsSet(Args.begin(), Args.end());
2030 if (OperandsSet.count(""))
2031 P->error("Cannot have unnamed 'node' values in pattern fragment!");
2033 // Parse the operands list.
2034 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
2035 DefInit *OpsOp = dynamic_cast<DefInit*>(OpsList->getOperator());
2036 // Special cases: ops == outs == ins. Different names are used to
2037 // improve readability.
2038 if (!OpsOp ||
2039 (OpsOp->getDef()->getName() != "ops" &&
2040 OpsOp->getDef()->getName() != "outs" &&
2041 OpsOp->getDef()->getName() != "ins"))
2042 P->error("Operands list should start with '(ops ... '!");
2044 // Copy over the arguments.
2045 Args.clear();
2046 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
2047 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
2048 static_cast<DefInit*>(OpsList->getArg(j))->
2049 getDef()->getName() != "node")
2050 P->error("Operands list should all be 'node' values.");
2051 if (OpsList->getArgName(j).empty())
2052 P->error("Operands list should have names for each operand!");
2053 if (!OperandsSet.count(OpsList->getArgName(j)))
2054 P->error("'" + OpsList->getArgName(j) +
2055 "' does not occur in pattern or was multiply specified!");
2056 OperandsSet.erase(OpsList->getArgName(j));
2057 Args.push_back(OpsList->getArgName(j));
2060 if (!OperandsSet.empty())
2061 P->error("Operands list does not contain an entry for operand '" +
2062 *OperandsSet.begin() + "'!");
2064 // If there is a code init for this fragment, keep track of the fact that
2065 // this fragment uses it.
2066 std::string Code = Fragments[i]->getValueAsCode("Predicate");
2067 if (!Code.empty())
2068 P->getOnlyTree()->addPredicateFn("Predicate_"+Fragments[i]->getName());
2070 // If there is a node transformation corresponding to this, keep track of
2071 // it.
2072 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
2073 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
2074 P->getOnlyTree()->setTransformFn(Transform);
2077 // Now that we've parsed all of the tree fragments, do a closure on them so
2078 // that there are not references to PatFrags left inside of them.
2079 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
2080 TreePattern *ThePat = PatternFragments[Fragments[i]];
2081 ThePat->InlinePatternFragments();
2083 // Infer as many types as possible. Don't worry about it if we don't infer
2084 // all of them, some may depend on the inputs of the pattern.
2085 try {
2086 ThePat->InferAllTypes();
2087 } catch (...) {
2088 // If this pattern fragment is not supported by this target (no types can
2089 // satisfy its constraints), just ignore it. If the bogus pattern is
2090 // actually used by instructions, the type consistency error will be
2091 // reported there.
2094 // If debugging, print out the pattern fragment result.
2095 DEBUG(ThePat->dump());
2099 void CodeGenDAGPatterns::ParseDefaultOperands() {
2100 std::vector<Record*> DefaultOps[2];
2101 DefaultOps[0] = Records.getAllDerivedDefinitions("PredicateOperand");
2102 DefaultOps[1] = Records.getAllDerivedDefinitions("OptionalDefOperand");
2104 // Find some SDNode.
2105 assert(!SDNodes.empty() && "No SDNodes parsed?");
2106 Init *SomeSDNode = new DefInit(SDNodes.begin()->first);
2108 for (unsigned iter = 0; iter != 2; ++iter) {
2109 for (unsigned i = 0, e = DefaultOps[iter].size(); i != e; ++i) {
2110 DagInit *DefaultInfo = DefaultOps[iter][i]->getValueAsDag("DefaultOps");
2112 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
2113 // SomeSDnode so that we can parse this.
2114 std::vector<std::pair<Init*, std::string> > Ops;
2115 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
2116 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
2117 DefaultInfo->getArgName(op)));
2118 DagInit *DI = new DagInit(SomeSDNode, "", Ops);
2120 // Create a TreePattern to parse this.
2121 TreePattern P(DefaultOps[iter][i], DI, false, *this);
2122 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
2124 // Copy the operands over into a DAGDefaultOperand.
2125 DAGDefaultOperand DefaultOpInfo;
2127 TreePatternNode *T = P.getTree(0);
2128 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
2129 TreePatternNode *TPN = T->getChild(op);
2130 while (TPN->ApplyTypeConstraints(P, false))
2131 /* Resolve all types */;
2133 if (TPN->ContainsUnresolvedType()) {
2134 if (iter == 0)
2135 throw "Value #" + utostr(i) + " of PredicateOperand '" +
2136 DefaultOps[iter][i]->getName() +"' doesn't have a concrete type!";
2137 else
2138 throw "Value #" + utostr(i) + " of OptionalDefOperand '" +
2139 DefaultOps[iter][i]->getName() +"' doesn't have a concrete type!";
2141 DefaultOpInfo.DefaultOps.push_back(TPN);
2144 // Insert it into the DefaultOperands map so we can find it later.
2145 DefaultOperands[DefaultOps[iter][i]] = DefaultOpInfo;
2150 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
2151 /// instruction input. Return true if this is a real use.
2152 static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
2153 std::map<std::string, TreePatternNode*> &InstInputs) {
2154 // No name -> not interesting.
2155 if (Pat->getName().empty()) {
2156 if (Pat->isLeaf()) {
2157 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
2158 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
2159 I->error("Input " + DI->getDef()->getName() + " must be named!");
2161 return false;
2164 Record *Rec;
2165 if (Pat->isLeaf()) {
2166 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
2167 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
2168 Rec = DI->getDef();
2169 } else {
2170 Rec = Pat->getOperator();
2173 // SRCVALUE nodes are ignored.
2174 if (Rec->getName() == "srcvalue")
2175 return false;
2177 TreePatternNode *&Slot = InstInputs[Pat->getName()];
2178 if (!Slot) {
2179 Slot = Pat;
2180 return true;
2182 Record *SlotRec;
2183 if (Slot->isLeaf()) {
2184 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
2185 } else {
2186 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
2187 SlotRec = Slot->getOperator();
2190 // Ensure that the inputs agree if we've already seen this input.
2191 if (Rec != SlotRec)
2192 I->error("All $" + Pat->getName() + " inputs must agree with each other");
2193 if (Slot->getExtTypes() != Pat->getExtTypes())
2194 I->error("All $" + Pat->getName() + " inputs must agree with each other");
2195 return true;
2198 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
2199 /// part of "I", the instruction), computing the set of inputs and outputs of
2200 /// the pattern. Report errors if we see anything naughty.
2201 void CodeGenDAGPatterns::
2202 FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
2203 std::map<std::string, TreePatternNode*> &InstInputs,
2204 std::map<std::string, TreePatternNode*>&InstResults,
2205 std::vector<Record*> &InstImpResults) {
2206 if (Pat->isLeaf()) {
2207 bool isUse = HandleUse(I, Pat, InstInputs);
2208 if (!isUse && Pat->getTransformFn())
2209 I->error("Cannot specify a transform function for a non-input value!");
2210 return;
2213 if (Pat->getOperator()->getName() == "implicit") {
2214 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2215 TreePatternNode *Dest = Pat->getChild(i);
2216 if (!Dest->isLeaf())
2217 I->error("implicitly defined value should be a register!");
2219 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
2220 if (!Val || !Val->getDef()->isSubClassOf("Register"))
2221 I->error("implicitly defined value should be a register!");
2222 InstImpResults.push_back(Val->getDef());
2224 return;
2227 if (Pat->getOperator()->getName() != "set") {
2228 // If this is not a set, verify that the children nodes are not void typed,
2229 // and recurse.
2230 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2231 if (Pat->getChild(i)->getNumTypes() == 0)
2232 I->error("Cannot have void nodes inside of patterns!");
2233 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
2234 InstImpResults);
2237 // If this is a non-leaf node with no children, treat it basically as if
2238 // it were a leaf. This handles nodes like (imm).
2239 bool isUse = HandleUse(I, Pat, InstInputs);
2241 if (!isUse && Pat->getTransformFn())
2242 I->error("Cannot specify a transform function for a non-input value!");
2243 return;
2246 // Otherwise, this is a set, validate and collect instruction results.
2247 if (Pat->getNumChildren() == 0)
2248 I->error("set requires operands!");
2250 if (Pat->getTransformFn())
2251 I->error("Cannot specify a transform function on a set node!");
2253 // Check the set destinations.
2254 unsigned NumDests = Pat->getNumChildren()-1;
2255 for (unsigned i = 0; i != NumDests; ++i) {
2256 TreePatternNode *Dest = Pat->getChild(i);
2257 if (!Dest->isLeaf())
2258 I->error("set destination should be a register!");
2260 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
2261 if (!Val)
2262 I->error("set destination should be a register!");
2264 if (Val->getDef()->isSubClassOf("RegisterClass") ||
2265 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
2266 if (Dest->getName().empty())
2267 I->error("set destination must have a name!");
2268 if (InstResults.count(Dest->getName()))
2269 I->error("cannot set '" + Dest->getName() +"' multiple times");
2270 InstResults[Dest->getName()] = Dest;
2271 } else if (Val->getDef()->isSubClassOf("Register")) {
2272 InstImpResults.push_back(Val->getDef());
2273 } else {
2274 I->error("set destination should be a register!");
2278 // Verify and collect info from the computation.
2279 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
2280 InstInputs, InstResults, InstImpResults);
2283 //===----------------------------------------------------------------------===//
2284 // Instruction Analysis
2285 //===----------------------------------------------------------------------===//
2287 class InstAnalyzer {
2288 const CodeGenDAGPatterns &CDP;
2289 bool &mayStore;
2290 bool &mayLoad;
2291 bool &HasSideEffects;
2292 bool &IsVariadic;
2293 public:
2294 InstAnalyzer(const CodeGenDAGPatterns &cdp,
2295 bool &maystore, bool &mayload, bool &hse, bool &isv)
2296 : CDP(cdp), mayStore(maystore), mayLoad(mayload), HasSideEffects(hse),
2297 IsVariadic(isv) {
2300 /// Analyze - Analyze the specified instruction, returning true if the
2301 /// instruction had a pattern.
2302 bool Analyze(Record *InstRecord) {
2303 const TreePattern *Pattern = CDP.getInstruction(InstRecord).getPattern();
2304 if (Pattern == 0) {
2305 HasSideEffects = 1;
2306 return false; // No pattern.
2309 // FIXME: Assume only the first tree is the pattern. The others are clobber
2310 // nodes.
2311 AnalyzeNode(Pattern->getTree(0));
2312 return true;
2315 private:
2316 void AnalyzeNode(const TreePatternNode *N) {
2317 if (N->isLeaf()) {
2318 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
2319 Record *LeafRec = DI->getDef();
2320 // Handle ComplexPattern leaves.
2321 if (LeafRec->isSubClassOf("ComplexPattern")) {
2322 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
2323 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
2324 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
2325 if (CP.hasProperty(SDNPSideEffect)) HasSideEffects = true;
2328 return;
2331 // Analyze children.
2332 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2333 AnalyzeNode(N->getChild(i));
2335 // Ignore set nodes, which are not SDNodes.
2336 if (N->getOperator()->getName() == "set")
2337 return;
2339 // Get information about the SDNode for the operator.
2340 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N->getOperator());
2342 // Notice properties of the node.
2343 if (OpInfo.hasProperty(SDNPMayStore)) mayStore = true;
2344 if (OpInfo.hasProperty(SDNPMayLoad)) mayLoad = true;
2345 if (OpInfo.hasProperty(SDNPSideEffect)) HasSideEffects = true;
2346 if (OpInfo.hasProperty(SDNPVariadic)) IsVariadic = true;
2348 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
2349 // If this is an intrinsic, analyze it.
2350 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
2351 mayLoad = true;// These may load memory.
2353 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteArgMem)
2354 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
2356 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem)
2357 // WriteMem intrinsics can have other strange effects.
2358 HasSideEffects = true;
2364 static void InferFromPattern(const CodeGenInstruction &Inst,
2365 bool &MayStore, bool &MayLoad,
2366 bool &HasSideEffects, bool &IsVariadic,
2367 const CodeGenDAGPatterns &CDP) {
2368 MayStore = MayLoad = HasSideEffects = IsVariadic = false;
2370 bool HadPattern =
2371 InstAnalyzer(CDP, MayStore, MayLoad, HasSideEffects, IsVariadic)
2372 .Analyze(Inst.TheDef);
2374 // InstAnalyzer only correctly analyzes mayStore/mayLoad so far.
2375 if (Inst.mayStore) { // If the .td file explicitly sets mayStore, use it.
2376 // If we decided that this is a store from the pattern, then the .td file
2377 // entry is redundant.
2378 if (MayStore)
2379 fprintf(stderr,
2380 "Warning: mayStore flag explicitly set on instruction '%s'"
2381 " but flag already inferred from pattern.\n",
2382 Inst.TheDef->getName().c_str());
2383 MayStore = true;
2386 if (Inst.mayLoad) { // If the .td file explicitly sets mayLoad, use it.
2387 // If we decided that this is a load from the pattern, then the .td file
2388 // entry is redundant.
2389 if (MayLoad)
2390 fprintf(stderr,
2391 "Warning: mayLoad flag explicitly set on instruction '%s'"
2392 " but flag already inferred from pattern.\n",
2393 Inst.TheDef->getName().c_str());
2394 MayLoad = true;
2397 if (Inst.neverHasSideEffects) {
2398 if (HadPattern)
2399 fprintf(stderr, "Warning: neverHasSideEffects set on instruction '%s' "
2400 "which already has a pattern\n", Inst.TheDef->getName().c_str());
2401 HasSideEffects = false;
2404 if (Inst.hasSideEffects) {
2405 if (HasSideEffects)
2406 fprintf(stderr, "Warning: hasSideEffects set on instruction '%s' "
2407 "which already inferred this.\n", Inst.TheDef->getName().c_str());
2408 HasSideEffects = true;
2411 if (Inst.Operands.isVariadic)
2412 IsVariadic = true; // Can warn if we want.
2415 /// ParseInstructions - Parse all of the instructions, inlining and resolving
2416 /// any fragments involved. This populates the Instructions list with fully
2417 /// resolved instructions.
2418 void CodeGenDAGPatterns::ParseInstructions() {
2419 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
2421 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
2422 ListInit *LI = 0;
2424 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
2425 LI = Instrs[i]->getValueAsListInit("Pattern");
2427 // If there is no pattern, only collect minimal information about the
2428 // instruction for its operand list. We have to assume that there is one
2429 // result, as we have no detailed info.
2430 if (!LI || LI->getSize() == 0) {
2431 std::vector<Record*> Results;
2432 std::vector<Record*> Operands;
2434 CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
2436 if (InstInfo.Operands.size() != 0) {
2437 if (InstInfo.Operands.NumDefs == 0) {
2438 // These produce no results
2439 for (unsigned j = 0, e = InstInfo.Operands.size(); j < e; ++j)
2440 Operands.push_back(InstInfo.Operands[j].Rec);
2441 } else {
2442 // Assume the first operand is the result.
2443 Results.push_back(InstInfo.Operands[0].Rec);
2445 // The rest are inputs.
2446 for (unsigned j = 1, e = InstInfo.Operands.size(); j < e; ++j)
2447 Operands.push_back(InstInfo.Operands[j].Rec);
2451 // Create and insert the instruction.
2452 std::vector<Record*> ImpResults;
2453 Instructions.insert(std::make_pair(Instrs[i],
2454 DAGInstruction(0, Results, Operands, ImpResults)));
2455 continue; // no pattern.
2458 // Parse the instruction.
2459 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
2460 // Inline pattern fragments into it.
2461 I->InlinePatternFragments();
2463 // Infer as many types as possible. If we cannot infer all of them, we can
2464 // never do anything with this instruction pattern: report it to the user.
2465 if (!I->InferAllTypes())
2466 I->error("Could not infer all types in pattern!");
2468 // InstInputs - Keep track of all of the inputs of the instruction, along
2469 // with the record they are declared as.
2470 std::map<std::string, TreePatternNode*> InstInputs;
2472 // InstResults - Keep track of all the virtual registers that are 'set'
2473 // in the instruction, including what reg class they are.
2474 std::map<std::string, TreePatternNode*> InstResults;
2476 std::vector<Record*> InstImpResults;
2478 // Verify that the top-level forms in the instruction are of void type, and
2479 // fill in the InstResults map.
2480 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
2481 TreePatternNode *Pat = I->getTree(j);
2482 if (Pat->getNumTypes() != 0)
2483 I->error("Top-level forms in instruction pattern should have"
2484 " void types");
2486 // Find inputs and outputs, and verify the structure of the uses/defs.
2487 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
2488 InstImpResults);
2491 // Now that we have inputs and outputs of the pattern, inspect the operands
2492 // list for the instruction. This determines the order that operands are
2493 // added to the machine instruction the node corresponds to.
2494 unsigned NumResults = InstResults.size();
2496 // Parse the operands list from the (ops) list, validating it.
2497 assert(I->getArgList().empty() && "Args list should still be empty here!");
2498 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]);
2500 // Check that all of the results occur first in the list.
2501 std::vector<Record*> Results;
2502 TreePatternNode *Res0Node = 0;
2503 for (unsigned i = 0; i != NumResults; ++i) {
2504 if (i == CGI.Operands.size())
2505 I->error("'" + InstResults.begin()->first +
2506 "' set but does not appear in operand list!");
2507 const std::string &OpName = CGI.Operands[i].Name;
2509 // Check that it exists in InstResults.
2510 TreePatternNode *RNode = InstResults[OpName];
2511 if (RNode == 0)
2512 I->error("Operand $" + OpName + " does not exist in operand list!");
2514 if (i == 0)
2515 Res0Node = RNode;
2516 Record *R = dynamic_cast<DefInit*>(RNode->getLeafValue())->getDef();
2517 if (R == 0)
2518 I->error("Operand $" + OpName + " should be a set destination: all "
2519 "outputs must occur before inputs in operand list!");
2521 if (CGI.Operands[i].Rec != R)
2522 I->error("Operand $" + OpName + " class mismatch!");
2524 // Remember the return type.
2525 Results.push_back(CGI.Operands[i].Rec);
2527 // Okay, this one checks out.
2528 InstResults.erase(OpName);
2531 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
2532 // the copy while we're checking the inputs.
2533 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
2535 std::vector<TreePatternNode*> ResultNodeOperands;
2536 std::vector<Record*> Operands;
2537 for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
2538 CGIOperandList::OperandInfo &Op = CGI.Operands[i];
2539 const std::string &OpName = Op.Name;
2540 if (OpName.empty())
2541 I->error("Operand #" + utostr(i) + " in operands list has no name!");
2543 if (!InstInputsCheck.count(OpName)) {
2544 // If this is an predicate operand or optional def operand with an
2545 // DefaultOps set filled in, we can ignore this. When we codegen it,
2546 // we will do so as always executed.
2547 if (Op.Rec->isSubClassOf("PredicateOperand") ||
2548 Op.Rec->isSubClassOf("OptionalDefOperand")) {
2549 // Does it have a non-empty DefaultOps field? If so, ignore this
2550 // operand.
2551 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
2552 continue;
2554 I->error("Operand $" + OpName +
2555 " does not appear in the instruction pattern");
2557 TreePatternNode *InVal = InstInputsCheck[OpName];
2558 InstInputsCheck.erase(OpName); // It occurred, remove from map.
2560 if (InVal->isLeaf() &&
2561 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
2562 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
2563 if (Op.Rec != InRec && !InRec->isSubClassOf("ComplexPattern"))
2564 I->error("Operand $" + OpName + "'s register class disagrees"
2565 " between the operand and pattern");
2567 Operands.push_back(Op.Rec);
2569 // Construct the result for the dest-pattern operand list.
2570 TreePatternNode *OpNode = InVal->clone();
2572 // No predicate is useful on the result.
2573 OpNode->clearPredicateFns();
2575 // Promote the xform function to be an explicit node if set.
2576 if (Record *Xform = OpNode->getTransformFn()) {
2577 OpNode->setTransformFn(0);
2578 std::vector<TreePatternNode*> Children;
2579 Children.push_back(OpNode);
2580 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
2583 ResultNodeOperands.push_back(OpNode);
2586 if (!InstInputsCheck.empty())
2587 I->error("Input operand $" + InstInputsCheck.begin()->first +
2588 " occurs in pattern but not in operands list!");
2590 TreePatternNode *ResultPattern =
2591 new TreePatternNode(I->getRecord(), ResultNodeOperands,
2592 GetNumNodeResults(I->getRecord(), *this));
2593 // Copy fully inferred output node type to instruction result pattern.
2594 for (unsigned i = 0; i != NumResults; ++i)
2595 ResultPattern->setType(i, Res0Node->getExtType(i));
2597 // Create and insert the instruction.
2598 // FIXME: InstImpResults should not be part of DAGInstruction.
2599 DAGInstruction TheInst(I, Results, Operands, InstImpResults);
2600 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
2602 // Use a temporary tree pattern to infer all types and make sure that the
2603 // constructed result is correct. This depends on the instruction already
2604 // being inserted into the Instructions map.
2605 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
2606 Temp.InferAllTypes(&I->getNamedNodesMap());
2608 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
2609 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
2611 DEBUG(I->dump());
2614 // If we can, convert the instructions to be patterns that are matched!
2615 for (std::map<Record*, DAGInstruction, RecordPtrCmp>::iterator II =
2616 Instructions.begin(),
2617 E = Instructions.end(); II != E; ++II) {
2618 DAGInstruction &TheInst = II->second;
2619 const TreePattern *I = TheInst.getPattern();
2620 if (I == 0) continue; // No pattern.
2622 // FIXME: Assume only the first tree is the pattern. The others are clobber
2623 // nodes.
2624 TreePatternNode *Pattern = I->getTree(0);
2625 TreePatternNode *SrcPattern;
2626 if (Pattern->getOperator()->getName() == "set") {
2627 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
2628 } else{
2629 // Not a set (store or something?)
2630 SrcPattern = Pattern;
2633 Record *Instr = II->first;
2634 AddPatternToMatch(I,
2635 PatternToMatch(Instr,
2636 Instr->getValueAsListInit("Predicates"),
2637 SrcPattern,
2638 TheInst.getResultPattern(),
2639 TheInst.getImpResults(),
2640 Instr->getValueAsInt("AddedComplexity"),
2641 Instr->getID()));
2646 typedef std::pair<const TreePatternNode*, unsigned> NameRecord;
2648 static void FindNames(const TreePatternNode *P,
2649 std::map<std::string, NameRecord> &Names,
2650 const TreePattern *PatternTop) {
2651 if (!P->getName().empty()) {
2652 NameRecord &Rec = Names[P->getName()];
2653 // If this is the first instance of the name, remember the node.
2654 if (Rec.second++ == 0)
2655 Rec.first = P;
2656 else if (Rec.first->getExtTypes() != P->getExtTypes())
2657 PatternTop->error("repetition of value: $" + P->getName() +
2658 " where different uses have different types!");
2661 if (!P->isLeaf()) {
2662 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
2663 FindNames(P->getChild(i), Names, PatternTop);
2667 void CodeGenDAGPatterns::AddPatternToMatch(const TreePattern *Pattern,
2668 const PatternToMatch &PTM) {
2669 // Do some sanity checking on the pattern we're about to match.
2670 std::string Reason;
2671 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this))
2672 Pattern->error("Pattern can never match: " + Reason);
2674 // If the source pattern's root is a complex pattern, that complex pattern
2675 // must specify the nodes it can potentially match.
2676 if (const ComplexPattern *CP =
2677 PTM.getSrcPattern()->getComplexPatternInfo(*this))
2678 if (CP->getRootNodes().empty())
2679 Pattern->error("ComplexPattern at root must specify list of opcodes it"
2680 " could match");
2683 // Find all of the named values in the input and output, ensure they have the
2684 // same type.
2685 std::map<std::string, NameRecord> SrcNames, DstNames;
2686 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
2687 FindNames(PTM.getDstPattern(), DstNames, Pattern);
2689 // Scan all of the named values in the destination pattern, rejecting them if
2690 // they don't exist in the input pattern.
2691 for (std::map<std::string, NameRecord>::iterator
2692 I = DstNames.begin(), E = DstNames.end(); I != E; ++I) {
2693 if (SrcNames[I->first].first == 0)
2694 Pattern->error("Pattern has input without matching name in output: $" +
2695 I->first);
2698 // Scan all of the named values in the source pattern, rejecting them if the
2699 // name isn't used in the dest, and isn't used to tie two values together.
2700 for (std::map<std::string, NameRecord>::iterator
2701 I = SrcNames.begin(), E = SrcNames.end(); I != E; ++I)
2702 if (DstNames[I->first].first == 0 && SrcNames[I->first].second == 1)
2703 Pattern->error("Pattern has dead named input: $" + I->first);
2705 PatternsToMatch.push_back(PTM);
2710 void CodeGenDAGPatterns::InferInstructionFlags() {
2711 const std::vector<const CodeGenInstruction*> &Instructions =
2712 Target.getInstructionsByEnumValue();
2713 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
2714 CodeGenInstruction &InstInfo =
2715 const_cast<CodeGenInstruction &>(*Instructions[i]);
2716 // Determine properties of the instruction from its pattern.
2717 bool MayStore, MayLoad, HasSideEffects, IsVariadic;
2718 InferFromPattern(InstInfo, MayStore, MayLoad, HasSideEffects, IsVariadic,
2719 *this);
2720 InstInfo.mayStore = MayStore;
2721 InstInfo.mayLoad = MayLoad;
2722 InstInfo.hasSideEffects = HasSideEffects;
2723 InstInfo.Operands.isVariadic = IsVariadic;
2727 /// Given a pattern result with an unresolved type, see if we can find one
2728 /// instruction with an unresolved result type. Force this result type to an
2729 /// arbitrary element if it's possible types to converge results.
2730 static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
2731 if (N->isLeaf())
2732 return false;
2734 // Analyze children.
2735 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2736 if (ForceArbitraryInstResultType(N->getChild(i), TP))
2737 return true;
2739 if (!N->getOperator()->isSubClassOf("Instruction"))
2740 return false;
2742 // If this type is already concrete or completely unknown we can't do
2743 // anything.
2744 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
2745 if (N->getExtType(i).isCompletelyUnknown() || N->getExtType(i).isConcrete())
2746 continue;
2748 // Otherwise, force its type to the first possibility (an arbitrary choice).
2749 if (N->getExtType(i).MergeInTypeInfo(N->getExtType(i).getTypeList()[0], TP))
2750 return true;
2753 return false;
2756 void CodeGenDAGPatterns::ParsePatterns() {
2757 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
2759 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
2760 Record *CurPattern = Patterns[i];
2761 DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
2762 TreePattern *Pattern = new TreePattern(CurPattern, Tree, true, *this);
2764 // Inline pattern fragments into it.
2765 Pattern->InlinePatternFragments();
2767 ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
2768 if (LI->getSize() == 0) continue; // no pattern.
2770 // Parse the instruction.
2771 TreePattern *Result = new TreePattern(CurPattern, LI, false, *this);
2773 // Inline pattern fragments into it.
2774 Result->InlinePatternFragments();
2776 if (Result->getNumTrees() != 1)
2777 Result->error("Cannot handle instructions producing instructions "
2778 "with temporaries yet!");
2780 bool IterateInference;
2781 bool InferredAllPatternTypes, InferredAllResultTypes;
2782 do {
2783 // Infer as many types as possible. If we cannot infer all of them, we
2784 // can never do anything with this pattern: report it to the user.
2785 InferredAllPatternTypes =
2786 Pattern->InferAllTypes(&Pattern->getNamedNodesMap());
2788 // Infer as many types as possible. If we cannot infer all of them, we
2789 // can never do anything with this pattern: report it to the user.
2790 InferredAllResultTypes =
2791 Result->InferAllTypes(&Pattern->getNamedNodesMap());
2793 IterateInference = false;
2795 // Apply the type of the result to the source pattern. This helps us
2796 // resolve cases where the input type is known to be a pointer type (which
2797 // is considered resolved), but the result knows it needs to be 32- or
2798 // 64-bits. Infer the other way for good measure.
2799 for (unsigned i = 0, e = std::min(Result->getTree(0)->getNumTypes(),
2800 Pattern->getTree(0)->getNumTypes());
2801 i != e; ++i) {
2802 IterateInference = Pattern->getTree(0)->
2803 UpdateNodeType(i, Result->getTree(0)->getExtType(i), *Result);
2804 IterateInference |= Result->getTree(0)->
2805 UpdateNodeType(i, Pattern->getTree(0)->getExtType(i), *Result);
2808 // If our iteration has converged and the input pattern's types are fully
2809 // resolved but the result pattern is not fully resolved, we may have a
2810 // situation where we have two instructions in the result pattern and
2811 // the instructions require a common register class, but don't care about
2812 // what actual MVT is used. This is actually a bug in our modelling:
2813 // output patterns should have register classes, not MVTs.
2815 // In any case, to handle this, we just go through and disambiguate some
2816 // arbitrary types to the result pattern's nodes.
2817 if (!IterateInference && InferredAllPatternTypes &&
2818 !InferredAllResultTypes)
2819 IterateInference = ForceArbitraryInstResultType(Result->getTree(0),
2820 *Result);
2821 } while (IterateInference);
2823 // Verify that we inferred enough types that we can do something with the
2824 // pattern and result. If these fire the user has to add type casts.
2825 if (!InferredAllPatternTypes)
2826 Pattern->error("Could not infer all types in pattern!");
2827 if (!InferredAllResultTypes) {
2828 Pattern->dump();
2829 Result->error("Could not infer all types in pattern result!");
2832 // Validate that the input pattern is correct.
2833 std::map<std::string, TreePatternNode*> InstInputs;
2834 std::map<std::string, TreePatternNode*> InstResults;
2835 std::vector<Record*> InstImpResults;
2836 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
2837 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
2838 InstInputs, InstResults,
2839 InstImpResults);
2841 // Promote the xform function to be an explicit node if set.
2842 TreePatternNode *DstPattern = Result->getOnlyTree();
2843 std::vector<TreePatternNode*> ResultNodeOperands;
2844 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
2845 TreePatternNode *OpNode = DstPattern->getChild(ii);
2846 if (Record *Xform = OpNode->getTransformFn()) {
2847 OpNode->setTransformFn(0);
2848 std::vector<TreePatternNode*> Children;
2849 Children.push_back(OpNode);
2850 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
2852 ResultNodeOperands.push_back(OpNode);
2854 DstPattern = Result->getOnlyTree();
2855 if (!DstPattern->isLeaf())
2856 DstPattern = new TreePatternNode(DstPattern->getOperator(),
2857 ResultNodeOperands,
2858 DstPattern->getNumTypes());
2860 for (unsigned i = 0, e = Result->getOnlyTree()->getNumTypes(); i != e; ++i)
2861 DstPattern->setType(i, Result->getOnlyTree()->getExtType(i));
2863 TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
2864 Temp.InferAllTypes();
2867 AddPatternToMatch(Pattern,
2868 PatternToMatch(CurPattern,
2869 CurPattern->getValueAsListInit("Predicates"),
2870 Pattern->getTree(0),
2871 Temp.getOnlyTree(), InstImpResults,
2872 CurPattern->getValueAsInt("AddedComplexity"),
2873 CurPattern->getID()));
2877 /// CombineChildVariants - Given a bunch of permutations of each child of the
2878 /// 'operator' node, put them together in all possible ways.
2879 static void CombineChildVariants(TreePatternNode *Orig,
2880 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
2881 std::vector<TreePatternNode*> &OutVariants,
2882 CodeGenDAGPatterns &CDP,
2883 const MultipleUseVarSet &DepVars) {
2884 // Make sure that each operand has at least one variant to choose from.
2885 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2886 if (ChildVariants[i].empty())
2887 return;
2889 // The end result is an all-pairs construction of the resultant pattern.
2890 std::vector<unsigned> Idxs;
2891 Idxs.resize(ChildVariants.size());
2892 bool NotDone;
2893 do {
2894 #ifndef NDEBUG
2895 DEBUG(if (!Idxs.empty()) {
2896 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
2897 for (unsigned i = 0; i < Idxs.size(); ++i) {
2898 errs() << Idxs[i] << " ";
2900 errs() << "]\n";
2902 #endif
2903 // Create the variant and add it to the output list.
2904 std::vector<TreePatternNode*> NewChildren;
2905 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2906 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
2907 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren,
2908 Orig->getNumTypes());
2910 // Copy over properties.
2911 R->setName(Orig->getName());
2912 R->setPredicateFns(Orig->getPredicateFns());
2913 R->setTransformFn(Orig->getTransformFn());
2914 for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
2915 R->setType(i, Orig->getExtType(i));
2917 // If this pattern cannot match, do not include it as a variant.
2918 std::string ErrString;
2919 if (!R->canPatternMatch(ErrString, CDP)) {
2920 delete R;
2921 } else {
2922 bool AlreadyExists = false;
2924 // Scan to see if this pattern has already been emitted. We can get
2925 // duplication due to things like commuting:
2926 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
2927 // which are the same pattern. Ignore the dups.
2928 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
2929 if (R->isIsomorphicTo(OutVariants[i], DepVars)) {
2930 AlreadyExists = true;
2931 break;
2934 if (AlreadyExists)
2935 delete R;
2936 else
2937 OutVariants.push_back(R);
2940 // Increment indices to the next permutation by incrementing the
2941 // indicies from last index backward, e.g., generate the sequence
2942 // [0, 0], [0, 1], [1, 0], [1, 1].
2943 int IdxsIdx;
2944 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
2945 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
2946 Idxs[IdxsIdx] = 0;
2947 else
2948 break;
2950 NotDone = (IdxsIdx >= 0);
2951 } while (NotDone);
2954 /// CombineChildVariants - A helper function for binary operators.
2956 static void CombineChildVariants(TreePatternNode *Orig,
2957 const std::vector<TreePatternNode*> &LHS,
2958 const std::vector<TreePatternNode*> &RHS,
2959 std::vector<TreePatternNode*> &OutVariants,
2960 CodeGenDAGPatterns &CDP,
2961 const MultipleUseVarSet &DepVars) {
2962 std::vector<std::vector<TreePatternNode*> > ChildVariants;
2963 ChildVariants.push_back(LHS);
2964 ChildVariants.push_back(RHS);
2965 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
2969 static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
2970 std::vector<TreePatternNode *> &Children) {
2971 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
2972 Record *Operator = N->getOperator();
2974 // Only permit raw nodes.
2975 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
2976 N->getTransformFn()) {
2977 Children.push_back(N);
2978 return;
2981 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
2982 Children.push_back(N->getChild(0));
2983 else
2984 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
2986 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
2987 Children.push_back(N->getChild(1));
2988 else
2989 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
2992 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
2993 /// the (potentially recursive) pattern by using algebraic laws.
2995 static void GenerateVariantsOf(TreePatternNode *N,
2996 std::vector<TreePatternNode*> &OutVariants,
2997 CodeGenDAGPatterns &CDP,
2998 const MultipleUseVarSet &DepVars) {
2999 // We cannot permute leaves.
3000 if (N->isLeaf()) {
3001 OutVariants.push_back(N);
3002 return;
3005 // Look up interesting info about the node.
3006 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
3008 // If this node is associative, re-associate.
3009 if (NodeInfo.hasProperty(SDNPAssociative)) {
3010 // Re-associate by pulling together all of the linked operators
3011 std::vector<TreePatternNode*> MaximalChildren;
3012 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
3014 // Only handle child sizes of 3. Otherwise we'll end up trying too many
3015 // permutations.
3016 if (MaximalChildren.size() == 3) {
3017 // Find the variants of all of our maximal children.
3018 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
3019 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
3020 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
3021 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
3023 // There are only two ways we can permute the tree:
3024 // (A op B) op C and A op (B op C)
3025 // Within these forms, we can also permute A/B/C.
3027 // Generate legal pair permutations of A/B/C.
3028 std::vector<TreePatternNode*> ABVariants;
3029 std::vector<TreePatternNode*> BAVariants;
3030 std::vector<TreePatternNode*> ACVariants;
3031 std::vector<TreePatternNode*> CAVariants;
3032 std::vector<TreePatternNode*> BCVariants;
3033 std::vector<TreePatternNode*> CBVariants;
3034 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
3035 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
3036 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
3037 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
3038 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
3039 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
3041 // Combine those into the result: (x op x) op x
3042 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
3043 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
3044 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
3045 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
3046 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
3047 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
3049 // Combine those into the result: x op (x op x)
3050 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
3051 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
3052 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
3053 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
3054 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
3055 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
3056 return;
3060 // Compute permutations of all children.
3061 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3062 ChildVariants.resize(N->getNumChildren());
3063 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3064 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
3066 // Build all permutations based on how the children were formed.
3067 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
3069 // If this node is commutative, consider the commuted order.
3070 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
3071 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
3072 assert((N->getNumChildren()==2 || isCommIntrinsic) &&
3073 "Commutative but doesn't have 2 children!");
3074 // Don't count children which are actually register references.
3075 unsigned NC = 0;
3076 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
3077 TreePatternNode *Child = N->getChild(i);
3078 if (Child->isLeaf())
3079 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
3080 Record *RR = DI->getDef();
3081 if (RR->isSubClassOf("Register"))
3082 continue;
3084 NC++;
3086 // Consider the commuted order.
3087 if (isCommIntrinsic) {
3088 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
3089 // operands are the commutative operands, and there might be more operands
3090 // after those.
3091 assert(NC >= 3 &&
3092 "Commutative intrinsic should have at least 3 childrean!");
3093 std::vector<std::vector<TreePatternNode*> > Variants;
3094 Variants.push_back(ChildVariants[0]); // Intrinsic id.
3095 Variants.push_back(ChildVariants[2]);
3096 Variants.push_back(ChildVariants[1]);
3097 for (unsigned i = 3; i != NC; ++i)
3098 Variants.push_back(ChildVariants[i]);
3099 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
3100 } else if (NC == 2)
3101 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
3102 OutVariants, CDP, DepVars);
3107 // GenerateVariants - Generate variants. For example, commutative patterns can
3108 // match multiple ways. Add them to PatternsToMatch as well.
3109 void CodeGenDAGPatterns::GenerateVariants() {
3110 DEBUG(errs() << "Generating instruction variants.\n");
3112 // Loop over all of the patterns we've collected, checking to see if we can
3113 // generate variants of the instruction, through the exploitation of
3114 // identities. This permits the target to provide aggressive matching without
3115 // the .td file having to contain tons of variants of instructions.
3117 // Note that this loop adds new patterns to the PatternsToMatch list, but we
3118 // intentionally do not reconsider these. Any variants of added patterns have
3119 // already been added.
3121 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
3122 MultipleUseVarSet DepVars;
3123 std::vector<TreePatternNode*> Variants;
3124 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
3125 DEBUG(errs() << "Dependent/multiply used variables: ");
3126 DEBUG(DumpDepVars(DepVars));
3127 DEBUG(errs() << "\n");
3128 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this,
3129 DepVars);
3131 assert(!Variants.empty() && "Must create at least original variant!");
3132 Variants.erase(Variants.begin()); // Remove the original pattern.
3134 if (Variants.empty()) // No variants for this pattern.
3135 continue;
3137 DEBUG(errs() << "FOUND VARIANTS OF: ";
3138 PatternsToMatch[i].getSrcPattern()->dump();
3139 errs() << "\n");
3141 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
3142 TreePatternNode *Variant = Variants[v];
3144 DEBUG(errs() << " VAR#" << v << ": ";
3145 Variant->dump();
3146 errs() << "\n");
3148 // Scan to see if an instruction or explicit pattern already matches this.
3149 bool AlreadyExists = false;
3150 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
3151 // Skip if the top level predicates do not match.
3152 if (PatternsToMatch[i].getPredicates() !=
3153 PatternsToMatch[p].getPredicates())
3154 continue;
3155 // Check to see if this variant already exists.
3156 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),
3157 DepVars)) {
3158 DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
3159 AlreadyExists = true;
3160 break;
3163 // If we already have it, ignore the variant.
3164 if (AlreadyExists) continue;
3166 // Otherwise, add it to the list of patterns we have.
3167 PatternsToMatch.
3168 push_back(PatternToMatch(PatternsToMatch[i].getSrcRecord(),
3169 PatternsToMatch[i].getPredicates(),
3170 Variant, PatternsToMatch[i].getDstPattern(),
3171 PatternsToMatch[i].getDstRegs(),
3172 PatternsToMatch[i].getAddedComplexity(),
3173 Record::getNewUID()));
3176 DEBUG(errs() << "\n");